sandforge 1.81.0 → 1.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-C4YGSK6W.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/{chunk-TKQQVB2D.mjs → chunk-2JZGCCPG.mjs} +1 -1
- package/lib/{chunk-TPHXRHOA.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-ZWZXQTAK.mjs → chunk-32EUNQT6.mjs} +14 -14
- package/lib/{chunk-HYOOJVR6.mjs → chunk-3C2ZZIFN.mjs} +1 -1
- package/lib/{chunk-AELFEK3G.mjs → chunk-3CX7GPCR.mjs} +1 -1
- package/lib/{chunk-YJEXE6HZ.mjs → chunk-3HEMJTAP.mjs} +2 -2
- package/lib/{chunk-DQR5NDMI.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-D7P7DTWL.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-MNITSYI2.mjs → chunk-3SKLBRPL.mjs} +1 -1
- package/lib/{chunk-MAHZMPMZ.mjs → chunk-3XG25GTF.mjs} +1 -1
- package/lib/{chunk-N7J6NJQ6.mjs → chunk-42BFLWHR.mjs} +1 -1
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/{chunk-DHGPDSXS.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-5344TZBT.mjs → chunk-5K2I2DMP.mjs} +1 -1
- package/lib/{chunk-2OZG6GRW.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/{chunk-SW2NUKQL.mjs → chunk-6KP6WETK.mjs} +1 -1
- package/lib/{chunk-FSZTXLNW.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-6NADW3OI.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-67CC7RAE.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-IBURU7T7.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/{chunk-CULAOP3U.mjs → chunk-7PY3VQP3.mjs} +1 -1
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/{chunk-V4RKM4QZ.mjs → chunk-7WSLT5VX.mjs} +1 -1
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-K77NR3UK.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/{chunk-MWLFFVQV.mjs → chunk-AUS6NFLZ.mjs} +1 -1
- package/lib/{chunk-NWPQF5XR.mjs → chunk-BMTNTBBM.mjs} +1 -1
- package/lib/{chunk-FTA5LOVX.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-WM5JI4JI.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-5UT2ZBGF.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-GYKNCYES.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/{chunk-W2AAGIZF.mjs → chunk-CCEH7L53.mjs} +1 -1
- package/lib/{chunk-WWTXRWNZ.mjs → chunk-CELEBWEZ.mjs} +1 -1
- package/lib/{chunk-D62KWDDT.mjs → chunk-CV47FDQW.mjs} +1 -1
- package/lib/{chunk-AJPSGVMD.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/{chunk-YIGFYZQY.mjs → chunk-DBBPDSFN.mjs} +1 -1
- package/lib/{chunk-T5VAULLQ.mjs → chunk-DIL62SUN.mjs} +1 -1
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-GK7VEYFM.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-MHW6DV6T.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-PYUEHBA6.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-E2OBAWSH.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-MKNAZPOT.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-UUSLTW5V.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-DHIW4IO5.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/{chunk-BZFIOZS3.mjs → chunk-FOIWWK7G.mjs} +1 -1
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/{chunk-XIZ5LMQM.mjs → chunk-G2JR3F63.mjs} +1 -1
- package/lib/{chunk-2Z54GB6X.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-2NAIUKVL.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-TQM2XJ27.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-2IB7I3IQ.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-YHIOS2PU.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-WI4HYWV6.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-KRNFVAGC.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/{chunk-OIIL4NVI.mjs → chunk-HIHCYMSL.mjs} +1 -1
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/{chunk-V2QO6KOE.mjs → chunk-IRZJU2PG.mjs} +14 -11
- package/lib/{chunk-CAFUNR6D.mjs → chunk-ISSP2FZ5.mjs} +1 -1
- package/lib/{chunk-OEHVAJAB.mjs → chunk-IVZJSDJD.mjs} +1 -1
- package/lib/{chunk-E2YJVSX6.mjs → chunk-J24TIGSI.mjs} +1 -1
- package/lib/{chunk-YCSFP6ER.mjs → chunk-JESRFE2Z.mjs} +1 -1
- package/lib/{chunk-KOQV4WXC.mjs → chunk-JFNLKHY6.mjs} +2 -2
- package/lib/{chunk-NJ3EOEHS.mjs → chunk-JH27IKCO.mjs} +1 -1
- package/lib/{chunk-DXOXLUZA.mjs → chunk-JJITOWZK.mjs} +1 -1
- package/lib/{chunk-KNIRA333.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-J6G23RUI.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/{chunk-6IGEASOF.mjs → chunk-JQZTMFO7.mjs} +1 -1
- package/lib/{chunk-55LQD3Y3.mjs → chunk-KIMQQ6JQ.mjs} +1 -1
- package/lib/{chunk-EH5YUA5W.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/{chunk-56MPPWLA.mjs → chunk-KP5G6FUC.mjs} +1 -1
- package/lib/{chunk-EAFLDSQ2.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-MO3N5XVV.mjs → chunk-LAUOSXMN.mjs} +2 -2
- package/lib/{chunk-HVC5CYIB.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-7PK5QDQI.mjs → chunk-LXDSRP2W.mjs} +1 -1
- package/lib/{chunk-YOGMP72T.mjs → chunk-MKTXJCXN.mjs} +1 -1
- package/lib/{chunk-VSU74RQ3.mjs → chunk-MUEQRIK7.mjs} +1 -1
- package/lib/{chunk-UCHAZ4ZU.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-OVOLG3AL.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/{chunk-6SEDOIO3.mjs → chunk-O2PUGRNW.mjs} +1 -1
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/{chunk-KGYXLSQ5.mjs → chunk-P55MKIZX.mjs} +1 -1
- package/lib/{chunk-KE2PGD6C.mjs → chunk-P63WJMXQ.mjs} +1 -1
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-OMZJ37JI.mjs → chunk-PE435FVH.mjs} +2 -2
- package/lib/{chunk-GR3NGDVM.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-ZUA5BNAO.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/{chunk-43K2C6H2.mjs → chunk-PWVDNN2C.mjs} +1 -1
- package/lib/{chunk-DMBR24CK.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-OXKZ4Y3B.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-EOSEMFPU.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/chunk-QROPNEGY.mjs +14 -0
- package/lib/{chunk-6CDIIFNX.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-X2ZVSQ54.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/{chunk-ETT5GP4P.mjs → chunk-SAMWHL22.mjs} +1 -1
- package/lib/{chunk-LO527YLT.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-33ZX3A56.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-GTIXJCGS.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/{chunk-OQQHNYR7.mjs → chunk-SZGGFST2.mjs} +2 -2
- package/lib/{chunk-OU5W7SCB.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-FLNLG43R.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-RKALOKAU.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/{chunk-WEZLXE34.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-ONMBSACW.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-HYBH5PFM.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-BNO5GIJ6.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-3AOKLIVE.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/{chunk-742SSN7I.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-GWRKS3AL.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-2OIRJEYE.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-FDGFUEK3.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-UIUPPEFB.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-XC2QKQT5.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-UT27HXE7.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/{chunk-5VQNKDFU.mjs → chunk-XK5W7BVE.mjs} +1 -1
- package/lib/{chunk-OZNLOV4U.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-FSDO4DJA.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/{chunk-AITNZWLB.mjs → chunk-XU25YA46.mjs} +1 -1
- package/lib/{chunk-XEB6HZ34.mjs → chunk-XZISAZA6.mjs} +1 -1
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/{chunk-4L7FBOJS.mjs → chunk-YAIIRFKJ.mjs} +1 -1
- package/lib/{chunk-T3PLRQ2T.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-Y5ZCPY36.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/{chunk-R6TF26V4.mjs → chunk-YMDFF657.mjs} +1 -1
- package/lib/{chunk-JU2XEKEO.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-NWVVCZUK.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-O6ADMP36.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/{chunk-QXLZINZB.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/{chunk-SQGP46QS.mjs → chunk-ZUOPC4W2.mjs} +1 -1
- package/lib/{chunk-3B5H24ZG.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-K55LH4ZQ.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +1 -1
- package/lib/sandforge-backup.mjs +1 -1
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +1 -1
- package/lib/sandforge-env.mjs +185 -139
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +14 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +157 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +17 -3
- package/lib/chunk-2ZMGVBLW.mjs +0 -7
- package/lib/chunk-5C5XEVZN.mjs +0 -11
- package/lib/chunk-5CKWGZX4.mjs +0 -9
- package/lib/chunk-5ZKCLBTN.mjs +0 -474
- package/lib/chunk-7DALDJMO.mjs +0 -7
- package/lib/chunk-DPYTG6DM.mjs +0 -48
- package/lib/chunk-G4VXPS3A.mjs +0 -7
- package/lib/chunk-GF247DA7.mjs +0 -7
- package/lib/chunk-IKGHRYCN.mjs +0 -7
- package/lib/chunk-IM2XA6JI.mjs +0 -7
- package/lib/chunk-K5HV4YRO.mjs +0 -7
- package/lib/chunk-N6HHNR6J.mjs +0 -7
- package/lib/chunk-O7DAFE6M.mjs +0 -14
- package/lib/chunk-R2BJWO5N.mjs +0 -20
- package/lib/chunk-T26C576X.mjs +0 -9
- package/lib/chunk-V473C7LY.mjs +0 -7
- package/lib/chunk-WD47PGUS.mjs +0 -10
- package/lib/chunk-XC54KKKC.mjs +0 -7
- package/lib/chunk-XGKSSCW7.mjs +0 -7
- package/lib/chunk-ZWCRWF7E.mjs +0 -7
|
@@ -4,9 +4,9 @@ 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{b as _a,c as Jf,d as Qf}from"./chunk-FTA5LOVX.mjs";import{b as Zp}from"./chunk-KNIRA333.mjs";import{d as ca,k as Vl,o as Jl,q as ua,r as Ql}from"./chunk-7DALDJMO.mjs";import{a as Pt,d as Ba,e as Kt,f as An,i as ws,j as St,k as at,l as Lf}from"./chunk-O7DAFE6M.mjs";import{b as vr,e as Jn}from"./chunk-BZ24IAP5.mjs";import{a as qt}from"./chunk-SCKUIE3R.mjs";import{a as yo,b as Ri,c as kt,d as Nn,e as Oi,f as nn,g as bo,h as ki,j as Si}from"./chunk-6FARZYMJ.mjs";import{$ as kp,A as Kf,Aa as Np,B as Vf,C as or,Ca as Cp,D as bs,Da as Mp,E as jn,Ea as Bp,F as Yf,G as Xf,H as Zf,I as qa,Ia as Lp,J as ep,Ja as Wp,K as tp,Ka as Xa,L as np,M as rp,Ma as Dp,N as op,O as Ua,Oa as _p,P as Rs,Pa as qp,Q as sp,Qa as Up,R as ip,Ra as Gp,S as ap,Sa as zp,T as gp,Ta as Za,U as mp,Ua as Hp,V as wp,Va as Kp,W as ir,Wa as ed,X as yp,Xa as Vp,Y as bp,Ya as Jp,Z as Rp,Za as Qp,_ as Op,_a as Yp,aa as Sp,ba as Tp,ca as za,cb as Xp,da as Ha,ea as ks,fa as Ap,ga as Ka,gb as eh,h as ps,ha as Lt,hb as Ss,ia as jp,ib as th,jb as td,ka as $p,kb as nd,lb as rd,m as La,ma as vp,mb as nh,n as Wf,na as Va,nb as rh,o as rr,p as We,pb as od,q as Df,qa as Ep,qb as sd,r as ys,ra as Ja,rb as oh,s as Wa,sa as Ip,sb as sh,t as Da,tb as ih,u as _f,ub as ah,v as qf,va as Qa,w as Uf,wa as xp,x as Gf,xa as Pp,y as zf,ya as Fp,z as Hf,za as Ya}from"./chunk-KGYXLSQ5.mjs";import{f as $f,g as Ea,h as vf,i as xf,j as Pf,k as Ff,l as Nf,m as Cf,n as xa,o as nr}from"./chunk-TEIBWMJM.mjs";import{a as _r,b as ms,c as Mf,d as Bf,e as Pa,f as Fa,g as Na,h as Ca,j as Ma}from"./chunk-DMBR24CK.mjs";import{c as Ia,e as hs,f as Ef,g as If,h as gs}from"./chunk-BWWQXU2B.mjs";import{a as tf,e as nf,h as rf,j as of}from"./chunk-4L7FBOJS.mjs";import{a as zl}from"./chunk-OXKZ4Y3B.mjs";import{a as Ll,b as Dr,c as Wl,d as is,f as Dl,g as _l,h as aa,i as ql,j as Ul,k as Gl}from"./chunk-MAHZMPMZ.mjs";import{b as Hl,c as da,e as Kl}from"./chunk-M6P5ZZLE.mjs";import{h as Bl,i as ia,j as ss}from"./chunk-UIUPPEFB.mjs";import{a as Hi,b as zu,c as Hu,d as Ku,f as Nr,g as Uo,h as Ki,n as tl}from"./chunk-6SEDOIO3.mjs";import{C as Gi,H as _o,N as Yn,O as Gu,P as Fr,Q as qo,a as ou,m as Ui}from"./chunk-ZWCRWF7E.mjs";import{b as Xu,c as Zu,d as el}from"./chunk-T63U4OZJ.mjs";import{a as nl}from"./chunk-YYZL7UGV.mjs";import{a as Mu,c as _i,g as Bu,h as Lu,i as Wu}from"./chunk-54HYHHVL.mjs";import{h as Vi}from"./chunk-MNITSYI2.mjs";import{a as zi}from"./chunk-QSRAEUGZ.mjs";import{a as dp,b as Os,c as cp,d as Ga,e as sr,f as up,g as lp,h as fp,l as pp,m as hp}from"./chunk-NJ3EOEHS.mjs";import{c as Qu,d as Yu,h as al,j as dl}from"./chunk-ETT5GP4P.mjs";import{b as zo,m as cl}from"./chunk-4JKR4PTZ.mjs";import{a as zc,b as Fn,c as On}from"./chunk-HVC5CYIB.mjs";import{B as Xn,s as Ji,t as Cr,v as il,w as Go,y as Qi,z as Yi}from"./chunk-T26C576X.mjs";import{d as kn}from"./chunk-BNO5GIJ6.mjs";import{a as Ye}from"./chunk-4TLYUZD5.mjs";import{f as wo}from"./chunk-SQGP46QS.mjs";import{b as rl,c as ol,g as sl}from"./chunk-6IGEASOF.mjs";import{$a as tr,A as gl,Ab as ds,Ac as Aa,Bb as ma,Bc as ja,C as ml,Cb as gf,D as wl,Dc as Af,E as yl,Eb as cs,F as Qo,Fc as jf,G as bl,Ga as Zl,Gb as mf,Gc as $a,H as Rl,Hc as va,J as ea,K as ta,Ka as ef,Kb as us,L as Ol,Lb as wf,M as kl,Ma as er,Mb as yf,N as Yo,Nb as bf,O as Xo,Ob as ls,P as Br,Pb as wa,Q as Lr,R as Sl,S as Tl,Sa as df,T as Al,U as jl,V as Bn,Vb as ya,Xb as ba,Yb as Ra,_a as as,ac as Oa,bc as ka,c as Ni,cc as Rf,e as su,eb as cf,fb as uf,fc as Sa,g as $o,hb as Tn,i as iu,ic as Of,j as Ci,ja as Yl,jc as kf,k as Mi,kb as lf,l as au,la as Xl,lb as ff,m as Bi,mc as Ht,n as Li,na as la,o as ul,p as Ho,q as Zn,qc as Sf,r as ll,s as fl,sc as Tf,t as Ko,tc as fs,u as pl,v as Vo,w as Jo,wb as pf,x as hl,xb as hf,xc as Pe,y as Xi,yb as ha,yc as Ta,z as Zi,zb as ga}from"./chunk-KOQV4WXC.mjs";import{a as na,b as Sn,c as $l,d as Zo,e as vl,f as Ke,g as El,h as Il,i as es,k as xl,l as Pl,m as Fl,n as ts,o as ra,p as Nl,q as zt,r as ns,s as on,t as oa,u as Cl,v as Wr,w as Ml,x as rs}from"./chunk-CULAOP3U.mjs";import{a as Pr,c as du,d as Wi,e as cu,f as uu,g as lu,h as fu,j as pu}from"./chunk-INIT2UKJ.mjs";import{a as os,b as sa}from"./chunk-HF6LAK3G.mjs";import{l as Uu}from"./chunk-KRNFVAGC.mjs";import{a as Uc}from"./chunk-SU65Z2BA.mjs";import{i as fa,q as pa,r as sf,s as af}from"./chunk-2OIRJEYE.mjs";import{b as Gc,d as Hc,h as dh}from"./chunk-LCDPCUXS.mjs";import{a as gu,b as mu,c as Mn,d as Eu,e as Iu,h as xu,i as Pu,j as Fu,k as Nu,l as Cu,m as Di}from"./chunk-XEB6HZ34.mjs";import{a as He,i as wu,j as yu,l as Eo,o as Io,p as bu,q as xo,r as Ru,s as Po,t as Ou,u as ku,v as Fo,w as Su,x as No}from"./chunk-ICIYL45C.mjs";import{a as Vu,d as Ju}from"./chunk-TUACWKIH.mjs";import{a as it,b as Mr}from"./chunk-TQ2TQHTT.mjs";import{b as Tu,c as Bo,d as Au,e as ju,f as $u,g as Lo,i as vu,l as Wo,m as Do}from"./chunk-HFSBDM7B.mjs";import{a as Co,b as Mo}from"./chunk-OHEOJISY.mjs";import{a as vo,c as hu}from"./chunk-EADHKH3A.mjs";import{C as $i,D as So,E as Qn,F as ze,G as Le,H as vi,I as Ir,L as Ei,M as Ii,N as Zc,Q as xi,X as Pi,a as Cn,aa as Fi,b as $e,ba as eu,c as ut,da as tu,f as Kc,g as Vc,h as Jc,i as Qc,ja as nu,ka as To,m as Yc,n as Ti,o as Oo,p as Ai,q as Se,r as ce,s as Er,t as rn,u as ko,w as ji,z as Xc}from"./chunk-55LQD3Y3.mjs";import{a as Ro,h as Be}from"./chunk-TZE3Y7IQ.mjs";import{c as Du,f as _u,j as qi,k as qu}from"./chunk-3B5H24ZG.mjs";import{a as Ao,b as jo,c as xr,e as ru}from"./chunk-EAFLDSQ2.mjs";import{b as V}from"./chunk-CA5NAXSU.mjs";import{Da as xc,Dd as qc,H as xn,Hd as Vn,I as uo,Ic as Kn,Id as mo,Lc as ho,P as Rc,T as Oc,W as lo,X as fo,Xb as Sr,Xc as Bc,Y as li,Yc as Lc,Z as kr,Zb as Pc,_ as bn,ac as Qe,ad as go,bc as Tr,ca as kc,da as Sc,dc as Ar,fc as et,gc as Ut,ha as Tc,hc as tn,hd as $r,ia as Ac,ic as mi,id as Wc,ja as jc,jc as gt,ka as $c,kd as Dc,lc as Fc,mc as Pn,na as po,nc as Hn,oa as fi,oc as jr,pa as pi,pc as Gt,qa as vc,qc as mt,qd as yi,ra as hi,sa as Ec,sc as wi,tc as Nc,ua as Rn,va as Ic,vd as bi,wc as Cc,xc as Mc,ya as gi,yd as _c}from"./chunk-DPYTG6DM.mjs";import{A as C}from"./chunk-WZQEK4WT.mjs";import{createHash as fy,randomUUID as Us}from"node:crypto";import{existsSync as Yt,readFileSync as pn,readdirSync as py,renameSync as Vg,rmSync as Ws,statSync as Jg,writeFileSync as Qg}from"node:fs";import{basename as rc,dirname as hy,join as Kd,resolve as Wt,sep as gy}from"node:path";import{createReadStream as Nm,existsSync as Cm}from"node:fs";import{createInterface as Mm}from"node:readline";var ch=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Bm(r){let e=[],t=Mm({input:Nm(r,"utf8"),crlfDelay:1/0}),n=(o,s)=>{typeof s!="string"||!Number.isFinite(Date.parse(s))||(o.endedAt===void 0||Date.parse(s)>Date.parse(o.endedAt))&&(o.endedAt=s)};for await(let o of t){let s=e.at(-1);if(o.startsWith('{"part":')){try{let{part:f}=JSON.parse(o),p=typeof f?.startedAt=="string"?f.startedAt:void 0;e.push({...p?{startedAt:p}:{},wrote:[]})}catch{e.push({wrote:[]})}continue}if(!s)continue;if(o.startsWith('{"end":')){try{n(s,JSON.parse(o).end?.at)}catch{}continue}let i=cl(o);if(i){n(s,i.at),(s.jobEndedAt===void 0||Date.parse(i.orgAt)>Date.parse(s.jobEndedAt))&&(s.jobEndedAt=i.orgAt);continue}if(!o.startsWith('["x"')&&!o.startsWith('["p"')&&!o.startsWith('["g"'))continue;let a;try{a=JSON.parse(o)}catch{continue}if(!Array.isArray(a))continue;let[d,c,u,l]=a;d==="x"?n(s,l):d==="p"&&typeof c=="string"&&ch.test(c)?s.wrote.push(c):d==="g"&&typeof u=="string"&&ch.test(u)&&s.wrote.push(u)}return e}async function uh(r,e){if(!Cm(r))return[];let t;try{t=await Bm(r)}catch{return[]}let n=[];for(let[o,s]of t.entries()){let i=await e.readAt(r,o).catch(()=>{});if(!i)return[];n.push({part:o,created:i.created,linked:i.remap.linked.flatMap(a=>{let d=i.remap.table[a];return d!==void 0?[d]:[]}),wrote:s.wrote,...s.startedAt?{startedAt:s.startedAt}:{},...s.endedAt?{endedAt:s.endedAt}:{},...s.jobEndedAt?{jobEndedAt:s.jobEndedAt}:{}})}return n}function Ln(r){let e=Date.parse(r.endedAt??"");if(!Number.isFinite(e))return;let t=Date.parse(r.startedAt??""),n=Date.parse(r.jobEndedAt??"");return{runRecordedAt:new Date(e),runDurationMs:Number.isFinite(t)&&t<=e?e-t:0,endedByItsWrites:!0,...Number.isFinite(n)?{writtenUntil:new Date(n)}:{}}}function ar(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=Ln(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function Wn(r){return r.flatMap(e=>e.ids)}function sn(r,e){if(e===void 0)return r.map(n=>({...n,ids:[...n.ids]}));let t=new Set(e.map(n=>n.slice(0,15)));return r.flatMap(n=>{let o=n.ids.filter(s=>t.has(s.slice(0,15)));return o.length>0?[{objectApiName:n.objectApiName,ids:o}]:[]})}function Fe(r,e=Date.now()){return Math.max(0,e-r)}var id=class{listenerMap=new Map;on(e,t){let n=this.listenerMap.get(e);return n||(n=new Set,this.listenerMap.set(e,n)),n.add(t),()=>{n.delete(t)}}emit(e,t){let n=this.listenerMap.get(e);if(n)for(let o of n)try{o(t)}catch(s){Ye.warn("Event listener threw an error",{eventType:String(e),error:V(s)})}}removeAllListeners(){this.listenerMap.clear()}};var qr=class r{constructor(e){this.store=e}store;map=new Map;existing=new Set;updated=new Set;objectOf=new Map;aliases=new Map;createdKeys=new Set;alias(e,t){e!==t&&this.aliases.set(e,t)}add(e,t,n){if(this.store){this.store.setMapping("created",e,t,n);return}this.forgetCreated(e),this.createdKeys.add(t.slice(0,15)),this.map.set(e,t),this.existing.delete(e),this.updated.delete(e),this.label(e,n)}addUpdated(e,t,n){if(this.store){this.store.setMapping("updated",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.delete(e),this.updated.add(e),this.label(e,n)}addExisting(e,t,n){if(this.store){this.store.setMapping("existing",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.add(e),this.updated.delete(e),this.label(e,n)}countsByObject(){if(this.store)return this.store.countsByObject();let e=new Map;for(let[t,n]of this.objectOf){let o=e.get(n)??{objectApiName:n,created:0,linked:0,updated:0};this.existing.has(t)?o.linked++:this.updated.has(t)?o.updated++:o.created++,e.set(n,o)}return[...e.values()].map(({updated:t,...n})=>t>0?{...n,updated:t}:n)}createdByObject(){let e=new Map;if(this.store){for(let{kind:t,sourceId:n,objectApiName:o,earlier:s}of this.store.mappings()){if(t!=="created"||s||!o)continue;let i=e.get(o)??[];i.push(n),e.set(o,i)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}for(let[t,n]of this.objectOf){if(this.existing.has(t)||this.updated.has(t))continue;let o=e.get(n)??[];o.push(t),e.set(n,o)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}forgetCreated(e){let t=this.map.get(e);t!==void 0&&!this.existing.has(e)&&!this.updated.has(e)&&this.createdKeys.delete(t.slice(0,15))}createdTarget(e){return this.store?this.store.createdTarget(e):this.createdKeys.has(e.slice(0,15))}label(e,t){t?this.objectOf.set(e,t):this.objectOf.delete(e)}isExisting(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&(t.kind==="existing"||t.earlier)}return this.existing.has(e)}isCreated(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&t.kind==="created"&&!t.earlier}return this.map.has(e)&&!this.existing.has(e)&&!this.updated.has(e)}wasCreated(e){return this.store?this.store.mapping(e)?.kind==="created":this.isCreated(e)}existingSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="existing"||t).map(({sourceId:e})=>e):[...this.existing]}updatedSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="updated"&&!t).map(({sourceId:e})=>e):[...this.updated]}get(e){let t=this.aliases.get(e)??e;return this.store?this.store.targetOf(t):this.map.get(t)}remapRecord(e,t){let n={...e};for(let o of t){let s=n[o];if(typeof s=="string"){let i=this.aliases.size>0?this.aliases.get(s)??s:s,a=this.store?this.store.targetOf(i):this.map.get(i);a!==void 0&&(n[o]=a)}}return n}persist(){this.store?.flush()}get count(){return this.store?this.store.mappedSize:this.map.size}clear(){this.aliases.clear(),this.map.clear(),this.existing.clear(),this.updated.clear(),this.objectOf.clear(),this.createdKeys.clear()}toJSON(){let e={};if(this.store){for(let{sourceId:t,targetId:n}of this.store.mappings())e[t]=n;return e}for(let[t,n]of this.map)e[t]=n;return e}static fromJSON(e){let t=new r;for(let[n,o]of Object.entries(e))n==="__proto__"||n==="constructor"||n==="prototype"||typeof o=="string"&&t.add(n,o);return t}};var Wm={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},Ts=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??Wm[e]??"Name",i=Be(e),a=Be(s),d=new Map;for(let b of t){let k=b.Id,O=b[s];typeof k=="string"&&typeof O=="string"&&O&&d.set(k,O)}if(d.size===0)return{mappings:[],unmatched:t.map(b=>({sourceId:typeof b.Id=="string"?b.Id:"",matchValue:typeof b[s]=="string"?b[s]:null})).filter(b=>b.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,u=Pr(`${c})`),l=Pr(", "),f=new Map,p=[],g=u,h=async()=>{if(p.length===0)return;let b=`${c}${p.join(", ")})`;p=[],g=u;for(let k of await this.query(n,b)){let O=k.Id,w=k[s];typeof O=="string"&&typeof w=="string"&&f.set(w,O)}};for(let b of new Set(d.values())){let k=`'${Ro(b)}'`,O=(p.length>0?l:0)+Pr(k);p.length>=$l||p.length>0&&g+O>14e3?(await h(),g+=Pr(k)):g+=O,p.push(k)}await h();let m=[],R=[];for(let[b,k]of d){let O=f.get(k);O?m.push({sourceId:b,targetId:O,matchedBy:s,matchValue:k}):R.push({sourceId:b,matchValue:k})}return{mappings:m,unmatched:R}}};function ad(r,e){let t=new Set(r.filter(s=>s.createable).map(s=>s.name)),n=new Set(r.filter(s=>s.updateable!==!1).map(s=>s.name)),o=new Map;for(let s of r)s.picklistValues&&s.picklistValues.length>0&&o.set(s.name,new Set(s.picklistValues));return{creatable:t,updateable:n,picklistValuesByField:o.size>0?o:null,picklistFields:ul(r,e),fields:r}}async function an(r,e,t){return ad(await r(e,t),t)}function dd(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function dr(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var Dm=new Map;function lh(r){let{objectApiName:e,records:t,fieldInfos:n,remapper:o,referenceFallback:s,failedObjects:i,writtenObjects:a,neverCopied:d,ownerMappings:c,resolvedLookups:u,targetLacks:l,inactiveOwners:f,excludedFields:p,fieldRename:g,creatableFields:h,updatableFields:m,picklistValuesByField:R,picklistFields:b,recordTypeValues:k,businessAccounts:O,contactPoints:w,decide:A,currencies:S,currencyFields:v=Dm,parentCurrencies:j,pricedIn:F,outsideTheSample:B,heldByTheRun:E}=r,_=n.filter(H=>H.isReference).map(H=>H.name),ee=new Set(_),X=w?.forObject(e,n,g),z=H=>h.has(H.name)||g[H.name]!==void 0,J=new Set(n.filter(H=>H.isReference&&(H.referenceTo??[]).some(Q=>i?.has(Q))).map(H=>H.name)),Me=new Set(n.filter(H=>{let Q=H.referenceTo??[];return H.isReference&&Q.length===1&&a?.has(Q[0])===!0}).map(H=>H.name)),ke=ru(n.filter(H=>H.isReference),d),ue=b??new Map;return t.map(H=>{let Q=[],pe=[],we=[],Ee=[],ae=u?.get(H);for(let U of n){if(!U.isReference||p.has(U.name)||ae?.[U.name]!==void 0)continue;let Oe=z(U),ye=dd(U,m,g[U.name]);if(!Oe&&!ye)continue;let le=H[U.name];if(B&&U.name!=="RecordTypeId"&&typeof le=="string"&&le!==""&&!o.get(le)&&B(U,le)){pe.push(U.name),we.push(g[U.name]??U.name);continue}if(E&&U.name!=="RecordTypeId"&&typeof le=="string"&&le!==""&&!o.get(le)&&E(le)){pe.push(U.name),Ee.push(g[U.name]??U.name);continue}if(s!=="nullify"&&!J.has(U.name)&&!Me.has(U.name)||U.name==="RecordTypeId"||ke.has(U.name))continue;let Nt=H[U.name];typeof Nt!="string"||!Nt||Oe&&o.get(Nt)||(pe.push(U.name),Q.push({field:g[U.name]??U.name,sourceRefId:Nt,targetObjects:U.referenceTo??[],...ye?{}:{insertOnly:!0}}))}let D=_.filter(U=>U!=="RecordTypeId"),L=o.remapRecord(H,D);for(let U of pe)L[U]=null;for(let[U,Oe]of Object.entries(ae??{}))L[U]=Oe;let Re=L.OwnerId,Ne=!1;typeof Re=="string"&&c[Re]&&(L.OwnerId=c[Re],Ne=!0);let Ie=ko(L,O?.has(H)===!0),ge={},K=new Set,te=[],M=[],q;for(let U of Object.keys(L)){if(p.has(U))continue;let Oe=g[U];if(Oe){L[U]!==null&&(ge[Oe]=L[U]),K.add(Oe);continue}if(!h.has(U))continue;if(ae?.[U]!==void 0){ge[U]=ae[U];continue}if(U!=="RecordTypeId"&&ke.has(U)&&!(U==="OwnerId"&&Ne)){if(s!=="keep")continue;let le=L[U];if(typeof le=="string"&&l?.has(le)){te.push(U);continue}if(U==="OwnerId"&&typeof le=="string"&&f?.has(le)){q=le;continue}}else if(s==="keep"&&U!=="RecordTypeId"&&ee.has(U)){let le=L[U];if(typeof le=="string"&&l?.has(le)){M.push(U);continue}}if(ho(e,U,Ie))continue;let ye=L[U];ye!==null&&(ge[U]=ye)}let G=ge.RecordTypeId;A?.(ge,typeof G=="string"?G:void 0);for(let U of Nc(e,ge))delete ge[U];let Te;S&&!K.has(He)?Te=xo(ge,{read:H[He],currencyFields:v,recordTypeDefault:Zn(k,G)?.picklists.get(He)?.defaultValue,ratesOn:Eo(e,H),pricedIn:F?.(H)},S):j&&(Te=ku(ge,{read:H[He],parent:Ou(e,H,_,j.changeOf),currencyFields:v},j.currencies));let ie=Ho(ge,R,ue,Zn(k,G),K),ne=Yc(e,ge);for(let U of ne)delete ge[U];return X?.(ge),{source:H,cleaned:ge,nullifiedFks:Q.filter(U=>!ne.includes(U.field)),picklistChanges:ie,...Te?{currencyChange:Te}:{},...te.length>0?{lookupsNotCarried:te}:{},...M.length>0?{lookupsOutsideTheRun:M}:{},...we.length>0?{lookupsOutsideTheSample:we}:{},...Ee.length>0?{lookupsHeldBack:Ee}:{},...q!==void 0?{ownerInactive:q}:{}}})}var _m=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,fh=Symbol("left to the platform"),As=class{constructor(e){this.deps=e}deps;expansionsUsed=0;failedOrphans=new Set;expansionErrors=[];pastTheCap=new Map;cap=0;async expandForNode(e){if(!e.enabled)return;this.cap=e.maxExpansions;let{fieldInfos:t,records:n,remapper:o,scopeCache:s}=e,i=new Map,a=t.filter(l=>l.isReference&&l.nillable===!1&&l.name!=="RecordTypeId");for(let l of n)for(let f of a){let p=l[f.name];if(typeof p!="string"||!p||o.get(p)||e.leftToThePlatform?.has(p))continue;let g=await this.parentObjectOf(e,f,p);if(!g)continue;let h=`${g}::${p}`;i.has(h)||i.set(h,{object:g,sourceId:p})}let d=4,c=[];for(let[,l]of i){let f=`${l.object}::${l.sourceId}`;if(!this.failedOrphans.has(f)&&!o.get(l.sourceId)){if(this.expansionsUsed+c.length>=e.maxExpansions){this.pastTheCap.set(f,l.object);continue}c.push({...l,cacheKey:f})}}let u=[c.filter(l=>l.object!==ce),c.filter(l=>l.object===ce)];for(let l of u){let f=[];for(let p=0;p<l.length;p+=d){let g=l.slice(p,p+d).filter(h=>!o.get(h.sourceId));await Promise.all(g.map(async h=>{try{let m=await this.expandSingleOrphanParent(e,h.object,h.sourceId);if(m===fh)return;m&&"id"in m?(this.expansionsUsed++,this.pastTheCap.delete(h.cacheKey),m.existing?o.addExisting(h.sourceId,m.id,h.object):(o.add(h.sourceId,m.id,h.object),m.owedStatus&&e.oweStatus?.(h.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(h.object,[h.sourceId]),h.object===Se&&rn(m.source)&&f.push(m.source)):(this.failedOrphans.add(h.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${h.object}/${h.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(h.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${h.object}/${h.sourceId}`,messages:[V(m)]})}}))}f.length>0&&await e.linkPersonContacts?.(f)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!Ao(a)),i;return o.length===1?i=s[0]:s.length>0&&(i=await e.objectOf?.(n,s)),i===e.node.objectApiName?void 0:i}capReport(){return this.pastTheCap.size===0?null:{cap:this.cap,notCopied:this.pastTheCap.size,objects:[...new Set(this.pastTheCap.values())]}}buildErrorReport(){return this.failedOrphans.size===0?null:{objectApiName:"__expandOrphanParents__",stage:"insert",failedCount:this.failedOrphans.size,attemptedCount:this.expansionsUsed+this.failedOrphans.size,samples:this.expansionErrors}}async expandSingleOrphanParent(e,t,n){let{sourceOrgId:o,targetOrgId:s,recordTypeMappings:i,recordTypeMapper:a}=e,{anonymize:d,withoutFileContent:c,startAsDraft:u,leftToThePlatform:l}=e;if(!_m.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let f=Be(t),p=await this.deps.describeFields(o,f),g=c?c(f,p):p,h=zt(g,e.fieldExclusions?.[f]);h.length===0&&h.push("Id");let m=`SELECT ${h.join(", ")} FROM ${f} WHERE Id = '${Ro(n)}'`,R=await this.deps.queryRecords(o,m);if(R.length===0)return null;if(l&&l.keep(f,R).length===0)return fh;let b=R[0],k=rn(b),O=k?await e.personAccountsInTarget?.():void 0;if(f===ce&&k&&O!==!1&&e.contactOnItsOwn?.(n)!==!0)throw new Error("Not copied: a person account's contact is written by the platform with its account, never on its own");let w=null;try{w=ad(await this.deps.describeFields(s,f),f)}catch(D){Ye.warn(`[forge] orphan-parent target describe failed for ${t}: ${D instanceof Error?D.message:String(D)}. Falling back to source createable.`)}let A=new Set(g.filter(D=>D.createable).map(D=>D.name)),S=w?dr(A,w.creatable):A,v=new Set(e.fieldExclusions?.[f]??[]),j=e.fieldMappings?.[f]??{},F=new Set,B=new Set(await e.maskedFieldsOf?.(f).catch(()=>[])??[]),E=[],_=S.has("RecordTypeId")&&!v.has("RecordTypeId")&&j.RecordTypeId===void 0,ee=f===Se&&k&&(e.businessAccountsAmong?(await e.businessAccountsAmong([b],_)).has(b):O===!1),X=ko(b,ee),z={};for(let D of g){let L=D.name;if(v.has(L))continue;let Re=b[L];if(Re==null)continue;if(B.has(L)){(j[L]!==void 0||S.has(L))&&E.push(L);continue}if(D.isReference&&typeof Re=="string"&&L!=="RecordTypeId")continue;let Ne=j[L];if(Ne){z[Ne]=Re,F.add(Ne);continue}S.has(L)&&(ho(f,L,X)||(z[L]=Re))}if(e.contactPoints?.forObject(f,g,j)?.(z),w){let D=new Set([...S].filter(L=>!v.has(L)&&!j[L]));await this.checkPicklists(e,f,b,z,w,D,F)}let J=a&&i?a.apply([z],i,D=>hs(f,D))[0]:z,Me=d?d(f,J,n,g):J,ke=u?await u(f,Me):void 0,ue=await this.insertParent(e,f,n,Me),H=ue.written,Q=ue.callId;if(!H)return null;let pe=H.success?void 0:_l(H,Me,void 0),we=H.errors;if(pe){let D=await this.insertParent(e,f,n,Bl(Me,pe));if(!D.written)return{refused:["No result returned for record",aa(pe,we)]};H=D.written,Q=D.callId}if(H.success)return E.length>0&&e.onMaskedLeftOut?.(f,E),pe&&e.onWrittenWithoutFields?.(f,{rows:1,fields:pe.map(D=>({...D,rows:1}))}),{id:H.id,existing:!1,owedStatus:ke,source:b,...Q!==void 0?{callId:Q}:{}};let Ee=this.deps.describeObject?await this.deps.describeObject(s,f).then(D=>D.keyPrefix,()=>null):null,ae=qu(H,Ee);return ae.kind==="linked"?{id:ae.id,existing:!0,source:b}:{refused:pe?[...H.errors,aa(pe,we)]:H.errors}}async insertParent(e,t,n,o){let s=e.calls?.sending(t,[{sourceId:n,payload:o}]),i;try{i=(await this.deps.insertRecords(e.targetOrgId,t,[o]))[0]}catch(a){throw s!==void 0&&nl(a)!=="may-have-written"&&e.calls?.answered(s),a}return s===void 0?{written:i}:i?.success?{written:i,callId:s}:(e.calls?.answered(s),{written:i})}async checkPicklists(e,t,n,o,s,i,a){let d=e.recordTypePicklists?await e.recordTypePicklists.forRows({objectApiName:t,rows:[n],fields:s.picklistFields,written:p=>i.has(p),recordTypeMappings:e.recordTypeMappings,withoutRecordTypes:!s.fields.some(p=>p.name==="RecordTypeId")}):void 0;for(let p of d?.notes??[])e.onRecordTypeNote?.(t,p);let c=o.RecordTypeId,u=n[He],l=e.currencies&&i.has(He)&&typeof u=="string"&&u!==""?await e.currencies():void 0;if(l){let p=xo(o,{read:u,currencyFields:Io(s.fields),recordTypeDefault:Zn(d?.byRecordType,c)?.picklists.get(He)?.defaultValue,ratesOn:Eo(t,n)},l);e.currencyChanges?.add(t,p);let g=n.Id;p&&typeof g=="string"&&e.currencyChangesById?.set(g,p)}let f=Ho(o,s.picklistValuesByField,s.picklistFields,Zn(d?.byRecordType,c),a);e.picklistChanges?.add(t,f)}};async function*js(r,e){let t=e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):0,n=0,o=[];for await(let s of r){if(t===0){if(s.length===0&&n>0)continue;n++,yield s;continue}for(o=o.length===0?[...s]:[...o,...s];o.length>=t;)n++,yield o.slice(0,t),o=o.slice(t)}(o.length>0||n===0)&&(yield o)}function Vt(r,e,t,n,o,s){let{queryPages:i}=r;if(i)return js(s?.all?i(e,t,s):i(e,t),n);if(s?.all)throw new Error("The deps read no archived row: no cursor to read through queryAll.");return js((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function hh(r){let e=async(...n)=>{let[o,s,...i]=n,a=Wi(s),d=cu(s,a===void 0?void 0:["Id",a.stamp]);if(!d)return r.queryRecords(...n);let c=await r.queryRecords(o,d.first,...i),u=l=>r.queryRecords(o,l);return a===void 0?lu(c,d,u):fu(c,d,u,a)},t=(n,o,s)=>pu(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??ph(),s?.all?i=>qm(r.queryPages?.(n,i,s)??ph()):i=>r.queryRecords(n,i),Wi(o));return new Proxy(r,{get(n,o,s){return o==="queryRecords"?e:o==="queryPages"?n.queryPages?t:void 0:Reflect.get(n,o,s)}})}async function qm(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*ph(){}var be=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},xd=Dr;function Gm(r){let e=r.from!=="plan"?r.from:r.fromTheJournal?"resumed":r.ofTheRunRetried?"retried":"simulation";return{objectApiName:r.objectApiName,count:r.ids.size,from:e,readAt:r.readAt}}var zm={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},Ft=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,mh=2e3;function Hm(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,failed:0,alreadyExists:0,unidentified:0,writtenBefore:0,withTheirAccount:0,withTheirEmail:0,teamOwners:0,teamOthers:0,teamValues:{notKept:new Map,unread:new Map},rolesOfTheirOpportunity:0,rolesGiven:0,personContactsUnlinked:0,sentOnTheirOwn:0,onTheirOwnWhy:"",withoutParent:0,withoutParentGroups:new Map,rowsLeft:()=>0,held:new Map,heldWholeRows:0,picklists:new Ko,currencies:new Fo,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,ownersInactive:0}}function wh(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function yh(r){return[Fi(r.flagsNotKept),ug(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function cd(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function ud(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var Km=5e3,Vm=2e3,bh="afterTask",ld=3,Rh=1e3,Dn=2e3;function Ur(r,e,t){return{objectApiName:r,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:e.filter(n=>n.createable).length,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}function Jm(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(et))}function sg(r,e){let t=[];for(let n of e){let o=n.referenceTo??[];if(!n.isReference||o.length!==1||!Qe(r,n.name,n.nillable))continue;let[s]=o;s!==r&&!Ke.has(s)&&t.push(s)}return t}function Qm(r,e,t){return sg(r,e).find(n=>t.has(n))}function Ym(r,e,t){let n=t.scopeCache;if(!n)return[];let o=new Set(t.graph.edges.filter(i=>i.targetObject===r).map(i=>i.sourceObject)),s=new Set;for(let i of e)if(i.isReference)for(let a of i.referenceTo??[])a!==r&&o.has(a)&&t.readObjects.has(a)&&!Ke.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var Xm=3,Zm=10,ew=5;function tw(r,e){let t=e.rows.filter(({objectApiName:s,row:i})=>{let a=i.Id;return typeof a!="string"||!r.heldForExclusions.get(s)?.has(a)});if(t.length===e.rows.length)return e;let n=new Set,o=new Set;for(let{objectApiName:s,row:i,field:a}of t)n.add(String(i[a])),o.add(s);return{ids:n,neededBy:o,rows:t}}function Oh(r,e){let t=r.readAsParents.get(e);return!t||t.count===0?"":`, ${t.count} read by id for the ${[...t.neededBy].sort().join(", ")} records that cannot be written without ${t.count===1?"it":"them"}`}function kh(r,e){let t=r.get(e)??new Set;if(!r.isRead(e))return new Set(t);let n=r.scopeOf(e);return new Set([...t].filter(o=>!n?.has(o)))}function Gr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function Sh(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function xs(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}var nw={storage:{past:"past the data storage the target has left",more:", or free data storage in the target"},within:{past:"past the MB it may take (--fit-within)",more:", or let it take more (--fit-within)"},maxTotal:{past:"past the records it may write (--max-total)",more:", or raise --max-total"},targetRequests:{past:"past the API requests the target has left today",more:", or run it once the target has more to spare"},bulkBatches:{past:"past the Bulk API batches the target has left today",more:", or run it once the target has more to spare"},sourceRequests:{past:"past the API requests the source has left today",more:", or run it once the source has more to spare"},heavyRoots:{past:"past what the sample may take",more:""},whole:{past:"past what the sample may take",more:""},draw:{past:"past what the sample may take",more:""}};function Th(r,e){let t=r/1048576*100;return(e==="up"?Math.ceil(t):Math.floor(t))/100}var jd=class extends ir{constructor(t,n,o){super("SAMPLE_CANNOT_FIT",t,n);this.sample=o}sample},Ah=3;function rw(r,e){let t=e.slice(0,Ah).map(({sourceId:i,matchValue:a})=>({recordSummary:`Id=${i} matchValue=${a??"null"}`,messages:[a===null?`This ${r} has no name to find it by in the target org: the records that point at it are not linked to one.`:`No ${r} of the target org is named "${a}": the records that point at it are not linked to one. Create a ${r} of that name in the target\u2019s Setup, or rename one of the target\u2019s to it, then run again.`]})),n=e.slice(Ah);if(n.length===0)return t;let o=n.map(({matchValue:i})=>i===null?"no name":`"${i}"`),s=o.length===1?o[0]:`${o.slice(0,-1).join(", ")} or ${o.at(-1)}`;return[...t,{recordSummary:`${n.length} more`,messages:[`No ${r} of the target org is named ${s} either.`]}]}function ow(r){let e=r.orphanExpander.capReport();return e?{orphanParentsCapped:e}:{}}function jh(r){let e=xs(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function sw(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function iw(r,e,t){let n=t.filter(d=>d.isReference),o=d=>n.filter(c=>(c.referenceTo??[]).includes(d)),s=d=>{let c=o(d);return c.length>0&&c.every(u=>(u.referenceTo??[]).length>1)},i=d=>{let c=o(d);return c.length>0&&c.every(u=>u.nillable===!0)},a=new Set(ts(e,new Map([[r,t]])).edges.filter(d=>d.targetObject===r&&(d.required===!0||d.type==="master-detail"&&!i(d.sourceObject))&&Fl(d)&&!s(d.sourceObject)).map(d=>d.sourceObject));for(let d of n){let c=d.referenceTo??[];c.length!==1||!Tr(d)||!Qe(r,d.name,d.nillable)||a.add(c[0])}return a.delete(r),[...a]}function aw(r,e){return $d(Hr(r.values()),e)}function Hr(r,e=new Map){for(let{field:t,parentObject:n,notInTarget:o,reason:s,recordType:i}of r){let a=`${t}|${n}|${o===!0?"outside":""}|${s??""}`,d=e.get(a)??{field:t,parentObject:n,...o?{notInTarget:o}:{},...s!==void 0?{reason:s}:{},...i?{recordType:i}:{},count:0};d.count++,e.set(a,d)}return e}function $d(r,e){return[...r.values()].sort((t,n)=>n.count-t.count).slice(0,3).map(({field:t,parentObject:n,notInTarget:o,reason:s,recordType:i,count:a})=>({recordSummary:i?`RecordType=${i.developerName} (${a} record${a===1?"":"s"})`:`${t} \u2192 ${n} (${a} record${a===1?"":"s"})`,messages:i?[Do({...i,recordCount:a})]:[s!==void 0?`Not written: ${s}`:o?`Not written: ${t} may not be left empty, and the target holds no ${n} record of the id it names, outside the run.`:`Not written: ${t} may not be left empty, and the ${n} it points at `+(e.has(n)?"failed in this run.":"was not written by this run.")]}))}var dw=3,$h=5e4;function cw(r,e){return!e||e.size===0?0:r.reduce((t,{node:n,read:o})=>t+(o>0?(e.get(n.objectApiName)??0)*Math.ceil(o/Dn):0),0)}var vh={field:"",parentObject:"",reason:"the source does not hold it"};function fd(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}function uw(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function lw(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function Eh(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function fw(r,e,t,n=()=>!0){return t.flatMap(o=>{let s=o.referenceTo??[],[i]=s;return o.isReference&&s.length===1&&i!==e&&n(o.name)&&r.writtenObjects.has(i)&&!r.config.referenceDataObjects.has(i)&&r.turnsEnded.has(i)&&Qe(e,o.name,o.nillable)?[{field:o.name,parent:i}]:[]})}var pw="held back for a record type closed to the user the run writes as",hw="held back for a record type the target has none of";function Ih(r){let e=0,t=0,n=0;for(let o of r)o.recordType?.unmapped?t++:o.recordType?e++:n++;return[...e>0?[{count:e,why:pw}]:[],...t>0?[{count:t,why:hw}]:[],...n>0?[{count:n,why:vd}]:[]]}function xh(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function Ph(r,e){return Di(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,lg(e))}function gw(r,e,t){let n=r.leftAside.get(e)??new Map;Hr(t,n),r.leftAside.set(e,n)}function mw(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function ww(r){return[...r.leftAside].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t.values()].sort((n,o)=>o.count-n.count).slice(0,3).map(({field:n,parentObject:o,reason:s,count:i})=>({recordSummary:`${n} \u2192 ${o} (${i} record${i===1?"":"s"})`,messages:[`Left aside, not written: ${s??""}`]}))}))}function Ps(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${Vc(n,t)}`).join("")+mw(r,e)}function yw(r){return[...bw(r),...ww(r)]}function bw(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:Jc(o,n),messages:[Qc(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Kr(r){return r==="not-creatable"?", which the target org takes no insert of":r==="not-in-target"?", which the target org does not have":", excluded from this run"}function Rw(r){let e=new Map([[void 0,new Set],["not-creatable",new Set],["not-in-target",new Set]]);for(let{excluded:t,target:n}of r)e.get(n)?.add(t);return[...e].filter(([,t])=>t.size>0).map(([t,n])=>`${[...n].sort().join(", ")}${Kr(t)}`).join("; ")}function Ow({field:r,excluded:e,through:t,namedBy:n,target:o}){return n!==void 0?`Not written: the only records that name it are ${n} records held back for ${e}${Kr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Kr(o)}.`:o==="not-creatable"?`Not written: ${r} may not be left empty, and the target org takes no insert of ${e}.`:o==="not-in-target"?`Not written: ${r} may not be left empty, and the target org does not have ${e}.`:e===Gt?`Not written: a price sold under a selling model needs its product's option for that model, and ${e} is excluded from this run.`:`Not written: ${r} may not be left empty, and ${e} is excluded from this run.`}var vd="held back for want of their parent",Fh=" \u2014 the records that cannot be written without one of those not written are held back",Nh={accountNotWritten:"not sent: a person account's contact goes in with its account, which this run did not write",contactNotFound:"not sent: a person account's contact goes in with its account, and the one the platform wrote was not found"};function Fs(r){let e=new Map;for(let{excluded:n,namedBy:o,target:s}of r){let i=o!==void 0,a=`${i?"named":"needing"}|${s??""}`,d=e.get(a)??{namedOnly:i,target:s,objects:[]};d.objects.push(n),e.set(a,d)}let t=({namedOnly:n,target:o})=>(n?3:0)+(o===void 0?0:o==="not-creatable"?1:2);return[...e.values()].sort((n,o)=>t(n)-t(o)).map(({namedOnly:n,target:o,objects:s})=>{let i=`${[...new Set(s)].sort().join(", ")}${Kr(o)}`;return{count:s.length,why:n?`held back, named only by records held back for ${i}`:`held back for want of ${i}`}})}function Qt(r,e){return Fs(r.heldForExclusions.get(e)?.values()??[])}function _n(r){return r.reduce((e,t)=>e+t.count,0)}function cn(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function Ns(r,e=!1){let t=_n(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+cn(r)}function Ch(r,e){return Ps(r,e)+Ns(Qt(r,e))}function kw(r){return[...r.heldForExclusions].map(([e,t])=>{let n=new Map;for(let o of t.values()){let s=`${o.field}|${o.through??""}|${o.namedBy??""}|${o.excluded}|`+(o.target??""),i=n.get(s)??{...o,count:0};i.count++,n.set(s,i)}return{objectApiName:e,stage:"scope",failedCount:t.size,attemptedCount:0,samples:[...n.values()].sort((o,s)=>s.count-o.count).slice(0,3).map(o=>{let s=`${o.count} record${o.count===1?"":"s"}`;return{recordSummary:o.namedBy!==void 0?`named by ${o.namedBy}.${o.field} (${s})`:`${o.field} \u2192 ${o.through??o.excluded} (${s})`,messages:[Ow(o)]}})}})}function Sw(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function Mh(r,e,t){for(let n of t){let o=e[n.name];if(typeof o!="string"||o===""||r.remapper.get(o))continue;let s=Sw(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function $n(r,e,t=[]){let n=e+_n(t);return`Held back ${r}, nothing written, ${n} failed${cn(t)}`}function Bh(r){return r>0?`, ${r} ${r===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:""}function ig(r,e=0){let t=r+e;if(t<=0)return"";let n=e>0?` (${e} of them outside the sample, with an account the run wrote)`:"";return`, ${t} written by the platform with their person account${n}`}function pd(r,e){if(e!==ce)return 0;let t=r.personContactsOutsideTheSample;return r.personContactsOutsideTheSample=0,t}function cr(r,e,t){t<=0||r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t)}function Ed(r,e){return r.writtenBefore.from==="resume"?`${e} already in the target, written before the run stopped`:`${e} already in the target from the run retried`}function ag(r,e){let t=Math.min(r,Math.max(0,e)),n=r-t;return(n>0?`, ${n} linked to records already in the target`:"")+(t>0?`, ${t} linked to records the run created (the target refused them as copies of those)`:"")}var Tw=3;function hd(r,e,t,n=0){let o=r.dryRun?"would be inserted":"succeeded",s=e.updated>0?`, ${e.updated} updated through their external id`:"",i=ag(e.linked,e.linkedToCreated),a=ig(e.withTheirAccount,n),d=e.withTheirEmail>0?`, ${e.withTheirEmail} written by the platform with their email`:"",c=dg(e.teamOwners,e.teamOthers)+cg(e.rolesOfTheirOpportunity,e.rolesGiven),u=e.writtenBefore>0?`, ${Ed(r,e.writtenBefore)}`:"",l=e.unidentified>0?` (${e.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${e.succeeded} ${o}${s}${i}${d}${a}${c}${u}, ${e.failed+_n(t)} failed${l}${cn(t)}`}function dg(r,e){return(r>0?`, ${r} written by the platform with their opportunity, for its owner`:"")+(e>0?`, ${e} on the team of their opportunity in the target already`:"")}function cg(r,e){if(r===0)return"";let t=e>0?`, ${e} given the source's fields ${e===1?"it":"they"} lacked`:"";return`, ${r} written by the platform with their opportunity, for its contact${t}`}function Aw(r,e,t){e.forEach(({source:n},o)=>{let s=n.Id,i=t[o]?.[Le];typeof s=="string"&&(typeof i=="string"&&i!==""?r.contactSentWith.set(s,i):r.contactSentWith.delete(s))})}function jw(r,e){for(let t of["notKept","unread"])for(let[n,o]of e[t])r[t].set(n,(r[t].get(n)??0)+o)}function ug(r){return[...[...r.notKept].map(([e,t])=>`${t} linked without the source's ${e}: the target's record keeps its own`),...[...r.unread].map(([e,t])=>`${t} linked whose ${e} was not read: the platform writes the record with the opportunity, which a dry run does not write`)].join(", ")}function zr(r,e,t=!0){let n=[...e.values()].filter(d=>d.namedBy===void 0),o=[...e.values()].filter(d=>d.namedBy!==void 0),s=[...e.values()].every(d=>d.target===void 0),i=d=>s?[...new Set(d.map(c=>c.excluded))].sort().join(", "):Rw(d),a=o.length===0?`every record needs ${i(n)}`:n.length===0?`the only records that name its records are held back for ${i(o)}`:`${n.length} of its records need ${i(n)}, and the only records that name the rest are held back for ${i(o)}`;return`${$n(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function Lh(r){let e=new Map(r.readAtItsTurn);for(let[s,i]of r.preread)e.set(s,i);let t=new Map,n=[];for(let[s,{records:i,fieldInfos:a}]of e){let d=a.filter(l=>l.isReference),c=Ke.has(s),u=r.scopeCache?.reachedOf(s);for(let l of i){let f=l.Id,p={row:l,lookups:d};c&&typeof f=="string"&&f!==r.config.rootRecordId&&r.roots?.ids.has(f)!==!0&&u?.has(f)!==!0?t.set(f,p):n.push(p)}}let o=new Set;for(let s=n.pop();s;s=n.pop())for(let i of s.lookups){let a=s.row[i.name];if(typeof a!="string"||a===""||o.has(a))continue;o.add(a);let d=t.get(a);d&&n.push(d)}return o}function Wh(r,e,t,n){let o=r.namedByRowsHeldBack.get(t);if(!(!o||n.has(t)||t===r.config.rootRecordId)&&r.roots?.ids.has(t)!==!0&&!(t===r.standardPricebookId||r.config.writtenBefore.has(t))&&r.scopeCache?.reachedOf(e)?.has(t)!==!0)return o}function Dh(r){for(let[e,t]of Object.entries(Ar))if(t.object===r)return{parent:e,lookup:t.lookup}}function $w(r,e){return e.filter(t=>t.isReference&&Qe(r,t.name,t.nillable)).map(t=>t.name)}function vw(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function gd(r){return r.size===0?"":`, written without a lookup naming a record the target does not hold, which the platform fills (the owner with the user the run writes as): ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}`}function _h(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function md(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the target holds no record of these ids, outside the run`}function wd(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Ew(r){return[...r.lookupsOutsideTheRun].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the target holds no record of these ids, outside the run.`]}))}))}function yd(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the record it names is held back by the run`}function bd(r,e){for(let{lookupsHeldBack:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Iw(r){return[...r.lookupsHeldBack].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the record it names is one the run holds back or leaves aside, never written.`]}))}))}var qh=10;function Rd(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function Uh(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function xw(r,e,t){let n=r.ownersInactive.get(e);for(let{ownerInactive:o}of t)o!==void 0&&(n??={rows:0,owners:new Set},n.rows+=1,n.owners.add(o));n&&r.ownersInactive.set(e,n)}function Pw(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,qh).join(", "),i=o.length-qh;return{objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`OwnerId \u2192 User (${t} record${t===1?"":"s"})`,messages:[`Written with the user the run writes as for owner: the target holds these owners inactive (${i>0?`${s}, and ${i} more`:s}) and that user may not give a record an inactive owner (Update Records with Inactive Owners). Map them to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line) to give the records to that user.`]}]}})}function $s(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function Od(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function Fw(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function ur(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function Nw(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function Gh(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var Cs=class extends Error{constructor(e,t){super(`Internal error: ${e} holds more rows than a clone of the whole org reads whole${t===void 0?"":` (${t})`}, which its gate should have refused before anything was written. The run stopped rather than write part of it: raise sandforge.forge.maxRecordsPerObject, or leave the object out.`),this.name="WholeReadPastBoundError"}},zh="files",kd=200,Cw=Dn,Sd=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function Hh(r,e){let t=r.objects.find(n=>n.objectApiName===e);return t||(t={objectApiName:e,planned:0,plannedBytes:0,copied:0,failed:0},r.objects.push(t)),t}function Mw(r,e){let t=[];for(let n of e){let o=n.Id,s=n.ParentId;if(typeof o!="string"||typeof s!="string"||!r.remapper.wasCreated(s))continue;let i=n.Name,a=typeof i=="string"&&i!==""?i:o,d=n.ContentType,c=n.BodyLength;t.push({objectApiName:"Attachment",sourceId:o,body:{objectApiName:"Attachment",id:o},name:a,bytes:typeof c=="number"&&Number.isFinite(c)?c:0,hosts:[{id:s}],fields:{Name:a,...typeof d=="string"&&d!==""?{ContentType:d}:{},IsPrivate:n.IsPrivate===!0}})}return t}function Kh(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||V(r).includes("INVALID_QUERY_LOCATOR")}function Vh(r){if(Uc(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:V(r).includes("SERVER_UNAVAILABLE")}function Jh(r){return new Promise(e=>setTimeout(e,r))}function Bw(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function vs(r,e){return jo(e)?xr(e)?!0:!r.writtenObjects.has(e):!1}function dn(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function Qh(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function Lw(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(Au)}function lg(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var Yh=200,Xh=200,Zh=/[\u0000-\u001f]/;function Td(r,e){if(!gt(e))return"";let t=[...Ma(r.pricesSwappedSaid),...Ww(r)];return t.length===0?"":`, ${t.join("; ")}`}function Ww(r){let e=[...r.pricesKeptAsRead].filter(([s])=>!r.prices.standsFor.has(s)).map(([,s])=>s);if(e.length===0)return[];let t=s=>{let i=new Map;for(let a of s)i.set(a,(i.get(a)??0)+1);return[...i].map(([a,d])=>`${d} ${a}`).join(", ")},n=e.filter(s=>s.to!==void 0&&s.from!==s.to);if(n.length>0)return[`${t(n.map(({from:s,to:i})=>`${s} \u2192 ${i}`))}: no price in the currency written in the source for the same product and price book, written in it at its amount as read, not converted`];let o=e.filter(s=>s.to===void 0).map(({from:s})=>s);return new Set(o).size<2?[]:[`prices written in the target's one currency, which it did not say: ${t(o)}, at their amount as read, not converted`]}var Dw=/^012000000000000(AAA)?$/;function eg(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var _w=["insert","upsert"],qw=["insert","upsert","update"];function tg(r,e){let t="";for(let n of _w){let o=r.splitting.sizes.report({objectApiName:e,op:n});if(!o||o.to>=o.from)continue;let s=`${n}\0${e}`,i=o.rows-(r.smallerCallsSaid.get(s)??0);i<=0||(r.smallerCallsSaid.set(s,o.rows),t+=`, ${i} sent ${o.to} at a time after the target's automation hit a Salesforce limit`)}return t}function Uw(r,e){let{objectApiName:t}=r,n=r.op==="update"?"lookup updates":"records",o=r.alone+r.notSplit+r.keptWhole,s=r.to<r.from&&r.rows>0?`${t}: ${r.rows} ${n} sent ${r.to} at a time`:`${t}: ${o} ${n} refused for a Salesforce limit`;return{objectApiName:t,stage:"scope",failedCount:0,attemptedCount:r.rows,samples:[{recordSummary:s,messages:[Bu(r),...r.notSplit>0?[Lu(r.notSplit,e,"run")]:[]]}]}}function Gw(r){return qw.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>Uw(t,Wu(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function Es(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=Op(s),a=o===!0&&n===void 0?Sp(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:u},l)=>d===void 0?[]:[{sourceId:d,fingerprint:kp(c,i),owes:u,...n!==void 0?{externalKey:Tp(c,n)}:{},...a[l]!==void 0?{jobKey:a[l]}:{}}]),new Date,n)},answered:e=>r.answered(e),opened:(e,t)=>r.jobOpened(e,t),unattributed:(e,t)=>r.createdUnattributed(e,t)}}function ng(r){let e=new Map;for(let{objectApiName:t,id:n,status:o}of r){let s=e.get(t)??[];s.push({id:n,status:o}),e.set(t,s)}return e}var zw=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],Hw=new Set(["CreatedDate","LastModifiedDate"]),Kw=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function Vw(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Is(r){return typeof r=="string"?Date.parse(r):Number.NaN}var rg="005",Id=class{ids=new Set;issued=0;idFor(e){this.issued++;let n=`${e&&/^[A-Za-z0-9]{3}$/.test(e)?e:"000"}SIM${String(this.issued).padStart(12,"0")}`;return this.ids.add(n),n}has(e){return this.ids.has(e)}};function Jw(r,e,t){return{...r,bulkWriteRecords:void 0,insertRecords:async(n,o,s)=>{let i=await t(n,o);return s.map(()=>({id:e.idFor(i),success:!0,errors:[]}))}}}function Qw(r,e,t){if(!r||!e)return"notRead";let n=r.source.RecordTypeId;return typeof n=="string"&&n!==""&&t.get(n)?.to===null?"decidedDefault":"RecordTypeId"in r.source&&Ia(n)?"masterInSource":"notRead"}function Yw(r,e){return{objectApiName:r,rows:e.rows,why:{...e.why},...e.predicted?{predicted:{...e.predicted}}:{},...e.readBack?{readBack:{...e.readBack,types:e.readBack.types.map(t=>({...t}))}}:{}}}function Ad(r,e){return[r[Pn],e?r[Hn]:"",r[mt]].map(t=>String(t??"")).join("|")}function og(r,e){let t=new Set(e??[]);return r.filter(n=>n.createable&&n.queryable&&!n.isReference&&!t.has(n.name)&&(n.type===void 0||Kw.has(n.type)))}var Xw=200,Zw="the standard price of its product, which it may not go without, changed since the sample";function ey(r){return r?{sample:r}:{}}function ty(r){let e=r.options,t=Object.entries(e.rootWhere??{});return{seed:e.seed??Rn.seed,draw:e.draw??Rn.draw,parents:e.parents??Rn.parents,children:e.children??Rn.children,floor:e.floor??Rn.floor,...e.whole&&e.whole.length>0?{whole:[...e.whole]}:{},...e.window?{window:{...e.window}}:{},...t.length>0?{rootWhere:Object.fromEntries(t)}:{},...e.strata&&e.strata.length>0?{strata:[...e.strata]}:{}}}var lr=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=hh(e)}summarySoFar(){return this.running?this.summaryOf(this.running):void 0}pause(){this.isPaused||(this.isPaused=!0)}resume(){this.isPaused=!1;let e=this.pauseResolve;this.pauseResolve=null,e?.()}abort(){this.isAborted=!0,this.bulkCancel.abort(),this.sampling.abort();let e=this.pauseResolve;this.pauseResolve=null,this.isPaused=!1,e?.()}async bulkTransportOf(e,t){if(e.writeApi!=="auto"||e.dryRun||!this.deps.bulkWriteRecords)return;let n=await this.deps.duplicateRuleObjects?.(t).catch(()=>{}),o=n??sa;return Ye.info(`[forge] writing through the Bulk API: a job per ${Dr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...os,...o].join(", ")}`+(n?"":" (the target did not say which objects its duplicate rules watch)")),this.bulkCancel=new AbortController,this.isAborted&&this.bulkCancel.abort(),{signal:this.bulkCancel.signal,restOnly:new Set([...os,...o]),bulkUnsupported:new Set,manager:new ou(1)}}bulkUpdatesOf(e){let{bulk:t}=e,n=this.deps.bulkWriteRecords;return!t||!n?{}:{bulkUpdate:(o,s)=>n(e.targetOrgId,o,"update",s,{bulkManager:t.manager,signal:t.signal}),restOnly:t.restOnly,bulkUnsupported:t.bulkUnsupported}}async waitIfPaused(){if(this.isAborted)throw new be("Forge execution was aborted by user request. No further batches will be processed.");if(this.isPaused&&(await new Promise(e=>{this.pauseResolve=e}),this.isAborted))throw new be("Forge execution was aborted while paused. No further batches will be processed.")}anonymizeRows(e,t,n,o,s,i){let a=e.config.anonymization;if(!e.anonymize||!a)return n;let d=a.fields[t]??this.detectedPersonalFields(e,a,t,s);if(d.length===0)return n;let c=new Map(s.map(u=>[u.name,u]));return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(u=>{let l=c.get(u);return{name:i[u]??u,type:l?.type??"",...l?.length!==void 0?{length:l.length}:{}}}),methods:a.methods})}detectedPersonalFields(e,t,n,o){let s=e.detectedPersonalFields.get(n);if(s)return s;let i=t.personalFieldsOf?.(o.map(a=>({name:a.name,type:a.type??""})))??[];return e.detectedPersonalFields.set(n,i),i}async fieldExclusionsOfTheSource(e,t,n){let o=Object.keys(e);if(o.length===0)return{exclusions:{},unmatched:[]};let s=t.nodes.map(a=>a.objectApiName),i=new Map;for(let a of o){let d=s.find(c=>c.toLowerCase()===a.toLowerCase())??a;if(!i.has(d))try{let c=await this.deps.describeFields(n,d);i.set(d,c.map(u=>u.name))}catch(c){i.set(d,nr(c)?void 0:null)}}return ns(e,s,a=>i.has(a)?i.get(a):null)}fileCopyUnwired(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return e&&t&&n?null:"This session cannot copy files: it reads no file content or file storage. Nothing was read or written."}fileCopyDeps(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return!e||!t||!n?null:{queryRecords:(o,s)=>this.deps.queryRecords(o,s),readFileBody:e,insertFile:t,insertRecords:this.deps.insertRecords,remainingFileStorageMB:n}}anonymizerForRun(){if(this.deps.anonymize)return this.deps.anonymize;let e=new sp;return t=>e.anonymize(t)}async execute(e,t,n,o,s){this.isAborted=!1,this.isPaused=!1,this.pauseResolve=null;let i=this.deps.requestsSent?.(),a=jl(s);if(a.files){let j=uo(a.anonymization!==void 0,a.files.acceptedAsIs);if(j)throw new jn(j,"FILES_NOT_ACCEPTED");let F=this.fileCopyUnwired();if(F)throw new jn(F,"FILES_NOT_COPYABLE")}let d=await this.chooseTheRoots(a,t,a.dryRun?void 0:a.stream?.store),c=await bs(a.ownerMappings,j=>this.deps.queryRecords(n,j),or);if(c)throw c;let u=new Map,l=await this.recordTypeDecisionsOf(s?.decisions?.recordTypeMappings??[],t,n,u),f=await this.fieldExclusionsOfTheSource(a.fieldExclusions,e,t),p={...a,fieldExclusions:f.exclusions,...l.bySource.size===0?{}:{recordTypeMappings:gl(a.recordTypeMappings,l),recordTypeDecisions:l.bySource}},g=p.dryRun?new Id:null,h=p.excludedObjects,m=await this.withWhatStatusesNeed(es(e,h),t,h),R=p.isScoped?await this.withWhatItsRecordsComeWith(m.graph,t,h):m.graph,b=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(R,t,h),t,h),k=this.deps.recordTypePicklists,O=p.dryRun?void 0:p.stream?.store,w=new Date;O?.beginPart(w),d&&O&&!d.fromTheJournal&&O.nameRoots({objectApiName:d.objectApiName,ids:[...d.ids],sha256:d.sha256,readAt:d.readAt,...d.query?{query:d.query}:{}});let A=Mu(),S=await this.bulkTransportOf(p,n),v={...S?{bulk:S}:{},config:p,sourceOrgId:t,targetOrgId:n,graph:b,onProgress:o,remapper:new qr(O),scopeCache:p.isScoped?new Wf:null,scopedBuilder:p.isScoped?new Sn:null,recordTypeMapper:p.recordTypeMappings?new gs:null,referenceDataMapper:new Ts((j,F)=>this.deps.queryRecords(j,F)),orphanExpander:new As(g?Jw(this.deps,g,async(j,F)=>this.deps.describeObject?this.deps.describeObject(j,F).then(B=>B.keyPrefix,()=>null):null):this.deps),batchWriter:new Ul(this.deps,this.deps.batchStrategy,void 0,A),splitting:A,smallerCallsSaid:new Map,failedObjects:new Set,failedInPart:new Set,heldInTheOrg:new Map,leftAside:new Map,turnsEnded:new Set,notCreatable:new Set,notInTarget:new Set,errors:[],truncatedObjects:new Set,cappedObjects:new Set,fieldExclusionsUnmatched:f.unmatched,pendingFkUpdates:[],owedToRowsWrittenBefore:[],deferredNodes:[],turnsAhead:new Set,waitingFor:new Map,readAgainUnder:new Map,askedForRowsThatNeedThem:new Map,targetHolds:new Map,targetReadsRefused:new Set,inactiveUsers:new Set,writesInactiveOwners:Vf(j=>this.deps.queryRecords(n,j)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:O?{add:j=>O.noteRead(j),has:j=>O.wasRead(j)}:new Set,catalogNodes:[],preread:new Map,readByObject:new Map,notSent:new Map,failedReads:new Set,sourceKeyPrefixes:new Map,cursors:new Map,counted:new Map,tableRecordTypes:new Map,keyPrefixesAsked:new Set,readObjects:new Set(b.nodes.filter(j=>j.included).map(j=>j.objectApiName)),writtenObjects:new Set,sellingModels:b.nodes.some(j=>j.included&&j.objectApiName===jr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...O?{store:O}:{},secondPassInStore:!1,statusesGiven:!1,leftDrafts:new Set,statusChildren:m.added,pastDraft:new Map,heldForExclusions:new Map,namedByRowsHeldBack:new Map,readAtItsTurn:new Map,statusChildrenRead:new Map,anonymize:p.anonymization?this.anonymizerForRun():null,contactPoints:p.keepContactPoints?null:new vf(void 0,{upsertKeys:p.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:Yu(Qu(j=>this.deps.queryRecords(t,j)),async j=>({fields:await this.deps.describeFields(t,j)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new ll(k&&((j,F)=>k(n,j,F))),picklistChanges:new Ko,currencyChanges:new Fo,currencyChangesById:new Map,recordTypesGiven:new Map,recordTypesUnderTheLease:new Map,pricesSwappedSaid:[],pricesKeptAsRead:new Map,prices:{standsFor:new Map,convertedInto:new Map,written:new Map,keys:new Map},readsEverythingFirst:!1,writtenWithoutFields:new Map,leftEmptyByFilter:new Map,contactsOnTheirOwn:new Set,withTheirRecord:new Set,startedAt:w,writtenByThePlatform:new Map,personContactsOutsideTheSample:0,contactSentWith:new Map,leftToThePlatform:new Kc,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,...d?{roots:d}:{},readUnder:new Map,simulated:g,gaps:p.dryRun?new Iu:null,decisionsApplied:new Xi,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:u,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[j,F]of p.writtenBefore)v.remapper.addExisting(j,F);for(let{decision:j,reason:F}of l.unresolved)v.errors.push({objectApiName:j.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${j.from} \u2192 ${j.to??"the default"})`,messages:[`The decision was not applied: ${F}.`]}]});this.running=v;try{return await this.runPasses(v)}catch(j){throw this.endBeforeTheEmailsThatWaited(v,v.emailsAfterTheirTask.length+v.emailsLeftForTheirTask,j instanceof be),this.saySyncedQuotesLeft(v),await this.readWrittenBetween(v),this.reportDraftsLeft(v),O?.settleReads(),ip(j,this.summaryOf(v)),j}finally{this.running===v&&(this.running=null),O?.settleReads(),O?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return Zi([],[]);let s=this.deps.describeObject,i=async(c,u)=>s?s(c,u).then(l=>this.namedRecordTypes(o,c,l.recordTypes),()=>[]):[],a=[...new Set(e.map(c=>c.object))],d=await Promise.all(a.map(async c=>({objectApiName:c,source:await i(t,c),target:await i(n,c)})));return Zi(e,d)}async namedRecordTypes(e,t,n){if(!n.some(s=>!s.master))return n;let o=e.get(t);return o||(o=this.deps.queryRecords(t,Co).then(s=>Mo(s),()=>[]),e.set(t,o)),Bo(n,await o)}async targetObjectInfoOf(e,t){let n=await this.objectInfoOf(e.targetOrgId,t);return!n||!(e.gaps!==null||n.recordTypes.some(s=>!s.available&&!s.master)||e.config.decisions.namesARecordTypeBare(t))?n:{...n,recordTypes:await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,n.recordTypes)}}async withMaskedLeftOut(e,t,n,o,s){if(o.length===0)return n;let i=await e.maskedSourceFields(t).catch(()=>[]),a=i.filter(d=>!n.has(d)&&s(d)&&o.some(c=>c[d]!==null&&c[d]!==void 0));return this.noteEncryptedLeftOut(e,t,a),i.length>0?new Set([...n,...i]):n}noteEncryptedLeftOut(e,t,n){if(n.length===0)return;let o=e.encryptedFieldsLeftOut.get(t)??new Set;for(let s of n)o.add(s);e.encryptedFieldsLeftOut.set(t,o)}withoutFileContent(e,t,n,o){let s=n.filter(i=>xn(i)&&i.createable);if(o&&s.length>0){let i=e.fileContentFieldsLeftOut.get(t)??new Set;for(let a of s)i.add(a.name);e.fileContentFieldsLeftOut.set(t,i)}return n.filter(i=>!xn(i))}async readWrittenBetween(e){if(e.config.dryRun||e.writtenBetween)return;if(e.config.stream?.everything===!0&&e.store){await this.readWrittenBetweenByObject(e,e.store);return}let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let{objectApiName:o,sourceIds:s}of e.remapper.createdByObject()){let i=s.flatMap(d=>{let c=e.remapper.get(d);return c?[c]:[]});if(i.length===0)continue;let a=await this.auditDatesCopied(e,o);for(let d of kn(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let u of c){let l=Is(u.SystemModstamp),f=h=>{let m=a?Number.NaN:Is(u[h]);return Number.isFinite(m)?m:l},p=f("CreatedDate"),g=f("LastModifiedDate");Number.isFinite(p)&&(t=Math.min(t,p)),Number.isFinite(g)&&(n=Math.max(n,g))}}}Number.isFinite(t)&&Number.isFinite(n)&&(e.writtenBetween={first:new Date(t).toISOString(),last:new Date(Math.max(t,n)).toISOString()})}async readWrittenBetweenByObject(e,t){let n=Vw(e.startedAt.getTime()-Ka),o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=!1;for(let{objectApiName:a,created:d}of t.countsByObject()){if(d===0)continue;let c=Be(a),l=[...await this.auditDatesCopied(e,a)?[]:[`SELECT MIN(CreatedDate) f, MAX(SystemModstamp) l FROM ${c} WHERE CreatedDate >= ${n}`],`SELECT MIN(SystemModstamp) f, MAX(SystemModstamp) l FROM ${c} WHERE SystemModstamp >= ${n}`],f=!1;for(let p of l)try{let[g]=await this.deps.queryRecords(e.targetOrgId,p),h=Is(g?.f),m=Is(g?.l);Number.isFinite(h)&&(o=Math.min(o,h)),Number.isFinite(m)&&(s=Math.max(s,m)),f=!0;break}catch{}f||(i=!0)}i&&(o=Math.min(o,e.startedAt.getTime()),s=Math.max(s,Date.now()+Ka)),Number.isFinite(o)&&Number.isFinite(s)&&(e.writtenBetween={first:new Date(o).toISOString(),last:new Date(Math.max(o,s)).toISOString()})}async writtenDatesOf(e,t,n){let o=Be(t);for(let s of zw)try{return await this.deps.queryRecords(e,`SELECT Id, ${s.join(", ")} FROM ${o} WHERE Id IN (${n})`)}catch{}}async auditDatesCopied(e,t){let n=o=>o.some(s=>Hw.has(s.name)&&s.createable);try{let[o,s]=await Promise.all([this.deps.describeFields(e.sourceOrgId,t),this.deps.describeFields(e.targetOrgId,t)]);return n(o)&&n(s)}catch{return!0}}async runPasses(e){let{config:t,graph:n,sourceOrgId:o,targetOrgId:s,onProgress:i}=e;e.scopeCache&&e.roots&&t.rootObjectApiName?e.scopeCache.add(t.rootObjectApiName,e.roots.ids):e.scopeCache&&t.rootRecordId&&t.rootObjectApiName&&e.scopeCache.add(t.rootObjectApiName,[t.rootRecordId]);let a=xl(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&vw(t);e.readsEverythingFirst=c,e.emailsInTwoPasses=d&&t.stream?.everything===!0,e.secondPassInStore=e.store!==void 0&&!c,c&&e.store&&e.pendingFkUpdates.push(...e.store.owedLeftByEarlierParts());let u=c?a:await this.singlePassOrder(e);if(c&&e.scopeCache)for(let O of u)O.included&&e.turnsAhead.add(O.objectApiName);if(n.nodes.some(O=>gt(O.objectApiName)))try{let[O,w]=await Promise.all([this.deps.queryRecords(o,mi),this.deps.queryRecords(s,mi)]),A=O[0]?.Id,S=w[0]?.Id;typeof A=="string"&&typeof S=="string"&&(e.standardPricebookId=A,e.remapper.addExisting(A,S),e.scopeCache?.add(Ut,[A]),e.readObjects.add(Ut),n.nodes.some(v=>v.included&&v.objectApiName===Ut)||e.scopeCache?.addRead(Ut,[]))}catch(O){e.errors.push({objectApiName:et,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[V(O)]}]})}let l=new Map,f=this.deps.isObjectCreatable;if(f){let O=[...new Set(a.filter(w=>w.included&&!t.referenceDataObjects.has(w.objectApiName)).map(w=>w.objectApiName))];for(let w=0;w<O.length&&!this.isAborted;w+=6){let A=O.slice(w,w+6),S=await Promise.allSettled(A.map(async v=>f(s,v)));A.forEach((v,j)=>l.set(v,S[j]))}}for(let[O,w]of l)w.status!=="rejected"||!nr(w.reason)||(e.notInTarget.add(O),e.readObjects.delete(O),e.turnsAhead.delete(O));for(let O of n.nodes){let w=l.get(O.objectApiName);!O.included||w?.status==="fulfilled"&&!w.value||e.notInTarget.has(O.objectApiName)||e.writtenObjects.add(O.objectApiName)}d&&await this.planTheSample(e,u),d&&t.beforeWrite&&await this.countBeforeWrite(e,u);for(let O of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!O.included){e.skippedCount++,i({objectName:O.objectApiName,status:"skipped",progress:100,message:`Skipped ${O.objectApiName} (${sw(O)})`});continue}if(e.notInTarget.has(O.objectApiName)){e.scopeCache&&O.objectApiName!==t.rootObjectApiName?(e.notInTargetPutOff??=[]).push(O):this.reportNotInTarget(O,e),await this.endTurn(O.objectApiName,e);continue}if(await this.skipForFailedParent(O,e)){await this.endTurn(O.objectApiName,e);continue}let w=l.get(O.objectApiName);if(w)if(w.status==="fulfilled")w.value||e.notCreatable.add(O.objectApiName);else{let A=w.reason;e.errors.push({objectApiName:O.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${A instanceof Error?A.message:String(A)}`]}]})}c?await this.readInTurn(O,e):d&&this.streamsNode(O,e)?(await this.streamNode(O,e),e.turnsEnded.add(O.objectApiName),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(O,e,!1,!0)&&await this.writeNode(O,e),e.turnsEnded.add(O.objectApiName),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e),O.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,O.objectApiName))}let p=Pl(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),g=p.map(O=>Ke.has(O.objectApiName)).lastIndexOf(!0);for(let[O,w]of p.entries()){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(w,e)||(c?(e.scopeCache&&Ke.has(w.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,w.objectApiName)),await this.readNode(w,e,!1,!1),await this.readUnderWhatWaited(w.objectApiName,e,g>=0&&O>g?"after the catalog":"before the catalog")):await this.readNode(w,e,!1,!0)&&(await this.writeNode(w,e),e.turnsEnded.add(w.objectApiName),this.releaseRows(e,w.objectApiName)))}await this.readCatalogAgain(e,g<0?[]:p.slice(g+1)),await this.reportNotInTargetOfTheScope(e);for(let O of[...e.preread.keys()])this.releaseRows(e,O,!0);if(c){do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e));if(await this.readParentsOutsideTheGraph(e))do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e))}let h=this.deps.requestsSent?.();e.roots&&h!==void 0&&e.requestsBefore!==void 0&&(e.readRequests=h-e.requestsBefore);let m=t.stream?.everything===!0,R=t.files&&!m?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let O=await this.pricesTheGateCounts(e),w=jh(e).cappedObjects,A=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([j,F])=>this.toWriteAtTheGate(e,j,F,gt(j)?O:0))))),S=t.dryRun?0:await this.readBackRequests(e,A),v=await t.beforeWrite({objects:A,...w?{capped:w}:{},...S>0?{readBack:S}:{},...e.roots?{roots:Gm(e.roots)}:{},dryRun:t.dryRun});await this.afterTheGate(e,v,A)}if(c)for(let O of this.writeOrderOf(e)){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let w=e.preread.get(O.objectApiName);if(w&&!await this.skipForFailedParent(O,e,w.fieldInfos,w.records)&&(await this.writeNode(O,e),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e),O.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let A=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),S=[],v=await _a({pendingFkUpdates:A,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:S,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(j,F,B)=>this.noteLeftEmptyByFilter(e,j,F,B),...this.secondPassOfTheSample(e)});v&&e.errors.push(v),e.pendingFkUpdates.push(...S)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let b=e.secondPassInStore?await this.secondPassFromTheJournal(e):await _a({pendingFkUpdates:this.sayLookupsOutsideTheClone(e,e.pendingFkUpdates),remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!t.dryRun,onProgress:i,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(O,w,A)=>this.noteLeftEmptyByFilter(e,O,w,A),...this.secondPassOfTheSample(e)});if(b&&e.errors.push(b),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");R.length>0&&!t.dryRun?await this.writeFiles(e,R):m&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let k=e.orphanExpander.buildErrorReport();return k&&e.errors.push(k),this.saySyncedQuotesLeft(e),await this.readWrittenBetween(e),await this.readBackRecordTypes(e),this.summaryOf(e)}async afterTheGate(e,t,n){let o=t?t.splitAllowance:void 0;o!==void 0&&e.splitting.allowance.limitTo(o);let s=t?t.lease:void 0;s&&(e.lease=s,s.assigned>0&&await this.readAgainUnderTheLease(e,n))}async readAgainUnderTheLease(e,t){let n=this.deps.describeObjectAgain;if(!n)return;let o=await Promise.all(t.map(async({objectApiName:s,rows:i,counted:a})=>{if(!await this.mayGoWithoutRecordType(e,s,i,a))return[];try{let d=await n(e.targetOrgId,s);return[[s,d.recordTypes]]}catch{return[]}}));for(let[s,i]of o.flat())e.recordTypesUnderTheLease.set(s,i)}async mayGoWithoutRecordType(e,t,n,o){if(n.length===0&&(o?.rows??0)===0||!(await this.objectInfoOf(e.targetOrgId,t))?.recordTypes.some(d=>!d.master))return!1;if(n.length===0)return!0;let{config:i}=e;return!(e.preread.get(t)?.createableSet.has("RecordTypeId")===!0&&!(i.fieldExclusions[t]??[]).includes("RecordTypeId")&&i.fieldMappings[t]?.RecordTypeId===void 0)||n.some(d=>{let c=d.RecordTypeId;return typeof c!="string"||Ia(c)||i.recordTypeDecisions.get(c)?.to===null})}async readBackRequests(e,t){let o=(await Promise.all(t.map(({objectApiName:i,rows:a,counted:d})=>this.mayGoWithoutRecordType(e,i,a,d)))).filter(Boolean).length,s=e.recordTypeRows.has(e.targetOrgId)&&!e.config.dryRun;return o>0&&!s?o+1:o}async giveTheLeaseBack(e){let t=e.lease;if(t){e.lease=void 0;try{await t.giveBack()}catch(n){Ye.warn(`[forge] the mute's lease was not given back as the writes ended: ${V(n)}`)}}}async readBackRecordTypes(e){e.simulated||await Promise.all([...e.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await this.deps.queryRecords(e.targetOrgId,Nf(t,n.ids));n.readBack=Cf(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:V(o)}}}))}async recordTypeCounter(e,t,n,o){let s=e.recordTypesUnderTheLease.get(t)??n?.recordTypes??[];if(!s.some(c=>!c.master))return;let i=await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,s),a=Pf(xf(i)),d=e.config.recordTypeDecisions;return(c,u)=>{let l=e.recordTypesGiven.get(t);l||(l={rows:0,why:{},...a?{predicted:a}:{},types:i,ids:[]},e.recordTypesGiven.set(t,l));let f=Qw(c,o,d);l.rows++,l.why[f]=(l.why[f]??0)+1,u!==void 0&&l.ids.length<Ff&&l.ids.push(u)}}streamsTheRun(e){let{config:t,graph:n}=e;return t.stream===void 0||t.isScoped?!1:t.stream.everything===!0?!0:t.files===void 0&&!n.nodes.some(o=>o.included&&o.objectApiName===$e)}async keysOfTheTable(e,t,n){let{config:o,sourceOrgId:s}=e;if(o.upsertMode!=="auto"||!this.deps.upsertRecords||e.simulated)return;let i=t.objectApiName,a={unique:new Set,sent:new Set};try{n.described??=await this.deps.describeFields(s,i);let d=new Set(o.fieldExclusions[i]??[]),c=o.fieldMappings[i]??{},u=n.described.filter(R=>R.externalId===!0&&R.createable&&R.queryable&&!d.has(R.name)&&c[R.name]===void 0);if(u.length===0)return a;let l=n.described.find(R=>R.name==="Id"),f=on({node:t,edges:e.graph.edges,fieldInfos:[...l?[l]:[],...u],scopedBuilder:null,scopeCache:null,extraWhere:this.filterOf(e,i),maxRecordsPerObject:this.readBound(e,t),inIdOrder:{}});if(f.kind!=="query"||f.statements.length!==1)return a;let p=f.limit??1/0,g=new Map(u.map(R=>[R.name,new Set])),h=0,m=Vt(this.deps,s,f.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let R of m){for(let b of R){if(h>=p)break;h++;for(let[k,O]of g){let w=b[k];typeof w!="string"||w.length===0||O.has(w)?g.delete(k):O.add(w)}}if(h>=p||g.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(g.keys()),sent:a.sent}}catch(d){return Ye.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+V(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!Ke.has(n)&&!gt(n)&&(n!==ut||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(Ke.has(t)||gt(t)))return;let o=e.preread.get(t);!o||o.records.length===0||e.preread.set(t,{...o,records:[]})}readsArchived(e,t){return e.config.stream?.everything===!0&&tf.has(t)}filterOf(e,t){let n=e.config.objectSoqlFilters?.[t];return this.readsArchived(e,t)?n?`(${n}) AND IsDeleted = false`:"IsDeleted = false":n}readOptionsOf(e,t){return this.readsArchived(e,t)?{all:!0}:void 0}async readWholeOf(e,t,n,o){let s=this.readOptionsOf(e,t);if(!s)return this.deps.queryRecords(e.sourceOrgId,n,o);let i=[],a=Vt(this.deps,e.sourceOrgId,n,void 0,void 0,s);for await(let d of a)for(let c of d)i.push(c);return i}readBound(e,t){if(e.sample?.drawn.has(t.objectApiName))return;let n=e.config.maxRecordsPerObject,o=n!==void 0&&n>0?Math.floor(n):void 0,s=this.streamsNode(t,e)?e.config.stream?.ceiling:void 0;return o===void 0?s:s===void 0?o:Math.min(o,s)}async chooseTheRoots(e,t,n){let o=e.roots,s=n?.resumes===!0,i=s?n?.roots:void 0;if(!o){if(i)throw Pe.of(Lr(i.objectApiName,"otherQuery"));return}let{objectApiName:a,cap:d}=o,c={cap:d,readTotal:o.readTotal,readingBound:ml(o.sourceRequestsLeft),...o.sourceRequestsLeft!==void 0?{sourceRequestsLeft:o.sourceRequestsLeft}:{}};if(s){if(!i)throw Pe.of(Sl(a));if(i.objectApiName.toLowerCase()!==a.toLowerCase())throw Pe.of(Lr(a,"otherQuery"));if(ta(i.ids)!==i.sha256)throw Pe.of(Lr(a,"changed"));return{objectApiName:a,from:"plan",...i.query?{query:i.query}:{},ids:new Set(i.ids),sha256:i.sha256,readAt:i.readAt,fromTheJournal:!0,...c}}let u,l=o.plan;if(l){let m=kl(l,{sourceOrgId:t,objectApiName:a,...o.query?{query:o.query}:{},...o.ids?{ids:o.ids}:{}});if(m)throw Pe.of(Lr(a,m));let R=o.planOfTheRunRetried===!0;if(Ip(l,new Date)<vp||o.query===void 0||R)return{objectApiName:a,from:"plan",...l.query?{query:l.query}:{},ids:new Set(l.ids),sha256:l.sha256,readAt:l.readAt,fromTheJournal:!1,...R?{ofTheRunRetried:!0}:{},...c};u={roots:l.ids.length,readAt:l.readAt}}let f,p,g;if(o.ids!==void 0){let m=o.ids.filter(R=>!Ol(R));if(m.length>0)throw Pe.of({code:"ROOTS_QUERY_REFUSED",message:`${JSON.stringify(m[0]?.slice(0,40))} is not the id of a record: name each ${a} record by its 15- or 18-character id. Nothing was read or written.`,roots:{objectApiName:a}});if(f=ea(o.ids),p="records",f.length>d)throw Pe.of(Br(a,d,p))}else if(o.query!==void 0){let m=yl(o.query);if(m)throw Pe.of(Yo(m,a));let R=o.chosen,b=R?R.ids.map(k=>({Id:k})):await this.deps.queryRecords(t,Qo(a,o.query,e.objectSoqlFilters?.[a],d));if(f=ea(b.flatMap(k=>typeof k.Id=="string"?[k.Id]:[])),p="query",g=R?.readAt,f.length>d)throw Pe.of(Br(a,d,p,o.query))}else throw new Error(`Internal error: the roots of ${a} were asked with neither a query nor ids.`);if(f.length===0)throw Pe.of(Xo(a,o.query,d));let h=g??new Date().toISOString();return o.keepAt!==void 0&&await Ep(o.keepAt,{sourceOrgId:t,fingerprint:o.fingerprint??"",objectApiName:a,...o.query?{query:o.query}:{},from:p==="records"?"records":"query",readAt:h,ids:f}),{objectApiName:a,from:p,...o.query?{query:o.query}:{},ids:new Set(f),sha256:ta(f),readAt:h,fromTheJournal:!1,...u?{readAgain:u}:{},...c}}holdTheRootsReading(e,t,n){let o=e.roots,s=this.deps.requestsSent?.();if(!o||s===void 0||e.requestsBefore===void 0)return;let i=s-e.requestsBefore;if(!(i+n<=o.readingBound))throw Pe.of(Al({roots:o.ids.size,bound:o.readingBound,sent:i,next:n,objectApiName:t,sourceRequestsLeft:o.sourceRequestsLeft}))}holdTheRootsRows(e,t){let n=e.roots;if(!n)return;let o=0;for(let i of e.readByObject.values())o+=i;if(o<=n.readTotal)return;let s=[...e.readByObject].filter(([i])=>i!==t).map(([i,a])=>({objectApiName:i,rows:a}));throw s.push({objectApiName:t,rows:e.readByObject.get(t)??0}),Pe.of(Tl(n.ids.size,n.readTotal,s))}async planTheSample(e,t){let{config:n,store:o}=e,s=n.stream?.everything===!0?n.stream.sample:void 0,i=o?.samplePlan;if(!s){if(i)throw new ir("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+or);return}let a;if(i)try{a=await sr.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof Os?new ir("SAMPLE_PLAN_GONE",`The plan of the sample the run resumes is ${d.refusal==="gone"?"no longer on this machine":"no longer as it was drawn"}: it cannot go on with the same records. ${or} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new ir("SAMPLE_PLAN_MISMATCH",`The run this one resumes copied every record of the whole org, not a sample: resume it as it was set up. ${or}`);a=s.plan??await this.drawThePlan(e,t,s)}o&&!i&&o.nameSamplePlan({dir:a.dir,sha256:a.sha256}),e.sample=await this.runSampleOf(e,a)}async drawThePlan(e,t,n){let{config:o,sourceOrgId:s}=e,i=ty(n),a=t.filter(w=>w.included&&(e.writtenObjects.has(w.objectApiName)||o.referenceDataObjects.has(w.objectApiName))),d=new Map;for(let w of a)d.set(w.objectApiName,await this.deps.describeFields(s,w.objectApiName));let c=(w,A)=>A.nillable===!1&&e.graph.edges.some(S=>S.type==="master-detail"&&S.targetObject===w&&(A.referenceTo??[]).includes(S.sourceObject)),u=[],l=new Map;for(let w of a){let A=w.objectApiName,S=new Set(o.fieldExclusions[A]??[]),v=(d.get(A)??[]).filter(j=>j.isReference&&!S.has(j.name)).map(j=>({name:j.name,referenceTo:j.referenceTo??[],isMasterDetail:c(A,j),...j.nillable!==void 0?{nillable:j.nillable}:{},createable:j.createable,...j.updateable!==void 0?{updateable:j.updateable}:{}}));if(u.push({objectApiName:A,rows:w.recordCount,keyPrefix:(await this.objectInfoOf(s,A))?.keyPrefix??e.sourceKeyPrefixes.get(A)??null,fields:v}),this.streamsNode(w,e)&&!o.referenceDataObjects.has(A)){let j=await this.recordTypesOfTable(e,w);j&&j.closedInSource.length>0&&l.set(A,{closed:new Set(j.closedInSource.map(it)),lacking:new Set(j.lackingInSource.map(it))})}}let f=await n.budget(),p=e.standardPricebookId&&a.some(w=>gt(w.objectApiName))?await this.runCurrencies(e):void 0,g=p&&this.priceCurrencyWrittenIn(e,p.target),h=new Map;if(a.some(w=>w.objectApiName===$e)){let w=await this.averageEmailBytes(e,d.get($e)??[]);w!==void 0&&h.set($e,w)}let m=g?w=>p.target.active.has(w)?void 0:g(w):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let R=Date.now(),b;try{b=await yp({source:{pages:(w,A)=>Vt(this.deps,s,w,void 0,void 0,A),count:async(w,A)=>{let S=this.deps.countRecords;if(S)return A?S(s,w,A):S(s,w);let v=0,j=w.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let F of Vt(this.deps,s,j,void 0,void 0,A))v+=F.length;return v}},objects:u,order:a.map(w=>w.objectApiName),excluded:new Map([...o.excludedObjects].map(w=>[w,null])),referenceData:o.referenceDataObjects,fieldsOf:w=>d.get(w)?.filter(A=>A.queryable).map(A=>({name:A.name,...A.type!==void 0?{type:A.type}:{},...A.groupable!==void 0?{groupable:A.groupable}:{},...A.sortable!==void 0?{sortable:A.sortable}:{},...A.aggregatable!==void 0?{aggregatable:A.aggregatable}:{}})),filterOf:w=>o.objectSoqlFilters?.[w],options:i,budget:f,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(w,A)=>{let S=l.get(w),v=it(A);return S?.lacking.has(v)?"recordTypeNotInTarget":S?.closed.has(v)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...m?{priceCurrencyWrittenIn:m}:{},...h.size>0?{averageBytes:h}:{},now:R,labelsOf:async(w,A)=>{if(A.toLowerCase()!=="recordtypeid")return;let S=(await this.objectInfoOf(s,w))?.recordTypes??[],v=new Map(S.map(j=>[it(j.recordTypeId),j.developerName]));return j=>typeof j=="string"?v.get(it(j)):void 0},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(w){throw w instanceof gp?new ir("SAMPLE_TOO_LARGE",`${w.message} Or draw among fewer roots: a window of dates (--fit-window) or a filter on the roots of the large objects (--fit-where).`):w instanceof mp||this.isAborted?new be("Forge execution was aborted by user request. Remaining objects were not processed."):w}let{cut:k}=b;if(k.kind==="cannotFit"){let w=k.heaviest.map(B=>`${B.objectApiName} (${B.rows} records${B.whole?", copied whole":""})`).join(", "),A=b.strataFloors,S=k.noRoot?"the objects copied whole and the first root drawn with the records it brings":A?`the objects copied whole and the roots kept of each object and of each value of its strata (${A.roots} roots for the floors of ${A.values} values)`:"the objects copied whole and the roots kept of each object",v=k.noRoot?"Leave objects out (--exclude-object)":A?"Keep no root of each object and value (--fit-floor 0), stratify fewer objects (--fit-strata), leave objects out (--exclude-object)":"Keep no root of each object (--fit-floor 0), leave objects out (--exclude-object)",j=nw[k.limitedBy],F=k.limitedBy==="storage"||k.limitedBy==="within";throw new jd(`No sample of the whole org fits: ${S} take ${k.rows} records, ${(k.storageBytes/1048576).toFixed(1)} MB, ${j.past}; the heaviest are ${w}. ${or} ${v}${j.more}.`,k.heaviest,{limitedBy:k.limitedBy,...F?{needMB:Th(k.storageBytes,"up"),budgetMB:Th(k.limitedBy==="storage"&&f.storageBytes!==void 0?f.storageBytes:f.budget.bytes,"down")}:{},heaviest:k.heaviest.map(B=>B.objectApiName)})}let O=Rp({...b,cut:k},i,f.budget);return up(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:O,...b.newestByIds.length>0?{newestByIds:b.newestByIds}:{},...b.oldestByIds.length>0?{oldestByIds:b.oldestByIds}:{},ids:[...k.ids].map(([w,A])=>({objectApiName:w,ids:A})),counts:{personAccounts:Object.fromEntries(k.personAccounts),byThePlatform:k.byThePlatform.map(w=>({...w}))}})}async averageEmailBytes(e,t){let n=og(t,e.config.fieldExclusions[$e]);if(n.length===0)return;let o=this.filterOf(e,$e);try{let s=await this.readWholeOf(e,$e,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${$e}${o?` WHERE ${o}`:""} LIMIT ${Xw}`);if(s.length===0)return;let i=0;for(let a of s)for(let[d,c]of Object.entries(a))d!=="Id"&&typeof c=="string"&&(i+=Buffer.byteLength(c,"utf8"));return Math.ceil(i/s.length)}catch(s){Ye.warn("[forge] the size of the emails could not be read before the sample was drawn: "+V(s));return}}async runSampleOf(e,t){let{manifest:n}=t,o=new Set(n.sample.whole.map(d=>d.objectApiName)),s=new Set([...e.writtenObjects].filter(d=>!o.has(d)&&!e.config.referenceDataObjects.has(d))),i=new Map,a=new Map;for(let d of s){let c=new Set;for await(let f of t.ids(d))for(let p of f)c.add(it(p));i.set(d,c);let l=c.values().next().value?.slice(0,3)??(await this.objectInfoOf(e.sourceOrgId,d))?.keyPrefix??e.sourceKeyPrefixes.get(d);l&&a.set(d,l)}return{plan:t,report:{...n.sample,plan:t.place},drawn:s,ids:i,prefixes:a,counts:n.counts??{personAccounts:{},byThePlatform:[]},gone:new Map,changed:new Map,leftEmpty:new Map,reads:new Map,withoutStandard:new Set}}drawnObjectNamed(e,t,n){let o=t.filter(s=>e.drawn.has(s));if(o.length!==0)return t.length===1?o[0]:o.find(s=>{let i=e.prefixes.get(s);return i!==void 0&&n.startsWith(i)})}inThePlan(e,t,n){return e.ids.get(t)?.has(it(n))===!0}outsideTheSample(e,t,n){let o=e.sample;if(!o)return!1;let s=this.drawnObjectNamed(o,t,n);return s===void 0?!1:!this.inThePlan(o,s,n)||o.gone.get(s)?.has(it(n))===!0}secondPassOfTheSample(e){let t=e.sample;return t?{outsideTheSample:n=>{let o=n.sourceRefId,s=[...t.drawn].find(i=>{let a=t.prefixes.get(i);return a!==void 0&&o.startsWith(a)});return s!==void 0&&this.outsideTheSample(e,[s],o)},onLeftOutsideTheSample:(n,o)=>this.noteLeftOutsideTheSample(e,n,o)}:{}}noteLeftOutsideTheSample(e,t,n){let o=e.sample;if(!o)return;let s=o.leftEmpty.get(t)??new Map;s.set(n,(s.get(n)??0)+1),o.leftEmpty.set(t,s)}async countToWriteOfThePlan(e,t,n){let o=t.objectApiName,s=e.config.stream?.resumeAfter.get(o),i=n.ids.get(o)??new Set,a=s&&Ft.test(s.lastId)?s.lastId:void 0,d=O=>a===void 0||Mr(O,a)>0,c=0;if(!s?.done)for(let O of i)d(O)&&c++;let u=Math.min(c,await this.writtenBeforeOf(e,t,s)),l=e.standardPricebookId,f=o===Ut&&l&&i.has(it(l))&&d(l)&&!e.config.writtenBefore.has(l)?Math.min(1,c-u):0,p=Math.max(0,c-u-f),g=Math.min(p,n.counts.personAccounts[o]??0),h=0;o===ce&&g>0&&await this.personAccountsInTarget(e)===!0&&(h=g);let m=n.counts.byThePlatform.find(O=>O.objectApiName===o);m&&(h+=Math.min(p-h,m.inPlan)),p-=h;let R=O=>n.report.dropped.filter(w=>w.objectApiName===o&&w.reason===O).reduce((w,A)=>w+A.rows,0),b={...u>0?{writtenBefore:u}:{},...f>0?{linkedToTarget:f}:{},...h>0?{byThePlatform:h}:{},...R("noParentInSource")>0?{noParentInSource:R("noParentInSource")}:{},...R("outsideFilter")>0?{outsideFilter:R("outsideFilter")}:{}},k=o===ce&&h>0?0:g;return{read:c,counted:{rows:p,...k>0?{personAccounts:Math.min(k,p)}:{}},...Object.keys(b).length>0?{leftOut:b}:{}}}async personContactsBeyondThePlan(e,t){if(!e.sample?.drawn.has(ce))return;let n=t.find(i=>i.objectApiName===ce),o=t.find(i=>i.objectApiName===Se)?.counted.personAccounts??0;if(!n||o<=0||await this.personAccountsInTarget(e)!==!0)return;let s=n.leftOut?.byThePlatform??0;o<=s||(n.leftOut={...n.leftOut,byThePlatform:o})}async readOfThePlan(e,t,n,o){let s=n.objectApiName,i=t.reads.get(s);if(i)return i;let a=await this.deps.describeFields(e.sourceOrgId,s),d=wp({objectApiName:s,columns:zt(a.filter(c=>!xn(c)),e.config.fieldExclusions[s]),sourceRows:n.recordCount,planRows:o});return t.reads.set(s,d),d}planRowsAfter(e,t,n){let o=e.ids.get(t);if(!o)return 0;if(n===void 0)return o.size;let s=0;for(let i of o)Mr(i,n)>0&&s++;return s}async*pagesOfThePlanByIds(e,t,n,o,s,i=!1){let a=Be(n),d=this.filterOf(e,a),c=Math.max(1,uu(a,du(o),d?`(${d})`:void 0));for await(let u of t.plan.ids(a,{...s!==void 0?{after:s}:{},size:c})){if(this.isAborted)return;let l=u.filter(g=>Ft.test(g));if(l.length===0)continue;let f=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${l.map(g=>`'${g}'`).join(", ")})`,p=await this.readWholeOf(e,a,f);if(p.sort((g,h)=>Mr(String(g.Id),String(h.Id))),i){let g=new Set(p.map(m=>it(String(m.Id)))),h=t.gone.get(a)??new Set;for(let m of l)g.has(it(m))||h.add(it(m));h.size>0&&t.gone.set(a,h)}yield p}}async rowsOfThePlan(e,t,n,o,s,i=!1){let a=[];for await(let d of this.pagesOfThePlanByIds(e,t,n,o,s,i))for(let c of d)a.push(c);return a}async*pagesOfThePlan(e,t,n,o,s){let i=n.objectApiName,a=o.lastId??o.resumeAfter,d=await this.readOfThePlan(e,t,n,this.planRowsAfter(t,i,a)),c=/^SELECT (.+?) FROM /.exec(s)?.[1]?.split(", ")??["Id"],u=d.by==="ids"?this.pagesOfThePlanByIds(e,t,i,c,a,!0):this.cursorKeptToThePlan(e,t,i,s,a);yield*js(u,e.config.stream?.writeWindow??e.config.stream?.pageSize)}async*cursorKeptToThePlan(e,t,n,o,s){let i=t.ids.get(n)??new Set,a=new Set,d=Vt(this.deps,e.sourceOrgId,o,void 0,()=>e.truncatedObjects.add(n),this.readOptionsOf(e,n));try{for await(let u of d){let l=u.filter(f=>{let p=it(String(f.Id));return i.has(p)?(a.add(p),!0):!1});l.length>0&&(yield l)}}finally{await d.return(void 0)}let c=t.gone.get(n)??new Set;for(let u of i)!a.has(u)&&(s===void 0||Mr(u,s)>0)&&c.add(u);c.size>0&&t.gone.set(n,c)}sampleResultOf(e){let t=e.sample;if(!t||e.simulated)return;let n=new Map(e.remapper.countsByObject().map(i=>[i.objectApiName,i])),o=t.report,s=bp(o.roots);return{seed:o.seed,draw:o.draw,share:o.share,sha256:o.plan.sha256,drawnAt:o.plan.drawnAt,drawnBy:o.plan.drawnBy,...s?{roots:s}:{},objects:o.objects.map(i=>{let a=n.get(i.objectApiName),d=a?a.created+(a.linked??0):0,c=e.store?.earlierRecordsOf(i.objectApiName)??0;return{...i,written:Math.min(i.kept,d+c),goneSinceTheSample:t.gone.get(i.objectApiName)?.size??0,changedSinceTheSample:t.changed.get(i.objectApiName)??0}}),...t.leftEmpty.size>0?{leftEmpty:[...t.leftEmpty].flatMap(([i,a])=>[...a].map(([d,c])=>({objectApiName:i,field:d,rows:c})))}:{}}}async countBeforeWrite(e,t){let{config:n}=e,o=n.beforeWrite;if(!o)return;let s=n.stream?.everything===!0,i=[],a=[],d=new Set,c=[],u=[];for(let A of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let S=A.objectApiName;if(!A.included||!e.writtenObjects.has(S))continue;let v=s&&!this.streamsNode(A,e);if(n.referenceDataObjects.has(S)){v&&c.push({objectApiName:S,rows:await this.rowsOf(e,A)});continue}let{read:j,counted:F,leftOut:B,capped:E,partial:_}=e.sample?.drawn.has(S)?await this.countToWriteOfThePlan(e,A,e.sample):await this.countToWrite(e,A);e.counted.set(S,j),E&&a.push(S),_&&d.add(S),v&&!e.sample?.drawn.has(S)&&c.push({objectApiName:S,rows:j}),s&&u.push({node:A,read:j,whole:v}),i.push({objectApiName:S,rows:[],counted:F,...B?{leftOut:B}:{}})}let l=e.sample?.drawn.has(ze)?void 0:i.find(A=>A.objectApiName===ze),f=i.find(A=>A.objectApiName===We),p=l?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(l&&p!==void 0&&p>0){let A=Math.min(p,l.counted.rows);l.counted={...l.counted,rows:l.counted.rows-A},l.leftOut={...l.leftOut,byThePlatform:A}}let g=f?.leftOut?.writtenBefore??0,h=l?this.rolesThePlatformMayWriteOfTheCounts(e,l.counted.rows,(p===void 0?f?.counted.rows??0:0)+g):0;if(l&&h>0&&(l.mayBeByThePlatform=p!==void 0?{rows:h,before:!0}:{rows:h}),await this.personContactsBeyondThePlan(e,i),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=s?await this.heldAtTheGate(e,t,i):void 0;m&&(m.requests+=await this.pricesReplacedAtTheGate(e,i)),m&&(m.requests+=await this.directRelationsAtTheGate(e,i,d));let R=s?await this.measureTheWholeOrg(e,i,c,u,m):void 0,b=R&&e.sample?{...R,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:R;if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let k=xs(n),O=n.dryRun&&!s?0:await this.readBackRequests(e,i),w=await o({objects:i,...k!==void 0&&a.length>0?{capped:{perObject:k,objects:a}}:{},...O>0?{readBack:O}:{},...b?{wholeOrg:b}:{},dryRun:n.dryRun});await this.afterTheGate(e,w,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(h=>h.included&&e.writtenObjects.has(h.objectApiName)&&!o.referenceDataObjects.has(h.objectApiName)),i=new Map(s.map((h,m)=>[h.objectApiName,m])),a=new Map,d=new Map,c=new Map,u=$h,l=new Map,f=(h,m,R)=>{let b=a.get(h)??new Map;b.has(m)||u<=0||(b.set(m,R),a.set(h,b),u--)},p={requests:0,lookups:new Map},g=async(h,m)=>{let R=await this.idsUnder(e,h,m);return p.requests+=Math.max(1,Math.ceil((R?.length??0)/Dn)),R};for(let h of s){if(this.isAborted)break;let m=h.objectApiName;if(e.sample?.drawn.has(m))continue;if(u>0&&this.streamsNode(h,e)){let b=await this.recordTypesOfTable(e,h);if(b&&b.closed.length>0&&this.typesHeldRowByRow(e,b)){let k=new Set(b.lackingInSource);for(let[O,w]of[[b.closedInSource.filter(A=>!k.has(A)),d],[b.lackingInSource,c]]){let A=O.map(v=>`'${v}'`).join(", ");if(!A)continue;let S=a.get(m)?.size??0;for(let v of await g(m,`RecordTypeId IN (${A})`)??[])f(m,v,"held");w.set(m,(a.get(m)?.size??0)-S)}}}let R=await this.deps.describeFields(e.sourceOrgId,m).catch(()=>[]);for(let b of R){let[k]=b.referenceTo??[],O=k===void 0?void 0:i.get(k);if(!b.isReference||(b.referenceTo??[]).length!==1||O===void 0||O>=(i.get(m)??0)||!b.createable||(o.fieldExclusions[m]??[]).includes(b.name)||!Qe(m,b.name,b.nillable)||(p.lookups.set(m,(p.lookups.get(m)??0)+1),u<=0))continue;let w=Be(b.name),A=await g(m,`${w} != null AND ${w} NOT IN (SELECT Id FROM ${Be(k)})`);for(let F of A??[])f(m,F,{field:b.name,parentObject:k,reason:fd(b.name,k)});let S=a.get(k);if(!S||S.size===0)continue;let v=[...S].filter(([,F])=>F==="held").map(([F])=>F),j=[...S].filter(([,F])=>F!=="held").map(([F])=>F);for(let[F,B]of[[v,"held"],[j,{field:b.name,parentObject:k,reason:Eh(b.name,k)}]])for(let E of kn(F)){if(u<=0)break;for(let _ of await g(m,`${w} IN (${E})`)??[])f(m,_,B)}}for(let b of R){if(!b.isReference||b.name==="RecordTypeId"||!b.createable||(o.fieldExclusions[m]??[]).includes(b.name)||(b.referenceTo??[]).length===1&&Qe(m,b.name,b.nillable))continue;let k=new Set;for(let w of b.referenceTo??[]){let A=w===m?void 0:a.get(w);if(!(!A||A.size===0))for(let S of kn([...A.keys()])){let v=await g(m,`${Be(b.name)} IN (${S})`);for(let j of v??[])k.add(j)}}for(let w of a.get(m)?.keys()??[])k.delete(w);if(k.size===0)continue;let O=l.get(m)??[];O.push({field:b.name,rows:k.size}),l.set(m,O)}}for(let h of n){let m=l.get(h.objectApiName);m&&(h.leftEmpty=m)}for(let h of n){let m=a.get(h.objectApiName);if(!m||m.size===0)continue;let R=d.get(h.objectApiName)??0,b=c.get(h.objectApiName)??0,k=[...m.values()].filter(S=>S==="held").length,O=m.size-k,w=Math.max(0,h.counted.rows-m.size),A=h.counted.personAccounts;h.counted={rows:w,...A!==void 0&&Math.min(A,w)>0?{personAccounts:Math.min(A,w)}:{}},h.leftOut={...h.leftOut,...R>0?{heldBack:(h.leftOut?.heldBack??0)+R}:{},...b>0?{recordTypeNotInTarget:(h.leftOut?.recordTypeNotInTarget??0)+b}:{},...k-R-b>0?{withoutParent:k-R-b}:{},...O>0?{noParentInSource:O}:{}}}for(let h of a.values())for(let[m,R]of h)e.heldInTheOrg.set(m,R);return p}async pricesReplacedAtTheGate(e,t){let n=t.find(h=>h.objectApiName===et);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(et)??0)>$h)return 0;let o=await this.deps.describeFields(e.sourceOrgId,et).catch(()=>[]);if(!o.some(h=>h.name===mt))return 0;let s=["Id",tn,Pn,mt,...o.some(h=>h.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(h=>h.name===Hn)?[Hn]:[]],i=this.filterOf(e,et),a=e.sample,d;try{d=a?.drawn.has(et)?await this.rowsOfThePlan(e,a,et,s):await this.readWholeOf(e,et,`SELECT ${s.join(", ")} FROM ${et}`+(i?` WHERE ${i}`:""))}catch(h){return Ye.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${V(h)}`),1}let c=Math.max(1,Math.ceil(d.length/Dn)),u=e.currencies===void 0,l=d.filter(h=>!e.heldInTheOrg.has(String(h.Id))),f=await this.priceCurrencyInput(e,l,o),p=c+(u&&e.currencies!==void 0?dw:0);if(!f){let h=e.oneCurrency===void 0,m=await this.pricesKeyOf(e);if(!m.oneCurrency)return p;let R=Math.min(n.counted.rows,wi(l,m).standsFor.length);return R>0&&(n.counted={...n.counted,rows:n.counted.rows-R},n.leftOut={...n.leftOut,currencyReplaced:R}),p+(h&&this.deps.orgCurrency?1:0)}let g=Math.min(n.counted.rows,Ca(f,[]).standsFor.size);return g===0||(n.counted={...n.counted,rows:n.counted.rows-g},n.leftOut={...n.leftOut,currencyReplaced:g}),p}async directRelationsAtTheGate(e,t,n){if(e.sample?.drawn.has(Cn))return 0;let o=t.find(p=>p.objectApiName===Cn);if(!o||o.counted.rows<=0||!t.some(p=>p.objectApiName===ce)||n.has(ce)||n.has(Cn))return 0;let s=this.deps.countRecords;if(!s)return 0;let i=e.config.stream?.resumeAfter.get(Cn),a=this.filterOf(e,Cn),d=[...a?[`(${a})`]:[],...i&&Ft.test(i.lastId)?[`Id > '${i.lastId}'`]:[],"IsDirect = true"],c;try{c=await s(e.sourceOrgId,`SELECT COUNT() FROM ${Cn} WHERE ${d.join(" AND ")}`)}catch(p){return Ye.warn(`[forge] the relations the platform writes with the contacts could not be counted at the gate: ${V(p)}`),1}let u=o.leftOut,l=(u?.writtenBefore??0)+(u?.withoutParent??0)+(u?.noParentInSource??0),f=Math.max(0,Math.min(c-l,o.counted.rows));return f===0||(o.counted={...o.counted,rows:o.counted.rows-f},o.leftOut={...u,byThePlatform:(u?.byThePlatform??0)+f}),1}async idsUnder(e,t,n){let o=e.config.stream?.resumeAfter.get(t),s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...o&&Ft.test(o.lastId)?[`Id > '${o.lastId}'`]:[],n];try{return(await this.readWholeOf(e,t,`SELECT Id FROM ${Be(t)} WHERE ${i.join(" AND ")}`)).map(d=>String(d.Id))}catch(a){Ye.warn(`[forge] the ${t} records held back could not be counted at the gate: ${V(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:k})=>k>a).map(({objectApiName:k,rows:O})=>({objectApiName:k,rows:O,bound:a})),c=new Set(o.filter(k=>k.whole).map(k=>k.node.objectApiName)),{writes:u,restOnly:l}=await this.writesOfTheWholeOrg(e,t,c),f=o.find(({node:k})=>k.objectApiName===$e&&k.included),p=t.find(k=>k.objectApiName===$e)?.counted?.rows??0,g=f&&p>0?await this.emailBytesOf(e,f.node):void 0,h=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o),R=t.find(k=>k.objectApiName===Se)?.counted?.personAccounts??0,b=R>0&&await this.personAccountsInTarget(e)===!1?R:0;return{writes:u,...l?{restOnly:l}:{},...g!==void 0?{emailTextBytes:g}:{},...i.files?{files:h??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,h)+cw(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{},...b>0?{personAccountsAsBusiness:b}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=e.bulk?.restOnly??new Set;if(s&&!e.bulk){let c=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});i=new Set([...os,...c??sa])}let a=o.stream?.writeWindow??o.stream?.pageSize??Dn,d=t.map(({objectApiName:c,counted:u})=>{let l=Math.max(0,u?.rows??0),f=s&&!i.has(c),p=n.has(c)?[l]:[...Array.from({length:Math.floor(l/a)},()=>a),...l%a>0?[l%a]:[]],g=0,h=0;for(let m of f?p:[])for(let R=0;R<m;R+=Dr){let b=Math.min(Dr,m-R);b<2e3||(g++,h+=b)}return{objectApiName:c,rows:l,jobs:g,jobRows:h,restRows:l-h}});return s?{writes:d,restOnly:i}:{writes:d}}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Dn)),i=new Map;for(let{node:c,read:u}of t)i.set(c.objectApiName,u);for(let{objectApiName:c,rows:u}of n)i.set(c,u);let a=0;for(let[c,u]of i){let l=t.find(f=>f.node.objectApiName===c)?.node;a+=e.sample?.drawn.has(c)&&l?(await this.readOfThePlan(e,e.sample,l,u)).requests:s(u)}let d=t.find(({node:c})=>c.objectApiName===$e);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===ut)){let c=await this.countOf(e,$e,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=Sd.length+Math.ceil(c/Dn),a+=Math.ceil(c/kd)+c}return a}async rowsOf(e,t){return await this.countOf(e,t.objectApiName)??t.recordCount}async countOf(e,t,n){let o=this.deps.countRecords;if(!o)return;let s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...n?[n]:[]],a=i.length>0?` WHERE ${i.join(" AND ")}`:"",d=`SELECT COUNT() FROM ${Be(t)}${a}`,c=this.readOptionsOf(e,t);try{return await(c?o(e.sourceOrgId,d,c):o(e.sourceOrgId,d))}catch{return}}async emailBytesOf(e,t){let n=t.objectApiName;try{let o=await this.deps.describeFields(e.sourceOrgId,n),s=og(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let g=0,h=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of h)for(let[R,b]of Object.entries(m))R!=="Id"&&typeof b=="string"&&(g+=Buffer.byteLength(b,"utf8"));return g}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&Ft.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],u=c.length>0?` WHERE ${c.join(" AND ")}`:"",l=["Id",...s.map(g=>g.name)].join(", "),f=0,p=Vt(this.deps,e.sourceOrgId,`SELECT ${l} FROM ${Be(n)}${u} ORDER BY Id`,e.config.stream?.pageSize,void 0,this.readOptionsOf(e,n));try{for await(let g of p){for(let h of g)for(let[m,R]of Object.entries(h))m!=="Id"&&typeof R=="string"&&(f+=Buffer.byteLength(R,"utf8"));if(this.isAborted)break}}finally{await p.return(void 0)}return f}catch(o){Ye.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+V(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of Sd){let c=[d,`${a} <= ${t}`].filter(Boolean).join(" AND "),u=[d,`${a} > ${t}`].filter(Boolean).join(" AND "),l=await this.sumOfFiles(e,i,a,c);if(!l)return;n+=l.bytes,o+=l.count;let f=await this.deps.countRecords?.(e.sourceOrgId,`SELECT COUNT() FROM ${i} WHERE ${u}`).catch(()=>{});s+=f??0}return{bytes:n,count:o,overCeiling:s}}async sumOfFiles(e,t,n,o){try{let[s]=await this.deps.queryRecords(e.sourceOrgId,`SELECT SUM(${n}) total, COUNT(Id) n FROM ${t} WHERE ${o}`),i=Number(s?.total??0),a=Number(s?.n??0);if(Number.isFinite(i)&&Number.isFinite(a))return{bytes:i,count:a}}catch{}try{let s=0,i=0,a=Vt(this.deps,e.sourceOrgId,`SELECT Id, ${n} FROM ${t} WHERE ${o} ORDER BY Id`,e.config.stream?.pageSize);try{for await(let d of a){for(let c of d){let u=c[n];s+=typeof u=="number"&&Number.isFinite(u)?u:0,i++}if(this.isAborted)break}}finally{await a.return(void 0)}return{bytes:s,count:i}}catch(s){Ye.warn(`[forge] the files of ${t} could not be measured: ${V(s)}`);return}}async phoneNumbersPastTheFiction(e,t){let n=0;for(let{node:o,read:s}of t){if(s===0||this.isAborted)continue;let i=o.objectApiName,a=new Set(e.config.fieldExclusions[i]??[]),c=(await this.deps.describeFields(e.sourceOrgId,i).catch(()=>[])).filter(u=>u.createable&&!a.has(u.name));for(let u of Ea(c)){if(u.kind!=="phone")continue;let l=await this.countOf(e,i,`${Be(u.name)} != null`);n+=Math.min(l??s,s)}}return Math.max(0,n-$f)}async countToWrite(e,t){let n=t.objectApiName,o=this.streamsNode(t,e),s=o?e.config.stream?.resumeAfter.get(n):void 0,i=this.filterOf(e,n),a=this.readOptionsOf(e,n),d=this.deps.countRecords,c=async z=>{if(!d)return;let J=[...i?[`(${i})`]:[],...z?[z]:[],...s&&Ft.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],Me=J.length>0?` WHERE ${J.join(" AND ")}`:"",ke=`SELECT COUNT() FROM ${Be(n)}${Me}`;try{return await(a?d(e.sourceOrgId,ke,a):d(e.sourceOrgId,ke))}catch{return}},u=this.readBound(e,t),l=u===void 0?void 0:Math.max(0,u-(s?.read??0)),f=await c(),p=f??t.recordCount,g=l===void 0?p:Math.min(p,l),h=xs(e.config),m=h===void 0?void 0:Math.max(0,h-(s?.read??0)),R=m!==void 0&&l===m&&p>m,b=o?await this.recordTypesOfTable(e,t):void 0;if(b&&b.closed.length>0&&!this.typesHeldRowByRow(e,b))return{read:g,counted:{rows:0},...g>0?{leftOut:xh(b.closed,g)}:{}};let k=Math.min(g,await this.writtenBeforeOf(e,t,s)),O=n===Ut?Math.min(g-k,await this.standardBookOfTheTable(e,c)):0,w=g-k-O,A=k>0||O>0?{...k>0?{writtenBefore:k}:{},...O>0?{linkedToTarget:O}:{}}:void 0,S=z=>z===void 0?{rows:w}:{rows:w,personAccounts:z},v=g<p,j=z=>({read:g,counted:S(z),...A?{leftOut:A}:{},...R?{capped:!0}:{},...v?{partial:!0}:{}});if(n!==Se&&n!==ce||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(z=>z.name==="IsPersonAccount"))return j();let B=await c("IsPersonAccount = true"),E=B===void 0?void 0:Math.min(B,w);if(n!==ce||B===void 0||f===void 0)return j(E);let _=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(_===void 0)return j(E);let ee=Math.max(0,B-_-(f-g)-k);if(ee===0)return j(E);let X=(E??0)-ee;return{read:g,counted:{rows:w-ee,...X>0?{personAccounts:X}:{}},leftOut:{...A,byThePlatform:ee},...R?{capped:!0}:{},...v?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!Ft.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,Ut)?Math.min(1,await t(`Id = '${n}'`)??0):1}async personContactsTakenAsBusinessAtTheGate(e,t){if(await this.personAccountsInTarget(e)!==!0)return;let n=await this.personRecordTypesInTarget(e);if(!n)return 0;let{config:o}=e;if(!((await this.deps.describeFields(e.sourceOrgId,Se).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[Se]??[]).includes("RecordTypeId")&&o.fieldMappings[Se]?.RecordTypeId===void 0)){let d=xa((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes);return d!==void 0&&!n.has(d.slice(0,15))?void 0:0}let a=(o.recordTypeMappings??[]).filter(d=>!n.has(d.targetId.slice(0,15))).map(d=>d.sourceId);if(a.length===0)return 0;if(a.every(d=>Ft.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return Hf({lookups:t.filter(s=>s.isReference&&o(s.name)),rows:n,ownerMappings:e.config.ownerMappings,outsideTheRun:s=>this.isOutsideTheRun(e,s),mapped:s=>e.remapper.get(s)!==void 0,known:e.targetHolds,refused:e.targetReadsRefused,inactive:e.inactiveUsers,query:s=>this.deps.queryRecords(e.targetOrgId,s),neverCopied:s=>vs(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=Kf(t,e.inactiveUsers,e.config.ownerMappings);if(o.size!==0&&!await e.writesInactiveOwners())return o}isOutsideTheRun(e,t){return!e.writtenObjects.has(t)&&!e.failedObjects.has(t)&&!e.notInTarget.has(t)}noteLookupsOutsideTheRun(e,t,n,o){let s=wd(new Map,o);if(s.size===0)return;let i=e.lookupsOutsideTheRun.get(t)??new Map;for(let[a,d]of s){let c=n.find(l=>l.name===a)?.referenceTo?.[0]??a,u=i.get(a)??{parent:c,rows:0};u.rows+=d,i.set(a,u)}e.lookupsOutsideTheRun.set(t,i)}async noteLookupsHeldBack(e,t,n,o){let s=bd(new Map,o);if(s.size===0)return;let i=e.lookupsHeldBack.get(t)??new Map;for(let[a,d]of s){let c=i.get(a)??{parent:await this.parentNamed(e,n,a,o),rows:0};c.rows+=d,i.set(a,c)}e.lookupsHeldBack.set(t,i)}async parentNamed(e,t,n,o){let s=t.find(d=>d.name===n)?.referenceTo??[];if(s.length===1)return s[0];let i=o.find(d=>d.lookupsHeldBack?.includes(n))?.source[n],a=s.filter(d=>e.writtenObjects.has(d));if(typeof i=="string"&&a.length>0){let c=(await this.sourceKeyPrefixes(e,new Set(a))).get(i.slice(0,3));if(c)return c}return s[0]??n}async rowsWhoseParentTheTargetLacks(e,t,n,o,s){let i=new Map,{config:a}=t;if(a.referenceFallback!=="keep"||a.expandOrphanParents)return i;let d=n.filter(u=>{let l=u.referenceTo??[];return u.isReference&&s(u.name)&&l.length===1&&!vs(t,l[0])&&this.isOutsideTheRun(t,l[0])&&Qe(e.objectApiName,u.name,u.nillable)});if(d.length===0||o.length===0)return i;let c=await this.idsTheTargetLacks(t,d,o,()=>!0);return c.size===0||o.forEach((u,l)=>{for(let f of d){let p=u[f.name];if(!(typeof p!="string"||!c.has(p)||t.remapper.get(p))){i.set(l,{field:f.name,parentObject:(f.referenceTo??[])[0],notInTarget:!0});return}}}),i}rowsOfClosedTypes(e,t,n,o){let{config:s}=e,i=new Map(o.map(c=>[c.recordTypeId,c])),a=n.map(c=>({RecordTypeId:s.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));e.recordTypeMapper&&s.recordTypeMappings&&(a=e.recordTypeMapper.apply(a,s.recordTypeMappings));let d=new Map;return n.forEach((c,u)=>{let l=a[u]?.RecordTypeId,f=typeof l=="string"?i.get(l):void 0;f&&d.set(c,{field:"RecordTypeId",parentObject:f.developerName,recordType:{...f,objectApiName:t.objectApiName}})}),d}async rowsHeldInTheWholeOrg(e,t,n,o,s){let i=new Map,a=new Map;if(t.config.stream?.everything!==!0||o.length===0)return{held:i,aside:a};let d=fw(t,e.objectApiName,n,s),c=new Set,u=new Map;o.forEach((l,f)=>{let p=t.heldInTheOrg.get(String(l.Id));if(p!==void 0&&p!=="held"){a.set(f,p);return}if(t.sample?.withoutStandard.has(it(String(l.Id)))){i.set(f,{field:Pn,parentObject:et,reason:Zw}),c.add(f);return}for(let{field:g,parent:h}of d){let m=l[g];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let R=t.sample;if(R?.drawn.has(h)){this.inThePlan(R,h,m)?R.gone.get(h)?.has(it(m))?a.set(f,{field:g,parentObject:h,reason:lw(g,h)}):i.set(f,{field:g,parentObject:h}):(i.set(f,{field:g,parentObject:h,reason:uw(g,h)}),c.add(f));return}let b=t.heldInTheOrg.get(m);if(b==="held"){i.set(f,{field:g,parentObject:h});return}if(b){let O=b===vh?fd(g,h):Eh(g,h);a.set(f,{field:g,parentObject:h,reason:O});return}let k=u.get(h)??new Map;k.set(m,[...k.get(m)??[],{index:f,field:g}]),u.set(h,k)}});for(let[l,f]of u){let p=await this.idsInTheSource(t,l,[...f.keys()]);for(let[g,h]of f){let m=p===void 0||p.has(g.slice(0,15));m||t.heldInTheOrg.set(g,vh);for(let{index:R,field:b}of h)i.has(R)||a.has(R)||(m?i.set(R,{field:b,parentObject:l}):a.set(R,{field:b,parentObject:l,reason:fd(b,l)}))}}for(let l of i.keys())a.delete(l);if(c.size>0&&t.sample){let l=e.objectApiName;t.sample.changed.set(l,(t.sample.changed.get(l)??0)+c.size)}return{held:i,aside:a}}async idsInTheSource(e,t,n){let o=new Set;try{for(let s of kn(n)){let i=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Be(t)} WHERE Id IN (${s})`);for(let a of i)o.add(String(a.Id).slice(0,15))}return o}catch(s){Ye.warn(`[forge] whether the source holds the ${t} records named could not be read: ${V(s)}`);return}}async writtenBeforeOf(e,t,n){let{writtenBefore:o}=e.config,s=t.objectApiName,i=e.store?.earlierRecordsOf(s,n!==void 0)??0;if(e.store&&i>0)return i;if(o.size===0||n)return 0;let a=(await this.objectInfoOf(e.sourceOrgId,s))?.keyPrefix??e.sourceKeyPrefixes.get(s);if(!a)return 0;let d=[];for(let p of o.keys())p.startsWith(a)&&d.push(p);let c=e.config.objectSoqlFilters?.[s],u=this.deps.countRecords;if(!c||d.length===0||!u)return d.length;let l=this.readOptionsOf(e,s),f=this.filterOf(e,s)??c;try{let p=0;for(let g of kn(d)){let h=`SELECT COUNT() FROM ${Be(s)} WHERE (${f}) AND Id IN (${g})`;p+=await(l?u(e.sourceOrgId,h,l):u(e.sourceOrgId,h))}return p}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===$e&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(zo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:Hm(),...n?{pass:n}:{}},d=n?void 0:this.readBound(t,e);if(i?.done||d!==void 0&&a.read>=d)return;let c=n?void 0:await this.recordTypesOfTable(t,e);if(c&&c.closed.length>0&&!this.typesHeldRowByRow(t,c)){let f=d===void 0?c.rows:Math.min(c.rows,d-a.read);this.holdBackTableForRecordTypes(e,t,c,f);return}let u=n?n.expected:t.counted.get(o)??Sh(e,d);a.carry.rowsLeft=n?()=>Math.max(0,u-a.carry.rows):()=>Math.max(0,u-(a.read-(i?.read??0)));let l=n?.stopped??`Stopped ${e.objectApiName}`;t.cursors.set(o,a);try{let f=n?void 0:await this.keysOfTheTable(t,e,a);for(f&&(a.carry.tableKeys=f);;){if(this.isAborted)throw a.carry.pages>0&&a.carry.rowsLeft()>0?this.stopStreamedNode(e,t,a.carry,0,l):a.carry.pages>0&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!await this.readNode(e,t,!1,!0))break;let p=n?t.preread.get(o)?.records??[]:void 0;if(await this.writeNode(e,t,p,a.carry),o===Se&&await this.mapContactsOfPersonAccounts(t),s&&await this.linkTasksOfTheEmailsWritten(t),await this.tellPage(t,e,a),a.ended)break}}finally{t.cursors.delete(o),await a.pages?.return(void 0)}t.store&&a.ended&&!a.failed&&a.lastId!==void 0&&t.store.checkpoint(o,{lastId:a.lastId,read:a.read,done:!0},n?.name),a.carry.pages>0&&!a.failed&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),this.releaseRows(t,o)}endOfAStreamedNode(e,t,n){if(n)return{...n.end,again:!0};if(t!==$e||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${$s(o)}`}:{}}}recordTypesOfTable(e,t){let n=t.objectApiName,o=e.tableRecordTypes.get(n);return o||(o=this.countRecordTypesOfTable(e,t),e.tableRecordTypes.set(n,o)),o}async countRecordTypesOfTable(e,t){let{config:n,sourceOrgId:o,targetOrgId:s}=e,i=t.objectApiName,a=await this.targetObjectInfoOf(e,i),d={closed:[],rows:0,target:a,closedInSource:[],lackingInSource:[]};if(!a||!a.recordTypes.some(c=>!c.available&&!c.master)&&!await this.mayLackRecordTypes(e,i,a)||(n.fieldExclusions[i]??[]).includes("RecordTypeId")||n.fieldMappings[i]?.RecordTypeId)return d;try{let[c,u]=await Promise.all([this.deps.describeFields(o,i),an(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(F=>F.name==="RecordTypeId"&&F.createable)||u&&!u.creatable.has("RecordTypeId"))return d;let f=n.stream?.resumeAfter.get(i),p=this.filterOf(e,i),g=[...p?[`(${p})`]:[],...f&&Ft.test(f.lastId)?[`Id > '${f.lastId}'`]:[]],h=g.length>0?` WHERE ${g.join(" AND ")}`:"",m=`FROM ${Be(i)}${h}`,R=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),b=R.reduce((F,B)=>F+(typeof B.n=="number"&&B.n>0?B.n:0),0),k=vu(R),O=async F=>[...$u(i,F,a.recordTypes),...await this.typesTheTargetLacks(e,i,F,a)],w=await O(this.recordTypesAsSent(e,k)),A=F=>{let B=new Set(F.map(E=>E.recordTypeId));return[...k.keys()].filter(E=>[...this.recordTypesAsSent(e,[[E,1]]).keys()].some(_=>B.has(_)))},S=(F,B)=>({closed:F,rows:B,target:a,closedInSource:A(F),lackingInSource:A(F.filter(E=>E.unmapped))}),v=this.readBound(e,t),j=v===void 0?void 0:Math.max(0,v-(f?.read??0));if(w.length>0&&j!==void 0&&b>j){let F=await this.recordTypesOfTheRowsRead(e,i,m,j);if(F)return S(await O(this.recordTypesAsSent(e,F.counts)),F.rows)}return S(w,b)}catch{return}}recordTypesAsSent(e,t){let{config:n}=e,o=new Map;for(let[s,i]of t){if(n.recordTypeDecisions.get(s)?.to===null)continue;let a=s;e.recordTypeMapper&&n.recordTypeMappings&&(a=e.recordTypeMapper.apply([{RecordTypeId:s}],n.recordTypeMappings)[0]?.RecordTypeId),typeof a=="string"&&o.set(a,(o.get(a)??0)+i)}return o}async typesTheTargetLacks(e,t,n,o){if(!e.recordTypeMapper||!e.config.recordTypeMappings)return[];if(!o||o.recordTypes.length===0)return[];if(Lo(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),Lo(t,n,o.recordTypes,i)}async mayLackRecordTypes(e,t,n){if(!e.recordTypeMapper||!e.config.recordTypeMappings||n.recordTypes.length===0)return!1;let s=((await this.objectInfoOf(e.sourceOrgId,t))?.recordTypes??[]).filter(a=>!a.master);if(s.length===0)return!1;let i=this.recordTypesAsSent(e,s.map(a=>[a.recordTypeId,1]));return Lo(t,i,n.recordTypes,[]).length>0}async recordTypesOfTheRowsRead(e,t,n,o){let s=!1;try{let i=await this.readWholeOf(e,t,`SELECT RecordTypeId ${n} ORDER BY Id LIMIT ${o}`,()=>{s=!0});if(s)return;let a=new Map;for(let d of i){let c=d.RecordTypeId;typeof c=="string"&&c!==""&&a.set(c,(a.get(c)??0)+1)}return{counts:a,rows:i.length}}catch{return}}typesHeldRowByRow(e,t){if(e.config.stream?.everything!==!0)return!1;let n=t.closed.reduce((o,s)=>o+s.recordCount,0);return t.rows>n}holdBackTableForRecordTypes(e,t,n,o){let s=e.objectApiName;t.gaps?.knowRecordTypes(s,"target",n.target?.recordTypes??[]);for(let i of n.closed)t.gaps?.add(Ph(i,n.target));t.failedObjects.add(s),t.failedCount+=o,t.errors.push({objectApiName:s,stage:"scope",failedCount:o,attemptedCount:0,samples:n.closed.map(i=>({recordSummary:`RecordType=${i.developerName} (${i.recordCount} record${i.recordCount===1?"":"s"})`,messages:[Do(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${$n(s,o,Qt(t,s))}: `+n.closed.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."})}async nextPage(e,t,n,o,s){if(n.ended)return[];let i=e.sample?.drawn.has(t.objectApiName)?e.sample:void 0,a=f=>i?this.pagesOfThePlan(e,i,t,n,f):Vt(this.deps,e.sourceOrgId,f,e.config.stream?.writeWindow??e.config.stream?.pageSize,()=>e.truncatedObjects.add(t.objectApiName),this.readOptionsOf(e,t.objectApiName));n.pages??=a(o);let d=e.config.stream?.everything===!0?ld:0,c;for(let f=0;;f++)try{c=await n.pages.next();break}catch(p){let g=Kh(p);if(!g&&!Vh(p)||f>=d||this.isAborted)throw p;let h=n.lastId===void 0?o:s?.(n.lastId);if(h===void 0)throw p;g||await Jh(Rh*2**f),Ye.warn(`[forge] ${t.objectApiName}: the source ${g?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${f+1}/${d}): `+V(p)),n.pages=a(h)}if(c.done)return n.ended=!0,[];n.taken++;let u=c.value;n.room!==void 0&&(u.length>n.room&&(u=u.slice(0,n.room),n.ended=!0,(n.cutBy==="cap"?e.cappedObjects:e.truncatedObjects).add(t.objectApiName)),n.room-=u.length),n.read+=u.length;let l=u[u.length-1]?.Id;return typeof l=="string"&&(n.lastId=l),u}async readWhole(e,t,n){let o=e.sample;if(o?.drawn.has(t)){let d=/^SELECT (.+?) FROM /.exec(n)?.[1]?.split(", ")??["Id"];return this.rowsOfThePlan(e,o,t,d,void 0,!0)}let s=!1,i=()=>{s=!0,e.truncatedObjects.add(t)},a=await this.readWholeRows(e,n,i);if(s&&e.config.stream?.everything===!0)throw new Cs(t,e.config.stream.wholeReadBound);return a}async readWholeRows(e,t,n){let{stream:o}=e.config,s=o?.pageSize;if(s===void 0||!this.deps.queryPages)return this.deps.queryRecords(e.sourceOrgId,t,n);let i=(o?.everything===!0?o.wholeReadBound:o?.ceiling)??5e4,a=[],d=Vt(this.deps,e.sourceOrgId,t,s);try{for await(let c of d)if(a.push(...c),a.length>i)return n(),a.slice(0,i)}finally{await d.return(void 0)}return a}pagedLimit(e,t){let n=xs(e.config),o=n===void 0?void 0:n-t.read,s=e.config.stream?.ceiling,i=s===void 0?void 0:s-t.read;if(i===void 0&&o===void 0)return;let a=i!==void 0&&(o===void 0||i<o);return t.room=Math.max(0,(a?i:o)??0),t.cutBy=a?"ceiling":"cap",Math.max(1,t.room)}async tellPage(e,t,n){e.store&&n.lastId!==void 0&&e.store.checkpoint(t.objectApiName,{lastId:n.lastId,read:n.read},n.pass?.name);let o=e.config.stream?.onPage;if(!o)return;let s=e.preread.get(t.objectApiName)?.records??[],i=e.simulated?[]:s.flatMap(a=>{let d=a.Id;if(typeof d!="string"||!e.remapper.isCreated(d))return[];let c=e.remapper.get(d);return c?[{sourceId:d,targetId:c}]:[]});await o({objectApiName:t.objectApiName,...n.lastId!==void 0&&!n.pass?{checkpoint:{lastId:n.lastId,read:n.read}}:{},created:i})}endStreamedNode(e,t,n,o={}){let{config:s}=t,i=o.say??t.onProgress,a=e.objectApiName;this.mergePageReports(t,a,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=o.again?[]:Qt(t,a),c=o.again?void 0:t.heldForExclusions.get(a),u=[...ud(n),...d],l=_n(u),f=v=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:v})};if(n.heldWhole!==void 0){f(`${$n(a,n.heldWholeRows,d)}: ${n.heldWhole} Objects that cannot be written without it will be skipped.`);return}if(n.rows===0&&c&&c.size>0){f(zr(a,c));return}let p=wh(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){f(`${$n(a,n.personContactsUnlinked,d)}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`);return}if(p===0&&n.failed===0&&n.sent===0&&n.withoutParent>0){f(`${$n(a,n.withoutParent,d)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`);return}let g=p+n.failed,h=g>0?n.failed/g:0,m=n.failed>0&&n.alreadyExists===n.failed,R=n.failed>0&&!m&&(p===0||h>.5),b=Vo(n.picklists.list())+No(n.currencies.list())+gd(n.lookupsNotCarried)+Rd(n.ownersInactive)+md(n.lookupsOutsideTheRun)+yd(n.lookupsHeldBack)+Td(t,a),k=ss(n.writtenWithoutFields),O=tg(t,a),w=Oh(t,a),A=Bh(n.sentOnTheirOwn);if(R){p>0&&t.failedInPart.add(a),f(p===0?`Failed all ${a} records: ${n.failed+l} failed${cn(u)}${A}${b}${w}`:`${n.failed+l}/${g+l} ${a} records failed (>50%)${cn(u)}${A}${b}${k}${O}${w}`+Fh);return}let S=yh(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${hd(s,n,u,pd(t,a))}${o.note??""}${A}${S}${b}${k}${O}${Ps(t,a)}${w}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();Od(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...ud(n),...Qt(t,i)],c=wh(n),u=c+n.failed,l=n.failed>0&&n.alreadyExists!==n.failed&&(c===0||n.failed/u>.5);l&&t.failedObjects.add(i),l&&c>0&&t.failedInPart.add(i),t.onProgress({objectName:i,status:l?"error":"stopped",progress:100,message:`${s}: ${hd(t.config,n,d,pd(t,i))}, ${a} not sent${Bh(n.sentOnTheirOwn)}${yh(n)}${Vo(n.picklists.list())}${No(n.currencies.list())}${gd(n.lookupsNotCarried)}${Rd(n.ownersInactive)}${md(n.lookupsOutsideTheRun)}${yd(n.lookupsHeldBack)}${Td(t,i)}${ss(n.writtenWithoutFields)}${Ps(t,i)}`})}mergePageReports(e,t,n){if(n.withoutParent>0&&!n.withoutParentSaid){let i={objectApiName:t,stage:"scope",failedCount:n.withoutParent,attemptedCount:0,samples:$d(n.withoutParentGroups,e.failedObjects)},a=e.errors.findIndex(d=>d.objectApiName===t&&d.stage==="insert");a===-1?e.errors.push(i):e.errors.splice(a,0,i),n.withoutParentSaid=!0}let o=e.errors.filter(i=>i.objectApiName===t&&i.stage==="insert");if(o.length>0){let[i]=o,a={...i,failedCount:o.reduce((u,l)=>u+l.failedCount,0),attemptedCount:n.succeeded+n.updated+n.linked+n.failed,samples:o.flatMap(u=>u.samples).slice(0,Tw)},d=e.errors.indexOf(i),c=e.errors.filter(u=>!o.includes(u));c.splice(d,0,a),e.errors.splice(0,e.errors.length,...c)}let s=e.existingRecords.filter(i=>i.objectApiName===t);if(s.length>1){let i=s.reduce((u,l)=>u+(l.linkedToCreated??0),0),a={objectApiName:t,linked:s.reduce((u,l)=>u+l.linked,0),...i>0?{linkedToCreated:i}:{},unidentified:s.reduce((u,l)=>u+l.unidentified,0)},d=e.existingRecords.indexOf(s[0]),c=e.existingRecords.filter(u=>!s.includes(u));c.splice(d,0,a),e.existingRecords.splice(0,e.existingRecords.length,...c)}}async startAsDrafts(e,t,n){let o=new Map;if(e.config.dryRun)return o;let s=await this.lifecycleOf(e,t);return s&&n.forEach((i,a)=>{let d=To(i.Status,s);d&&(o.set(a,String(i.Status)),i.Status=d)}),o}async oweStatusesFoundAfterStop(e,t,n){let{store:o}=e;if(!o)return;let s=n.filter(a=>{let d=a.Id;return typeof d=="string"&&o.wasFoundAfterStop(d)});if(s.length===0)return;let i=await this.lifecycleOf(e,t);if(i)for(let a of s){if(!To(a.Status,i))continue;let d=e.config.writtenBefore.get(String(a.Id));d&&this.oweStatus(e,t,d,String(a.Status))}}async lifecycleOf(e,t){let n=tu[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=nu(s=>this.deps.queryRecords(e.targetOrgId,s),n),e.lifecycles.set(t,o)),o}async notePastDraft(e,t,n){if(!([...e.statusChildren.values()].some(({parent:a})=>a===t)||e.config.excludedObjects.size>0&&Ar[t]!==void 0))return;let s=await this.lifecycleOf(e,t);if(!s)return;let i=e.pastDraft.get(t)??new Map;for(let a of n){let d=a.Id;typeof d=="string"&&To(a.Status,s)&&i.set(d,String(a.Status))}e.pastDraft.set(t,i)}async restoreStatuses(e){let t=this.deps.updateRecords;if(t&&e.store){await this.restoreStatusesFromTheJournal(e,t);return}if(!t||e.deferredStatuses.length===0)return;let n=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[o,s]of ng(n)){let i=0,a=[];for(let d=0;d<s.length;d+=is.rest){let c=s.slice(d,d+is.rest),u;try{u=await t(e.targetOrgId,o,c.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=c.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}c.forEach(({id:l,status:f},p)=>{let g=u[p];g?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${l} Status=${f}`,messages:g?.errors??["No result returned for the status update"]}))})}e.onProgress({objectName:o,status:i>0?"error":"done",progress:100,message:`Restored the status of ${s.length-i}/${s.length} ${o} records written as drafts`}),i>0&&e.errors.push({objectApiName:o,stage:"insert",failedCount:i,attemptedCount:s.length,samples:a})}}async restoreStatusesFromTheJournal(e,t){let{store:n}=e;if(!n||e.statusesGiven||n.statusesOwed().size===0)return;e.statusesGiven=!0;let o=new Map,s=new Map,i=async a=>{let d=s.get(a)??[];if(s.set(a,[]),d.length===0)return;let c=o.get(a);if(!c)return;let u;try{u=await t(e.targetOrgId,a,d.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=d.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}d.forEach(({id:l,status:f},p)=>{let g=u[p];if(g?.success){n.gaveStatus(a,l);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${l} Status=${f}`,messages:g?.errors??["No result returned for the status update"]})})};for(let{objectApiName:a,id:d,status:c}of n.statusLines()){if(e.leftDrafts.has(d)||n.statusGiven(d))continue;let u=o.get(a)??{entries:0,failed:0,samples:[]};u.entries++,o.set(a,u);let l=s.get(a)??[];l.push({id:d,status:c}),s.set(a,l),l.length>=is.rest&&await i(a)}for(let[a,{entries:d,failed:c,samples:u}]of o)await i(a),e.onProgress({objectName:a,status:c>0?"error":"done",progress:100,message:`Restored the status of ${d-c}/${d} ${a} records written as drafts`}),c>0&&e.errors.push({objectApiName:a,stage:"insert",failedCount:c,attemptedCount:d,samples:u})}reportDraftsExclusionsLeave(e){let t=e.config.excludedObjects;if(t.size===0)return;let n=new Set;for(let[s,i]of Object.entries(Ar)){let a=e.pastDraft.get(s);if(!a||a.size===0)continue;let d=e.statusChildrenRead.get(s),c=[];for(let[u,l]of a){let f=e.remapper.get(u);if(!e.config.dryRun&&!f)continue;let p;if(t.has(i.object))p=`${i.object} is excluded from this run`;else if(d&&!d.kept.has(u)){let h=d.held.get(u);h&&(p=`none of its ${i.object} records can be written without ${h.excluded}`+(h.target?Kr(h.target):", which is excluded from this run"))}if(!p)continue;f&&n.add(f);let g=f!==void 0&&!e.simulated?.has(f)?f:u;c.push({recordSummary:`${s} ${g} Status=${l}`,messages:[`Left a draft: the platform gives ${s} this status only with ${i.object} records under it, and ${p}.`]})}c.length!==0&&e.errors.push({objectApiName:s,stage:"insert",failedCount:c.length,attemptedCount:c.length,samples:c.slice(0,3)})}if(n.size===0)return;for(let s of n)e.leftDrafts.add(s);let o=e.deferredStatuses.splice(0,e.deferredStatuses.length);e.deferredStatuses.push(...o.filter(({id:s})=>!n.has(s)))}reportDraftsLeft(e){if(e.store){if(e.statusesGiven)return;e.statusesGiven=!0;for(let[n,{count:o,samples:s}]of e.store.statusesOwed())e.errors.push({objectApiName:n,stage:"insert",failedCount:o,attemptedCount:o,samples:s.map(({id:i,status:a})=>({recordSummary:`${n} ${i} Status=${a}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))});return}let t=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[n,o]of ng(t))e.errors.push({objectApiName:n,stage:"insert",failedCount:o.length,attemptedCount:o.length,samples:o.slice(0,3).map(({id:s,status:i})=>({recordSummary:`${n} ${s} Status=${i}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))})}async skipForFailedParent(e,t,n,o){let s=u=>iw(e.objectApiName,t.graph,u).filter(l=>t.failedObjects.has(l)&&!t.failedInPart.has(l)),i=s(n??[]);if(i.length===0)return!1;if(!n)try{if(i=s(await this.deps.describeFields(t.sourceOrgId,e.objectApiName)),i.length===0)return!1}catch{}t.skippedCount++,t.failedObjects.add(e.objectApiName);let a=o?.filter(u=>!dn(t.config,u)).length??t.counted.get(e.objectApiName);a!==0&&(t.failedCount+=a??0,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:a??0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:[...i.map(u=>`Not written: its records cannot be written without ${u}, which failed in this run.`),...a===void 0?["Skipped before its records were read: how many there were is not known."]:[]]}]}));let d=Qt(t,e.objectApiName),c=(a??0)+_n(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${cn(d)}`:"")}),!0}async rowsWithoutTheirParent(e,t,n,o){let s=new Map;o.forEach((u,l)=>{for(let f of n){let[p]=f.referenceTo??[];if(!f.isReference||(f.referenceTo??[]).length!==1||p===e.objectApiName||!t.failedInPart.has(p)||!Qe(e.objectApiName,f.name,f.nillable))continue;let g=u[f.name];if(typeof g=="string"&&g&&!t.remapper.get(g)){s.set(l,{field:f.name,parentObject:p});return}}});let i=n.filter(u=>u.isReference&&(u.referenceTo??[]).length>1&&Qe(e.objectApiName,u.name,u.nillable)),a=[];if(o.forEach((u,l)=>{for(let f of i){let p=u[f.name];typeof p=="string"&&p&&!t.remapper.get(p)&&a.push({index:l,field:f.name,id:p})}}),a.length===0)return s;let d=new Set(t.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName));d.delete(e.objectApiName);let c=await this.sourceKeyPrefixes(t,new Set(i.flatMap(u=>(u.referenceTo??[]).filter(l=>d.has(l)))));for(let{index:u,field:l,id:f}of a){let p=c.get(f.slice(0,3));p&&!s.has(u)&&s.set(u,{field:l,parentObject:p})}return s}async sourceKeyPrefixes(e,t){let n=[];for(let s of t){if(e.sourceKeyPrefixes.has(s))continue;let i=e.preread.get(s)?.records.find(a=>typeof a.Id=="string");i?e.sourceKeyPrefixes.set(s,String(i.Id).slice(0,3)):n.push(s)}for(let s=0;s<n.length;s+=6){let i=n.slice(s,s+6),a=await Promise.all(i.map(d=>this.objectInfoOf(e.sourceOrgId,d)));i.forEach((d,c)=>{let u=a[c]?.keyPrefix;u&&e.sourceKeyPrefixes.set(d,u)})}let o=new Map;for(let s of t){let i=e.sourceKeyPrefixes.get(s);i&&!o.has(i)&&o.set(i,s)}return o}async keyPrefixesNamedBy(e,t){let n=new Set(e.graph.nodes.map(s=>s.objectApiName)),o=new Set;for(let s of t){let i=s.isReference?s.referenceTo??[]:[];if(!(i.length<2))for(let a of i)n.has(a)&&!e.keyPrefixesAsked.has(a)&&o.add(a)}if(o.size>0){for(let s of o)e.keyPrefixesAsked.add(s);await this.sourceKeyPrefixes(e,o)}return e.sourceKeyPrefixes}async excludedByKeyPrefix(e,t,n){let o=e.config.excludedObjects;if(o.size===0)return new Map;let s=new Set;for(let d of n){let c=d.isReference?d.referenceTo??[]:[];if(!(c.length<2||!Qe(t,d.name,d.nillable)))for(let u of c)o.has(u)&&s.add(u)}let i=new Set([...s].filter(d=>!e.keyPrefixesAsked.has(d)));if(i.size>0){for(let d of i)e.keyPrefixesAsked.add(d);await this.sourceKeyPrefixes(e,i)}let a=new Map;for(let d of s){let c=e.sourceKeyPrefixes.get(d);c&&!a.has(c)&&a.set(c,d)}return a}async objectOfSourceId(e,t,n){let o=t.slice(0,3),s=n.find(u=>e.sourceKeyPrefixes.get(u)===o);if(s)return s;let i=new Set(e.graph.nodes.map(u=>u.objectApiName)),a=n.filter(u=>!e.sourceKeyPrefixes.has(u)),d=a.filter(u=>!i.has(u)),c=[a.filter(u=>i.has(u))];for(let u=0;u<d.length;u+=6)c.push(d.slice(u,u+6));for(let u of c){let l=(await this.sourceKeyPrefixes(e,new Set(u))).get(o);if(l)return l}}writeOrderOf(e){return this.orderByFields(e,new Map([...e.preread].map(([t,n])=>[t,n.fieldInfos])))}orderByFields(e,t){let n=e.parentsOutside.size>0?{...e.graph,nodes:[...e.graph.nodes,...e.parentsOutside.values()]}:e.graph,o=new Set(n.nodes.filter(c=>c.included).map(c=>c.objectApiName)),s=[],i=[];for(let[c,u]of t){Jm(u)&&i.push(c);for(let l of u)if(!(!l.isReference||!Tr(l)||!Qe(c,l.name,l.nillable)))for(let f of l.referenceTo??[])f===c||!o.has(f)||s.push({sourceObject:f,targetObject:c,relationshipName:l.name,type:"lookup",required:!0})}let a=Nl(o,i),d=t.get(et)?.some(c=>c.name===mt);return ra(ts(n,t),[...s,...a,...d?Mf(o,i,[...s,...a]):[],...Ti(o),...ji(o,t),..._f(o,t),...xi(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>gt(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(Se)&&o.has(ce)&&(await Promise.allSettled([Se,ce].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([Se,ce][d],a.value)}),ra(ts(e.graph,s),[...Ti(o),...ji(o,s),...xi(o)])}let n=new Map;for(let o=0;o<t.length&&!this.isAborted;o+=6){let s=t.slice(o,o+6);(await Promise.allSettled(s.map(a=>this.deps.describeFields(e.sourceOrgId,a.objectApiName)))).forEach((a,d)=>{a.status==="fulfilled"&&n.set(s[d].objectApiName,a.value)})}return this.orderByFields(e,n)}async withWhatStatusesNeed(e,t,n){let o=new Set(e.nodes.map(d=>d.objectApiName)),s=new Map,i=[],a=[];for(let d of e.nodes){if(this.isAborted)break;let c=Ar[d.objectApiName];if(!d.included||!c||o.has(c.object)||s.has(c.object)||n.has(c.object))continue;let u;try{u=await this.deps.describeFields(t,c.object)}catch{continue}let l=u.find(f=>f.name===c.lookup&&f.isReference&&(f.referenceTo??[]).includes(d.objectApiName));l&&(s.set(c.object,{parent:d.objectApiName,lookup:c.lookup}),i.push(Ur(c.object,u,d.level+1)),a.push({sourceObject:d.objectApiName,targetObject:c.object,relationshipName:l.name,type:"lookup",required:Qe(c.object,l.name,l.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...a]},added:s}}async withWhatItsRecordsComeWith(e,t,n){let o=new Set(e.nodes.map(a=>a.objectApiName)),s=[],i=[];for(let a of e.nodes){if(this.isAborted)break;let d=zm[a.objectApiName];if(!a.included||!d||o.has(d.object)||n.has(d.object))continue;let c;try{c=await this.deps.describeFields(t,d.object)}catch{continue}let u=c.find(l=>l.name===d.lookup&&l.isReference&&(l.referenceTo??[]).includes(a.objectApiName));u&&(o.add(d.object),s.push(Ur(d.object,c,a.level+1)),i.push({sourceObject:a.objectApiName,targetObject:d.object,relationshipName:u.name,type:"lookup",required:Qe(d.object,u.name,u.nillable)}))}return s.length===0?e:{...e,nodes:[...e.nodes,...s],edges:[...e.edges,...i]}}async withTheCatalogItNeeds(e,t,n){let o=Il(e,n);if(o.size===0)return e;let s=new Set(e.edges.map(u=>`${u.sourceObject}|${u.targetObject}`)),i=new Map,a=new Map,d=[],c=e.nodes.filter(u=>u.included);for(;c.length>0&&!this.isAborted;){let u=[];for(let l=0;l<c.length&&!this.isAborted;l+=6){let f=c.slice(l,l+6);(await Promise.allSettled(f.map(({objectApiName:g})=>this.deps.describeFields(t,g)))).forEach((g,h)=>{if(g.status!=="fulfilled")return;let{objectApiName:m,level:R}=f[h];a.set(m,g.value);for(let b of g.value){let k=b.referenceTo??[];if(!b.isReference||k.length!==1)continue;let[O]=k;O===m||!(o.has(O)||i.has(O))||El(m,b)&&(o.delete(O)&&(i.set(O,R+1),u.push({objectApiName:O,level:R+1})),!s.has(`${O}|${m}`)&&(s.add(`${O}|${m}`),d.push({sourceObject:O,targetObject:m,relationshipName:b.name,type:"lookup",required:Qe(m,b.name,b.nillable)})))}})}c=u}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([u,l])=>Ur(u,a.get(u)??[],l))],edges:[...e.edges,...d]}}async withSellingModelOptions(e,t,n){let o=u=>e.nodes.find(l=>l.included&&l.objectApiName===u),s=o(Zo),i=o(jr);if(!o(et)||!s||!i||n.has(Gt)||e.nodes.some(u=>u.objectApiName===Gt))return e;let a;try{a=await this.deps.describeFields(t,Gt)}catch{return e}let d=Ur(Gt,a,Math.max(s.level,i.level)+1),c=(u,l)=>({sourceObject:u,targetObject:Gt,relationshipName:l,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(Zo,"Product2Id"),c(jr,"ProductSellingModelId")]}}summaryOf(e){let t=this.deps.requestsSent?.(),{simulated:n}=e,o=e.config.stream?.summaryBound;if(e.store&&o!==void 0&&e.remapper.count>o)return this.summaryOfTheJournal(e,t);let s=e.remapper.toJSON();if(n)for(let[c,u]of Object.entries(s))n.has(u)&&delete s[c];let i=c=>c in s,a=Gh(e),d=[...e.mayHaveBeenWritten].map(([c,u])=>({objectApiName:c,sourceIds:[...u]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0&&!n?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...kw(e),...yw(e),...Ew(e),...Iw(e),...Pw(e),...Gw(e)],truncatedObjects:[...e.truncatedObjects],...jh(e),...e.fieldExclusionsUnmatched.length>0?{fieldExclusionsUnmatched:[...e.fieldExclusionsUnmatched]}:{},...ow(e),remapTable:s,existingRecords:[...e.existingRecords],existingSourceIds:e.remapper.existingSourceIds().filter(i),updatedSourceIds:e.remapper.updatedSourceIds().filter(i),...a.length>0&&!n?{withTheirRecordSourceIds:a}:{},...e.writtenByThePlatform.size>0?{writtenByThePlatform:[...e.writtenByThePlatform].map(([c,u])=>({objectApiName:c,rows:u}))}:{},...e.leftEmptyByFilter.size>0&&!n?{lookupsLeftEmptyByFilter:[...e.leftEmptyByFilter].flatMap(([c,u])=>[...u].map(([l,{records:f,ids:p}])=>({objectApiName:c,field:l,records:f,recordIds:[...p]})))}:{},remapByObject:n?[]:e.remapper.countsByObject(),...e.notSent.size>0?{notSentByObject:[...e.notSent].map(([c,u])=>({objectApiName:c,notSent:u}))}:{},createdByObject:n?[]:e.remapper.createdByObject(),readByObject:[...e.readByObject].map(([c,u])=>({objectApiName:c,read:u,...this.originOf(e,c,u)})),failedReads:[...e.failedReads],...e.files?{files:structuredClone(e.files)}:{},...e.fileContentFieldsLeftOut.size>0?{fileContentFieldsLeftOut:[...e.fileContentFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.encryptedFieldsLeftOut.size>0?{encryptedFieldsLeftOut:[...e.encryptedFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.picklistChanges.size>0?{picklistValuesChanged:e.picklistChanges.list()}:{},...e.currencyChanges.size>0?{currenciesReplaced:e.currencyChanges.list()}:{},...e.recordTypesGiven.size>0?{recordTypesGiven:[...e.recordTypesGiven].map(([c,u])=>Yw(c,u))}:{},...e.writtenWithoutFields.size>0?{writtenWithoutFields:[...e.writtenWithoutFields].map(([c,{rows:u,fields:l}])=>({objectApiName:c,rows:u,fields:l.map(f=>({...f}))}))}:{},contactPoints:e.contactPoints?e.contactPoints.report():{neutralized:!1,fields:[],values:0},...e.writtenBetween?{writtenBetween:{...e.writtenBetween}}:{},...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},...n?{dryRun:!0}:{},...e.gaps?{gaps:e.gaps.list(e.config.decisions.ignoredGaps)}:{},...e.decisionsApplied.size>0?{decisionsApplied:e.decisionsApplied.list()}:{},...d.length>0?{mayHaveBeenWritten:d}:{},...ey(this.sampleResultOf(e)),...e.roots?{roots:this.rootsResultOf(e,e.roots)}:{},...e.roots&&e.readRequests!==void 0?{reads:{source:e.readRequests}}:{}}}originOf(e,t,n){let o=e.roots;if(!o)return{};let s=t===e.config.rootObjectApiName,i=0;if(s)for(let u of o.ids)e.idsRead.has(u)&&i++;i=Math.min(i,n);let a=0;for(let u of e.scopeCache?.reachedOf(t)??[])s&&o.ids.has(u)||a++;let d=Math.min(a,n-i),c=e.readUnder.get(t);return{origin:{roots:i,under:d,named:n-i-d},...c&&c.size>0?{readUnder:[...c]}:{}}}rootsResultOf(e,t){let n=[],o=[],s=0,i=0,a=0,d=e.errors.find(m=>m.objectApiName===t.objectApiName)?.samples.flatMap(m=>m.messages)[0]??"not written",c=new Set(e.remapper.updatedSourceIds()),u=new Set(Gh(e)),l=new Map((e.preread.get(t.objectApiName)?.records??[]).map(m=>[String(m.Id),m])),f=m=>{let R=l.get(m);return e.simulated!==null&&t.objectApiName===ce&&R!==void 0&&rn(R)&&!e.contactsOnTheirOwn.has(m)&&typeof R.AccountId=="string"&&e.remapper.wasCreated(R.AccountId)},p=0,g=[],h=(m,R)=>{if(g.length>=bn)return;let b=R&&e.simulated===null?e.remapper.get(m):void 0;g.push(b!==void 0?{source:m,target:b}:{source:m})};for(let m of t.ids){if(!e.idsRead.has(m)){n.push(m),h(m,!1);continue}s++,e.remapper.wasCreated(m)||c.has(m)?(i++,h(m,!0)):u.has(m)||f(m)?(i++,p++,h(m,!0)):e.remapper.isExisting(m)?(a++,h(m,!0)):(o.push({id:m,reason:d}),h(m,!1))}return{objectApiName:t.objectApiName,from:t.from,...t.query?{query:{...t.query}}:{},cap:t.cap,asked:t.ids.size,read:s,gone:n,written:i,linked:a,failed:o,sha256:t.sha256,readAt:t.readAt,...t.readAgain?{readAgain:{...t.readAgain}}:{},...p>0?{withTheirAccount:p}:{},ids:g,...t.ids.size>g.length?{idsLeftOut:t.ids.size-g.length}:{},...t.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}summaryOfTheJournal(e,t){let n=this.summaryOf({...e,config:{...e.config,stream:e.config.stream&&{...e.config.stream,summaryBound:void 0}},remapper:new qr,store:void 0,withTheirRecord:new Set,linkedToCreatedCount:0}),o=e.store?.withTheirRecordCount??0,s=e.store?.linkedToCreatedCount()??0;return{...n,remapCount:e.remapper.count,...o>0?{withTheirRecordCount:o}:{},...s>0?{linkedToCreatedCount:s}:{},remapByObject:e.remapper.countsByObject(),...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},remapInJournal:!0}}async prepareFiles(e){let{config:t,onProgress:n}=e,o=t.files,s=this.fileCopyDeps();if(!o||!s)return[];let i=await Yf({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=Xf(i);if(a&&!t.dryRun)throw new jn(`${a} Nothing was written.`,"FILES_UNREAD");e.errors.push(...i.errors);let d=await this.filesCopiedBefore(e,i.files,s),c={...i,files:d.filter(p=>p.into?.unchanged!==!0)},u;if(c.files.length>0)try{u=await np(s,e.targetOrgId)}catch(p){let g=`The file storage the target has left could not be read (${V(p)}), so the files could not be checked against it.`;if(!t.dryRun)throw new jn(`${g} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(qa(g))}e.files=rp(c,o.maxFileBytes,u),a&&(e.files.lookupFailure=a);let l=ep(c.files),f=u===void 0?null:tp(l,u);if(f&&u!==void 0&&!t.dryRun)throw new jn(`${f} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:l,remainingBytes:u});if(f&&e.errors.push(qa(f)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:p,sourceId:g,name:h,bytes:m})=>({objectApiName:p,sourceId:g,name:h,bytes:m}));for(let p of e.files.objects)n({objectName:p.objectApiName,status:"done",progress:100,message:op(p)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await Zf({files:t,targetOrgId:e.targetOrgId,copiedBefore:i=>{let a=o.mapping(i);return a?.earlier&&a.kind==="created"&&a.objectApiName?{objectApiName:a.objectApiName,targetId:a.targetId}:void 0},queryRecords:n.queryRecords});return e.errors.push(...s.errors),s.files}async writeFiles(e,t){let n=this.fileCopyDeps();if(!n||!e.files)return;let{remapper:o}=e;e.failedCount+=await Ua({files:t,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:s=>o.wasCreated(s),get:s=>o.get(s),add:(s,i,a)=>o.add(s,i,a),persist:()=>o.persist()},deps:n,report:e.files,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:e.onProgress,...e.store?{calls:Es(e.store)}:{}})}async copyFilesOfTheOrg(e,t){let n=this.fileCopyDeps();if(!n)return;e.files??={maxFileBytes:t,objects:[],links:0,leftOut:[]};let o=e.files,s=0,i=(d,c)=>e.onProgress({objectName:d,status:"running",progress:50,message:c}),a=e.config.stream?.pageSize??Cw;for(let d of Sd){let{counted:c}=d,u=e.config.stream?.resumeAfter.get(zo(c,zh));if(u?.done)continue;let f=`SELECT ${d.object==="ContentVersion"?"Id, ContentDocumentId, Title, PathOnClient, ContentSize, SharingPrivacy":"Id, ParentId, Name, ContentType, BodyLength, IsPrivate"} FROM ${d.object} WHERE `+[d.where,`${d.size} <= ${t}`].filter(Boolean).join(" AND "),p=u?.read??0,g=u&&Ft.test(u.lastId)?u.lastId:void 0;for(let h=!1;!h;){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,f,g,a);if(!m)break;h=m.length<a;let R=!0;for(let k=0;k<m.length;k+=kd){let O=m.slice(k,k+kd),w=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,O):Mw(e,O);if(!w){R=!1;break}if(w.length===0)continue;let A=await this.filesCopiedBefore(e,w,n);for(let v of A){if(v.into?.unchanged)continue;let j=Hh(o,v.objectApiName);j.planned++,j.plannedBytes+=v.bytes}s+=A.filter(v=>v.into?.unchanged).length,e.failedCount+=await Ua({files:A,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:v=>e.remapper.wasCreated(v),get:v=>e.remapper.get(v),add:(v,j,F)=>e.remapper.add(v,j,F),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:Es(e.store)}:{}});let S=Hh(o,c);i(c,`Copying files: ${S.copied} of ${S.planned} copied so far`)}if(!R)break;p+=m.length;let b=m[m.length-1]?.Id;typeof b=="string"&&(g=b),g!==void 0&&e.store?.checkpoint(c,{lastId:g,read:p,...h?{done:!0}:{}},zh)}}for(let d of o.objects){let c=d.objectApiName==="Attachment"?"attachment":"file";e.onProgress({objectName:d.objectApiName,status:d.failed>0&&d.copied===0?"error":"done",progress:100,message:`Copied ${d.copied} ${c}${d.copied===1?"":"s"} of ${d.planned}`+(d.failed>0?`, ${d.failed} failed`:"")})}s>0&&Ye.info(`[forge] ${s} file(s) copied by the run this one takes up: linked to the records they lacked`)}async filesPageAfter(e,t,n,o,s){let i=n+(o?` AND Id > '${o}'`:"")+` ORDER BY Id LIMIT ${s}`;try{return await this.readOnPassingFailure(t,()=>this.deps.queryRecords(e.sourceOrgId,i))}catch(a){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:o?`(files after ${o})`:"(files)",messages:[`Not read, so not copied \u2014 a run taken up reads them again: ${V(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=Kh(o);if(!s&&!Vh(o)||n>=ld||this.isAborted)throw o;s||await Jh(Rh*2**n),Ye.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${ld}): ${V(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&Ft.test(c)&&n.set(c,d)}if(n.size===0)return[];let o=new Map,s=d=>{e.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(links of ${n.size} files)`,messages:[d]}]})},i=!1;try{let d=await this.readOnPassingFailure("ContentDocumentLink",()=>this.deps.queryRecords(e.sourceOrgId,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE ContentDocumentId IN (${[...n.keys()].map(c=>`'${c}'`).join(", ")})`,()=>i=!0));for(let c of d){let u=c.ContentDocumentId,l=c.LinkedEntityId;if(typeof u!="string"||typeof l!="string"||!e.remapper.wasCreated(l))continue;let f=o.get(u)??[];if(f.some(h=>h.id===l))continue;let p=c.ShareType,g=c.Visibility;f.push({id:l,...typeof p=="string"?{shareType:p}:{},...typeof g=="string"?{visibility:g}:{}}),o.set(u,f)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${V(d)}`);return}i&&s("More links than the source reads at once: the files were copied onto the records of the run among those read, and may lack a link to the others.");let a=[];for(let[d,c]of o){let u=n.get(d),l=u?.Id;if(!u||typeof l!="string")continue;let f=u.Title,p=typeof f=="string"&&f!==""?f:d,g=u.PathOnClient,h=u.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:l},name:p,bytes:typeof h=="number"&&Number.isFinite(h)?h:0,hosts:c,fields:{Title:p,PathOnClient:typeof g=="string"&&g!==""?g:p,...u.SharingPrivacy==="P"?{SharingPrivacy:"P"}:{}}})}return a}async readInTurn(e,t){t.turnsAhead.delete(e.objectApiName),await this.readNode(e,t,!0,!1),![...t.waitingFor.values()].some(o=>o.includes(e))&&(await this.readUnderWhatWaited(e.objectApiName,t,"at its turn"),await this.endTurn(e.objectApiName,t))}async readUnderWhatWaited(e,t,n){let o=t.scopeCache,s=t.readAgainUnder.get(e);if(!(!o||!s||!o.isRead(e))){t.readAgainUnder.delete(e);for(let{node:i,fieldInfos:a,whileWaiting:d}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");t.failedObjects.has(i.objectApiName)||n==="at its turn"&&!d||n==="after the catalog"&&!d&&!sg(i.objectApiName,a).includes(e)||await this.readAgainUnderRowsOf(t,i,[...a],e)&&await this.readUnderRowsAdded(i.objectApiName,t,1)}}}async readAgainUnderRowsOf(e,t,n,o){let s=on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:e.config.objectSoqlFilters?.[t.objectApiName],fieldsLeftOut:e.config.fieldExclusions[t.objectApiName],readObjects:e.readObjects,catalog:Ke,under:new Set([o])});return s.kind!=="query"?!1:(await this.readMore(e,t,n,s.statements,`under the ${o} records read after it`)).length>0}async readUnderRowsAdded(e,t,n){let o=t.scopeCache;if(!o||n>=Xm)return;let{config:s}=t,i=new Set(t.graph.edges.filter(a=>a.sourceObject===e&&a.targetObject!==e).map(a=>a.targetObject));for(let a of t.graph.nodes){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(!a.included||!i.has(d)||!o.isRead(d)||d===s.rootObjectApiName||Ke.has(d)||s.referenceDataObjects.has(d)||t.failedObjects.has(d)||t.notCreatable.has(d))continue;let c=await this.fieldsReadAgain(t,a);!c||!await this.readAgainUnderRowsOf(t,a,c.fields,e)||(c.described&&this.withoutFileContent(t,d,c.described,!0),await this.readUnderRowsAdded(d,t,n+1))}}async readWhatTheyCannotBeWrittenWithout(e,t,n,o){let s=e.scopeCache;if(!s||o.length===0)return;let{config:i}=e,a=new Set(i.fieldExclusions[t]??[]),d=new Map;for(let c of n){let u=c.referenceTo??[];if(!c.isReference||u.length!==1||a.has(c.name)||!Tr(c)||!Qe(t,c.name,c.nillable))continue;let[l]=u;if(l===t||l===i.rootObjectApiName||Ke.has(l)||i.referenceDataObjects.has(l)||!e.readObjects.has(l)||e.failedObjects.has(l)||e.notCreatable.has(l)||!s.isRead(l))continue;let f=s.scopeOf(l),p=e.askedForRowsThatNeedThem.get(l),g=e.heldForExclusions.get(l);for(let h of o){let m=h[c.name];typeof m!="string"||m===""||f?.has(m)||p?.has(m)||g?.has(m)||e.remapper.get(m)||e.leftToThePlatform.has(m)||d.set(l,(d.get(l)??new Set).add(m))}}for(let[c,u]of d){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let l=e.graph.nodes.find(m=>m.included&&m.objectApiName===c);if(!l)continue;let f=e.askedForRowsThatNeedThem.get(c)??new Set;for(let m of u)f.add(m);e.askedForRowsThatNeedThem.set(c,f);let p=await this.fieldsReadAgain(e,l);if(!p)continue;let g=zt(p.fields,i.fieldExclusions[c]);(await this.readMore(e,l,p.fields,new Sn().buildById({objectApiName:c,selectFields:g.length>0?g:["Id"],ids:u,extraWhere:i.objectSoqlFilters?.[c]}),`which the ${t} records read after it cannot be written without`)).length!==0&&(p.described&&this.withoutFileContent(e,c,p.described,!0),await this.readUnderRowsAdded(c,e,0))}}async readParentsOutsideTheGraph(e){let{config:t}=e;if(!e.scopeCache||t.referenceFallback!=="nullify")return!1;let n=new Map(e.graph.nodes.map(d=>[d.objectApiName,d])),o=new Map,s=new Map,i=!1,a=[...e.preread].filter(([d])=>!e.failedObjects.has(d)).map(([d,c])=>({objectApiName:d,fieldInfos:c.fieldInfos,records:c.records}));for(let d=0;d<ew&&a.length>0;d++){let c=this.parentsWanted(e,a,d>0,n);c.size>0&&(i=!0);let u=[];for(let[f,p]of c){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let g=await this.refusalOf(e,f,n.get(f),o);g?await this.holdBackForARefusedParent(e,f,g,p,s):u.push([f,p])}let l=[];for(let[f,p]of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let g=tw(e,p);if(g.ids.size===0)continue;let h=await this.readParentsById(e,f,n.get(f),g);h&&l.push(h)}a=l}return i}parentsWanted(e,t,n,o){let{config:s}=e,i=new Map,a=new Map,d=c=>{let u=a.get(c);return u||(u=new Set((e.preread.get(c)?.records??[]).flatMap(l=>typeof l.Id=="string"?[l.Id]:[])),a.set(c,u)),u};for(let{objectApiName:c,fieldInfos:u,records:l}of t){let f=new Set(s.fieldExclusions[c]??[]);for(let p of u){let g=p.referenceTo??[];if(!p.isReference||g.length!==1||f.has(p.name)||!Tr(p)||!Qe(c,p.name,p.nillable))continue;let[h]=g;if(h===c||h===s.rootObjectApiName||Ke.has(h)||s.referenceDataObjects.has(h)||s.excludedObjects.has(h)||vs(e,h))continue;let m=o.get(h);if(m&&(!n||!m.included||e.failedObjects.has(h)))continue;let R=e.askedForRowsThatNeedThem.get(h),b=e.heldForExclusions.get(h);for(let k of l){let O=k[p.name];if(typeof O!="string"||O===""||dn(s,k)||e.remapper.get(O)||e.leftToThePlatform.has(O)||R?.has(O)||b?.has(O)||d(h).has(O))continue;let w=i.get(h);w||(w={ids:new Set,neededBy:new Set,rows:[]},i.set(h,w)),w.ids.add(O),w.neededBy.add(c),w.rows.push({objectApiName:c,row:k,field:p.name})}}}return i}async refusalOf(e,t,n,o){if(n)return e.notInTarget.has(t)?"not-in-target":e.notCreatable.has(t)?"not-creatable":void 0;let s=o.get(t);if(s!==void 0)return s??void 0;let i,a=this.deps.isObjectCreatable;if(a)try{await a(e.targetOrgId,t)||(i="not-creatable")}catch(d){nr(d)?i="not-in-target":e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${d instanceof Error?d.message:String(d)}`]}]})}return o.set(t,i??null),i}async holdBackForARefusedParent(e,t,n,o,s){let i=new Map;for(let{objectApiName:a,row:d,field:c}of o.rows){let u=d.Id;if(typeof u!="string"||i.get(a)?.has(u)||!await this.carriesTheLookup(e,a,c,s))continue;let l=i.get(a)??new Map;l.set(u,{row:d,why:{field:c,excluded:t,target:n}}),i.set(a,l)}for(let[a,d]of i){let c=e.preread.get(a);if(!c)continue;let u=c.records.filter(l=>typeof l.Id!="string"||!d.has(l.Id));this.holdBackRowsRead(e,a,c,u,[...d].map(([l,{row:f,why:p}])=>({id:l,row:f,why:p})))}}async carriesTheLookup(e,t,n,o){if(e.config.fieldMappings[t]?.[n])return!0;let s=o.get(t);if(s===void 0){try{s=await an(this.deps.describeFields,e.targetOrgId,t)}catch{s=null}o.set(t,s)}return s===null||s.creatable.has(n)}async readParentsById(e,t,n,o){let{config:s}=e,i=[...o.neededBy].sort().join(", "),a=s.maxRecordsPerObject?Math.floor(s.maxRecordsPerObject):0,d=a>0?a-(e.readByObject.get(t)??0):0;if(a>0&&d<=0){o.ids.size>0&&e.cappedObjects.add(t);return}let c=e.preread.get(t),u,l;if(c)u=[...c.fieldInfos];else{try{l=await this.deps.describeFields(e.sourceOrgId,t)}catch(S){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(describe, for the ${i} records that cannot be written without its records)`,messages:[V(S)]}]});return}u=l.filter(S=>!xn(S))}let f=e.askedForRowsThatNeedThem.get(t)??new Set;for(let S of o.ids)f.add(S);e.askedForRowsThatNeedThem.set(t,f);let p=zt(u,s.fieldExclusions[t]),g=new Sn().buildById({objectApiName:t,selectFields:p.length>0?p:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]});this.holdTheRootsReading(e,t,g.length);let h;try{h=await Wr(d>0?oa(g,d,{byIdCount:g.length}):{kind:"query",statements:g,byIdCount:g.length},S=>this.deps.queryRecords(e.sourceOrgId,S,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(S){if(S instanceof be)throw S;e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(read by id, for the ${i} records that cannot be written without them)`,messages:[V(S)]}]});return}Gr(e,h);let m=new Set((c?.records??[]).flatMap(S=>typeof S.Id=="string"?[S.Id]:[])),R=h.filter(S=>typeof S.Id!="string"||!m.has(S.Id)),b=S=>(e.graph.nodes.find(v=>v.objectApiName===S)??e.parentsOutside.get(S))?.level??0,k=n??e.parentsOutside.get(t)??Ur(t,u,1+Math.max(0,...[...o.neededBy].map(b))),O=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,k,u,R,void 0,await this.excludedByKeyPrefix(e,t,u));let w=[...e.heldForExclusions.get(t)??[]].filter(([S])=>!O.has(S));if(this.leaveToThePlatform(e,t,R,u),R.length===0&&w.length===0)return;let A=c?.createableSet??new Set(u.filter(S=>S.createable).map(S=>S.name));if(R.length>0){e.preread.set(t,c?{...c,records:[...c.records,...R]}:{fieldInfos:u,createableSet:A,records:R,targetSetsPending:null}),l&&this.withoutFileContent(e,t,l,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,k),e.writtenObjects.add(t));let S=R.find(j=>typeof j.Id=="string")?.Id;typeof S=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,S.slice(0,3));let v=e.readAsParents.get(t)??{count:0,neededBy:new Set};v.count+=R.length;for(let j of o.neededBy)v.neededBy.add(j);e.readAsParents.set(t,v)}else if(!n){let S=e.heldForExclusions.get(t);S&&e.onProgress({objectName:t,status:"error",progress:100,message:zr(t,S,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+R.length+w.length),this.holdTheRootsRows(e,t),s.dryRun){let S=R.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,R,A):0,v=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${R.length-S} ${v}record(s) would be inserted`+(S>0?`, ${S} ${v}would be written by the platform with ${Qn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+Ns(Fs(w.map(([,j])=>j)),c!==void 0)})}return R.length>0?{objectApiName:t,fieldInfos:u,records:R}:void 0}async endTurn(e,t){t.turnsAhead.delete(e);let n=t.waitingFor.get(e);if(n){t.waitingFor.delete(e);for(let o of n){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.readInTurn(o,t)}}}async readNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,onProgress:d,remapper:c}=t;t.readAtItsTurn.delete(e.objectApiName);let u=t.cursors.get(e.objectApiName);try{(!u||u.taken===0)&&d({objectName:e.objectApiName,status:"scanning",progress:0,message:`Querying ${e.objectApiName} records...`});let l=u?.described??await this.deps.describeFields(i,e.objectApiName);u&&(u.described=l);let f=l.filter(E=>!xn(E)),p=new Set(f.filter(E=>E.createable).map(E=>E.name));if(await this.skipForFailedParent(e,t,f))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let E=Qm(e.objectApiName,f,t.turnsAhead);if(E)return t.waitingFor.set(E,[...t.waitingFor.get(E)??[],e]),!1}let g={node:e,edges:t.graph.edges,fieldInfos:f,scopedBuilder:t.scopedBuilder,scopeCache:t.scopeCache,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:t.roots?.ids,extraWhere:Bw(this.filterOf(t,e.objectApiName),u?.pass),fieldsLeftOut:s.fieldExclusions[e.objectApiName],maxRecordsPerObject:u?t.sample?.drawn.has(e.objectApiName)?void 0:this.pagedLimit(t,u):s.maxRecordsPerObject,...u?{inIdOrder:u.resumeAfter!==void 0?{afterId:u.resumeAfter}:{}}:{},readObjects:t.readObjects,catalog:Ke,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},h=on(g);if(n&&this.waitsForWhatPointsAtIt(e,h,t))return t.catalogNodes.push({node:e,fieldInfos:f}),!1;if(h.kind==="skip"){if(n&&h.reason===na)return t.deferredNodes.push(e),!1;let E=t.heldForExclusions.get(e.objectApiName);return E&&E.size>0?(t.readByObject.set(e.objectApiName,E.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,E,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${h.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let E=on({...g,maxRecordsPerObject:1}),_=E.kind==="query"?await Wr(E,ee=>this.deps.queryRecords(i,ee)):[];return this.reportNotCreatable(e,t,_.length>0),!1}if(this.holdTheRootsReading(t,e.objectApiName,h.statements.length),t.roots&&h.readUnder){let E=t.readUnder.get(e.objectApiName)??new Set;for(let _ of h.readUnder)E.add(_);t.readUnder.set(e.objectApiName,E)}let R=o&&!s.referenceDataObjects.has(e.objectApiName)?u?.targetSets??an(this.deps.describeFields,a,e.objectApiName).then(E=>({ok:!0,sets:E}),E=>({ok:!1,error:E})):null;u&&(u.targetSets=R);let b=t.scopeCache?new Set:void 0,k=u?E=>{let _=on({...g,maxRecordsPerObject:u.room===void 0?void 0:Math.max(1,u.room),inIdOrder:{afterId:E}});return _.kind==="query"&&_.statements.length===1?_.statements[0]:void 0}:void 0,O=await Wr(h,E=>u?this.nextPage(t,e,u,E,k):this.readWhole(t,e.objectApiName,E),b,()=>t.cappedObjects.add(e.objectApiName));if(u?.ended&&O.length===0&&u.taken>0)return!1;let w=u?.pass?O.filter(u.pass.keep):O;Gr(t,w),this.keepWhatStatusesNeed(t,e,w,b);let A=this.holdBackWhatExclusionsCost(t,e,f,w,b,await this.excludedByKeyPrefix(t,e.objectApiName,f));b&&t.scopeCache?.addReached(e.objectApiName,b);let S=w.find(E=>typeof E.Id=="string")?.Id;if(typeof S=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,S.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,w.length);let E=await t.referenceDataMapper.resolve(e.objectApiName,w,a);for(let _ of E.mappings)c.addExisting(_.sourceId,_.targetId);return E.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:E.unmatched.length,attemptedCount:w.length,referenceData:!0,samples:rw(e.objectApiName,E.unmatched)}),t.scopeCache&&Ml(t.scopeCache,e.objectApiName,w),t.linkedCount+=E.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${E.mappings.length} resolved, ${E.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,w,f),e.objectApiName===Ut&&t.standardPricebookId){let E=t.standardPricebookId,_=w.filter(ee=>ee.Id!==E);_.length!==w.length&&(w.length=0,w.push(..._))}let v=t.scopeCache;if(n&&v&&Ke.has(e.objectApiName))return rs(v,e.objectApiName,w,f,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),t.catalogNodes.push({node:e,fieldInfos:f}),t.readAtItsTurn.set(e.objectApiName,{records:w,fieldInfos:f}),!1;let j=t.heldForExclusions.get(e.objectApiName);if(A>0&&w.length===0&&j&&!u)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,j.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,j)}),!1;if(gt(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,w,f);let E=t.sample;if(E?.drawn.has(e.objectApiName)){let ee=w.filter(J=>this.inThePlan(E,e.objectApiName,String(J.Id)));w.length=0,w.push(...ee);let X=t.standardPricebookId,z=new Set(w.filter(J=>J[tn]===X).map(J=>Ad(J,t.sellingModels)));for(let J of w)J[tn]!==X&&(z.has(Ad(J,t.sellingModels))||E.withoutStandard.add(it(String(J.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,w,f);let _=await this.keptPrices(t,w);_.length!==w.length&&(w.length=0,w.push(..._))}t.scopeCache&&rs(t.scopeCache,e.objectApiName,w,f,{keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),await this.notePastDraft(t,e.objectApiName,w);let F=e.objectApiName===s.rootObjectApiName||Ke.has(e.objectApiName)?[]:Ym(e.objectApiName,f,t),B=new Set(n?[...t.waitingFor.values()].flat().map(E=>E.objectApiName):[]);for(let E of F){let _=t.readAgainUnder.get(E)??[];t.readAgainUnder.set(E,[..._,{node:e,fieldInfos:f,whileWaiting:B.has(E)}])}if(s.files&&s.stream?.everything!==!0){let E=w.flatMap(_=>typeof _.Id=="string"&&!s.writtenBefore.retried(_.Id)?[_.Id]:[]);t.fileScope.set(e.objectApiName,E)}if(this.withoutFileContent(t,e.objectApiName,l,w.length>0),u&&(u.carry.rows+=w.length),u?.pass||t.readByObject.set(e.objectApiName,(u?u.carry.rows:w.length)+(j?.size??0)),this.holdTheRootsRows(t,e.objectApiName),t.preread.set(e.objectApiName,{fieldInfos:f,createableSet:p,records:w,targetSetsPending:R}),s.dryRun){let E=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,w,p),_=w.length-E;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${_} record(s) would be inserted`+(E>0?`, ${E} would be written by the platform with ${Qn(e.objectApiName)}`:"")+Ch(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,f,w),!0}catch(l){if(l instanceof be||l instanceof Cs||Ta(l))throw l;if(t.notCreatable.has(e.objectApiName))return this.reportNotCreatable(e,t,!0),!1;t.failedObjects.add(e.objectApiName),t.failedReads.add(e.objectApiName),u&&(u.failed=!0);let f=s.isScoped?0:Math.max(0,Sh(e,s.maxRecordsPerObject)-(u?.read??0));return t.failedCount+=f,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:f,attemptedCount:f,samples:[{recordSummary:"(stage failed before insert)",messages:[V(l)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(l)}`}),!1}}holdBackWhatExclusionsCost(e,t,n,o,s,i){let a=e.config.excludedObjects;if(a.size===0)return 0;let d=t.objectApiName,c=n.filter(O=>O.isReference&&Qe(d,O.name,O.nillable)),u=c.filter(O=>{let w=O.referenceTo??[];return w.length===1&&w[0]!==d&&a.has(w[0])}),l=c.filter(O=>{let w=O.referenceTo??[];return w.length>1&&w.some(A=>a.has(A))}),f=d===et&&e.sellingModels&&a.has(Gt),p=Dh(d),g=c.length>0&&e.heldForExclusions.size>0;if(u.length===0&&l.length===0&&!g&&!f&&!p)return 0;let h=O=>{for(let S of u){let v=O[S.name];if(typeof v=="string"&&v!==""&&!e.remapper.get(v))return{field:S.name,excluded:(S.referenceTo??[])[0]}}for(let S of l){let v=O[S.name];if(typeof v!="string"||v===""||e.remapper.get(v))continue;let j=i.get(v.slice(0,3));if(j!==void 0&&(S.referenceTo??[]).includes(j))return{field:S.name,excluded:j}}let w=g?Mh(e,O,c):void 0;if(w)return w;let A=O[Hn];if(f&&typeof A=="string"&&A!=="")return{field:Hn,excluded:Gt}},m=e.heldForExclusions.get(d)??new Map,R=p?e.statusChildrenRead.get(p.parent)??{kept:new Set,held:new Map}:void 0,b=[];for(let O of o){let w=h(O),A=p?O[p.lookup]:void 0;if(!w){b.push(O),R&&typeof A=="string"&&R.kept.add(A);continue}R&&typeof A=="string"&&!R.held.has(A)&&R.held.set(A,w);let S=O.Id;typeof S=="string"&&(s?.delete(S),!m.has(S)&&(m.set(S,w),e.failedCount++))}R&&p&&e.statusChildrenRead.set(p.parent,R),m.size>0&&e.heldForExclusions.set(d,m);let k=o.length-b.length;return k>0&&(o.length=0,o.push(...b)),k}holdBackWhatHeldRowsCost(e){let{config:t}=e;if(e.heldForExclusions.size!==0)for(let n=!0;n&&!this.isAborted;){n=!1;for(let[o,s]of[...e.preread]){let i=s.fieldInfos.filter(c=>c.isReference&&Qe(o,c.name,c.nillable));if(i.length===0)continue;let a=[],d=[];for(let c of s.records){let u=c.Id,l=typeof u=="string"&&!dn(t,c)?Mh(e,c,i):void 0;typeof u=="string"&&l?d.push({id:u,row:c,why:l}):a.push(c)}d.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,a,d))}}}holdBackWhatOnlyRowsHeldBackName(e){if(!e.scopeCache||e.namedByRowsHeldBack.size===0)return!1;let t=Lh(e),n=!1;for(let[o,s]of[...e.preread]){if(!Ke.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,u=typeof c=="string"?Wh(e,o,c,t):void 0;typeof c=="string"&&u?a.push({id:c,row:d,why:u}):i.push(d)}a.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,i,a))}return n}leaveOutWhatOnlyRowsHeldBackName(e,t){let n=e.scopeCache,o=n?.get(t);if(!n||!o||o.size===0||e.namedByRowsHeldBack.size===0)return;let s=Lh(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=Wh(e,t,d,s);c&&(a.push(d),!i.has(d)&&(i.set(d,c),e.failedCount++))}a.length!==0&&(e.heldForExclusions.set(t,i),n.forget(t,a))}holdBackRowsRead(e,t,n,o,s){let{config:i,onProgress:a}=e,d=e.heldForExclusions.get(t)??new Map;for(let{id:f,why:p}of s)d.set(f,p);e.heldForExclusions.set(t,d),e.failedCount+=s.length;let c=n.fieldInfos.filter(f=>f.isReference);for(let{row:f,why:p}of s)for(let g of c){let h=f[g.name];typeof h!="string"||h===""||e.namedByRowsHeldBack.has(h)||e.namedByRowsHeldBack.set(h,{field:g.name,excluded:p.excluded,namedBy:t})}let u=new Set(s.map(({id:f})=>f)),l=e.fileScope.get(t)??[];if(l.length>0&&e.fileScope.set(t,l.filter(f=>!u.has(f))),this.noteStatusRowsHeld(e,t,o,s),i.dryRun&&a({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${s.length} fewer would be inserted`+Ns(Fs(s.map(({why:f})=>f)))}),o.length>0){e.preread.set(t,{...n,records:o});return}e.preread.delete(t),e.failedObjects.add(t),a({objectName:t,status:"error",progress:100,message:zr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=Dh(t);if(!s)return;let i=e.statusChildrenRead.get(s.parent),a=new Map(i?.held??[]);for(let{row:c,why:u}of o){let l=c[s.lookup];typeof l=="string"&&!a.has(l)&&a.set(l,u)}let d=new Set;for(let c of n){let u=c[s.lookup];typeof u=="string"&&d.add(u)}e.statusChildrenRead.set(s.parent,{kept:d,held:a})}keepWhatStatusesNeed(e,t,n,o){let s=e.statusChildren.get(t.objectApiName);if(!s)return;let i=e.pastDraft.get(s.parent),a=[];for(let d of n){let c=d[s.lookup];typeof c=="string"&&i?.has(c)===!0?a.push(d):typeof d.Id=="string"&&o?.delete(d.Id)}a.length!==n.length&&(n.length=0,n.push(...a))}leaveToThePlatform(e,t,n,o){let s=e.leftToThePlatform.keep(t,n,$w(t,o)),i=n.length-s.length;return i>0&&(n.length=0,n.push(...s)),i}leaveWhatHangsFromThePlatform(e,t,n,o){let s=[...o],i=this.leaveToThePlatform(e,t.objectApiName,s,n),a=e.readByObject.get(t.objectApiName);return i>0&&a!==void 0&&e.readByObject.set(t.objectApiName,a-i),s}holdEmailsForTheirTask(e,t){if(e.taskTurnOver||!e.graph.nodes.some(s=>s.included&&s.objectApiName===ut))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(ut)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)Oo(s)&&(n===void 0||n.has(String(s.ActivityId)))?e.emailsInTwoPasses?e.emailsLeftForTheirTask++:e.emailsAfterTheirTask.push(s):o.push(s);return o}async writeEmailsAfterTheirTask(e){if(e.emailsInTwoPasses){await this.streamEmailsAfterTheirTask(e);return}e.taskTurnOver=!0;let t=e.emailsAfterTheirTask.splice(0,e.emailsAfterTheirTask.length),n=e.graph.nodes.find(o=>o.objectApiName===$e);n&&t.length>0&&!this.isAborted&&(e.emailsAllWaiting=void 0,await this.writeNode(n,e,t)),this.endBeforeTheEmailsThatWaited(e,t.length,this.isAborted)}async streamEmailsAfterTheirTask(e){if(e.taskTurnOver)return;e.taskTurnOver=!0;let t=e.emailsLeftForTheirTask;e.emailsLeftForTheirTask=0;let n=e.graph.nodes.find(u=>u.included&&u.objectApiName===$e),o=e.config.stream?.resumeAfter,s=o?.has($e)===!0||o?.has(zo($e,bh))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has($e)&&e.graph.nodes.some(u=>u.included&&u.objectApiName===ut))||this.isAborted){this.endBeforeTheEmailsThatWaited(e,t,this.isAborted);return}let a=e.emailsWrittenFirst!==void 0,d=e.config.dryRun?"Simulated":"Completed";try{await this.streamNode(n,e,{name:bh,where:"ActivityId != null",keep:u=>Oo(u),expected:t,stopped:`Stopped ${$e} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${$e} after their task`}})}catch(u){throw e.emailsWrittenFirst=void 0,u}let c=e.emailsWrittenFirst;c&&(e.emailsWrittenFirst=void 0,e.onProgress(c))}endBeforeTheEmailsThatWaited(e,t,n){let o=e.emailsWrittenFirst??e.emailsAllWaiting;e.emailsWrittenFirst=void 0,e.emailsAllWaiting=void 0,o&&(Od(e,$e,t),e.onProgress(Fw(o,t,n,Ch(e,$e))))}endOfTheEmails(e,t){return n=>{if(n.status!=="done"&&n.status!=="error"&&n.status!=="stopped"){e.onProgress(n);return}if(!t){if(e.emailsAfterTheirTask.length===0&&e.emailsLeftForTheirTask===0){e.onProgress(n);return}e.emailsWrittenFirst=n,e.onProgress({...n,status:"running"});return}let o=e.emailsWrittenFirst;e.emailsWrittenFirst=void 0,e.onProgress(o?{...n,status:o.status==="error"?"error":n.status,message:`${o.message}; ${n.message}`}:n)}}async linkTasksWrittenWithEmails(e,t){if(e.emailsInTwoPasses)return this.tasksLinkedBeforeTheirTurn(e,t);let n=new Map;for(let c of e.preread.get($e)?.records??[]){let u=c.ActivityId,l=c.Id;if(typeof u!="string"||u===""||typeof l!="string"||!e.remapper.isCreated(l))continue;let f=e.remapper.get(l);f&&n.set(u,f)}let o=[...new Set(t.flatMap(c=>n.get(String(c.Id))??[]))];if(o.length===0)return{rows:t,linked:0};let s,{simulated:i}=e;try{s=i?new Map(o.map(c=>[c,i.idFor(null)])):await Ai(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:ut,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(c)}`]}]}),{rows:t,linked:0}}let a=t.filter(c=>{let u=String(c.Id),l=n.get(u),f=l===void 0?void 0:s.get(l);return f===void 0?!0:(e.remapper.addExisting(u,f,ut),ur(e,u),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),cr(e,ut,d),{rows:a,linked:d}}tasksLinkedBeforeTheirTurn(e,t){let n=t.filter(s=>{let i=s.Id;return typeof i!="string"||e.remapper.get(i)===void 0}),o=t.length-n.length;return o>0&&(e.linkedCount+=o),cr(e,ut,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get($e)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||Oo(i)||!e.remapper.isCreated(d))continue;let c=e.remapper.get(d);c&&t.set(c,a)}if(t.size===0)return;let n=[...t.keys()],{simulated:o}=e,s;try{s=o?new Map(n.map(i=>[i,o.idFor(null)])):await Ai(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:ut,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(i)}`]}]});return}for(let[i,a]of s){let d=t.get(i);d===void 0||e.remapper.get(d)!==void 0||(e.remapper.addExisting(d,a,ut),ur(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!So(t)||n.length===0)return{rows:n,lookups:new Map,held:new Map,linked:0,owners:0,values:i};let{config:a,remapper:d,simulated:c}=e,u=$i[t],l=a.decisions.defaultOf(t,u),f=c?await this.writesAs(e):void 0,p=await Pi(t,n,{source:R=>this.deps.queryRecords(e.sourceOrgId,R),target:R=>this.deps.queryRecords(e.targetOrgId,R),targetIdOf:R=>d.get(R),mappedUser:R=>a.ownerMappings[R],...l!==void 0?{defaultUser:l}:{},written:s,...c?{simulated:{ownerOf:R=>a.ownerMappings[R]??(f??=c.idFor(rg)),idFor:()=>c.idFor(o)}}:{}});p.defaulted.size>0&&l!==void 0&&e.decisionsApplied.add({kind:"set_default",objectApiName:t,field:u,to:l},p.defaulted.size);for(let[,{field:R,parentObject:b}]of p.held)b==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:R,rows:1,detail:{type:"reference"},decisions:[...Eu.required_field_missing??[]]});let g=0,h=0;for(let[R,{id:b,owners:k,notKept:O,unread:w=[]}]of p.linked){let A=String(R.Id);d.addExisting(A,b,t),d.isCreated(String(R.OpportunityId))&&(ur(e,A),h++),k&&g++;for(let S of O)i.notKept.set(S,(i.notKept.get(S)??0)+1);for(let S of w)i.unread.set(S,(i.unread.get(S)??0)+1)}let m=p.linked.size;return m>0&&(e.linkedCount+=m),cr(e,t,h),m>h&&e.existingRecords.push({objectApiName:t,linked:m-h,unidentified:0}),{rows:m>0?n.filter(R=>!p.linked.has(R)):n,lookups:p.lookups,held:p.held,linked:m,owners:g,values:i}}async takeTheSyncCopies(e,t,n,o,s){let i={taken:0,given:0};if(!e.readsEverythingFirst)return i;let{remapper:a,simulated:d,config:c}=e,u=h=>a.wasCreated(h)||c.writtenBefore.has(h),l=[];if(t.forEach(({source:h},m)=>{let R=h[Wa],b=h[Da];if(typeof R!="string"||typeof b!="string"||!u(R)||!u(b))return;let k=a.get(R),O=a.get(b);k&&O&&l.push({index:m,quote:k,product:O})}),l.length===0)return i;let f=h=>s.updatable?s.updatable.has(h):s.fields?.find(m=>m.name===h)?.updateable!==!1,p;if(d)p=this.copiesASimulationFinds(e,t,l,s.keyPrefix);else{let h=k=>s.fields===void 0||s.fields.some(O=>O.name===k&&O.queryable!==!1),m=[...new Set(l.flatMap(({index:k})=>Object.keys(n[k]??{})))].filter(k=>f(k)&&h(k)),R;try{R=await qf(k=>this.deps.queryRecords(e.targetOrgId,k),l,m)}catch(k){return e.errors.push({objectApiName:rr,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(quote lines the platform copied from their opportunity products)",messages:[`Not looked up, so written as read: a quote that syncs with its opportunity may hold a line twice. ${V(k)}`]}]}),i}let b=new Set;for(let k of o){let O=a.get(String(k.Id));O&&b.add(O.slice(0,15))}p=Uf(l,R,b)}if(p.size===0)return i;let g=d?0:await this.giveTheCopiesTheirFields(e,t,n,p,f);for(let[h,m]of p){let R=t[h],b=typeof R.source.Id=="string"?R.source.Id:void 0,k=String(m.Id);b!==void 0&&a.add(b,k,rr),R.nullifiedFks.length>0&&this.oweToTheSecondPass(e,R.nullifiedFks.map(O=>({objectApiName:rr,newId:k,sourceId:b,fieldName:O.field,sourceRefId:O.sourceRefId,...O.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let h of[...p.keys()].sort((m,R)=>R-m))t.splice(h,1),n.splice(h,1);return{taken:p.size,given:g}}copiesASimulationFinds(e,t,n,o){let s=new Map,{simulated:i}=e;if(!i)return s;let a=l=>typeof l=="string"&&l!==""?l.slice(0,15):void 0,d=new Map;for(let l of e.pendingFkUpdates){let f=a(l.sourceId),p=a(l.sourceRefId);l.objectApiName===We&&l.fieldName===ys&&f&&p&&d.set(f,p)}if(d.size===0)return s;let c=new Map;for(let l of e.preread.get(Df)?.records??[]){let f=a(l.Id),p=a(l.OpportunityId);f&&p&&c.set(f,p)}let u=new Set;for(let{index:l}of n){let{source:f}=t[l],p=a(f[Da]),g=a(f[Wa]),h=p?c.get(p):void 0;!p||!g||!h||d.get(h)!==g||u.has(p)||(u.add(p),s.set(l,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:rr,recordSummary:"(quote lines the platform copied from their opportunity products)",leftAs:"Taken, and left as the platform copied them, without the fields of the source's lines"}){let a=[];for(let[l,f]of o){let p=new Set(t[l].nullifiedFks.map(h=>h.field)),g=Gf(n[l]??{},f,s,p);Object.keys(g).length>0&&a.push({Id:f.Id,...g})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],u=0;for(let l=0;l<a.length;l+=Xh){let f=a.slice(l,l+Xh);if(!d||this.isAborted){c.push(`${f.length} not sent: ${d?"the run was cancelled first":"the run sends no update"}`);continue}try{let p=await d(e.targetOrgId,i.objectApiName,f);f.forEach((g,h)=>{let m=p[h];m?.success?u++:c.push(`${String(g.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(p){c.push(`${f.length} not updated: ${V(p)}`)}}return c.length>0&&e.errors.push({objectApiName:i.objectApiName,stage:"insert",failedCount:0,attemptedCount:a.length,samples:[{recordSummary:i.recordSummary,messages:[`${i.leftAs}: ${c.slice(0,3).join(" | ")}`]}]}),u}async linkTheRolesThePlatformWrote(e,t,n,o){let s={linked:0,given:0};if(t.length===0)return s;let{remapper:i,simulated:a,config:d}=e,c=new Map;if(d.writtenBefore.size>0&&t.forEach(({source:R},b)=>{let k=R.OpportunityId,O=n[b]?.[Le];typeof k!="string"||typeof O!="string"||O===""||vi(R)&&d.writtenBefore.has(k)&&c.set(k,O)}),e.contactSentWith.size===0&&c.size===0)return s;let u=Ir(t.map(({source:R},b)=>({OpportunityId:R.OpportunityId,[Le]:n[b]?.[Le],IsPrimary:R.IsPrimary})),R=>i.isCreated(R)?e.contactSentWith.get(R):c.get(R));if(u.length===0)return s;let l=R=>o.updatable?o.updatable.has(R):o.fields?.find(b=>b.name===R)?.updateable!==!1,f=a?u.filter(R=>i.isCreated(String(t[R].source.OpportunityId))):[],p=u.filter(R=>!f.includes(R)),g=new Map(f.map(R=>[R,{Id:a?.idFor(o.keyPrefix)??""}]));if(p.length>0){let R=S=>o.fields===void 0||o.fields.some(v=>v.name===S&&v.queryable!==!1),b=a?[]:[...new Set(p.flatMap(S=>Object.keys(n[S]??{})))].filter(S=>l(S)&&R(S)),k=new Map(p.map(S=>[S,{opportunity:String(i.get(String(t[S].source.OpportunityId))),contact:String(n[S]?.[Le])}])),O;try{O=await Ei(S=>this.deps.queryRecords(e.targetOrgId,S),[...new Set([...k.values()].map(({opportunity:S})=>S))],b)}catch(S){e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[`Not looked up, so written as read: an opportunity may hold the role of its contact twice. ${V(S)}`]}]}),O=[]}let{found:w,alike:A}=Ii(k,O);for(let[S,v]of w)g.set(S,v);if(A.length>0){for(let S of A)e.contactSentWith.delete(String(t[S].source.OpportunityId));e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[Zc(A.length)]}]})}}if(g.size===0)return s;let h=a?0:await this.giveTheCopiesTheirFields(e,t,n,g,l,{objectApiName:ze,recordSummary:"(contact roles the platform wrote with their opportunities)",leftAs:"Linked, and left as the platform wrote them, without the fields of the source's roles"}),m=0;for(let[R,b]of g){let k=t[R],O=typeof k.source.Id=="string"?k.source.Id:void 0,w=String(b.Id);if(O===void 0)continue;let A=String(k.source.OpportunityId);e.contactSentWith.delete(A),i.addExisting(O,w,ze),i.wasCreated(A)&&(ur(e,O),m++),k.nullifiedFks.length>0&&this.oweToTheSecondPass(e,k.nullifiedFks.map(S=>({objectApiName:ze,newId:w,sourceId:O,fieldName:S.field,sourceRefId:S.sourceRefId,...S.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let R of[...g.keys()].sort((b,k)=>k-b))t.splice(R,1),n.splice(R,1);return e.linkedCount+=g.size,cr(e,ze,m),g.size>m&&e.existingRecords.push({objectApiName:ze,linked:g.size-m,unidentified:0}),{linked:g.size,given:h}}async mapContactsOfPersonAccounts(e,t=e.preread.get(Se)?.records??[]){let n=new Map;for(let i of t){let a=i[Er],d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||e.remapper.get(a))continue;let c=e.remapper.get(d);c&&n.set(c,{contact:a,account:d})}if(n.size===0||await this.personAccountsInTarget(e)===!1)return;let{simulated:o}=e;if(o){for(let[,{contact:i,account:a}]of n)e.contactsOnTheirOwn.has(i)||(e.remapper.addExisting(i,o.idFor(null),ce),e.remapper.isCreated(a)&&this.contactWithItsAccount(e,i));return}let s;try{s=await Xc(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:Se,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contacts the platform wrote with the person accounts)",messages:[`Not looked up, so what points at them is left empty: ${V(i)}`]}]});return}for(let[i,{contact:a,account:d}]of n){let c=s.get(i);if(!c){e.contactsOnTheirOwn.add(a);continue}e.remapper.addExisting(a,c,ce),e.remapper.isCreated(d)&&this.contactWithItsAccount(e,a)}}contactWithItsAccount(e,t){ur(e,t);let n=e.sample;(n?.drawn.has(ce)?this.inThePlan(n,ce,t):e.writtenObjects.has(ce))||(e.linkedCount++,cr(e,ce,1),n?.drawn.has(ce)&&e.personContactsOutsideTheSample++)}writesAs(e){let{runningUser:t}=this.deps;return e.writesAs??=t?t(e.targetOrgId).then(n=>typeof n=="string"&&n!==""?n:void 0,()=>{}):Promise.resolve(void 0),e.writesAs}personAccountsInTarget(e){return e.personAccountsInTarget??=this.deps.describeFields(e.targetOrgId,Se).then(t=>t.some(n=>n.name===Er),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${Se}'`).then(t=>t.length===0?void 0:new Set(t.filter(n=>n.IsPersonType===!0||n.IsPersonType==="true").map(n=>String(n.Id).slice(0,15))),()=>{}),e.personRecordTypes}async takenAsBusinessAccounts(e,t,n){let o=t.filter(rn);if(o.length===0)return new Set;let s=await this.personAccountsInTarget(e);if(s!==!0)return new Set(s===!1?o:[]);let i=await this.personRecordTypesInTarget(e);if(!i)return new Set;let a=new Map((e.config.recordTypeMappings??[]).map(u=>[u.sourceId,u.targetId])),d=u=>{let l=u.RecordTypeId;return n&&typeof l=="string"&&l!==""?l:void 0},c=o.some(u=>d(u)===void 0)?xa((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes):void 0;return new Set(o.filter(u=>{let l=d(u),f=l===void 0?c:a.get(l);return f!==void 0&&!i.has(f.slice(0,15))}))}async noteContactsOfBusinessAccounts(e,t,n){let o=n.has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[Er];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if(So(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!dn(e.config,a)).map(a=>String(a.Id)));return n.length===0||i.size===0?0:(await this.teamThePlatformWrites(e,t,n,i)).size}if(t===ze)return(await this.rolesThePlatformWritesOfTheRead(e,e.preread.get(We)?.records??[],e.preread.get(ce)?.records??[],n)).size;if(t===Se)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==ce)return 0;let s=n.filter(i=>rn(i)&&!e.contactsOnTheirOwn.has(String(i.Id))).length;return s>0&&await this.personAccountsInTarget(e)!==!1?s:0}async personContactsOnTheirOwn(e,t){if(t.length===0)return{rows:new Set,why:""};let n=await this.personAccountsInTarget(e);return{rows:new Set(t.filter(i=>n===!1||e.contactsOnTheirOwn.has(String(i.Id)))),why:n===!1?"the target has no person accounts":"their account is no person account in the target"}}saySentOnTheirOwn(e,t,n){t!==0&&e.errors.push({objectApiName:ce,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`IsPersonAccount=true (${t} record${t===1?"":"s"})`,messages:[`Sent as contacts of their own: ${n}, and wrote no contact with it.`]}]})}linkPersonContacts(e,t){let n=0,o=0,s=0,i=0;for(let c of t){let u=String(c.Id),l=e.remapper.get(u);if(l){e.remapper.addExisting(u,l,ce),n++,Nw(e,u)&&o++;continue}let f=c.AccountId;typeof f=="string"&&e.remapper.get(f)?i++:s++}n>0&&(e.linkedCount+=n),cr(e,ce,o),n>o&&e.existingRecords.push({objectApiName:ce,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:Nh.accountNotWritten}]:[],...i>0?[{count:i,why:Nh.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:ce,stage:"scope",failedCount:d,attemptedCount:0,samples:a.map(({count:c,why:u})=>({recordSummary:`IsPersonAccount=true (${c} record${c===1?"":"s"})`,messages:[`Not written: ${u.replace(/^not sent: /,"")}.`]}))})),{linked:n,notSent:a}}reportNotCreatable(e,t,n){t.skippedCount++,n&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not createable on target org"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:n?`Skipped ${e.objectApiName} (target org rejects inserts on this entity)`:`Skipped ${e.objectApiName} (target org rejects inserts on this entity; the clone holds none of its records)`})}async reportNotInTargetOfTheScope(e){for(let t of e.notInTargetPutOff?.splice(0)??[]){let n=await this.deps.describeFields(e.sourceOrgId,t.objectApiName).catch(()=>{}),o=n&&on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,readObjects:e.readObjects,catalog:Ke});if(o?.kind!=="skip"||o.reason!==na){this.reportNotInTarget(t,e);continue}e.skippedCount++,e.onProgress({objectName:t.objectApiName,status:"skipped",progress:100,message:`Skipped ${t.objectApiName} (not in the target org; nothing the run read names its records)`})}}reportNotInTarget(e,t){t.skippedCount++,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not in the target org, or the user the run writes as cannot see it: none of its records can be written there"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (not in the target org)`})}waitsForWhatPointsAtIt(e,t,n){return!n.scopeCache||!Ke.has(e.objectApiName)?!1:t.kind==="skip"||!Cl(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=vl.flatMap(d=>e.catalogNodes.filter(({node:c})=>c.objectApiName===d)).filter(({node:d})=>!e.failedObjects.has(d.objectApiName)&&!e.notCreatable.has(d.objectApiName)&&!o.referenceDataObjects.has(d.objectApiName));if(!s.some(({node:d})=>kh(n,d.objectApiName).size>0))return;let i=new Map([...n.entries()].map(([d,c])=>[d,new Set(c)])),a=new Set;for(let{node:d,fieldInfos:c}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let u=d.objectApiName,l=[...c],f=o.objectSoqlFilters?.[u],p=async m=>u===Ut&&e.standardPricebookId?m.filter(R=>R.Id!==e.standardPricebookId):gt(u)&&e.standardPricebookId?(await this.addStandardPricebookEntries(d,e,m,l),e.readsEverythingFirst||await this.pricesInTheCurrencyWritten(d,e,m,l),this.keptPrices(e,m)):m;if(u===Gt){if(!a.has(Zo)&&!a.has(jr))continue;let m=on({node:d,edges:e.graph.edges,fieldInfos:l,scopedBuilder:e.scopedBuilder,scopeCache:n,rootObjectApiName:o.rootObjectApiName,rootRecordId:o.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:f,fieldsLeftOut:o.fieldExclusions[u],readObjects:e.readObjects,catalog:Ke});if(m.kind!=="query")continue;(await this.readMore(e,d,l,m.statements,"named by records read after the catalog",p)).length>0&&a.add(u);continue}let g=zt(l,o.fieldExclusions[u]),h=new Set;for(let m=0;m<Zm;m++){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let R=[...kh(n,u)].filter(k=>!h.has(k));if(R.length===0)break;for(let k of R)h.add(k);if((await this.readMore(e,d,l,new Sn().buildById({objectApiName:u,selectFields:g.length>0?g:["Id"],ids:new Set(R),extraWhere:f}),m===0?"named by records read after the catalog":"named by its own records read before them",p)).length===0)break;a.add(u)}}a.size>0&&await this.readAfterTheCatalogAgain(e,t,i)}async readAfterTheCatalogAgain(e,t,n){let o=e.scopeCache;if(!o)return;let{config:s}=e,i=new Set;for(let a of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(e.failedObjects.has(d)||e.notCreatable.has(d)||s.referenceDataObjects.has(d))continue;let c=n.get(d),u=o.isRead(d)?o.scopeOf(d):void 0,l=new Set([...o.get(d)??[]].filter(b=>!c?.has(b)&&!u?.has(b))),f=new Set(e.graph.edges.filter(b=>b.targetObject===d&&i.has(b.sourceObject)).map(b=>b.sourceObject));if(l.size===0&&f.size===0)continue;let p=await this.fieldsReadAgain(e,a);if(!p)continue;let{fields:g}=p,h=s.objectSoqlFilters?.[d],m=[];if(l.size>0){let b=zt(g,s.fieldExclusions[d]);m.push(...new Sn().buildById({objectApiName:d,selectFields:b.length>0?b:["Id"],ids:l,extraWhere:h}))}if(f.size>0){let b=on({node:a,edges:e.graph.edges,fieldInfos:g,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:h,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:Ke,under:f});b.kind==="query"&&m.push(...b.statements)}m.length===0||(await this.readMore(e,a,g,m,"for what the catalog read again brought")).length===0||(i.add(d),p.described&&this.withoutFileContent(e,d,p.described,!0))}}async fieldsReadAgain(e,t){let n=e.preread.get(t.objectApiName);if(n)return{fields:[...n.fieldInfos]};try{let o=await this.deps.describeFields(e.sourceOrgId,t.objectApiName);return{fields:o.filter(s=>!xn(s)),described:o}}catch{return}}async readMore(e,t,n,o,s,i=async a=>a){let a=e.scopeCache;if(!a)return[];let{config:d}=e,c=t.objectApiName,u=d.maxRecordsPerObject?Math.floor(d.maxRecordsPerObject):0,l=u>0?u-(e.readByObject.get(c)??0):0;if(u>0&&l<=0)return o.length>0&&e.cappedObjects.add(c),[];let f=a.isRead(c),p=new Set(f?a.scopeOf(c)??[]:[]),g=m=>typeof m.Id!="string"||!p.has(m.Id);this.holdTheRootsReading(e,c,o.length);let h;try{let m=await Wr(l>0?oa(o,l,{byIdCount:o.length}):{kind:"query",statements:o,byIdCount:o.length},B=>this.deps.queryRecords(e.sourceOrgId,B,()=>e.truncatedObjects.add(c)),void 0,()=>e.cappedObjects.add(c));Gr(e,m);let R=m.filter(g);this.keepWhatStatusesNeed(e,t,R,void 0);let b=e.heldForExclusions.get(c),k=0;for(let B of b?R:[]){let E=B.Id;typeof E!="string"||b?.get(E)?.namedBy===void 0||(b.delete(E),k++)}k>0&&(b?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=k,e.readByObject.set(c,(e.readByObject.get(c)??k)-k));let O=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,R,void 0,await this.excludedByKeyPrefix(e,c,n));let w=[...e.heldForExclusions.get(c)??[]].filter(([B])=>!O.has(B));if(this.leaveToThePlatform(e,c,R,n),h=(await i(R)).filter(g),rs(a,c,h,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,h.flatMap(B=>typeof B.Id=="string"?[B.Id]:[])),await this.notePastDraft(e,c,h),h.length===0&&w.length===0)return[];if(d.files&&d.stream?.everything!==!0){let B=h.flatMap(E=>typeof E.Id=="string"?[E.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...B])}f||e.skippedCount--;let A=e.preread.get(c),S=A?.records??[],v=gt(c)?await this.keptPrices(e,[...S,...h]):[...S,...h],j=v.length-S.length,F=A?.createableSet??new Set(n.filter(B=>B.createable).map(B=>B.name));if(e.preread.set(c,A?{...A,records:v}:{fieldInfos:n,createableSet:F,records:v,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+j+w.length),this.holdTheRootsRows(e,c),d.dryRun){let B=await this.writtenWithTheirAccountOnADryRun(e,c,gt(c)?[]:h,F);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${j-B} more record(s) would be inserted`+(B>0?`, ${B} more would be written by the platform with ${Qn(c)}`:"")+`, ${s}`+Ns(Fs(w.map(([,E])=>E)),!0)})}}catch(m){if(m instanceof be||Ta(m))throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[V(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,h),h}async keptPrices(e,t){let n=await this.pricesKeyOf(e),{kept:o,standsFor:s}=wi(t,n);if(this.pricesStandFor(e,s),n.oneCurrency)for(let i of o){let a=i.Id,d=i[mt];typeof a=="string"&&typeof d=="string"&&d!==""&&e.pricesKeptAsRead.set(a,{from:d,to:n.oneCurrency.code})}return o}async pricesKeyOf(e){e.oneCurrency??=(async()=>{let n=a=>this.deps.describeFields(a,et).catch(()=>[]),[o,s]=await Promise.all([n(e.sourceOrgId),n(e.targetOrgId)]),i=a=>a.some(d=>d.name===mt);if(!(s.length===0||!i(o)||i(s)))try{let a=await this.deps.orgCurrency?.(e.targetOrgId);return typeof a=="string"&&/^[A-Z]{3}$/.test(a)?{code:a}:{}}catch(a){return Ye.warn(`[forge] the target's one currency could not be read: ${V(a)}`),{}}})();let t=await e.oneCurrency;return{sellingModel:e.sellingModels,...t?{oneCurrency:t}:{}}}pricesStandFor(e,t){for(let{left:n,kept:o}of t){let s=n.Id,i=o.Id;if(typeof s!="string"||typeof i!="string"||s===i||e.prices.standsFor.get(s)===i)continue;e.remapper.alias(s,i),e.prices.standsFor.set(s,i);for(let[c,u]of e.prices.standsFor)u===s&&(e.remapper.alias(c,i),e.prices.standsFor.set(c,i));let a=n[mt],d=o[mt];typeof a=="string"&&typeof d=="string"&&a!==d&&e.pricesSwappedSaid.push({from:a,to:d,how:"replaced",forLines:!1})}}async addStandardPricebookEntries(e,t,n,o){let s=t.standardPricebookId;if(!s)return;let i=u=>Ad(u,t.sellingModels),a=new Set,d=new Set,c=new Set;for(let u of n){let l=u.Id;if(typeof l=="string"&&c.add(l),u[tn]===s)continue;let f=u[Pn];typeof f=="string"&&f&&(a.add(f),d.add(i(u)))}if(a.size!==0)try{let u=new Sn().buildJoining({objectApiName:e.objectApiName,selectFields:zt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Pn,ids:a},whole:{field:tn,ids:new Set([s])}}),l=0;for(let f of u)for(let p of await this.deps.queryRecords(t.sourceOrgId,f)){let g=p.Id;typeof g=="string"&&c.has(g)||d.has(i(p))&&(n.push(p),Gr(t,[p]),l++)}l>0&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:`Added ${l} standard price book entr${l===1?"y":"ies"} the custom prices depend on`})}catch(u){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book entries)",messages:[V(u)]}]})}}async pricesInTheCurrencyWritten(e,t,n,o,s){let i=await this.priceCurrencyInput(t,n,o);if(!i)return;let a={...i,...s?{wanted:s}:{}},d=s?t.pricesTheGateCounted:void 0,c=Na(a).filter(h=>!d||d.has(Fa(h))),u=[],l=[...new Set(c.map(({currency:h})=>h))].filter(h=>/^[A-Z]{3}$/.test(h));if(l.length>0)try{let h=new Sn().buildJoining({objectApiName:e.objectApiName,selectFields:zt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Pn,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:tn,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${mt} IN (${l.map(m=>`'${m}'`).join(", ")})`});for(let m of h)u.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(h){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[V(h)]}]});return}let f=t.sample;if(f?.drawn.has(e.objectApiName)){let h=u.filter(m=>this.inThePlan(f,e.objectApiName,String(m.Id)));u.length=0,u.push(...h)}let p=Ca(a,d?u.filter(h=>d.has(Pa(Bf(h,t.sellingModels),String(h[mt])))):u),g=new Set(n);n.length=0,n.push(...p.rows),Gr(t,p.rows.filter(h=>!g.has(h)));for(let[h,m]of p.standsFor)t.remapper.alias(h,m),t.prices.standsFor.set(h,m);for(let[h,m]of t.prices.standsFor){let R=p.standsFor.get(m);R!==void 0&&(t.remapper.alias(h,R),t.prices.standsFor.set(h,R))}for(let[h,m]of p.convertedInto)t.prices.convertedInto.set(h,m);for(let[h,m]of p.written)t.prices.written.set(h,m);for(let[h,m]of p.keys)t.prices.keys.set(h,m);t.pricesSwappedSaid.push(...p.said),!(p.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:Ma(p.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===mt)||!t.some(d=>typeof d[mt]=="string"))return;let s=await this.runCurrencies(e);if(!s)return;let{target:i}=s,a=this.priceCurrencyWrittenIn(e,i);return{prices:t,standardBookId:o,sellingModels:e.sellingModels,writtenIn:a,active:i.active}}priceCurrencyWrittenIn(e,t){return n=>{let o={[mt]:n};e.config.decisions.applyToRow(et,o,void 0,new Xi);let s=o[mt];return typeof s=="string"&&t.active.has(s)?s:bu(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(et);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=Na({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(Fa)),o.length}currenciesTheirLinesMayWant(e,t,n){let o=new Set(t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[])),{decisions:s}=e.config,i=d=>{if(s.changesRowsOf(d))return!0;if(!Po(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(u=>u.name===Ru[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:u}]of Object.entries(ms)){let l=i(c);for(let f of e.preread.get(d)?.records??[]){let p=f[_r];if(typeof p!="string"||typeof f[u]!="string")continue;let g=e.prices.standsFor.get(p)??p;if(!o.has(g))continue;let h=f[He],m=!l&&typeof h=="string"&&n.has(h)?[h]:[...n],R=a.get(g)??new Set;for(let b of m)R.add(b);a.set(g,R)}}return a}currenciesTheirLinesWant(e,t){let n=new Set(t.flatMap(s=>typeof s.Id=="string"?[s.Id]:[])),o=new Map;for(let[s,{field:i}]of Object.entries(ms))for(let a of e.preread.get(s)?.records??[]){let d=a[_r];if(typeof d!="string")continue;let c=e.prices.standsFor.get(d)??d;if(!n.has(c))continue;let u=this.currencyTheirRecordWentIn(e,a,i);if(u===void 0)continue;let l=o.get(c)??new Set;l.add(u),o.set(c,l)}return o}currencyTheirRecordWentIn(e,t,n){let o=t[n];if(typeof o!="string"||e.remapper.get(o)===void 0)return;let s=e.currencyChangesById.get(o)?.to;if(s!==void 0)return s;let i=t[He];return typeof i=="string"&&i!==""?i:void 0}pricedInTheirRecordsCurrency(e,t,n){let o=ms[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[_r];if(typeof i!="string")return s;let a=e.prices.standsFor.get(i)??i,d=e.prices.keys.get(a),c=d?this.currencyTheirRecordWentIn(e,s,o):void 0;if(d===void 0||c===void 0)return s;let u=e.prices.written.get(Pa(d,c));return u===void 0||u===a||u===i||e.remapper.get(u)===void 0?s:{...s,[_r]:u}})}async objectInfoOf(e,t){if(!this.deps.describeObject)return null;try{return await this.deps.describeObject(e,t)}catch{return null}}async toWriteAtTheGate(e,t,n,o=0){let s=n.records.filter(u=>!dn(e.config,u)),i=n.records.length-s.length,a=s.length>0?await this.heldBackAtTheGate(e,t,n,s):[],d=a.length>0,c={...i>0?{writtenBefore:i}:{},...d?xh(a,s.length):{}};return{objectApiName:t,rows:d?[]:s,...Object.keys(c).length>0?{leftOut:c}:{},...o>0&&!d?{mayAdd:o}:{}}}async withoutWhatThePlatformWrites(e,t){let n=u=>t.find(l=>l.objectApiName===u)?.rows??[],o=new Map,s=new Set(n("Opportunity").map(u=>String(u.Id)));for(let u of t)if(!(!So(u.objectApiName)||u.rows.length===0)){if(s.size===0)break;o.set(u.objectApiName,await this.teamThePlatformWrites(e,u.objectApiName,u.rows,s))}let i=await this.personContactsThePlatformWrites(e,n(Se),n(ce));i.size>0&&o.set(ce,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(We),n(ce),n(ze)),d=await this.rolesOfOpportunitiesWrittenBefore(e,n(ze).filter(u=>!a.has(u))),c=new Set([...a,...d.linked]);return c.size>0&&o.set(ze,c),t.map(u=>{let l=o.get(u.objectApiName),f=u.objectApiName===ze&&d.mayBe>0?{mayBeByThePlatform:{rows:d.mayBe,before:!0}}:{};return!l||l.size===0?{...u,...f}:{...u,rows:u.rows.filter(p=>!l.has(p)),leftOut:{...u.leftOut,byThePlatform:l.size},...f}})}async withoutWhatTheTargetHoldsByValue(e,t){let{config:n}=e,o=[];for(let s of t){let{objectApiName:i,rows:a}=s,d=e.preread.get(i);if(a.length===0||s.counted||!d){o.push(s);continue}let c=await(d.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,i).then(w=>({ok:!0,sets:w}),w=>({ok:!1,error:w})));if(!c.ok){o.push(s);continue}let u=dr(d.createableSet,c.sets.creatable),l=new Set(n.fieldExclusions[i]??[]),f=n.fieldMappings[i]??{},p=new Set(Object.values(f)),g=new Set(await e.maskedSourceFields(i).catch(()=>[])),h=n.anonymization,m=new Set(e.anonymize&&h?h.fields[i]??this.detectedPersonalFields(e,h,i,d.fieldInfos):[]),R=new Set(e.contactPoints?Ea(d.fieldInfos).map(({name:w})=>w):[]),b=n.decisions.truncatedFieldsOf(i),k=c.sets.fields.filter(({name:w,unique:A,externalId:S})=>A===!0&&u.has(w)&&!(n.upsertMode==="auto"&&S===!0)&&!l.has(w)&&f[w]===void 0&&!p.has(w)&&!g.has(w)&&!m.has(w)&&!R.has(w)&&!b.has(w)&&!(i===Se&&w.endsWith("__pc"))),O=new Map;for(let w of k){let{name:A}=w,S=new Map;for(let F of a){let B=F[A];if(typeof B!="string"||B===""||Zh.test(B))continue;let E=Mn(w,B);S.has(E)||S.set(E,B)}let v=[...S.values()];if(v.length===0)continue;let j=new Set;try{let F=Be(i),B=Be(A);for(let E of kn(v,Yh)){let _=await this.deps.queryRecords(e.targetOrgId,`SELECT ${B} FROM ${F} WHERE ${B} IN (${E})`);for(let ee of _){let X=ee[A];typeof X=="string"&&j.add(Mn(w,X))}}}catch{continue}for(let F of a){let B=F[A];typeof B=="string"&&j.has(Mn(w,B))&&!O.has(F)&&O.set(F,A)}}if(O.size===0){o.push(s);continue}o.push({...s,rows:a.filter(w=>!O.has(w)),leftOut:{...s.leftOut,linkedByValue:{rows:O.size,fields:[...new Set(O.values())]}}})}return o}async rolesOfOpportunitiesWrittenBefore(e,t){let{config:n}=e,o={linked:new Set,mayBe:0};if(n.writtenBefore.size===0)return o;let s=u=>u.slice(0,15),i=new Map;for(let u of t){let l=u.OpportunityId,f=u[Le];typeof l!="string"||typeof f!="string"||f===""||vi(u)&&n.writtenBefore.has(l)&&i.set(s(l),f)}if(i.size===0)return o;let a=Ir(t,u=>i.get(s(u))),d=u=>typeof u=="string"&&u!==""?n.writtenBefore.get(u)??e.remapper.get(u):void 0,c=new Map;for(let u of a){let l=d(t[u].OpportunityId),f=d(t[u][Le]);l!==void 0&&f!==void 0&&c.set(u,{opportunity:l,contact:f})}if(c.size===0)return{...o,mayBe:a.length};try{let u=await Ei(f=>this.deps.queryRecords(e.targetOrgId,f),[...new Set([...c.values()].map(({opportunity:f})=>f))]),{found:l}=Ii(c,u);return{linked:new Set([...l.keys()].map(f=>t[f])),mayBe:a.length-c.size}}catch{return{...o,mayBe:a.length}}}async rolesThePlatformWritesOfTheTables(e,t,n,o){let{config:s}=e,i=new Set(n.map(u=>u.objectApiName));if(!i.has(We)||(s.fieldExclusions[We]??[]).includes(Le)||s.fieldMappings[We]?.[Le]!==void 0)return 0;if([We,ze,ce].some(u=>o.has(u)))return;let d=u=>t.findIndex(l=>l.objectApiName===u),c=i.has(ce)&&d(ce)<d(We);try{if(!(await this.deps.describeFields(e.sourceOrgId,We)).some(w=>w.name===Le&&w.createable)||!(await an(this.deps.describeFields,e.targetOrgId,We)).creatable.has(Le))return 0;let f=w=>s.objectSoqlFilters?.[w],p=s.stream?.resumeAfter.get(ze),g=f(We),h=f(ce),m=[...f(ze)?[`(${f(ze)})`]:[],`Opportunity.${Le} != null`,...p&&Ft.test(p.lastId)?[`Id > '${p.lastId}'`]:[],...g?[`OpportunityId IN (SELECT Id FROM ${We} WHERE (${g}))`]:[],...c&&h?[`${Le} IN (SELECT Id FROM ${ce} WHERE (${h}))`]:[]],R=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${Le}, IsPrimary, Opportunity.${Le} FROM ${ze} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${mh+1}`);if(R.length>mh)return;let b=w=>c||s.writtenBefore.has(w)||e.remapper.get(w)!==void 0,k=w=>{let A=w.Opportunity,S=A!==null&&typeof A=="object"?A[Le]:void 0;return typeof S=="string"&&S!==""?S:void 0},O=new Map;for(let w of R){let A=w.OpportunityId,S=k(w);typeof A!="string"||S===void 0||s.writtenBefore.has(A)||!b(S)||O.set(A.slice(0,15),S)}return Ir(R,w=>O.get(w.slice(0,15))).length}catch{return}}rolesThePlatformMayWriteOfTheCounts(e,t,n){let{config:o}=e;return(o.fieldExclusions[We]??[]).includes(Le)||o.fieldMappings[We]?.[Le]!==void 0?0:Math.min(t,n)}async rolesThePlatformWritesOfTheRead(e,t,n,o){if(o.length===0||t.length===0)return new Set;let{config:s,remapper:i}=e;if((s.fieldExclusions[We]??[]).includes(Le)||s.fieldMappings[We]?.[Le]!==void 0)return new Set;let a=e.preread.get(We);if(!a?.createableSet.has(Le))return new Set;let d=await(a.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,We).then(f=>({ok:!0,sets:f}),f=>({ok:!1,error:f})));if(!d.ok||!d.sets.creatable.has(Le))return new Set;let c=f=>f.slice(0,15),u=new Set(n.map(f=>c(String(f.Id)))),l=new Map;for(let f of t){let p=f.Id,g=f[Le];typeof p!="string"||typeof g!="string"||g===""||dn(s,f)||!u.has(c(g))&&i.get(g)===void 0||l.set(c(p),g)}return l.size===0?new Set:new Set(Ir(o,f=>l.get(c(f))).map(f=>o[f]))}async teamThePlatformWrites(e,t,n,o){let{config:s}=e,i=s.decisions.defaultOf(t,$i[t]),a=await this.writesAs(e);try{let d=await Pi(t,n,{source:c=>this.deps.queryRecords(e.sourceOrgId,c),target:c=>this.deps.queryRecords(e.targetOrgId,c),targetIdOf:c=>o.has(c)?c:void 0,mappedUser:c=>s.ownerMappings[c],...i!==void 0?{defaultUser:i}:{},written:[],simulated:{ownerOf:c=>s.ownerMappings[c]??a??`${rg}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>rn(d)&&!e.contactsOnTheirOwn.has(String(d.Id)));if(o.length===0)return new Set;if(await this.personAccountsInTarget(e)===!1)return new Set;let i=(e.preread.get(Se)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[Er])));return new Set(o.filter(d=>!a.has(String(d.Id))))}async heldBackAtTheGate(e,t,n,o){let s=e.graph.nodes.find(u=>u.objectApiName===t);if(!s)return[];let i=await this.objectInfoOf(e.targetOrgId,t);if(!i||i.recordTypes.length===0)return[];if(!(e.recordTypeMapper!==null&&e.config.recordTypeMappings!==void 0)&&!i.recordTypes.some(u=>!u.available&&!u.master))return[];let d=await(n.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,t).then(u=>({ok:!0,sets:u}),u=>({ok:!1,error:u}))),c=d.ok?dr(n.createableSet,d.sets.creatable):n.createableSet;return this.recordTypesHeldBack(s,o,i,c,e)}async recordTypesHeldBack(e,t,n,o,s){let{config:i}=s;if(!n||n.recordTypes.length===0)return[];if(!o.has("RecordTypeId"))return[];if((i.fieldExclusions[e.objectApiName]??[]).includes("RecordTypeId"))return[];if(i.fieldMappings[e.objectApiName]?.RecordTypeId)return[];let a=t.map(c=>({RecordTypeId:i.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));s.recordTypeMapper&&i.recordTypeMappings&&(a=s.recordTypeMapper.apply(a,i.recordTypeMappings));let d=new Map;for(let c of a){let u=c.RecordTypeId;typeof u=="string"&&d.set(u,(d.get(u)??0)+1)}return[...ju(e.objectApiName,a,n.recordTypes),...await this.typesTheTargetLacks(s,e.objectApiName,d,n)]}oweToTheSecondPass(e,t){let n=this.withoutSyncedQuotes(e,t);if(e.secondPassInStore&&e.store){for(let o of n)e.store.owe(o);return}if(e.store)for(let o of n)e.store.owe(o);e.pendingFkUpdates.push(...n)}withoutSyncedQuotes(e,t){if(e.config.stream?.everything!==!0)return t;let n=t.filter(o=>o.objectApiName!==We||o.fieldName!==ys);return e.syncedQuotesLeft+=t.length-n.length,n.length===t.length?t:n}saySyncedQuotesLeft(e){let t=e.syncedQuotesLeft;t!==0&&(e.syncedQuotesLeft=0,e.errors.push({objectApiName:We,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(${We}.${ys})`,messages:[`Left empty on ${t} opportunit${t===1?"y":"ies"}: filled in, the target syncs the quote at once and writes its lines over the opportunity's products the run copied. Start the sync in the target to fill it in.`]}]}))}patchedInTheJournal(e){let{store:t}=e;if(!(!t||e.secondPassInStore))return eg(t)}oweStatus(e,t,n,o){e.store?e.store.oweStatus(t,n,o):e.deferredStatuses.push({objectApiName:t,id:n,status:o})}countWrites(e,t,n){e.simulated?e.wouldInsertCount+=n.successCount:e.successCount+=n.successCount,e.updatedCount+=n.updatedCount,n.mayHaveBeenWritten&&n.mayHaveBeenWritten.length>0&&e.mayHaveBeenWritten.set(t,[...e.mayHaveBeenWritten.get(t)??[],...n.mayHaveBeenWritten]),e.linkedCount+=n.linkedExistingCount,e.linkedToCreatedCount+=n.linkedToCreatedCount??0,e.failedCount+=n.failureCount,this.oweToTheSecondPass(e,n.pendingFkUpdates),n.writtenWithoutFields&&this.countWrittenWithoutFields(e,t,n.writtenWithoutFields);for(let{field:o,recordId:s}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,o,s);for(let o of n.withTheirRecord??[])ur(e,o);(n.linkedExistingCount>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:n.linkedExistingCount,...n.linkedToCreatedCount?{linkedToCreated:n.linkedToCreatedCount}:{},unidentified:n.unidentifiedExistingCount}),n.failureCount>0&&e.errors.push({objectApiName:t,stage:"insert",failedCount:n.failureCount,attemptedCount:n.successCount+n.updatedCount+n.linkedExistingCount+n.failureCount,samples:n.errorSamples})}countWrittenWithoutFields(e,t,n){e.writtenWithoutFields.set(t,ia(e.writtenWithoutFields.get(t),n))}noteLeftEmptyByFilter(e,t,n,o){let s=e.leftEmptyByFilter.get(t);s||(s=new Map,e.leftEmptyByFilter.set(t,s));let i=s.get(n)??{records:0,ids:[]};i.records++,i.ids.length<Km&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[fl(n)]})}oweLookupsOfRowsWrittenBefore(e,t,n,o,s){let{config:i}=e,a=new Set(e.graph.nodes.filter(l=>l.included).map(l=>l.objectApiName)),d=new Set(i.fieldExclusions[t.objectApiName]??[]),c=i.fieldMappings[t.objectApiName]??{},u=o.filter(l=>l.isReference&&l.name!=="RecordTypeId"&&!d.has(l.name)&&dd(l,s,c[l.name])&&(l.referenceTo??[]).some(f=>a.has(f)));if(u.length!==0)for(let l of n){let f=l.Id;if(typeof f!="string")continue;let p=i.writtenBefore.get(f);if(p)for(let g of u){let h=l[g.name];if(typeof h!="string"||!h||i.writtenBefore.has(h)&&!e.store?.owesUntold(f))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:p,sourceId:f,fieldName:c[g.name]??g.name,sourceRefId:h}]);m&&(e.secondPassInStore&&e.store?e.store.owe(m,!0):e.owedToRowsWrittenBefore.push(m))}}}owedNowWritten(e){if(e.owedToRowsWrittenBefore.length===0)return[];let t=[],n=[];for(let o of e.owedToRowsWrittenBefore)e.remapper.get(o.sourceRefId)?t.push(o):n.push(o);return e.owedToRowsWrittenBefore=n,t}sayLookupsOutsideTheClone(e,t){let n=new Map,o=this.keepLookupsInTheClone(e,t,n);return this.sayLeftEmpty(e,n),o}keepLookupsInTheClone(e,t,n){let o=[];for(let s of t){if(e.remapper.get(s.sourceRefId)||e.idsRead.has(s.sourceRefId)){o.push(s);continue}let i=this.objectPointedAt(e,s);if(i!==void 0&&(e.failedObjects.has(i)||e.notCreatable.has(i)||e.notInTarget.has(i))){o.push(s);continue}let a=n.get(s.objectApiName)??new Map,d=`${s.fieldName}|${i??""}`,c=a.get(d)??{field:s.fieldName,parent:i,count:0};c.count++,a.set(d,c),n.set(s.objectApiName,a)}return o}sayLeftEmpty(e,t){for(let[n,o]of t)e.errors.push({objectApiName:n,stage:"scope",failedCount:0,attemptedCount:0,samples:[...o.values()].sort((s,i)=>i.count-s.count).slice(0,3).map(({field:s,parent:i,count:a})=>({recordSummary:`${i===void 0?s:`${s} \u2192 ${i}`} (${a} record${a===1?"":"s"})`,messages:[`Written with the lookup empty: the ${i===void 0?"":`${i} `}record it points at is not in the clone.`]}))})}async secondPassFromTheJournal(e){let{store:t}=e;if(!t)return null;let n=new Qf({remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:e.targetOrgId,enabled:!e.config.dryRun,onProgress:e.onProgress,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:eg(t),onAnswered:()=>t.flush(),onRefusedByFilter:(l,f,p)=>this.noteLeftEmptyByFilter(e,l,f,p),...this.secondPassOfTheSample(e)}),o=new Map,s=e.config.stream?.secondPassPageSize??Vm,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=l=>t.wasPatched(l.newId,l.fieldName),d=new Jf;for(let l of i)d.note(0,l.newId);let c=1;for(let l of t.owedPages(s)){for(let{update:f}of l)a(f)||d.note(c,f.newId);c++}let u=l=>d.spans(l.newId);await n.patch(this.keepLookupsInTheClone(e,i,o),u);for(let l of t.owedPages(s)){let f=l.filter(({update:p,toRowWrittenBefore:g})=>!a(p)&&(!g||e.remapper.get(p.sourceRefId)!==void 0)).map(({update:p})=>p);await n.patch(this.keepLookupsInTheClone(e,f,o),u)}return await n.sendHeld(),this.sayLeftEmpty(e,o),n.finish()}objectPointedAt(e,t){let n=e.config.fieldMappings[t.objectApiName]??{},s=e.preread.get(t.objectApiName)?.fieldInfos.find(a=>a.isReference&&(n[a.name]??a.name)===t.fieldName)?.referenceTo??[];if(s.length===1)return s[0];let i=t.sourceRefId.slice(0,3);return s.find(a=>e.sourceKeyPrefixes.get(a)===i)}applyRecordTypeDecisions(e,t,n,o){let{config:s}=e,i=new Map,a=e.recordTypeMapper&&s.recordTypeMappings?new Set(s.recordTypeMappings.map(d=>d.sourceId)):void 0;return o.forEach((d,c)=>{let u=n[c]?.cleaned.RecordTypeId;if(typeof u!="string"||u===""||!("RecordTypeId"in d))return;let l=s.recordTypeDecisions.get(u);if(l){l.to===null&&delete d.RecordTypeId,e.decisionsApplied.add({kind:"map_record_type",objectApiName:t,from:l.from,...l.to!==null?{to:l.to}:{}});return}!e.simulated||!a||Dw.test(u)||a.has(u)||i.set(u,(i.get(u)??0)+1)}),i}simulateWrite(e,t,n,o,s,i,a,d,c=new Map){let{simulated:u}=e;if(!u)return;let l=t.objectApiName,f=new Set,p=0;i({objectName:l,status:"running",progress:0,recordCount:n.records.length,message:`Simulating the write of ${n.records.length} ${l} records: nothing is sent...`});for(let[g,h]of n.cleaned.entries()){let m=n.records[g]??{},R=d?Pu(l,m,h.source,d):[];if(R.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:Gl(m),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${R.map(w=>w.name).join(", ")}]`]});continue}let b=u.idFor(o),k=typeof h.source.Id=="string"?h.source.Id:void 0,O=c.get(m);if(O!==void 0){s.linkedExistingCount++,p++,f.add(O),k!==void 0&&e.remapper.addExisting(k,b,l);continue}s.successCount++,a&&!Dl(n.records[g]??{})&&a(h),k!==void 0&&e.remapper.add(k,b,l);for(let w of h.nullifiedFks)s.pendingFkUpdates.push({objectApiName:l,newId:b,sourceId:k,fieldName:w.field,sourceRefId:w.sourceRefId,...w.insertOnly?{insertOnly:!0}:{}})}p>0&&i({objectName:l,status:"running",progress:0,message:`[dry-run] ${l}: ${p} fewer would be inserted, linked to the record${p===1?"":"s"} the target holds under the same ${[...f].join(", ")}, which its refusal of the row names`})}holdBackSkippedRows(e,t,n,o,s){let{config:i}=e;if(!i.decisions.skipsRowsOf(t.objectApiName))return n;let a=new Set(i.fieldExclusions[t.objectApiName]??[]),d=new Map(Object.entries(i.fieldMappings[t.objectApiName]??{}).map(([l,f])=>[f,l])),c=n.filter(l=>{let f=l.RecordTypeId;return!i.decisions.holdsBack(t.objectApiName,p=>{let g=d.get(p)??p;return a.has(g)?void 0:l[g]},Qh(i,typeof f=="string"?f:void 0),e.decisionsApplied,s)}),u=n.length-c.length;return u>0&&o({objectName:t.objectApiName,status:"running",progress:0,message:`${t.objectApiName}: ${u} record${u===1?"":"s"} held back, as decided on the gaps`}),c}async findGaps(e,t,n){let{gaps:o}=e;if(!o)return new Map;let s=t.objectApiName,i=new Map([...n.recordTypes?.values()??[]].map(d=>[d.recordType,d]));for(let{picklistChanges:d=[]}of n.cleanedRecords){let c=xu(s,d,u=>{if(u.recordType!==void 0)return i.get(u.recordType)?.picklists.get(u.field)?.values;let l=n.picklistValuesByField?.get(u.field);return l?[...l]:void 0});for(let u of c)o.add(u)}if(n.unmapped.size>0){let d=await this.sourceRecordTypesOf(e,s);o.knowRecordTypes(s,"source",d);for(let[c,u]of n.unmapped){let l=d.find(f=>f.recordTypeId.slice(0,15)===c.slice(0,15))?.developerName??c;o.add(Di("record_type_unmapped",s,l,u,lg(n.targetObject)))}}let a=n.targetFields;return a?(Fu({objectApiName:s,rows:n.recordsToInsert.map((d,c)=>{let u=n.cleanedRecords[c]?.cleaned.RecordTypeId;return{payload:d,source:n.cleanedRecords[c]?.source??{},typed:typeof u=="string"&&n.recordTypes?.has(u)===!0}}),targetFields:a,picklistValuesByField:n.picklistValuesByField,picklistFields:n.picklistFields??new Map},o),await this.currencyGaps(e,s,a,n.cleanedRecords),this.uniqueValueGaps(e,s,a,n.recordsToInsert)):new Map}sourceRecordTypesOf(e,t){let n=e.sourceRecordTypes.get(t);if(!n){let o=this.deps.describeObject;n=o?o(e.sourceOrgId,t).then(s=>this.namedRecordTypes(e.recordTypeRows,e.sourceOrgId,s.recordTypes),()=>[]):Promise.resolve([]),e.sourceRecordTypes.set(t,n)}return n}currenciesFor(e,t,n,o){return t?.some(i=>i.name===He&&i.createable)===!0&&o(He)&&n.some(i=>typeof i[He]=="string"&&i[He]!=="")?this.runCurrencies(e):Promise.resolve(void 0)}async parentCurrenciesFor(e,t,n,o){if(e.currencyChangesById.size===0)return;let s=n?.find(a=>a.name===He);if(!s||s.createable&&!Po(t)||!o.some(a=>typeof a[He]=="string"&&a[He]!==""))return;let i=await e.currencies;return{changeOf:a=>e.currencyChangesById.get(a),...i?{currencies:i}:{}}}runCurrencies(e){let t=this.deps.queryTooling;return e.currencies??=yu(n=>this.deps.queryRecords(e.sourceOrgId,n),n=>this.deps.queryRecords(e.targetOrgId,n),t?{source:n=>t(e.sourceOrgId,n),target:n=>t(e.targetOrgId,n)}:{}),e.currencies}async currencyGaps(e,t,n,o){if(!n.some(d=>d.name===He&&d.createable))return;let s=new Map,i=new Map;for(let{source:d,currencyChange:c}of o){let u=d[He];if(typeof u!="string"||u===""||(s.set(u,(s.get(u)??0)+1),!c||c.chosenBy==="decision"))continue;let l=i.get(u)??{to:new Set,fields:new Set,kept:!1};l.to.add(c.to);for(let f of c.fields)l.fields.add(f);c.notConverted&&(l.kept=!0),i.set(u,l)}if(s.size===0)return;let a=(await e.currencies)?.target.active;if(!(!a||a.size===0))for(let[d,c]of s){if(a.has(d))continue;let u=i.get(d);e.gaps?.add(Nu(t,d,c,u&&{to:[...u.to].sort(),converted:[...u.fields].sort(),asRead:u.kept}))}}async uniqueValueGaps(e,t,n,o){let s=new Map,i=n.filter(a=>a.unique===!0&&a.createable&&!(e.config.upsertMode==="auto"&&a.externalId===!0));for(let a of i){let d=new Map;for(let f of o){let p=f[a.name];if(typeof p!="string"||p===""||Zh.test(p))continue;let g=Mn(a,p),h=d.get(g);h?h.rows++:d.set(g,{value:p,rows:1})}if(d.size===0)continue;let c=new Set;try{let f=Be(t),p=Be(a.name),g=[...d.values()].map(({value:h})=>h);for(let h of kn(g,Yh)){let m=await this.deps.queryRecords(e.targetOrgId,`SELECT ${p} FROM ${f} WHERE ${p} IN (${h})`);for(let R of m){let b=R[a.name];typeof b=="string"&&c.add(Mn(a,b))}}}catch{continue}let u=0,l=0;for(let[f,{rows:p}]of d)c.has(f)&&(u+=p,l++);u>0&&e.gaps?.add(Cu(t,a.name,u,l));for(let f of o){let p=f[a.name];typeof p=="string"&&c.has(Mn(a,p))&&!s.has(f)&&s.set(f,a.name)}}return s}async writeNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,remapper:d}=t;o&&o.pages++;let c=e.objectApiName===$e?this.endOfTheEmails(t,n!==void 0):t.onProgress,u=s.dryRun?"Simulated":"Completed",l=n===void 0?`${u} ${e.objectApiName}`:t.emailsWrittenFirst?"after their task":`${u} ${e.objectApiName} after their task`,f=n===void 0?`Stopped ${e.objectApiName}`:t.emailsWrittenFirst&&!o?"stopped after their task":`Stopped ${e.objectApiName} after their task`,p=t.preread.get(e.objectApiName);if(!p)return;let{fieldInfos:g,createableSet:h,targetSetsPending:m}=p;if(gt(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,p.records,g,this.currenciesTheirLinesWant(t,p.records));let j=await this.keptPrices(t,p.records);j.length!==p.records.length&&(p.records.length=0,p.records.push(...j))}let R=n??p.records,b=R.filter(j=>dn(s,j)),k=e.objectApiName===ce?R.filter(j=>rn(j)&&!dn(s,j)):[],O=await this.personContactsOnTheirOwn(t,k),w=new Set(k.filter(j=>!O.rows.has(j))),A=b.length>0||w.size>0?R.filter(j=>!dn(s,j)&&!w.has(j)):R,S=A,v=[];try{let j=null,F,B=null,E,_,ee=await(m??an(this.deps.describeFields,a,e.objectApiName).then($=>({ok:!0,sets:$}),$=>({ok:!1,error:$})));if(ee.ok)j=ee.sets.creatable,F=ee.sets.updateable,B=ee.sets.picklistValuesByField,E=ee.sets.picklistFields,_=ee.sets.fields;else{let $=ee.error;t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed \u2014 falling back to source schema)",messages:[$ instanceof Error?$.message:String($)]}]})}let X=j?dr(h,j):h,z=this.linkPersonContacts(t,[...w]);if(o&&(o.withTheirAccount+=z.linked,cd(o,z.notSent),z.linked===0&&(o.personContactsUnlinked+=w.size)),w.size>0&&z.linked===0&&A.length===0&&b.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,w.size,Qt(t,e.objectApiName))}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`});return}if(b.length>0&&(t.linkedCount+=b.length,o&&(o.writtenBefore+=b.length),this.oweLookupsOfRowsWrittenBefore(t,e,b,g,F),await this.oweStatusesFoundAfterStop(t,e.objectApiName,b),A.length===0&&w.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: 0 succeeded, ${Ed(s,b.length)}, 0 failed`});return}let J=await this.targetObjectInfoOf(t,e.objectApiName),Me=Lw(J);t.gaps?.knowRecordTypes(e.objectApiName,"target",J?.recordTypes??[]);let ke=await this.recordTypesHeldBack(e,A,J,X,t),ue=ke.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,A,ke):void 0,H=ue!==void 0&&ue.size>0&&(o!==void 0||ue.size<A.length);if(H){S=A.filter(W=>!ue.has(W)),t.failedCount+=ue.size;for(let W of ue.keys())t.heldInTheOrg.set(String(W.Id),"held");let $=[...ue.values()];if(v.push(...$),o?(o.withoutParent+=$.length,Hr($,o.withoutParentGroups),cd(o,Ih($))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:$.length,attemptedCount:0,samples:$d(Hr($),t.failedObjects)}),o&&S.length===0)return}else if(o?.heldWhole!==void 0&&ke.length===0){t.failedCount+=A.length,o.heldWholeRows+=A.length;return}if(ke.length>0&&!H){for(let W of ke)t.gaps?.add(Ph(W,J));if(t.failedObjects.add(e.objectApiName),t.failedCount+=A.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:A.length,attemptedCount:0,samples:ke.map(W=>({recordSummary:`RecordType=${W.developerName} (${W.recordCount} record${W.recordCount===1?"":"s"})`,messages:[Do(W)]}))}),o){o.heldWhole??=ke.map(Wo).join(" "),o.heldWholeRows+=A.length;return}let $=Qt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,A.length,$)}: `+ke.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."});return}S=this.holdBackSkippedRows(t,e,S,c,Me),S=this.leaveWhatHangsFromThePlatform(t,e,g,S);let Q=0;if(e.objectApiName===$e&&n===void 0){let $=this.holdEmailsForTheirTask(t,S);if(Q=S.length-$.length,S=$,Q>0&&S.length===0){let W={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${$s(Q)}`};c(W),o||(t.emailsAllWaiting={...W,status:"done",progress:100});return}}let pe=0;if(e.objectApiName===ut){let $=await this.linkTasksWrittenWithEmails(t,S);S=$.rows,pe=$.linked,o&&(o.withTheirEmail+=$.linked)}let we=new Set(s.fieldExclusions[e.objectApiName]??[]),Ee=s.fieldMappings[e.objectApiName]??{},ae=await this.teamOfTheOpportunities(t,e.objectApiName,S,J?.keyPrefix,g.flatMap($=>!$.isReference&&X.has($.name)&&!we.has($.name)&&Ee[$.name]===void 0?[$.name]:[]));S=ae.rows,o&&(o.teamOwners+=ae.owners,o.teamOthers+=ae.linked-ae.owners,jw(o.teamValues,ae.values));let D=await this.rowsWithoutTheirParent(e,t,g,S);for(let[$,W]of await this.rowsWhoseParentTheTargetLacks(e,t,g,S,me=>X.has(me)&&!we.has(me)&&Ee[me]===void 0))D.has($)||D.set($,W);let L=await this.rowsHeldInTheWholeOrg(e,t,g,S,$=>X.has($)&&!we.has($)&&Ee[$]===void 0);for(let[$,W]of L.held)D.has($)||D.set($,W);if(L.aside.size>0){for(let fe of D.keys())L.aside.delete(fe);gw(t,e.objectApiName,L.aside.values()),S.forEach((fe,Ce)=>{let ot=L.aside.get(Ce);ot&&t.heldInTheOrg.set(String(fe.Id),ot)});let $=S.filter((fe,Ce)=>!L.aside.has(Ce)),W=new Map;S.forEach((fe,Ce)=>{L.aside.has(Ce)||W.set(Ce,W.size)});let me=new Map;for(let[fe,Ce]of D){let ot=W.get(fe);ot!==void 0&&me.set(ot,Ce)}D.clear();for(let[fe,Ce]of me)D.set(fe,Ce);S=$}if(S.forEach(($,W)=>{let me=ae.held.get($);me&&!D.has(W)&&D.set(W,{field:me.field,parentObject:me.parentObject,reason:me.why})}),D.size>0&&(s.stream?.everything===!0&&S.forEach(($,W)=>{D.has(W)&&t.heldInTheOrg.set(String($.Id),"held")}),S=S.filter(($,W)=>!D.has(W)),t.failedCount+=D.size,o?(o.withoutParent+=D.size,Hr(D.values(),o.withoutParentGroups),cd(o,[{count:D.size,why:vd}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:D.size,attemptedCount:0,samples:aw(D,t.failedObjects)}),S.length===0&&ae.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let $=Q===0?Qt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,D.size,$)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`});return}await t.orphanExpander.expandForNode({node:e,fieldInfos:g,records:S,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?($,W,me,fe)=>this.anonymizeRows(t,$,[W],[me],fe,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:($,W)=>this.withoutFileContent(t,$,W,!0),startAsDraft:async($,W)=>(await this.startAsDrafts(t,$,[W])).get(0),oweStatus:($,W,me)=>this.oweStatus(t,$,W,me),objectOf:($,W)=>this.objectOfSourceId(t,$,W),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:($,W)=>this.sayRecordTypeNote(t,$,W),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:($,W)=>this.countWrittenWithoutFields(t,$,W),linkPersonContacts:$=>this.mapContactsOfPersonAccounts(t,$),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:$=>t.maskedSourceFields($),onMaskedLeftOut:($,W)=>this.noteEncryptedLeftOut(t,$,W),businessAccountsAmong:($,W)=>this.takenAsBusinessAccounts(t,$,W),contactOnItsOwn:$=>t.contactsOnTheirOwn.has($),...t.store?{calls:Es(t.store)}:{}}),S=this.leaveWhatHangsFromThePlatform(t,e,g,S);let Re=s.fieldMappings[e.objectApiName]??{},Ne=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),S,$=>X.has($)||Re[$]!==void 0),Ie=E?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:S,fields:E,written:$=>X.has($)&&!Ne.has($)&&Re[$]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:_!==void 0&&!_.some($=>$.name==="RecordTypeId")}):void 0;for(let $ of Ie?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,$);let ge=X.has("RecordTypeId")&&!Ne.has("RecordTypeId")&&Re.RecordTypeId===void 0,K=e.objectApiName===Se?await this.takenAsBusinessAccounts(t,S,ge):void 0,te=Po(e.objectApiName)?void 0:await this.currenciesFor(t,_,S,$=>X.has($)&&!Ne.has($)&&Re[$]===void 0),M=te?void 0:await this.parentCurrenciesFor(t,e.objectApiName,_,S);S=this.pricedInTheirRecordsCurrency(t,e.objectApiName,S);let q=gt(e.objectApiName)?$=>t.prices.convertedInto.get(String($.Id)):void 0,G=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,g,S,$=>X.has($)&&!Ne.has($)&&Re[$]===void 0):void 0,Te=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,S,X.has("OwnerId")&&!Ne.has("OwnerId")&&Re.OwnerId===void 0):void 0,ie=lh({objectApiName:e.objectApiName,records:S,...q?{pricedIn:q}:{},fieldInfos:g,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:$=>vs(t,$),ownerMappings:s.ownerMappings,...ae.lookups.size>0?{resolvedLookups:ae.lookups}:{},...G&&G.size>0?{targetLacks:G}:{},...Te?{inactiveOwners:Te}:{},...t.sample?{outsideTheSample:($,W)=>this.outsideTheSample(t,$.referenceTo??[],W)||t.heldInTheOrg.has(W)}:s.stream?.everything===!0?{heldByTheRun:$=>t.heldInTheOrg.has($)}:{},excludedFields:Ne,fieldRename:Re,creatableFields:X,updatableFields:F,picklistValuesByField:B,picklistFields:E,recordTypeValues:Ie?.byRecordType,businessAccounts:K,contactPoints:t.contactPoints??void 0,decide:($,W)=>s.decisions.applyToRow(e.objectApiName,$,Qh(s,W),t.decisionsApplied,Me),...te||M?{currencyFields:Io(_??[])}:{},...te?{currencies:te}:{},...M?{parentCurrencies:M}:{}}),ne=new Ko,U=new Fo;for(let{picklistChanges:$=[],currencyChange:W,source:me}of ie){ne.add(e.objectApiName,$),t.picklistChanges.add(e.objectApiName,$),o?.picklists.add(e.objectApiName,$),U.add(e.objectApiName,W),t.currencyChanges.add(e.objectApiName,W),o?.currencies.add(e.objectApiName,W);let fe=me.Id;W&&typeof fe=="string"&&t.currencyChangesById.set(fe,W)}let Oe=Vo(ne.list())+No(U.list())+gd(_h(new Map,ie))+Rd(Uh(ie))+md(wd(new Map,ie))+yd(bd(new Map,ie))+(o?"":Td(t,e.objectApiName));o&&(_h(o.lookupsNotCarried,ie),wd(o.lookupsOutsideTheRun,ie),bd(o.lookupsHeldBack,ie),o.ownersInactive+=Uh(ie)),this.noteLookupsOutsideTheRun(t,e.objectApiName,g,ie),await this.noteLookupsHeldBack(t,e.objectApiName,g,ie);for(let $ of ie)for(let W of $.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,W);xw(t,e.objectApiName,ie);let ye=ie.map($=>$.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(ye=t.recordTypeMapper.apply(ye,s.recordTypeMappings,$=>hs(e.objectApiName,$)));let le=this.applyRecordTypeDecisions(t,e.objectApiName,ie,ye);ye=this.anonymizeRows(t,e.objectApiName,ye,ie.map($=>String($.source.Id??"")),g,s.fieldMappings[e.objectApiName]??{});let Nt=new Map((_??[]).flatMap($=>$.length!==void 0&&$.length>0?[[$.name,$.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let $ of ye)s.decisions.truncate(e.objectApiName,$,Nt,t.decisionsApplied);let ft=new Map;t.gaps&&(ft=await this.findGaps(t,e,{cleanedRecords:ie,recordsToInsert:ye,targetFields:_,targetObject:J,picklistValuesByField:B,picklistFields:E,recordTypes:Ie?.byRecordType,unmapped:le}));let Tt=e.objectApiName===rr?await this.takeTheSyncCopies(t,ie,ye,b,{fields:_,updatable:F,keyPrefix:J?.keyPrefix}):{taken:0,given:0};e.objectApiName===We&&Aw(t,ie,ye);let wt=e.objectApiName===ze?await this.linkTheRolesThePlatformWrote(t,ie,ye,{fields:_,updatable:F,keyPrefix:J?.keyPrefix}):{linked:0,given:0},nt=await this.startAsDrafts(t,e.objectApiName,ye),At=new Map;if(t.store)for(let[$,W]of nt){let me=ie[$];me&&At.set(me,W)}let dt=[];if(gt(e.objectApiName)&&t.standardPricebookId){let $=ie.map((fe,Ce)=>Ce),{standard:W,custom:me}=Fc($.map(fe=>({index:fe,[tn]:ie[fe].source[tn]})),t.standardPricebookId);for(let fe of[W,me])fe.length!==0&&dt.push({records:fe.map(Ce=>ye[Ce.index]),cleaned:fe.map(Ce=>ie[Ce.index])})}dt.length===0&&(ye.length>0||Tt.taken===0&&wt.linked===0)&&dt.push({records:ye,cleaned:ie});let Xt=await this.recordTypeCounter(t,e.objectApiName,J,ge),Ae=ql();Ae.successCount+=Tt.taken;let yt;try{for(let $ of dt){if(t.simulated){this.simulateWrite(t,e,$,J?.keyPrefix,Ae,c,Xt,_,ft);continue}await t.batchWriter.writeNode({node:e,records:$.records,cleanedRecords:$.cleaned,fieldInfos:g,creatableFields:X,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:J?.keyPrefix,picklistFields:E,remapper:d,...t.store?{oweLookups:W=>this.oweToTheSecondPass(t,W)}:{},...t.store?{calls:Es(t.store)}:{},...At.size>0?{onWritten:(W,me)=>{let fe=At.get(W);fe!==void 0&&(At.delete(W),this.oweStatus(t,e.objectApiName,me,fe))}}:{},...Xt?{onCreatedWithoutRecordType:Xt}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(W=>W.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},Ae)}}catch($){if(!($ instanceof be))throw $;yt=$}finally{for(let[$,W]of nt){let me=ie[$];if(me&&t.store&&!At.has(me))continue;let fe=me?.source.Id;if(typeof fe!="string")continue;let Ce=d.get(fe);!Ce||d.isExisting(fe)||this.oweStatus(t,e.objectApiName,Ce,W)}this.countWrites(t,e.objectApiName,Ae)}let _e=Ae.successCount,pt=Ae.updatedCount,$t=Ae.linkedExistingCount,x=Ae.failureCount,Y=Ae.unidentifiedExistingCount;if(o){let $=dt.reduce((ot,zn)=>ot+zn.records.length,0),W=dt.flatMap(ot=>ot.cleaned);o.sent+=$,o.succeeded+=_e,o.updated+=pt,o.linked+=$t,o.linkedToCreated+=Ae.linkedToCreatedCount??0,o.failed+=x,o.alreadyExists+=Ae.alreadyExistsCount,o.unidentified+=Y,o.rolesOfTheirOpportunity+=wt.linked,o.rolesGiven+=wt.given,o.writtenWithoutFields=Ae.writtenWithoutFields?ia(o.writtenWithoutFields,Ae.writtenWithoutFields):o.writtenWithoutFields,Ae.flagsNotKept&&(o.flagsNotKept=eu(o.flagsNotKept,Ae.flagsNotKept));let me=yt?$-(_e+pt+$t+x):0,fe=W.slice(0,$-me).filter(ot=>O.rows.has(ot.source)).length;o.sentOnTheirOwn+=fe,fe>0&&(o.onTheirOwnWhy=O.why);let Ce=[...ud(o),...Qt(t,e.objectApiName)];if(yt)throw this.stopStreamedNode(e,t,o,me,f),yt;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${hd(s,o,Ce)}`});return}let re=_e+pt+$t+b.length+z.linked+ae.linked+wt.linked,ve=re+x,oe=ve>0?x/ve:0,se=x>0&&Ae.alreadyExistsCount===x,rt=x>0&&!se&&(re===0||oe>.5),he=ag($t,Ae.linkedToCreatedCount??0),qe=pt>0?`, ${pt} updated through their external id`:"",Ve=Y>0?` (${Y} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",bt=$=>[...Ih(v),...D.size>0?[{count:D.size,why:vd}]:[],...z.notSent,...$?Qt(t,e.objectApiName):[]],Zt=bt(Q===0),In=pe>0?`, ${pe} written by the platform with their email`:"",Ct=ig(z.linked,pd(t,e.objectApiName)),Un=dg(ae.owners,ae.linked-ae.owners)+cg(wt.linked,wt.given),vt=dt.flatMap($=>$.cleaned),Je=$=>vt.slice(0,$).filter(W=>O.rows.has(W.source)).length,en=$=>$>0?`, ${$} ${$===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",Xe=en(Je(vt.length)),Dt=b.length>0?`, ${Ed(s,b.length)}`:"",Mt=Q>0?`, ${$s(Q)}`:"",Rt=[Fi(Ae.flagsNotKept),ug(ae.values)].flatMap($=>$?[`, ${$}`]:[]).join(""),ct=ss(Ae.writtenWithoutFields),De=tg(t,e.objectApiName),Et=Ps(t,e.objectApiName),hn=n===void 0?Oh(t,e.objectApiName):"",eo=s.dryRun?"would be inserted":"succeeded",Gn=Tt.taken>0?` (${zf(Tt.taken,Tt.given,s.dryRun)})`:"",to=$=>`${_e} ${eo}${Gn}${qe}${he}${In}${Ct}${Un}${Dt}, ${x+_n($)} failed${Ve}${cn($)}`,gn=`${Xe}${Mt}${Rt}${Oe}${ct}${De}${Q===0?Et:""}${hn}`;if(yt){let $=dt.reduce((Ce,ot)=>Ce+ot.records.length,0),W=$-(_e+pt+$t+x)+Q;Od(t,e.objectApiName,W);let me=Q>0?` (${$s(Q)})`:"",fe=Je($-W+Q);throw this.saySentOnTheirOwn(t,fe,O.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:rt?"error":"stopped",progress:100,message:`${f}: ${to(bt(!0))}, ${W} not sent${me}${en(fe)}${Rt}${Oe}${ct}${De}${Et}`}),yt}if(this.saySentOnTheirOwn(t,Je(vt.length),O.why),rt){t.failedObjects.add(e.objectApiName),re>0&&t.failedInPart.add(e.objectApiName);let $=_n(Zt);c({objectName:e.objectApiName,status:"error",progress:100,message:re===0?`Failed all ${e.objectApiName} records: ${x+$} failed${cn(Zt)}${Xe}${Oe}${hn}`:`${x+$}/${ve+$} ${e.objectApiName} records failed (>50%)${cn(Zt)}${Xe}${Oe}${ct}${De}${hn}${Fh}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: ${to(Zt)}${gn}`})}catch(j){if(j instanceof be)throw j;t.failedObjects.add(e.objectApiName),t.failedCount+=S.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:S.length,attemptedCount:S.length,samples:[{recordSummary:"(stage failed before insert)",messages:[V(j)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(j)}`})}}};function ny(r,e){if(r.sample===void 0){if(e===void 0)return;throw new Error("A sample was handed to a run whose config copies every record, or walks from a record: run it as its config says, or ask the sample in its config. Nothing was read or written.")}if(r.inputMode!=="org"||e===void 0)throw new Error("The config asks a sample of the whole org, and the run was handed nothing to keep or take up its plan with: it would have copied every record. Nothing was read or written.");return{...e,options:r.sample}}function Pd(r,e,t,n){let o=t?.recordTypeMappings,s=Rs(e.anonymizePII,r,t?.anonymizationRules,n),i=t?.files?{maxFileBytes:t.files.maxFileSizeMB*1048576,acceptedAsIs:t.files.acceptedAsIs}:void 0,a=t?.writtenBefore,d=t?.beforeWrite,c=e.inputMode==="org",u=t?.stream,l=ny(e,u?.sample),f=c?{...u,everything:!0,writeWindow:xd,secondPassPageSize:xd,ceiling:void 0,wholeReadBound:u?.wholeReadBound??u?.ceiling??fo,...l?{sample:l}:{}}:u,p=[...new Set([...r.nodes.filter(Wc).map(O=>O.objectApiName),...e.excludedObjects??[]])],g=p.length>0?p:void 0,h=e.dryRun===!0?!0:void 0,m=Jo(e),R=e.keepContactPoints===!0?!0:void 0,b=ry(r,e,t?.roots);return b||e.inputMode==="record"&&typeof e.recordId=="string"?{...b?{roots:b}:{rootRecordId:e.recordId},rootObjectApiName:b?.objectApiName??r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:g,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:R,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:h,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||g||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||R||i||a||d||f||h||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:g,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:R,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:h,decisions:m}:void 0}function ry(r,e,t){let n=e.maxRoots??kr,o=r.nodes.find(a=>a.level===0)??r.nodes[0],s={...t?.plan?{plan:t.plan}:{},...t?.plan&&t.planOfTheRunRetried?{planOfTheRunRetried:!0}:{},...t?.keepAt!==void 0?{keepAt:t.keepAt}:{},...t?.fingerprint!==void 0?{fingerprint:t.fingerprint}:{},...t?.sourceRequestsLeft!==void 0?{sourceRequestsLeft:t.sourceRequestsLeft}:{},...t?.readTotal!==void 0?{readTotal:t.readTotal}:{}};if(e.inputMode==="record"&&t?.ids!==void 0){let a=o?.objectApiName;return a===void 0?void 0:{objectApiName:a,ids:[...t.ids],cap:n,...s}}if(!jc(e)||e.inputMode!=="soql")return;let i=wl(e.soqlQuery??"");if("issue"in i)throw Pe.of(Yo(i.issue,o?.objectApiName));return{objectApiName:o?.objectApiName??i.objectApiName,query:i.query,cap:n,...s}}var Jr="--checkpoint-first",Fd={switches:[Jr],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},oy=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function pg(r){return[` --checkpoint-first ${r.step??""}take a checkpoint of what ${r.run} writes before its`," first write: each object it writes, and each the"," target's flows that still run create as it writes"," them, held whole, as every checkpoint holds an object."," Its cost is that of the tables, not of the records",` written, and is said first. A rewind to it takes ${r.run}`," back (sandforge checkpoint rewind), and the work of"," anyone else on those objects since with it. Refused",` \u2014 another run writing, a limit, the disk \u2014 ${r.run}`," writes nothing, exit 1; deleted again when it writes",` nothing; with ${r.simulation}, says what it would hold and`," cost, and takes nothing (default: off)",...(r.note??[]).map(t=>` ${t}`)," --checkpoint-keep-days <n>"," the days that checkpoint is kept on this machine,"," 0 to 3650, 0 until it is deleted (default: 7)"," --checkpoint-exclude-object <ApiName>"," leave an object out of that checkpoint, named; a"," rewind leaves its records as they are; repeat for more"].join(`
|
|
7
|
+
import{b as _a,c as Jf,d as Qf}from"./chunk-BN33LVPQ.mjs";import{b as Zp}from"./chunk-JKT5YAQ2.mjs";import{d as ca,k as Vl,o as Jl,q as ua,r as Ql}from"./chunk-QAPVKPEC.mjs";import{a as Pt,d as Ba,e as Kt,f as An,i as ws,j as St,k as at}from"./chunk-BNKT3R3F.mjs";import{a as Lf}from"./chunk-QROPNEGY.mjs";import{b as vr,e as Jn}from"./chunk-BZ24IAP5.mjs";import{a as qt}from"./chunk-SCKUIE3R.mjs";import{a as yo,b as Ri,c as kt,d as Nn,e as Oi,f as nn,g as bo,h as ki,j as Si}from"./chunk-6FARZYMJ.mjs";import{$ as kp,A as Kf,Aa as Np,B as Vf,C as or,Ca as Cp,D as bs,Da as Mp,E as jn,Ea as Bp,F as Yf,G as Xf,H as Zf,I as qa,Ia as Lp,J as ep,Ja as Wp,K as tp,Ka as Xa,L as np,M as rp,Ma as Dp,N as op,O as Ua,Oa as _p,P as Rs,Pa as qp,Q as sp,Qa as Up,R as ip,Ra as Gp,S as ap,Sa as zp,T as gp,Ta as Za,U as mp,Ua as Hp,V as wp,Va as Kp,W as ir,Wa as ed,X as yp,Xa as Vp,Y as bp,Ya as Jp,Z as Rp,Za as Qp,_ as Op,_a as Yp,aa as Sp,ba as Tp,ca as za,cb as Xp,da as Ha,ea as ks,fa as Ap,ga as Ka,gb as eh,h as ps,ha as Lt,hb as Ss,ia as jp,ib as th,jb as td,ka as $p,kb as nd,lb as rd,m as La,ma as vp,mb as nh,n as Wf,na as Va,nb as rh,o as rr,p as We,pb as od,q as Df,qa as Ep,qb as sd,r as ys,ra as Ja,rb as oh,s as Wa,sa as Ip,sb as sh,t as Da,tb as ih,u as _f,ub as ah,v as qf,va as Qa,w as Uf,wa as xp,x as Gf,xa as Pp,y as zf,ya as Fp,z as Hf,za as Ya}from"./chunk-P55MKIZX.mjs";import{a as _r,b as ms,c as Mf,d as Bf,e as Pa,f as Fa,g as Na,h as Ca,j as Ma}from"./chunk-PYRZFUVU.mjs";import{a as Hi,b as zu,c as Hu,d as Ku,f as Nr,g as Uo,h as Ki,n as tl}from"./chunk-O2PUGRNW.mjs";import{C as Gi,H as _o,N as Yn,O as Gu,P as Fr,Q as qo,a as ou,m as Ui}from"./chunk-7SDZR6SR.mjs";import{f as $f,g as Ea,h as vf,i as xf,j as Pf,k as Ff,l as Nf,m as Cf,n as xa,o as nr}from"./chunk-TEIBWMJM.mjs";import{c as Ia,e as hs,f as Ef,g as If,h as gs}from"./chunk-BWWQXU2B.mjs";import{b as Xu,c as Zu,d as el}from"./chunk-T63U4OZJ.mjs";import{a as tf,e as nf,h as rf,j as of}from"./chunk-YAIIRFKJ.mjs";import{a as zl}from"./chunk-Q3DY7TO2.mjs";import{a as Ll,b as Dr,c as Wl,d as is,f as Dl,g as _l,h as aa,i as ql,j as Ul,k as Gl}from"./chunk-3XG25GTF.mjs";import{a as nl}from"./chunk-YYZL7UGV.mjs";import{a as Mu,c as _i,g as Bu,h as Lu,i as Wu}from"./chunk-54HYHHVL.mjs";import{b as Hl,c as da,e as Kl}from"./chunk-M6P5ZZLE.mjs";import{h as Bl,i as ia,j as ss}from"./chunk-WSUKC2U3.mjs";import{h as Vi}from"./chunk-3SKLBRPL.mjs";import{a as zi}from"./chunk-QSRAEUGZ.mjs";import{a as dp,b as Os,c as cp,d as Ga,e as sr,f as up,g as lp,h as fp,l as pp,m as hp}from"./chunk-JH27IKCO.mjs";import{c as Qu,d as Yu,h as al,j as dl}from"./chunk-SAMWHL22.mjs";import{b as zo,m as cl}from"./chunk-4JKR4PTZ.mjs";import{a as Ji,b as Cr,d as il,e as Go,g as Qi,h as Yi,j as Xn}from"./chunk-HKUWHVI7.mjs";import{d as kn}from"./chunk-VPDEJGPS.mjs";import{a as zc,b as Fn,c as On}from"./chunk-LHU6CPGE.mjs";import{f as wo}from"./chunk-ZUOPC4W2.mjs";import{b as rl,c as ol,g as sl}from"./chunk-JQZTMFO7.mjs";import{$a as tr,A as gl,Ab as ds,Ac as Aa,Bb as ma,Bc as ja,C as ml,Cb as gf,D as wl,Dc as Af,E as yl,Eb as cs,F as Qo,Fc as jf,G as bl,Ga as Zl,Gb as mf,Gc as $a,H as Rl,Hc as va,J as ea,K as ta,Ka as ef,Kb as us,L as Ol,Lb as wf,M as kl,Ma as er,Mb as yf,N as Yo,Nb as bf,O as Xo,Ob as ls,P as Br,Pb as wa,Q as Lr,R as Sl,S as Tl,Sa as df,T as Al,U as jl,V as Bn,Vb as ya,Xb as ba,Yb as Ra,_a as as,ac as Oa,bc as ka,c as Ni,cc as Rf,e as su,eb as cf,fb as uf,fc as Sa,g as $o,hb as Tn,i as iu,ic as Of,j as Ci,ja as Yl,jc as kf,k as Mi,kb as lf,l as au,la as Xl,lb as ff,m as Bi,mc as Ht,n as Li,na as la,o as ul,p as Ho,q as Zn,qc as Sf,r as ll,s as fl,sc as Tf,t as Ko,tc as fs,u as pl,v as Vo,w as Jo,wb as pf,x as hl,xb as hf,xc as Pe,y as Xi,yb as ha,yc as Ta,z as Zi,zb as ga}from"./chunk-JFNLKHY6.mjs";import{i as fa,q as pa,r as sf,s as af}from"./chunk-VZVICK7Q.mjs";import{a as Ye}from"./chunk-4TLYUZD5.mjs";import{a as na,b as Sn,c as $l,d as Zo,e as vl,f as Ke,g as El,h as Il,i as es,k as xl,l as Pl,m as Fl,n as ts,o as ra,p as Nl,q as zt,r as ns,s as on,t as oa,u as Cl,v as Wr,w as Ml,x as rs}from"./chunk-7PY3VQP3.mjs";import{a as Pr,c as du,d as Wi,e as cu,f as uu,g as lu,h as fu,j as pu}from"./chunk-INIT2UKJ.mjs";import{a as Uc}from"./chunk-SU65Z2BA.mjs";import{a as os,b as sa}from"./chunk-HF6LAK3G.mjs";import{l as Uu}from"./chunk-HFUDCNU5.mjs";import{a as gu,b as mu,c as Mn,d as Eu,e as Iu,h as xu,i as Pu,j as Fu,k as Nu,l as Cu,m as Di}from"./chunk-XZISAZA6.mjs";import{b as Gc,d as Hc,h as dh}from"./chunk-LCDPCUXS.mjs";import{a as it,b as Mr}from"./chunk-TQ2TQHTT.mjs";import{b as Tu,c as Bo,d as Au,e as ju,f as $u,g as Lo,i as vu,l as Wo,m as Do}from"./chunk-HFSBDM7B.mjs";import{a as Co,b as Mo}from"./chunk-OHEOJISY.mjs";import{a as vo,c as hu}from"./chunk-EADHKH3A.mjs";import{a as Ao,b as jo,c as xr,e as ru}from"./chunk-L4INJ5TZ.mjs";import{C as $i,D as So,E as Qn,F as ze,G as Le,H as vi,I as Ir,L as Ei,M as Ii,N as Zc,Q as xi,X as Pi,a as Cn,aa as Fi,b as $e,ba as eu,c as ut,da as tu,f as Kc,g as Vc,h as Jc,i as Qc,ja as nu,ka as To,m as Yc,n as Ti,o as Oo,p as Ai,q as Se,r as ce,s as Er,t as rn,u as ko,w as ji,z as Xc}from"./chunk-KIMQQ6JQ.mjs";import{a as Ro,h as Be}from"./chunk-TZE3Y7IQ.mjs";import{b as V}from"./chunk-CA5NAXSU.mjs";import{c as Du,f as _u,j as qi,k as qu}from"./chunk-ZUTUYBNW.mjs";import{a as He,i as wu,j as yu,l as Eo,o as Io,p as bu,q as xo,r as Ru,s as Po,t as Ou,u as ku,v as Fo,w as Su,x as No}from"./chunk-ICIYL45C.mjs";import{a as Vu,d as Ju}from"./chunk-TUACWKIH.mjs";import{Ac as jr,Bc as Gt,Cc as mt,Cd as yi,Da as xc,Ec as wi,Fc as Nc,H as xn,Hd as bi,I as uo,Ic as Cc,Jc as Mc,Kd as _c,P as Rc,Pd as qc,T as Oc,Td as Vn,Uc as Kn,Ud as mo,W as lo,X as fo,Xc as ho,Y as li,Z as kr,_ as bn,ca as kc,da as Sc,ha as Tc,hc as Sr,hd as Bc,ia as Ac,id as Lc,ja as jc,jc as Pc,ka as $c,mc as Qe,md as go,na as po,nc as Tr,oa as fi,pa as pi,pc as Ar,qa as vc,ra as hi,rc as et,sa as Ec,sc as Ut,tc as tn,td as $r,ua as Rn,uc as mi,ud as Wc,va as Ic,vc as gt,wd as Dc,xc as Fc,ya as gi,yc as Pn,zc as Hn}from"./chunk-ZQO5PDX5.mjs";import{A as C}from"./chunk-WZQEK4WT.mjs";import{createHash as fy,randomUUID as Us}from"node:crypto";import{existsSync as Yt,readFileSync as pn,readdirSync as py,renameSync as Vg,rmSync as Ws,statSync as Jg,writeFileSync as Qg}from"node:fs";import{basename as rc,dirname as hy,join as Kd,resolve as Wt,sep as gy}from"node:path";import{createReadStream as Nm,existsSync as Cm}from"node:fs";import{createInterface as Mm}from"node:readline";var ch=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Bm(r){let e=[],t=Mm({input:Nm(r,"utf8"),crlfDelay:1/0}),n=(o,s)=>{typeof s!="string"||!Number.isFinite(Date.parse(s))||(o.endedAt===void 0||Date.parse(s)>Date.parse(o.endedAt))&&(o.endedAt=s)};for await(let o of t){let s=e.at(-1);if(o.startsWith('{"part":')){try{let{part:f}=JSON.parse(o),p=typeof f?.startedAt=="string"?f.startedAt:void 0;e.push({...p?{startedAt:p}:{},wrote:[]})}catch{e.push({wrote:[]})}continue}if(!s)continue;if(o.startsWith('{"end":')){try{n(s,JSON.parse(o).end?.at)}catch{}continue}let i=cl(o);if(i){n(s,i.at),(s.jobEndedAt===void 0||Date.parse(i.orgAt)>Date.parse(s.jobEndedAt))&&(s.jobEndedAt=i.orgAt);continue}if(!o.startsWith('["x"')&&!o.startsWith('["p"')&&!o.startsWith('["g"'))continue;let a;try{a=JSON.parse(o)}catch{continue}if(!Array.isArray(a))continue;let[d,c,u,l]=a;d==="x"?n(s,l):d==="p"&&typeof c=="string"&&ch.test(c)?s.wrote.push(c):d==="g"&&typeof u=="string"&&ch.test(u)&&s.wrote.push(u)}return e}async function uh(r,e){if(!Cm(r))return[];let t;try{t=await Bm(r)}catch{return[]}let n=[];for(let[o,s]of t.entries()){let i=await e.readAt(r,o).catch(()=>{});if(!i)return[];n.push({part:o,created:i.created,linked:i.remap.linked.flatMap(a=>{let d=i.remap.table[a];return d!==void 0?[d]:[]}),wrote:s.wrote,...s.startedAt?{startedAt:s.startedAt}:{},...s.endedAt?{endedAt:s.endedAt}:{},...s.jobEndedAt?{jobEndedAt:s.jobEndedAt}:{}})}return n}function Ln(r){let e=Date.parse(r.endedAt??"");if(!Number.isFinite(e))return;let t=Date.parse(r.startedAt??""),n=Date.parse(r.jobEndedAt??"");return{runRecordedAt:new Date(e),runDurationMs:Number.isFinite(t)&&t<=e?e-t:0,endedByItsWrites:!0,...Number.isFinite(n)?{writtenUntil:new Date(n)}:{}}}function ar(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=Ln(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function Wn(r){return r.flatMap(e=>e.ids)}function sn(r,e){if(e===void 0)return r.map(n=>({...n,ids:[...n.ids]}));let t=new Set(e.map(n=>n.slice(0,15)));return r.flatMap(n=>{let o=n.ids.filter(s=>t.has(s.slice(0,15)));return o.length>0?[{objectApiName:n.objectApiName,ids:o}]:[]})}function Fe(r,e=Date.now()){return Math.max(0,e-r)}var id=class{listenerMap=new Map;on(e,t){let n=this.listenerMap.get(e);return n||(n=new Set,this.listenerMap.set(e,n)),n.add(t),()=>{n.delete(t)}}emit(e,t){let n=this.listenerMap.get(e);if(n)for(let o of n)try{o(t)}catch(s){Ye.warn("Event listener threw an error",{eventType:String(e),error:V(s)})}}removeAllListeners(){this.listenerMap.clear()}};var qr=class r{constructor(e){this.store=e}store;map=new Map;existing=new Set;updated=new Set;objectOf=new Map;aliases=new Map;createdKeys=new Set;alias(e,t){e!==t&&this.aliases.set(e,t)}add(e,t,n){if(this.store){this.store.setMapping("created",e,t,n);return}this.forgetCreated(e),this.createdKeys.add(t.slice(0,15)),this.map.set(e,t),this.existing.delete(e),this.updated.delete(e),this.label(e,n)}addUpdated(e,t,n){if(this.store){this.store.setMapping("updated",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.delete(e),this.updated.add(e),this.label(e,n)}addExisting(e,t,n){if(this.store){this.store.setMapping("existing",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.add(e),this.updated.delete(e),this.label(e,n)}countsByObject(){if(this.store)return this.store.countsByObject();let e=new Map;for(let[t,n]of this.objectOf){let o=e.get(n)??{objectApiName:n,created:0,linked:0,updated:0};this.existing.has(t)?o.linked++:this.updated.has(t)?o.updated++:o.created++,e.set(n,o)}return[...e.values()].map(({updated:t,...n})=>t>0?{...n,updated:t}:n)}createdByObject(){let e=new Map;if(this.store){for(let{kind:t,sourceId:n,objectApiName:o,earlier:s}of this.store.mappings()){if(t!=="created"||s||!o)continue;let i=e.get(o)??[];i.push(n),e.set(o,i)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}for(let[t,n]of this.objectOf){if(this.existing.has(t)||this.updated.has(t))continue;let o=e.get(n)??[];o.push(t),e.set(n,o)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}forgetCreated(e){let t=this.map.get(e);t!==void 0&&!this.existing.has(e)&&!this.updated.has(e)&&this.createdKeys.delete(t.slice(0,15))}createdTarget(e){return this.store?this.store.createdTarget(e):this.createdKeys.has(e.slice(0,15))}label(e,t){t?this.objectOf.set(e,t):this.objectOf.delete(e)}isExisting(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&(t.kind==="existing"||t.earlier)}return this.existing.has(e)}isCreated(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&t.kind==="created"&&!t.earlier}return this.map.has(e)&&!this.existing.has(e)&&!this.updated.has(e)}wasCreated(e){return this.store?this.store.mapping(e)?.kind==="created":this.isCreated(e)}existingSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="existing"||t).map(({sourceId:e})=>e):[...this.existing]}updatedSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="updated"&&!t).map(({sourceId:e})=>e):[...this.updated]}get(e){let t=this.aliases.get(e)??e;return this.store?this.store.targetOf(t):this.map.get(t)}remapRecord(e,t){let n={...e};for(let o of t){let s=n[o];if(typeof s=="string"){let i=this.aliases.size>0?this.aliases.get(s)??s:s,a=this.store?this.store.targetOf(i):this.map.get(i);a!==void 0&&(n[o]=a)}}return n}persist(){this.store?.flush()}get count(){return this.store?this.store.mappedSize:this.map.size}clear(){this.aliases.clear(),this.map.clear(),this.existing.clear(),this.updated.clear(),this.objectOf.clear(),this.createdKeys.clear()}toJSON(){let e={};if(this.store){for(let{sourceId:t,targetId:n}of this.store.mappings())e[t]=n;return e}for(let[t,n]of this.map)e[t]=n;return e}static fromJSON(e){let t=new r;for(let[n,o]of Object.entries(e))n==="__proto__"||n==="constructor"||n==="prototype"||typeof o=="string"&&t.add(n,o);return t}};var Wm={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},Ts=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??Wm[e]??"Name",i=Be(e),a=Be(s),d=new Map;for(let b of t){let k=b.Id,O=b[s];typeof k=="string"&&typeof O=="string"&&O&&d.set(k,O)}if(d.size===0)return{mappings:[],unmatched:t.map(b=>({sourceId:typeof b.Id=="string"?b.Id:"",matchValue:typeof b[s]=="string"?b[s]:null})).filter(b=>b.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,u=Pr(`${c})`),l=Pr(", "),f=new Map,p=[],g=u,h=async()=>{if(p.length===0)return;let b=`${c}${p.join(", ")})`;p=[],g=u;for(let k of await this.query(n,b)){let O=k.Id,w=k[s];typeof O=="string"&&typeof w=="string"&&f.set(w,O)}};for(let b of new Set(d.values())){let k=`'${Ro(b)}'`,O=(p.length>0?l:0)+Pr(k);p.length>=$l||p.length>0&&g+O>14e3?(await h(),g+=Pr(k)):g+=O,p.push(k)}await h();let m=[],R=[];for(let[b,k]of d){let O=f.get(k);O?m.push({sourceId:b,targetId:O,matchedBy:s,matchValue:k}):R.push({sourceId:b,matchValue:k})}return{mappings:m,unmatched:R}}};function ad(r,e){let t=new Set(r.filter(s=>s.createable).map(s=>s.name)),n=new Set(r.filter(s=>s.updateable!==!1).map(s=>s.name)),o=new Map;for(let s of r)s.picklistValues&&s.picklistValues.length>0&&o.set(s.name,new Set(s.picklistValues));return{creatable:t,updateable:n,picklistValuesByField:o.size>0?o:null,picklistFields:ul(r,e),fields:r}}async function an(r,e,t){return ad(await r(e,t),t)}function dd(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function dr(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var Dm=new Map;function lh(r){let{objectApiName:e,records:t,fieldInfos:n,remapper:o,referenceFallback:s,failedObjects:i,writtenObjects:a,neverCopied:d,ownerMappings:c,resolvedLookups:u,targetLacks:l,inactiveOwners:f,excludedFields:p,fieldRename:g,creatableFields:h,updatableFields:m,picklistValuesByField:R,picklistFields:b,recordTypeValues:k,businessAccounts:O,contactPoints:w,decide:A,currencies:S,currencyFields:v=Dm,parentCurrencies:j,pricedIn:F,outsideTheSample:B,heldByTheRun:E}=r,_=n.filter(H=>H.isReference).map(H=>H.name),ee=new Set(_),X=w?.forObject(e,n,g),z=H=>h.has(H.name)||g[H.name]!==void 0,J=new Set(n.filter(H=>H.isReference&&(H.referenceTo??[]).some(Q=>i?.has(Q))).map(H=>H.name)),Me=new Set(n.filter(H=>{let Q=H.referenceTo??[];return H.isReference&&Q.length===1&&a?.has(Q[0])===!0}).map(H=>H.name)),ke=ru(n.filter(H=>H.isReference),d),ue=b??new Map;return t.map(H=>{let Q=[],pe=[],we=[],Ee=[],ae=u?.get(H);for(let U of n){if(!U.isReference||p.has(U.name)||ae?.[U.name]!==void 0)continue;let Oe=z(U),ye=dd(U,m,g[U.name]);if(!Oe&&!ye)continue;let le=H[U.name];if(B&&U.name!=="RecordTypeId"&&typeof le=="string"&&le!==""&&!o.get(le)&&B(U,le)){pe.push(U.name),we.push(g[U.name]??U.name);continue}if(E&&U.name!=="RecordTypeId"&&typeof le=="string"&&le!==""&&!o.get(le)&&E(le)){pe.push(U.name),Ee.push(g[U.name]??U.name);continue}if(s!=="nullify"&&!J.has(U.name)&&!Me.has(U.name)||U.name==="RecordTypeId"||ke.has(U.name))continue;let Nt=H[U.name];typeof Nt!="string"||!Nt||Oe&&o.get(Nt)||(pe.push(U.name),Q.push({field:g[U.name]??U.name,sourceRefId:Nt,targetObjects:U.referenceTo??[],...ye?{}:{insertOnly:!0}}))}let D=_.filter(U=>U!=="RecordTypeId"),L=o.remapRecord(H,D);for(let U of pe)L[U]=null;for(let[U,Oe]of Object.entries(ae??{}))L[U]=Oe;let Re=L.OwnerId,Ne=!1;typeof Re=="string"&&c[Re]&&(L.OwnerId=c[Re],Ne=!0);let Ie=ko(L,O?.has(H)===!0),ge={},K=new Set,te=[],M=[],q;for(let U of Object.keys(L)){if(p.has(U))continue;let Oe=g[U];if(Oe){L[U]!==null&&(ge[Oe]=L[U]),K.add(Oe);continue}if(!h.has(U))continue;if(ae?.[U]!==void 0){ge[U]=ae[U];continue}if(U!=="RecordTypeId"&&ke.has(U)&&!(U==="OwnerId"&&Ne)){if(s!=="keep")continue;let le=L[U];if(typeof le=="string"&&l?.has(le)){te.push(U);continue}if(U==="OwnerId"&&typeof le=="string"&&f?.has(le)){q=le;continue}}else if(s==="keep"&&U!=="RecordTypeId"&&ee.has(U)){let le=L[U];if(typeof le=="string"&&l?.has(le)){M.push(U);continue}}if(ho(e,U,Ie))continue;let ye=L[U];ye!==null&&(ge[U]=ye)}let G=ge.RecordTypeId;A?.(ge,typeof G=="string"?G:void 0);for(let U of Nc(e,ge))delete ge[U];let Te;S&&!K.has(He)?Te=xo(ge,{read:H[He],currencyFields:v,recordTypeDefault:Zn(k,G)?.picklists.get(He)?.defaultValue,ratesOn:Eo(e,H),pricedIn:F?.(H)},S):j&&(Te=ku(ge,{read:H[He],parent:Ou(e,H,_,j.changeOf),currencyFields:v},j.currencies));let ie=Ho(ge,R,ue,Zn(k,G),K),ne=Yc(e,ge);for(let U of ne)delete ge[U];return X?.(ge),{source:H,cleaned:ge,nullifiedFks:Q.filter(U=>!ne.includes(U.field)),picklistChanges:ie,...Te?{currencyChange:Te}:{},...te.length>0?{lookupsNotCarried:te}:{},...M.length>0?{lookupsOutsideTheRun:M}:{},...we.length>0?{lookupsOutsideTheSample:we}:{},...Ee.length>0?{lookupsHeldBack:Ee}:{},...q!==void 0?{ownerInactive:q}:{}}})}var _m=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,fh=Symbol("left to the platform"),As=class{constructor(e){this.deps=e}deps;expansionsUsed=0;failedOrphans=new Set;expansionErrors=[];pastTheCap=new Map;cap=0;async expandForNode(e){if(!e.enabled)return;this.cap=e.maxExpansions;let{fieldInfos:t,records:n,remapper:o,scopeCache:s}=e,i=new Map,a=t.filter(l=>l.isReference&&l.nillable===!1&&l.name!=="RecordTypeId");for(let l of n)for(let f of a){let p=l[f.name];if(typeof p!="string"||!p||o.get(p)||e.leftToThePlatform?.has(p))continue;let g=await this.parentObjectOf(e,f,p);if(!g)continue;let h=`${g}::${p}`;i.has(h)||i.set(h,{object:g,sourceId:p})}let d=4,c=[];for(let[,l]of i){let f=`${l.object}::${l.sourceId}`;if(!this.failedOrphans.has(f)&&!o.get(l.sourceId)){if(this.expansionsUsed+c.length>=e.maxExpansions){this.pastTheCap.set(f,l.object);continue}c.push({...l,cacheKey:f})}}let u=[c.filter(l=>l.object!==ce),c.filter(l=>l.object===ce)];for(let l of u){let f=[];for(let p=0;p<l.length;p+=d){let g=l.slice(p,p+d).filter(h=>!o.get(h.sourceId));await Promise.all(g.map(async h=>{try{let m=await this.expandSingleOrphanParent(e,h.object,h.sourceId);if(m===fh)return;m&&"id"in m?(this.expansionsUsed++,this.pastTheCap.delete(h.cacheKey),m.existing?o.addExisting(h.sourceId,m.id,h.object):(o.add(h.sourceId,m.id,h.object),m.owedStatus&&e.oweStatus?.(h.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(h.object,[h.sourceId]),h.object===Se&&rn(m.source)&&f.push(m.source)):(this.failedOrphans.add(h.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${h.object}/${h.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(h.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${h.object}/${h.sourceId}`,messages:[V(m)]})}}))}f.length>0&&await e.linkPersonContacts?.(f)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!Ao(a)),i;return o.length===1?i=s[0]:s.length>0&&(i=await e.objectOf?.(n,s)),i===e.node.objectApiName?void 0:i}capReport(){return this.pastTheCap.size===0?null:{cap:this.cap,notCopied:this.pastTheCap.size,objects:[...new Set(this.pastTheCap.values())]}}buildErrorReport(){return this.failedOrphans.size===0?null:{objectApiName:"__expandOrphanParents__",stage:"insert",failedCount:this.failedOrphans.size,attemptedCount:this.expansionsUsed+this.failedOrphans.size,samples:this.expansionErrors}}async expandSingleOrphanParent(e,t,n){let{sourceOrgId:o,targetOrgId:s,recordTypeMappings:i,recordTypeMapper:a}=e,{anonymize:d,withoutFileContent:c,startAsDraft:u,leftToThePlatform:l}=e;if(!_m.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let f=Be(t),p=await this.deps.describeFields(o,f),g=c?c(f,p):p,h=zt(g,e.fieldExclusions?.[f]);h.length===0&&h.push("Id");let m=`SELECT ${h.join(", ")} FROM ${f} WHERE Id = '${Ro(n)}'`,R=await this.deps.queryRecords(o,m);if(R.length===0)return null;if(l&&l.keep(f,R).length===0)return fh;let b=R[0],k=rn(b),O=k?await e.personAccountsInTarget?.():void 0;if(f===ce&&k&&O!==!1&&e.contactOnItsOwn?.(n)!==!0)throw new Error("Not copied: a person account's contact is written by the platform with its account, never on its own");let w=null;try{w=ad(await this.deps.describeFields(s,f),f)}catch(D){Ye.warn(`[forge] orphan-parent target describe failed for ${t}: ${D instanceof Error?D.message:String(D)}. Falling back to source createable.`)}let A=new Set(g.filter(D=>D.createable).map(D=>D.name)),S=w?dr(A,w.creatable):A,v=new Set(e.fieldExclusions?.[f]??[]),j=e.fieldMappings?.[f]??{},F=new Set,B=new Set(await e.maskedFieldsOf?.(f).catch(()=>[])??[]),E=[],_=S.has("RecordTypeId")&&!v.has("RecordTypeId")&&j.RecordTypeId===void 0,ee=f===Se&&k&&(e.businessAccountsAmong?(await e.businessAccountsAmong([b],_)).has(b):O===!1),X=ko(b,ee),z={};for(let D of g){let L=D.name;if(v.has(L))continue;let Re=b[L];if(Re==null)continue;if(B.has(L)){(j[L]!==void 0||S.has(L))&&E.push(L);continue}if(D.isReference&&typeof Re=="string"&&L!=="RecordTypeId")continue;let Ne=j[L];if(Ne){z[Ne]=Re,F.add(Ne);continue}S.has(L)&&(ho(f,L,X)||(z[L]=Re))}if(e.contactPoints?.forObject(f,g,j)?.(z),w){let D=new Set([...S].filter(L=>!v.has(L)&&!j[L]));await this.checkPicklists(e,f,b,z,w,D,F)}let J=a&&i?a.apply([z],i,D=>hs(f,D))[0]:z,Me=d?d(f,J,n,g):J,ke=u?await u(f,Me):void 0,ue=await this.insertParent(e,f,n,Me),H=ue.written,Q=ue.callId;if(!H)return null;let pe=H.success?void 0:_l(H,Me,void 0),we=H.errors;if(pe){let D=await this.insertParent(e,f,n,Bl(Me,pe));if(!D.written)return{refused:["No result returned for record",aa(pe,we)]};H=D.written,Q=D.callId}if(H.success)return E.length>0&&e.onMaskedLeftOut?.(f,E),pe&&e.onWrittenWithoutFields?.(f,{rows:1,fields:pe.map(D=>({...D,rows:1}))}),{id:H.id,existing:!1,owedStatus:ke,source:b,...Q!==void 0?{callId:Q}:{}};let Ee=this.deps.describeObject?await this.deps.describeObject(s,f).then(D=>D.keyPrefix,()=>null):null,ae=qu(H,Ee);return ae.kind==="linked"?{id:ae.id,existing:!0,source:b}:{refused:pe?[...H.errors,aa(pe,we)]:H.errors}}async insertParent(e,t,n,o){let s=e.calls?.sending(t,[{sourceId:n,payload:o}]),i;try{i=(await this.deps.insertRecords(e.targetOrgId,t,[o]))[0]}catch(a){throw s!==void 0&&nl(a)!=="may-have-written"&&e.calls?.answered(s),a}return s===void 0?{written:i}:i?.success?{written:i,callId:s}:(e.calls?.answered(s),{written:i})}async checkPicklists(e,t,n,o,s,i,a){let d=e.recordTypePicklists?await e.recordTypePicklists.forRows({objectApiName:t,rows:[n],fields:s.picklistFields,written:p=>i.has(p),recordTypeMappings:e.recordTypeMappings,withoutRecordTypes:!s.fields.some(p=>p.name==="RecordTypeId")}):void 0;for(let p of d?.notes??[])e.onRecordTypeNote?.(t,p);let c=o.RecordTypeId,u=n[He],l=e.currencies&&i.has(He)&&typeof u=="string"&&u!==""?await e.currencies():void 0;if(l){let p=xo(o,{read:u,currencyFields:Io(s.fields),recordTypeDefault:Zn(d?.byRecordType,c)?.picklists.get(He)?.defaultValue,ratesOn:Eo(t,n)},l);e.currencyChanges?.add(t,p);let g=n.Id;p&&typeof g=="string"&&e.currencyChangesById?.set(g,p)}let f=Ho(o,s.picklistValuesByField,s.picklistFields,Zn(d?.byRecordType,c),a);e.picklistChanges?.add(t,f)}};async function*js(r,e){let t=e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):0,n=0,o=[];for await(let s of r){if(t===0){if(s.length===0&&n>0)continue;n++,yield s;continue}for(o=o.length===0?[...s]:[...o,...s];o.length>=t;)n++,yield o.slice(0,t),o=o.slice(t)}(o.length>0||n===0)&&(yield o)}function Vt(r,e,t,n,o,s){let{queryPages:i}=r;if(i)return js(s?.all?i(e,t,s):i(e,t),n);if(s?.all)throw new Error("The deps read no archived row: no cursor to read through queryAll.");return js((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function hh(r){let e=async(...n)=>{let[o,s,...i]=n,a=Wi(s),d=cu(s,a===void 0?void 0:["Id",a.stamp]);if(!d)return r.queryRecords(...n);let c=await r.queryRecords(o,d.first,...i),u=l=>r.queryRecords(o,l);return a===void 0?lu(c,d,u):fu(c,d,u,a)},t=(n,o,s)=>pu(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??ph(),s?.all?i=>qm(r.queryPages?.(n,i,s)??ph()):i=>r.queryRecords(n,i),Wi(o));return new Proxy(r,{get(n,o,s){return o==="queryRecords"?e:o==="queryPages"?n.queryPages?t:void 0:Reflect.get(n,o,s)}})}async function qm(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*ph(){}var be=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},xd=Dr;function Gm(r){let e=r.from!=="plan"?r.from:r.fromTheJournal?"resumed":r.ofTheRunRetried?"retried":"simulation";return{objectApiName:r.objectApiName,count:r.ids.size,from:e,readAt:r.readAt}}var zm={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},Ft=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,mh=2e3;function Hm(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,failed:0,alreadyExists:0,unidentified:0,writtenBefore:0,withTheirAccount:0,withTheirEmail:0,teamOwners:0,teamOthers:0,teamValues:{notKept:new Map,unread:new Map},rolesOfTheirOpportunity:0,rolesGiven:0,personContactsUnlinked:0,sentOnTheirOwn:0,onTheirOwnWhy:"",withoutParent:0,withoutParentGroups:new Map,rowsLeft:()=>0,held:new Map,heldWholeRows:0,picklists:new Ko,currencies:new Fo,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,ownersInactive:0}}function wh(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function yh(r){return[Fi(r.flagsNotKept),ug(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function cd(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function ud(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var Km=5e3,Vm=2e3,bh="afterTask",ld=3,Rh=1e3,Dn=2e3;function Ur(r,e,t){return{objectApiName:r,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:e.filter(n=>n.createable).length,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}function Jm(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(et))}function sg(r,e){let t=[];for(let n of e){let o=n.referenceTo??[];if(!n.isReference||o.length!==1||!Qe(r,n.name,n.nillable))continue;let[s]=o;s!==r&&!Ke.has(s)&&t.push(s)}return t}function Qm(r,e,t){return sg(r,e).find(n=>t.has(n))}function Ym(r,e,t){let n=t.scopeCache;if(!n)return[];let o=new Set(t.graph.edges.filter(i=>i.targetObject===r).map(i=>i.sourceObject)),s=new Set;for(let i of e)if(i.isReference)for(let a of i.referenceTo??[])a!==r&&o.has(a)&&t.readObjects.has(a)&&!Ke.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var Xm=3,Zm=10,ew=5;function tw(r,e){let t=e.rows.filter(({objectApiName:s,row:i})=>{let a=i.Id;return typeof a!="string"||!r.heldForExclusions.get(s)?.has(a)});if(t.length===e.rows.length)return e;let n=new Set,o=new Set;for(let{objectApiName:s,row:i,field:a}of t)n.add(String(i[a])),o.add(s);return{ids:n,neededBy:o,rows:t}}function Oh(r,e){let t=r.readAsParents.get(e);return!t||t.count===0?"":`, ${t.count} read by id for the ${[...t.neededBy].sort().join(", ")} records that cannot be written without ${t.count===1?"it":"them"}`}function kh(r,e){let t=r.get(e)??new Set;if(!r.isRead(e))return new Set(t);let n=r.scopeOf(e);return new Set([...t].filter(o=>!n?.has(o)))}function Gr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function Sh(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function xs(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}var nw={storage:{past:"past the data storage the target has left",more:", or free data storage in the target"},within:{past:"past the MB it may take (--fit-within)",more:", or let it take more (--fit-within)"},maxTotal:{past:"past the records it may write (--max-total)",more:", or raise --max-total"},targetRequests:{past:"past the API requests the target has left today",more:", or run it once the target has more to spare"},bulkBatches:{past:"past the Bulk API batches the target has left today",more:", or run it once the target has more to spare"},sourceRequests:{past:"past the API requests the source has left today",more:", or run it once the source has more to spare"},heavyRoots:{past:"past what the sample may take",more:""},whole:{past:"past what the sample may take",more:""},draw:{past:"past what the sample may take",more:""}};function Th(r,e){let t=r/1048576*100;return(e==="up"?Math.ceil(t):Math.floor(t))/100}var jd=class extends ir{constructor(t,n,o){super("SAMPLE_CANNOT_FIT",t,n);this.sample=o}sample},Ah=3;function rw(r,e){let t=e.slice(0,Ah).map(({sourceId:i,matchValue:a})=>({recordSummary:`Id=${i} matchValue=${a??"null"}`,messages:[a===null?`This ${r} has no name to find it by in the target org: the records that point at it are not linked to one.`:`No ${r} of the target org is named "${a}": the records that point at it are not linked to one. Create a ${r} of that name in the target\u2019s Setup, or rename one of the target\u2019s to it, then run again.`]})),n=e.slice(Ah);if(n.length===0)return t;let o=n.map(({matchValue:i})=>i===null?"no name":`"${i}"`),s=o.length===1?o[0]:`${o.slice(0,-1).join(", ")} or ${o.at(-1)}`;return[...t,{recordSummary:`${n.length} more`,messages:[`No ${r} of the target org is named ${s} either.`]}]}function ow(r){let e=r.orphanExpander.capReport();return e?{orphanParentsCapped:e}:{}}function jh(r){let e=xs(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function sw(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function iw(r,e,t){let n=t.filter(d=>d.isReference),o=d=>n.filter(c=>(c.referenceTo??[]).includes(d)),s=d=>{let c=o(d);return c.length>0&&c.every(u=>(u.referenceTo??[]).length>1)},i=d=>{let c=o(d);return c.length>0&&c.every(u=>u.nillable===!0)},a=new Set(ts(e,new Map([[r,t]])).edges.filter(d=>d.targetObject===r&&(d.required===!0||d.type==="master-detail"&&!i(d.sourceObject))&&Fl(d)&&!s(d.sourceObject)).map(d=>d.sourceObject));for(let d of n){let c=d.referenceTo??[];c.length!==1||!Tr(d)||!Qe(r,d.name,d.nillable)||a.add(c[0])}return a.delete(r),[...a]}function aw(r,e){return $d(Hr(r.values()),e)}function Hr(r,e=new Map){for(let{field:t,parentObject:n,notInTarget:o,reason:s,recordType:i}of r){let a=`${t}|${n}|${o===!0?"outside":""}|${s??""}`,d=e.get(a)??{field:t,parentObject:n,...o?{notInTarget:o}:{},...s!==void 0?{reason:s}:{},...i?{recordType:i}:{},count:0};d.count++,e.set(a,d)}return e}function $d(r,e){return[...r.values()].sort((t,n)=>n.count-t.count).slice(0,3).map(({field:t,parentObject:n,notInTarget:o,reason:s,recordType:i,count:a})=>({recordSummary:i?`RecordType=${i.developerName} (${a} record${a===1?"":"s"})`:`${t} \u2192 ${n} (${a} record${a===1?"":"s"})`,messages:i?[Do({...i,recordCount:a})]:[s!==void 0?`Not written: ${s}`:o?`Not written: ${t} may not be left empty, and the target holds no ${n} record of the id it names, outside the run.`:`Not written: ${t} may not be left empty, and the ${n} it points at `+(e.has(n)?"failed in this run.":"was not written by this run.")]}))}var dw=3,$h=5e4;function cw(r,e){return!e||e.size===0?0:r.reduce((t,{node:n,read:o})=>t+(o>0?(e.get(n.objectApiName)??0)*Math.ceil(o/Dn):0),0)}var vh={field:"",parentObject:"",reason:"the source does not hold it"};function fd(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}function uw(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function lw(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function Eh(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function fw(r,e,t,n=()=>!0){return t.flatMap(o=>{let s=o.referenceTo??[],[i]=s;return o.isReference&&s.length===1&&i!==e&&n(o.name)&&r.writtenObjects.has(i)&&!r.config.referenceDataObjects.has(i)&&r.turnsEnded.has(i)&&Qe(e,o.name,o.nillable)?[{field:o.name,parent:i}]:[]})}var pw="held back for a record type closed to the user the run writes as",hw="held back for a record type the target has none of";function Ih(r){let e=0,t=0,n=0;for(let o of r)o.recordType?.unmapped?t++:o.recordType?e++:n++;return[...e>0?[{count:e,why:pw}]:[],...t>0?[{count:t,why:hw}]:[],...n>0?[{count:n,why:vd}]:[]]}function xh(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function Ph(r,e){return Di(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,lg(e))}function gw(r,e,t){let n=r.leftAside.get(e)??new Map;Hr(t,n),r.leftAside.set(e,n)}function mw(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function ww(r){return[...r.leftAside].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t.values()].sort((n,o)=>o.count-n.count).slice(0,3).map(({field:n,parentObject:o,reason:s,count:i})=>({recordSummary:`${n} \u2192 ${o} (${i} record${i===1?"":"s"})`,messages:[`Left aside, not written: ${s??""}`]}))}))}function Ps(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${Vc(n,t)}`).join("")+mw(r,e)}function yw(r){return[...bw(r),...ww(r)]}function bw(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:Jc(o,n),messages:[Qc(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Kr(r){return r==="not-creatable"?", which the target org takes no insert of":r==="not-in-target"?", which the target org does not have":", excluded from this run"}function Rw(r){let e=new Map([[void 0,new Set],["not-creatable",new Set],["not-in-target",new Set]]);for(let{excluded:t,target:n}of r)e.get(n)?.add(t);return[...e].filter(([,t])=>t.size>0).map(([t,n])=>`${[...n].sort().join(", ")}${Kr(t)}`).join("; ")}function Ow({field:r,excluded:e,through:t,namedBy:n,target:o}){return n!==void 0?`Not written: the only records that name it are ${n} records held back for ${e}${Kr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Kr(o)}.`:o==="not-creatable"?`Not written: ${r} may not be left empty, and the target org takes no insert of ${e}.`:o==="not-in-target"?`Not written: ${r} may not be left empty, and the target org does not have ${e}.`:e===Gt?`Not written: a price sold under a selling model needs its product's option for that model, and ${e} is excluded from this run.`:`Not written: ${r} may not be left empty, and ${e} is excluded from this run.`}var vd="held back for want of their parent",Fh=" \u2014 the records that cannot be written without one of those not written are held back",Nh={accountNotWritten:"not sent: a person account's contact goes in with its account, which this run did not write",contactNotFound:"not sent: a person account's contact goes in with its account, and the one the platform wrote was not found"};function Fs(r){let e=new Map;for(let{excluded:n,namedBy:o,target:s}of r){let i=o!==void 0,a=`${i?"named":"needing"}|${s??""}`,d=e.get(a)??{namedOnly:i,target:s,objects:[]};d.objects.push(n),e.set(a,d)}let t=({namedOnly:n,target:o})=>(n?3:0)+(o===void 0?0:o==="not-creatable"?1:2);return[...e.values()].sort((n,o)=>t(n)-t(o)).map(({namedOnly:n,target:o,objects:s})=>{let i=`${[...new Set(s)].sort().join(", ")}${Kr(o)}`;return{count:s.length,why:n?`held back, named only by records held back for ${i}`:`held back for want of ${i}`}})}function Qt(r,e){return Fs(r.heldForExclusions.get(e)?.values()??[])}function _n(r){return r.reduce((e,t)=>e+t.count,0)}function cn(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function Ns(r,e=!1){let t=_n(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+cn(r)}function Ch(r,e){return Ps(r,e)+Ns(Qt(r,e))}function kw(r){return[...r.heldForExclusions].map(([e,t])=>{let n=new Map;for(let o of t.values()){let s=`${o.field}|${o.through??""}|${o.namedBy??""}|${o.excluded}|`+(o.target??""),i=n.get(s)??{...o,count:0};i.count++,n.set(s,i)}return{objectApiName:e,stage:"scope",failedCount:t.size,attemptedCount:0,samples:[...n.values()].sort((o,s)=>s.count-o.count).slice(0,3).map(o=>{let s=`${o.count} record${o.count===1?"":"s"}`;return{recordSummary:o.namedBy!==void 0?`named by ${o.namedBy}.${o.field} (${s})`:`${o.field} \u2192 ${o.through??o.excluded} (${s})`,messages:[Ow(o)]}})}})}function Sw(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function Mh(r,e,t){for(let n of t){let o=e[n.name];if(typeof o!="string"||o===""||r.remapper.get(o))continue;let s=Sw(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function $n(r,e,t=[]){let n=e+_n(t);return`Held back ${r}, nothing written, ${n} failed${cn(t)}`}function Bh(r){return r>0?`, ${r} ${r===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:""}function ig(r,e=0){let t=r+e;if(t<=0)return"";let n=e>0?` (${e} of them outside the sample, with an account the run wrote)`:"";return`, ${t} written by the platform with their person account${n}`}function pd(r,e){if(e!==ce)return 0;let t=r.personContactsOutsideTheSample;return r.personContactsOutsideTheSample=0,t}function cr(r,e,t){t<=0||r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t)}function Ed(r,e){return r.writtenBefore.from==="resume"?`${e} already in the target, written before the run stopped`:`${e} already in the target from the run retried`}function ag(r,e){let t=Math.min(r,Math.max(0,e)),n=r-t;return(n>0?`, ${n} linked to records already in the target`:"")+(t>0?`, ${t} linked to records the run created (the target refused them as copies of those)`:"")}var Tw=3;function hd(r,e,t,n=0){let o=r.dryRun?"would be inserted":"succeeded",s=e.updated>0?`, ${e.updated} updated through their external id`:"",i=ag(e.linked,e.linkedToCreated),a=ig(e.withTheirAccount,n),d=e.withTheirEmail>0?`, ${e.withTheirEmail} written by the platform with their email`:"",c=dg(e.teamOwners,e.teamOthers)+cg(e.rolesOfTheirOpportunity,e.rolesGiven),u=e.writtenBefore>0?`, ${Ed(r,e.writtenBefore)}`:"",l=e.unidentified>0?` (${e.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${e.succeeded} ${o}${s}${i}${d}${a}${c}${u}, ${e.failed+_n(t)} failed${l}${cn(t)}`}function dg(r,e){return(r>0?`, ${r} written by the platform with their opportunity, for its owner`:"")+(e>0?`, ${e} on the team of their opportunity in the target already`:"")}function cg(r,e){if(r===0)return"";let t=e>0?`, ${e} given the source's fields ${e===1?"it":"they"} lacked`:"";return`, ${r} written by the platform with their opportunity, for its contact${t}`}function Aw(r,e,t){e.forEach(({source:n},o)=>{let s=n.Id,i=t[o]?.[Le];typeof s=="string"&&(typeof i=="string"&&i!==""?r.contactSentWith.set(s,i):r.contactSentWith.delete(s))})}function jw(r,e){for(let t of["notKept","unread"])for(let[n,o]of e[t])r[t].set(n,(r[t].get(n)??0)+o)}function ug(r){return[...[...r.notKept].map(([e,t])=>`${t} linked without the source's ${e}: the target's record keeps its own`),...[...r.unread].map(([e,t])=>`${t} linked whose ${e} was not read: the platform writes the record with the opportunity, which a dry run does not write`)].join(", ")}function zr(r,e,t=!0){let n=[...e.values()].filter(d=>d.namedBy===void 0),o=[...e.values()].filter(d=>d.namedBy!==void 0),s=[...e.values()].every(d=>d.target===void 0),i=d=>s?[...new Set(d.map(c=>c.excluded))].sort().join(", "):Rw(d),a=o.length===0?`every record needs ${i(n)}`:n.length===0?`the only records that name its records are held back for ${i(o)}`:`${n.length} of its records need ${i(n)}, and the only records that name the rest are held back for ${i(o)}`;return`${$n(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function Lh(r){let e=new Map(r.readAtItsTurn);for(let[s,i]of r.preread)e.set(s,i);let t=new Map,n=[];for(let[s,{records:i,fieldInfos:a}]of e){let d=a.filter(l=>l.isReference),c=Ke.has(s),u=r.scopeCache?.reachedOf(s);for(let l of i){let f=l.Id,p={row:l,lookups:d};c&&typeof f=="string"&&f!==r.config.rootRecordId&&r.roots?.ids.has(f)!==!0&&u?.has(f)!==!0?t.set(f,p):n.push(p)}}let o=new Set;for(let s=n.pop();s;s=n.pop())for(let i of s.lookups){let a=s.row[i.name];if(typeof a!="string"||a===""||o.has(a))continue;o.add(a);let d=t.get(a);d&&n.push(d)}return o}function Wh(r,e,t,n){let o=r.namedByRowsHeldBack.get(t);if(!(!o||n.has(t)||t===r.config.rootRecordId)&&r.roots?.ids.has(t)!==!0&&!(t===r.standardPricebookId||r.config.writtenBefore.has(t))&&r.scopeCache?.reachedOf(e)?.has(t)!==!0)return o}function Dh(r){for(let[e,t]of Object.entries(Ar))if(t.object===r)return{parent:e,lookup:t.lookup}}function $w(r,e){return e.filter(t=>t.isReference&&Qe(r,t.name,t.nillable)).map(t=>t.name)}function vw(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function gd(r){return r.size===0?"":`, written without a lookup naming a record the target does not hold, which the platform fills (the owner with the user the run writes as): ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}`}function _h(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function md(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the target holds no record of these ids, outside the run`}function wd(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Ew(r){return[...r.lookupsOutsideTheRun].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the target holds no record of these ids, outside the run.`]}))}))}function yd(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the record it names is held back by the run`}function bd(r,e){for(let{lookupsHeldBack:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Iw(r){return[...r.lookupsHeldBack].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the record it names is one the run holds back or leaves aside, never written.`]}))}))}var qh=10;function Rd(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function Uh(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function xw(r,e,t){let n=r.ownersInactive.get(e);for(let{ownerInactive:o}of t)o!==void 0&&(n??={rows:0,owners:new Set},n.rows+=1,n.owners.add(o));n&&r.ownersInactive.set(e,n)}function Pw(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,qh).join(", "),i=o.length-qh;return{objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`OwnerId \u2192 User (${t} record${t===1?"":"s"})`,messages:[`Written with the user the run writes as for owner: the target holds these owners inactive (${i>0?`${s}, and ${i} more`:s}) and that user may not give a record an inactive owner (Update Records with Inactive Owners). Map them to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line) to give the records to that user.`]}]}})}function $s(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function Od(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function Fw(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function ur(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function Nw(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function Gh(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var Cs=class extends Error{constructor(e,t){super(`Internal error: ${e} holds more rows than a clone of the whole org reads whole${t===void 0?"":` (${t})`}, which its gate should have refused before anything was written. The run stopped rather than write part of it: raise sandforge.forge.maxRecordsPerObject, or leave the object out.`),this.name="WholeReadPastBoundError"}},zh="files",kd=200,Cw=Dn,Sd=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function Hh(r,e){let t=r.objects.find(n=>n.objectApiName===e);return t||(t={objectApiName:e,planned:0,plannedBytes:0,copied:0,failed:0},r.objects.push(t)),t}function Mw(r,e){let t=[];for(let n of e){let o=n.Id,s=n.ParentId;if(typeof o!="string"||typeof s!="string"||!r.remapper.wasCreated(s))continue;let i=n.Name,a=typeof i=="string"&&i!==""?i:o,d=n.ContentType,c=n.BodyLength;t.push({objectApiName:"Attachment",sourceId:o,body:{objectApiName:"Attachment",id:o},name:a,bytes:typeof c=="number"&&Number.isFinite(c)?c:0,hosts:[{id:s}],fields:{Name:a,...typeof d=="string"&&d!==""?{ContentType:d}:{},IsPrivate:n.IsPrivate===!0}})}return t}function Kh(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||V(r).includes("INVALID_QUERY_LOCATOR")}function Vh(r){if(Uc(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:V(r).includes("SERVER_UNAVAILABLE")}function Jh(r){return new Promise(e=>setTimeout(e,r))}function Bw(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function vs(r,e){return jo(e)?xr(e)?!0:!r.writtenObjects.has(e):!1}function dn(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function Qh(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function Lw(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(Au)}function lg(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var Yh=200,Xh=200,Zh=/[\u0000-\u001f]/;function Td(r,e){if(!gt(e))return"";let t=[...Ma(r.pricesSwappedSaid),...Ww(r)];return t.length===0?"":`, ${t.join("; ")}`}function Ww(r){let e=[...r.pricesKeptAsRead].filter(([s])=>!r.prices.standsFor.has(s)).map(([,s])=>s);if(e.length===0)return[];let t=s=>{let i=new Map;for(let a of s)i.set(a,(i.get(a)??0)+1);return[...i].map(([a,d])=>`${d} ${a}`).join(", ")},n=e.filter(s=>s.to!==void 0&&s.from!==s.to);if(n.length>0)return[`${t(n.map(({from:s,to:i})=>`${s} \u2192 ${i}`))}: no price in the currency written in the source for the same product and price book, written in it at its amount as read, not converted`];let o=e.filter(s=>s.to===void 0).map(({from:s})=>s);return new Set(o).size<2?[]:[`prices written in the target's one currency, which it did not say: ${t(o)}, at their amount as read, not converted`]}var Dw=/^012000000000000(AAA)?$/;function eg(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var _w=["insert","upsert"],qw=["insert","upsert","update"];function tg(r,e){let t="";for(let n of _w){let o=r.splitting.sizes.report({objectApiName:e,op:n});if(!o||o.to>=o.from)continue;let s=`${n}\0${e}`,i=o.rows-(r.smallerCallsSaid.get(s)??0);i<=0||(r.smallerCallsSaid.set(s,o.rows),t+=`, ${i} sent ${o.to} at a time after the target's automation hit a Salesforce limit`)}return t}function Uw(r,e){let{objectApiName:t}=r,n=r.op==="update"?"lookup updates":"records",o=r.alone+r.notSplit+r.keptWhole,s=r.to<r.from&&r.rows>0?`${t}: ${r.rows} ${n} sent ${r.to} at a time`:`${t}: ${o} ${n} refused for a Salesforce limit`;return{objectApiName:t,stage:"scope",failedCount:0,attemptedCount:r.rows,samples:[{recordSummary:s,messages:[Bu(r),...r.notSplit>0?[Lu(r.notSplit,e,"run")]:[]]}]}}function Gw(r){return qw.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>Uw(t,Wu(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function Es(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=Op(s),a=o===!0&&n===void 0?Sp(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:u},l)=>d===void 0?[]:[{sourceId:d,fingerprint:kp(c,i),owes:u,...n!==void 0?{externalKey:Tp(c,n)}:{},...a[l]!==void 0?{jobKey:a[l]}:{}}]),new Date,n)},answered:e=>r.answered(e),opened:(e,t)=>r.jobOpened(e,t),unattributed:(e,t)=>r.createdUnattributed(e,t)}}function ng(r){let e=new Map;for(let{objectApiName:t,id:n,status:o}of r){let s=e.get(t)??[];s.push({id:n,status:o}),e.set(t,s)}return e}var zw=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],Hw=new Set(["CreatedDate","LastModifiedDate"]),Kw=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function Vw(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Is(r){return typeof r=="string"?Date.parse(r):Number.NaN}var rg="005",Id=class{ids=new Set;issued=0;idFor(e){this.issued++;let n=`${e&&/^[A-Za-z0-9]{3}$/.test(e)?e:"000"}SIM${String(this.issued).padStart(12,"0")}`;return this.ids.add(n),n}has(e){return this.ids.has(e)}};function Jw(r,e,t){return{...r,bulkWriteRecords:void 0,insertRecords:async(n,o,s)=>{let i=await t(n,o);return s.map(()=>({id:e.idFor(i),success:!0,errors:[]}))}}}function Qw(r,e,t){if(!r||!e)return"notRead";let n=r.source.RecordTypeId;return typeof n=="string"&&n!==""&&t.get(n)?.to===null?"decidedDefault":"RecordTypeId"in r.source&&Ia(n)?"masterInSource":"notRead"}function Yw(r,e){return{objectApiName:r,rows:e.rows,why:{...e.why},...e.predicted?{predicted:{...e.predicted}}:{},...e.readBack?{readBack:{...e.readBack,types:e.readBack.types.map(t=>({...t}))}}:{}}}function Ad(r,e){return[r[Pn],e?r[Hn]:"",r[mt]].map(t=>String(t??"")).join("|")}function og(r,e){let t=new Set(e??[]);return r.filter(n=>n.createable&&n.queryable&&!n.isReference&&!t.has(n.name)&&(n.type===void 0||Kw.has(n.type)))}var Xw=200,Zw="the standard price of its product, which it may not go without, changed since the sample";function ey(r){return r?{sample:r}:{}}function ty(r){let e=r.options,t=Object.entries(e.rootWhere??{});return{seed:e.seed??Rn.seed,draw:e.draw??Rn.draw,parents:e.parents??Rn.parents,children:e.children??Rn.children,floor:e.floor??Rn.floor,...e.whole&&e.whole.length>0?{whole:[...e.whole]}:{},...e.window?{window:{...e.window}}:{},...t.length>0?{rootWhere:Object.fromEntries(t)}:{},...e.strata&&e.strata.length>0?{strata:[...e.strata]}:{}}}var lr=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=hh(e)}summarySoFar(){return this.running?this.summaryOf(this.running):void 0}pause(){this.isPaused||(this.isPaused=!0)}resume(){this.isPaused=!1;let e=this.pauseResolve;this.pauseResolve=null,e?.()}abort(){this.isAborted=!0,this.bulkCancel.abort(),this.sampling.abort();let e=this.pauseResolve;this.pauseResolve=null,this.isPaused=!1,e?.()}async bulkTransportOf(e,t){if(e.writeApi!=="auto"||e.dryRun||!this.deps.bulkWriteRecords)return;let n=await this.deps.duplicateRuleObjects?.(t).catch(()=>{}),o=n??sa;return Ye.info(`[forge] writing through the Bulk API: a job per ${Dr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...os,...o].join(", ")}`+(n?"":" (the target did not say which objects its duplicate rules watch)")),this.bulkCancel=new AbortController,this.isAborted&&this.bulkCancel.abort(),{signal:this.bulkCancel.signal,restOnly:new Set([...os,...o]),bulkUnsupported:new Set,manager:new ou(1)}}bulkUpdatesOf(e){let{bulk:t}=e,n=this.deps.bulkWriteRecords;return!t||!n?{}:{bulkUpdate:(o,s)=>n(e.targetOrgId,o,"update",s,{bulkManager:t.manager,signal:t.signal}),restOnly:t.restOnly,bulkUnsupported:t.bulkUnsupported}}async waitIfPaused(){if(this.isAborted)throw new be("Forge execution was aborted by user request. No further batches will be processed.");if(this.isPaused&&(await new Promise(e=>{this.pauseResolve=e}),this.isAborted))throw new be("Forge execution was aborted while paused. No further batches will be processed.")}anonymizeRows(e,t,n,o,s,i){let a=e.config.anonymization;if(!e.anonymize||!a)return n;let d=a.fields[t]??this.detectedPersonalFields(e,a,t,s);if(d.length===0)return n;let c=new Map(s.map(u=>[u.name,u]));return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(u=>{let l=c.get(u);return{name:i[u]??u,type:l?.type??"",...l?.length!==void 0?{length:l.length}:{}}}),methods:a.methods})}detectedPersonalFields(e,t,n,o){let s=e.detectedPersonalFields.get(n);if(s)return s;let i=t.personalFieldsOf?.(o.map(a=>({name:a.name,type:a.type??""})))??[];return e.detectedPersonalFields.set(n,i),i}async fieldExclusionsOfTheSource(e,t,n){let o=Object.keys(e);if(o.length===0)return{exclusions:{},unmatched:[]};let s=t.nodes.map(a=>a.objectApiName),i=new Map;for(let a of o){let d=s.find(c=>c.toLowerCase()===a.toLowerCase())??a;if(!i.has(d))try{let c=await this.deps.describeFields(n,d);i.set(d,c.map(u=>u.name))}catch(c){i.set(d,nr(c)?void 0:null)}}return ns(e,s,a=>i.has(a)?i.get(a):null)}fileCopyUnwired(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return e&&t&&n?null:"This session cannot copy files: it reads no file content or file storage. Nothing was read or written."}fileCopyDeps(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return!e||!t||!n?null:{queryRecords:(o,s)=>this.deps.queryRecords(o,s),readFileBody:e,insertFile:t,insertRecords:this.deps.insertRecords,remainingFileStorageMB:n}}anonymizerForRun(){if(this.deps.anonymize)return this.deps.anonymize;let e=new sp;return t=>e.anonymize(t)}async execute(e,t,n,o,s){this.isAborted=!1,this.isPaused=!1,this.pauseResolve=null;let i=this.deps.requestsSent?.(),a=jl(s);if(a.files){let j=uo(a.anonymization!==void 0,a.files.acceptedAsIs);if(j)throw new jn(j,"FILES_NOT_ACCEPTED");let F=this.fileCopyUnwired();if(F)throw new jn(F,"FILES_NOT_COPYABLE")}let d=await this.chooseTheRoots(a,t,a.dryRun?void 0:a.stream?.store),c=await bs(a.ownerMappings,j=>this.deps.queryRecords(n,j),or);if(c)throw c;let u=new Map,l=await this.recordTypeDecisionsOf(s?.decisions?.recordTypeMappings??[],t,n,u),f=await this.fieldExclusionsOfTheSource(a.fieldExclusions,e,t),p={...a,fieldExclusions:f.exclusions,...l.bySource.size===0?{}:{recordTypeMappings:gl(a.recordTypeMappings,l),recordTypeDecisions:l.bySource}},g=p.dryRun?new Id:null,h=p.excludedObjects,m=await this.withWhatStatusesNeed(es(e,h),t,h),R=p.isScoped?await this.withWhatItsRecordsComeWith(m.graph,t,h):m.graph,b=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(R,t,h),t,h),k=this.deps.recordTypePicklists,O=p.dryRun?void 0:p.stream?.store,w=new Date;O?.beginPart(w),d&&O&&!d.fromTheJournal&&O.nameRoots({objectApiName:d.objectApiName,ids:[...d.ids],sha256:d.sha256,readAt:d.readAt,...d.query?{query:d.query}:{}});let A=Mu(),S=await this.bulkTransportOf(p,n),v={...S?{bulk:S}:{},config:p,sourceOrgId:t,targetOrgId:n,graph:b,onProgress:o,remapper:new qr(O),scopeCache:p.isScoped?new Wf:null,scopedBuilder:p.isScoped?new Sn:null,recordTypeMapper:p.recordTypeMappings?new gs:null,referenceDataMapper:new Ts((j,F)=>this.deps.queryRecords(j,F)),orphanExpander:new As(g?Jw(this.deps,g,async(j,F)=>this.deps.describeObject?this.deps.describeObject(j,F).then(B=>B.keyPrefix,()=>null):null):this.deps),batchWriter:new Ul(this.deps,this.deps.batchStrategy,void 0,A),splitting:A,smallerCallsSaid:new Map,failedObjects:new Set,failedInPart:new Set,heldInTheOrg:new Map,leftAside:new Map,turnsEnded:new Set,notCreatable:new Set,notInTarget:new Set,errors:[],truncatedObjects:new Set,cappedObjects:new Set,fieldExclusionsUnmatched:f.unmatched,pendingFkUpdates:[],owedToRowsWrittenBefore:[],deferredNodes:[],turnsAhead:new Set,waitingFor:new Map,readAgainUnder:new Map,askedForRowsThatNeedThem:new Map,targetHolds:new Map,targetReadsRefused:new Set,inactiveUsers:new Set,writesInactiveOwners:Vf(j=>this.deps.queryRecords(n,j)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:O?{add:j=>O.noteRead(j),has:j=>O.wasRead(j)}:new Set,catalogNodes:[],preread:new Map,readByObject:new Map,notSent:new Map,failedReads:new Set,sourceKeyPrefixes:new Map,cursors:new Map,counted:new Map,tableRecordTypes:new Map,keyPrefixesAsked:new Set,readObjects:new Set(b.nodes.filter(j=>j.included).map(j=>j.objectApiName)),writtenObjects:new Set,sellingModels:b.nodes.some(j=>j.included&&j.objectApiName===jr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...O?{store:O}:{},secondPassInStore:!1,statusesGiven:!1,leftDrafts:new Set,statusChildren:m.added,pastDraft:new Map,heldForExclusions:new Map,namedByRowsHeldBack:new Map,readAtItsTurn:new Map,statusChildrenRead:new Map,anonymize:p.anonymization?this.anonymizerForRun():null,contactPoints:p.keepContactPoints?null:new vf(void 0,{upsertKeys:p.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:Yu(Qu(j=>this.deps.queryRecords(t,j)),async j=>({fields:await this.deps.describeFields(t,j)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new ll(k&&((j,F)=>k(n,j,F))),picklistChanges:new Ko,currencyChanges:new Fo,currencyChangesById:new Map,recordTypesGiven:new Map,recordTypesUnderTheLease:new Map,pricesSwappedSaid:[],pricesKeptAsRead:new Map,prices:{standsFor:new Map,convertedInto:new Map,written:new Map,keys:new Map},readsEverythingFirst:!1,writtenWithoutFields:new Map,leftEmptyByFilter:new Map,contactsOnTheirOwn:new Set,withTheirRecord:new Set,startedAt:w,writtenByThePlatform:new Map,personContactsOutsideTheSample:0,contactSentWith:new Map,leftToThePlatform:new Kc,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,...d?{roots:d}:{},readUnder:new Map,simulated:g,gaps:p.dryRun?new Iu:null,decisionsApplied:new Xi,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:u,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[j,F]of p.writtenBefore)v.remapper.addExisting(j,F);for(let{decision:j,reason:F}of l.unresolved)v.errors.push({objectApiName:j.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${j.from} \u2192 ${j.to??"the default"})`,messages:[`The decision was not applied: ${F}.`]}]});this.running=v;try{return await this.runPasses(v)}catch(j){throw this.endBeforeTheEmailsThatWaited(v,v.emailsAfterTheirTask.length+v.emailsLeftForTheirTask,j instanceof be),this.saySyncedQuotesLeft(v),await this.readWrittenBetween(v),this.reportDraftsLeft(v),O?.settleReads(),ip(j,this.summaryOf(v)),j}finally{this.running===v&&(this.running=null),O?.settleReads(),O?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return Zi([],[]);let s=this.deps.describeObject,i=async(c,u)=>s?s(c,u).then(l=>this.namedRecordTypes(o,c,l.recordTypes),()=>[]):[],a=[...new Set(e.map(c=>c.object))],d=await Promise.all(a.map(async c=>({objectApiName:c,source:await i(t,c),target:await i(n,c)})));return Zi(e,d)}async namedRecordTypes(e,t,n){if(!n.some(s=>!s.master))return n;let o=e.get(t);return o||(o=this.deps.queryRecords(t,Co).then(s=>Mo(s),()=>[]),e.set(t,o)),Bo(n,await o)}async targetObjectInfoOf(e,t){let n=await this.objectInfoOf(e.targetOrgId,t);return!n||!(e.gaps!==null||n.recordTypes.some(s=>!s.available&&!s.master)||e.config.decisions.namesARecordTypeBare(t))?n:{...n,recordTypes:await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,n.recordTypes)}}async withMaskedLeftOut(e,t,n,o,s){if(o.length===0)return n;let i=await e.maskedSourceFields(t).catch(()=>[]),a=i.filter(d=>!n.has(d)&&s(d)&&o.some(c=>c[d]!==null&&c[d]!==void 0));return this.noteEncryptedLeftOut(e,t,a),i.length>0?new Set([...n,...i]):n}noteEncryptedLeftOut(e,t,n){if(n.length===0)return;let o=e.encryptedFieldsLeftOut.get(t)??new Set;for(let s of n)o.add(s);e.encryptedFieldsLeftOut.set(t,o)}withoutFileContent(e,t,n,o){let s=n.filter(i=>xn(i)&&i.createable);if(o&&s.length>0){let i=e.fileContentFieldsLeftOut.get(t)??new Set;for(let a of s)i.add(a.name);e.fileContentFieldsLeftOut.set(t,i)}return n.filter(i=>!xn(i))}async readWrittenBetween(e){if(e.config.dryRun||e.writtenBetween)return;if(e.config.stream?.everything===!0&&e.store){await this.readWrittenBetweenByObject(e,e.store);return}let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let{objectApiName:o,sourceIds:s}of e.remapper.createdByObject()){let i=s.flatMap(d=>{let c=e.remapper.get(d);return c?[c]:[]});if(i.length===0)continue;let a=await this.auditDatesCopied(e,o);for(let d of kn(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let u of c){let l=Is(u.SystemModstamp),f=h=>{let m=a?Number.NaN:Is(u[h]);return Number.isFinite(m)?m:l},p=f("CreatedDate"),g=f("LastModifiedDate");Number.isFinite(p)&&(t=Math.min(t,p)),Number.isFinite(g)&&(n=Math.max(n,g))}}}Number.isFinite(t)&&Number.isFinite(n)&&(e.writtenBetween={first:new Date(t).toISOString(),last:new Date(Math.max(t,n)).toISOString()})}async readWrittenBetweenByObject(e,t){let n=Vw(e.startedAt.getTime()-Ka),o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=!1;for(let{objectApiName:a,created:d}of t.countsByObject()){if(d===0)continue;let c=Be(a),l=[...await this.auditDatesCopied(e,a)?[]:[`SELECT MIN(CreatedDate) f, MAX(SystemModstamp) l FROM ${c} WHERE CreatedDate >= ${n}`],`SELECT MIN(SystemModstamp) f, MAX(SystemModstamp) l FROM ${c} WHERE SystemModstamp >= ${n}`],f=!1;for(let p of l)try{let[g]=await this.deps.queryRecords(e.targetOrgId,p),h=Is(g?.f),m=Is(g?.l);Number.isFinite(h)&&(o=Math.min(o,h)),Number.isFinite(m)&&(s=Math.max(s,m)),f=!0;break}catch{}f||(i=!0)}i&&(o=Math.min(o,e.startedAt.getTime()),s=Math.max(s,Date.now()+Ka)),Number.isFinite(o)&&Number.isFinite(s)&&(e.writtenBetween={first:new Date(o).toISOString(),last:new Date(Math.max(o,s)).toISOString()})}async writtenDatesOf(e,t,n){let o=Be(t);for(let s of zw)try{return await this.deps.queryRecords(e,`SELECT Id, ${s.join(", ")} FROM ${o} WHERE Id IN (${n})`)}catch{}}async auditDatesCopied(e,t){let n=o=>o.some(s=>Hw.has(s.name)&&s.createable);try{let[o,s]=await Promise.all([this.deps.describeFields(e.sourceOrgId,t),this.deps.describeFields(e.targetOrgId,t)]);return n(o)&&n(s)}catch{return!0}}async runPasses(e){let{config:t,graph:n,sourceOrgId:o,targetOrgId:s,onProgress:i}=e;e.scopeCache&&e.roots&&t.rootObjectApiName?e.scopeCache.add(t.rootObjectApiName,e.roots.ids):e.scopeCache&&t.rootRecordId&&t.rootObjectApiName&&e.scopeCache.add(t.rootObjectApiName,[t.rootRecordId]);let a=xl(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&vw(t);e.readsEverythingFirst=c,e.emailsInTwoPasses=d&&t.stream?.everything===!0,e.secondPassInStore=e.store!==void 0&&!c,c&&e.store&&e.pendingFkUpdates.push(...e.store.owedLeftByEarlierParts());let u=c?a:await this.singlePassOrder(e);if(c&&e.scopeCache)for(let O of u)O.included&&e.turnsAhead.add(O.objectApiName);if(n.nodes.some(O=>gt(O.objectApiName)))try{let[O,w]=await Promise.all([this.deps.queryRecords(o,mi),this.deps.queryRecords(s,mi)]),A=O[0]?.Id,S=w[0]?.Id;typeof A=="string"&&typeof S=="string"&&(e.standardPricebookId=A,e.remapper.addExisting(A,S),e.scopeCache?.add(Ut,[A]),e.readObjects.add(Ut),n.nodes.some(v=>v.included&&v.objectApiName===Ut)||e.scopeCache?.addRead(Ut,[]))}catch(O){e.errors.push({objectApiName:et,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[V(O)]}]})}let l=new Map,f=this.deps.isObjectCreatable;if(f){let O=[...new Set(a.filter(w=>w.included&&!t.referenceDataObjects.has(w.objectApiName)).map(w=>w.objectApiName))];for(let w=0;w<O.length&&!this.isAborted;w+=6){let A=O.slice(w,w+6),S=await Promise.allSettled(A.map(async v=>f(s,v)));A.forEach((v,j)=>l.set(v,S[j]))}}for(let[O,w]of l)w.status!=="rejected"||!nr(w.reason)||(e.notInTarget.add(O),e.readObjects.delete(O),e.turnsAhead.delete(O));for(let O of n.nodes){let w=l.get(O.objectApiName);!O.included||w?.status==="fulfilled"&&!w.value||e.notInTarget.has(O.objectApiName)||e.writtenObjects.add(O.objectApiName)}d&&await this.planTheSample(e,u),d&&t.beforeWrite&&await this.countBeforeWrite(e,u);for(let O of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!O.included){e.skippedCount++,i({objectName:O.objectApiName,status:"skipped",progress:100,message:`Skipped ${O.objectApiName} (${sw(O)})`});continue}if(e.notInTarget.has(O.objectApiName)){e.scopeCache&&O.objectApiName!==t.rootObjectApiName?(e.notInTargetPutOff??=[]).push(O):this.reportNotInTarget(O,e),await this.endTurn(O.objectApiName,e);continue}if(await this.skipForFailedParent(O,e)){await this.endTurn(O.objectApiName,e);continue}let w=l.get(O.objectApiName);if(w)if(w.status==="fulfilled")w.value||e.notCreatable.add(O.objectApiName);else{let A=w.reason;e.errors.push({objectApiName:O.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${A instanceof Error?A.message:String(A)}`]}]})}c?await this.readInTurn(O,e):d&&this.streamsNode(O,e)?(await this.streamNode(O,e),e.turnsEnded.add(O.objectApiName),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(O,e,!1,!0)&&await this.writeNode(O,e),e.turnsEnded.add(O.objectApiName),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e),O.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,O.objectApiName))}let p=Pl(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),g=p.map(O=>Ke.has(O.objectApiName)).lastIndexOf(!0);for(let[O,w]of p.entries()){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(w,e)||(c?(e.scopeCache&&Ke.has(w.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,w.objectApiName)),await this.readNode(w,e,!1,!1),await this.readUnderWhatWaited(w.objectApiName,e,g>=0&&O>g?"after the catalog":"before the catalog")):await this.readNode(w,e,!1,!0)&&(await this.writeNode(w,e),e.turnsEnded.add(w.objectApiName),this.releaseRows(e,w.objectApiName)))}await this.readCatalogAgain(e,g<0?[]:p.slice(g+1)),await this.reportNotInTargetOfTheScope(e);for(let O of[...e.preread.keys()])this.releaseRows(e,O,!0);if(c){do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e));if(await this.readParentsOutsideTheGraph(e))do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e))}let h=this.deps.requestsSent?.();e.roots&&h!==void 0&&e.requestsBefore!==void 0&&(e.readRequests=h-e.requestsBefore);let m=t.stream?.everything===!0,R=t.files&&!m?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let O=await this.pricesTheGateCounts(e),w=jh(e).cappedObjects,A=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([j,F])=>this.toWriteAtTheGate(e,j,F,gt(j)?O:0))))),S=t.dryRun?0:await this.readBackRequests(e,A),v=await t.beforeWrite({objects:A,...w?{capped:w}:{},...S>0?{readBack:S}:{},...e.roots?{roots:Gm(e.roots)}:{},dryRun:t.dryRun});await this.afterTheGate(e,v,A)}if(c)for(let O of this.writeOrderOf(e)){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let w=e.preread.get(O.objectApiName);if(w&&!await this.skipForFailedParent(O,e,w.fieldInfos,w.records)&&(await this.writeNode(O,e),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e),O.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let A=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),S=[],v=await _a({pendingFkUpdates:A,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:S,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(j,F,B)=>this.noteLeftEmptyByFilter(e,j,F,B),...this.secondPassOfTheSample(e)});v&&e.errors.push(v),e.pendingFkUpdates.push(...S)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let b=e.secondPassInStore?await this.secondPassFromTheJournal(e):await _a({pendingFkUpdates:this.sayLookupsOutsideTheClone(e,e.pendingFkUpdates),remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!t.dryRun,onProgress:i,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(O,w,A)=>this.noteLeftEmptyByFilter(e,O,w,A),...this.secondPassOfTheSample(e)});if(b&&e.errors.push(b),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");R.length>0&&!t.dryRun?await this.writeFiles(e,R):m&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let k=e.orphanExpander.buildErrorReport();return k&&e.errors.push(k),this.saySyncedQuotesLeft(e),await this.readWrittenBetween(e),await this.readBackRecordTypes(e),this.summaryOf(e)}async afterTheGate(e,t,n){let o=t?t.splitAllowance:void 0;o!==void 0&&e.splitting.allowance.limitTo(o);let s=t?t.lease:void 0;s&&(e.lease=s,s.assigned>0&&await this.readAgainUnderTheLease(e,n))}async readAgainUnderTheLease(e,t){let n=this.deps.describeObjectAgain;if(!n)return;let o=await Promise.all(t.map(async({objectApiName:s,rows:i,counted:a})=>{if(!await this.mayGoWithoutRecordType(e,s,i,a))return[];try{let d=await n(e.targetOrgId,s);return[[s,d.recordTypes]]}catch{return[]}}));for(let[s,i]of o.flat())e.recordTypesUnderTheLease.set(s,i)}async mayGoWithoutRecordType(e,t,n,o){if(n.length===0&&(o?.rows??0)===0||!(await this.objectInfoOf(e.targetOrgId,t))?.recordTypes.some(d=>!d.master))return!1;if(n.length===0)return!0;let{config:i}=e;return!(e.preread.get(t)?.createableSet.has("RecordTypeId")===!0&&!(i.fieldExclusions[t]??[]).includes("RecordTypeId")&&i.fieldMappings[t]?.RecordTypeId===void 0)||n.some(d=>{let c=d.RecordTypeId;return typeof c!="string"||Ia(c)||i.recordTypeDecisions.get(c)?.to===null})}async readBackRequests(e,t){let o=(await Promise.all(t.map(({objectApiName:i,rows:a,counted:d})=>this.mayGoWithoutRecordType(e,i,a,d)))).filter(Boolean).length,s=e.recordTypeRows.has(e.targetOrgId)&&!e.config.dryRun;return o>0&&!s?o+1:o}async giveTheLeaseBack(e){let t=e.lease;if(t){e.lease=void 0;try{await t.giveBack()}catch(n){Ye.warn(`[forge] the mute's lease was not given back as the writes ended: ${V(n)}`)}}}async readBackRecordTypes(e){e.simulated||await Promise.all([...e.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await this.deps.queryRecords(e.targetOrgId,Nf(t,n.ids));n.readBack=Cf(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:V(o)}}}))}async recordTypeCounter(e,t,n,o){let s=e.recordTypesUnderTheLease.get(t)??n?.recordTypes??[];if(!s.some(c=>!c.master))return;let i=await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,s),a=Pf(xf(i)),d=e.config.recordTypeDecisions;return(c,u)=>{let l=e.recordTypesGiven.get(t);l||(l={rows:0,why:{},...a?{predicted:a}:{},types:i,ids:[]},e.recordTypesGiven.set(t,l));let f=Qw(c,o,d);l.rows++,l.why[f]=(l.why[f]??0)+1,u!==void 0&&l.ids.length<Ff&&l.ids.push(u)}}streamsTheRun(e){let{config:t,graph:n}=e;return t.stream===void 0||t.isScoped?!1:t.stream.everything===!0?!0:t.files===void 0&&!n.nodes.some(o=>o.included&&o.objectApiName===$e)}async keysOfTheTable(e,t,n){let{config:o,sourceOrgId:s}=e;if(o.upsertMode!=="auto"||!this.deps.upsertRecords||e.simulated)return;let i=t.objectApiName,a={unique:new Set,sent:new Set};try{n.described??=await this.deps.describeFields(s,i);let d=new Set(o.fieldExclusions[i]??[]),c=o.fieldMappings[i]??{},u=n.described.filter(R=>R.externalId===!0&&R.createable&&R.queryable&&!d.has(R.name)&&c[R.name]===void 0);if(u.length===0)return a;let l=n.described.find(R=>R.name==="Id"),f=on({node:t,edges:e.graph.edges,fieldInfos:[...l?[l]:[],...u],scopedBuilder:null,scopeCache:null,extraWhere:this.filterOf(e,i),maxRecordsPerObject:this.readBound(e,t),inIdOrder:{}});if(f.kind!=="query"||f.statements.length!==1)return a;let p=f.limit??1/0,g=new Map(u.map(R=>[R.name,new Set])),h=0,m=Vt(this.deps,s,f.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let R of m){for(let b of R){if(h>=p)break;h++;for(let[k,O]of g){let w=b[k];typeof w!="string"||w.length===0||O.has(w)?g.delete(k):O.add(w)}}if(h>=p||g.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(g.keys()),sent:a.sent}}catch(d){return Ye.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+V(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!Ke.has(n)&&!gt(n)&&(n!==ut||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(Ke.has(t)||gt(t)))return;let o=e.preread.get(t);!o||o.records.length===0||e.preread.set(t,{...o,records:[]})}readsArchived(e,t){return e.config.stream?.everything===!0&&tf.has(t)}filterOf(e,t){let n=e.config.objectSoqlFilters?.[t];return this.readsArchived(e,t)?n?`(${n}) AND IsDeleted = false`:"IsDeleted = false":n}readOptionsOf(e,t){return this.readsArchived(e,t)?{all:!0}:void 0}async readWholeOf(e,t,n,o){let s=this.readOptionsOf(e,t);if(!s)return this.deps.queryRecords(e.sourceOrgId,n,o);let i=[],a=Vt(this.deps,e.sourceOrgId,n,void 0,void 0,s);for await(let d of a)for(let c of d)i.push(c);return i}readBound(e,t){if(e.sample?.drawn.has(t.objectApiName))return;let n=e.config.maxRecordsPerObject,o=n!==void 0&&n>0?Math.floor(n):void 0,s=this.streamsNode(t,e)?e.config.stream?.ceiling:void 0;return o===void 0?s:s===void 0?o:Math.min(o,s)}async chooseTheRoots(e,t,n){let o=e.roots,s=n?.resumes===!0,i=s?n?.roots:void 0;if(!o){if(i)throw Pe.of(Lr(i.objectApiName,"otherQuery"));return}let{objectApiName:a,cap:d}=o,c={cap:d,readTotal:o.readTotal,readingBound:ml(o.sourceRequestsLeft),...o.sourceRequestsLeft!==void 0?{sourceRequestsLeft:o.sourceRequestsLeft}:{}};if(s){if(!i)throw Pe.of(Sl(a));if(i.objectApiName.toLowerCase()!==a.toLowerCase())throw Pe.of(Lr(a,"otherQuery"));if(ta(i.ids)!==i.sha256)throw Pe.of(Lr(a,"changed"));return{objectApiName:a,from:"plan",...i.query?{query:i.query}:{},ids:new Set(i.ids),sha256:i.sha256,readAt:i.readAt,fromTheJournal:!0,...c}}let u,l=o.plan;if(l){let m=kl(l,{sourceOrgId:t,objectApiName:a,...o.query?{query:o.query}:{},...o.ids?{ids:o.ids}:{}});if(m)throw Pe.of(Lr(a,m));let R=o.planOfTheRunRetried===!0;if(Ip(l,new Date)<vp||o.query===void 0||R)return{objectApiName:a,from:"plan",...l.query?{query:l.query}:{},ids:new Set(l.ids),sha256:l.sha256,readAt:l.readAt,fromTheJournal:!1,...R?{ofTheRunRetried:!0}:{},...c};u={roots:l.ids.length,readAt:l.readAt}}let f,p,g;if(o.ids!==void 0){let m=o.ids.filter(R=>!Ol(R));if(m.length>0)throw Pe.of({code:"ROOTS_QUERY_REFUSED",message:`${JSON.stringify(m[0]?.slice(0,40))} is not the id of a record: name each ${a} record by its 15- or 18-character id. Nothing was read or written.`,roots:{objectApiName:a}});if(f=ea(o.ids),p="records",f.length>d)throw Pe.of(Br(a,d,p))}else if(o.query!==void 0){let m=yl(o.query);if(m)throw Pe.of(Yo(m,a));let R=o.chosen,b=R?R.ids.map(k=>({Id:k})):await this.deps.queryRecords(t,Qo(a,o.query,e.objectSoqlFilters?.[a],d));if(f=ea(b.flatMap(k=>typeof k.Id=="string"?[k.Id]:[])),p="query",g=R?.readAt,f.length>d)throw Pe.of(Br(a,d,p,o.query))}else throw new Error(`Internal error: the roots of ${a} were asked with neither a query nor ids.`);if(f.length===0)throw Pe.of(Xo(a,o.query,d));let h=g??new Date().toISOString();return o.keepAt!==void 0&&await Ep(o.keepAt,{sourceOrgId:t,fingerprint:o.fingerprint??"",objectApiName:a,...o.query?{query:o.query}:{},from:p==="records"?"records":"query",readAt:h,ids:f}),{objectApiName:a,from:p,...o.query?{query:o.query}:{},ids:new Set(f),sha256:ta(f),readAt:h,fromTheJournal:!1,...u?{readAgain:u}:{},...c}}holdTheRootsReading(e,t,n){let o=e.roots,s=this.deps.requestsSent?.();if(!o||s===void 0||e.requestsBefore===void 0)return;let i=s-e.requestsBefore;if(!(i+n<=o.readingBound))throw Pe.of(Al({roots:o.ids.size,bound:o.readingBound,sent:i,next:n,objectApiName:t,sourceRequestsLeft:o.sourceRequestsLeft}))}holdTheRootsRows(e,t){let n=e.roots;if(!n)return;let o=0;for(let i of e.readByObject.values())o+=i;if(o<=n.readTotal)return;let s=[...e.readByObject].filter(([i])=>i!==t).map(([i,a])=>({objectApiName:i,rows:a}));throw s.push({objectApiName:t,rows:e.readByObject.get(t)??0}),Pe.of(Tl(n.ids.size,n.readTotal,s))}async planTheSample(e,t){let{config:n,store:o}=e,s=n.stream?.everything===!0?n.stream.sample:void 0,i=o?.samplePlan;if(!s){if(i)throw new ir("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+or);return}let a;if(i)try{a=await sr.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof Os?new ir("SAMPLE_PLAN_GONE",`The plan of the sample the run resumes is ${d.refusal==="gone"?"no longer on this machine":"no longer as it was drawn"}: it cannot go on with the same records. ${or} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new ir("SAMPLE_PLAN_MISMATCH",`The run this one resumes copied every record of the whole org, not a sample: resume it as it was set up. ${or}`);a=s.plan??await this.drawThePlan(e,t,s)}o&&!i&&o.nameSamplePlan({dir:a.dir,sha256:a.sha256}),e.sample=await this.runSampleOf(e,a)}async drawThePlan(e,t,n){let{config:o,sourceOrgId:s}=e,i=ty(n),a=t.filter(w=>w.included&&(e.writtenObjects.has(w.objectApiName)||o.referenceDataObjects.has(w.objectApiName))),d=new Map;for(let w of a)d.set(w.objectApiName,await this.deps.describeFields(s,w.objectApiName));let c=(w,A)=>A.nillable===!1&&e.graph.edges.some(S=>S.type==="master-detail"&&S.targetObject===w&&(A.referenceTo??[]).includes(S.sourceObject)),u=[],l=new Map;for(let w of a){let A=w.objectApiName,S=new Set(o.fieldExclusions[A]??[]),v=(d.get(A)??[]).filter(j=>j.isReference&&!S.has(j.name)).map(j=>({name:j.name,referenceTo:j.referenceTo??[],isMasterDetail:c(A,j),...j.nillable!==void 0?{nillable:j.nillable}:{},createable:j.createable,...j.updateable!==void 0?{updateable:j.updateable}:{}}));if(u.push({objectApiName:A,rows:w.recordCount,keyPrefix:(await this.objectInfoOf(s,A))?.keyPrefix??e.sourceKeyPrefixes.get(A)??null,fields:v}),this.streamsNode(w,e)&&!o.referenceDataObjects.has(A)){let j=await this.recordTypesOfTable(e,w);j&&j.closedInSource.length>0&&l.set(A,{closed:new Set(j.closedInSource.map(it)),lacking:new Set(j.lackingInSource.map(it))})}}let f=await n.budget(),p=e.standardPricebookId&&a.some(w=>gt(w.objectApiName))?await this.runCurrencies(e):void 0,g=p&&this.priceCurrencyWrittenIn(e,p.target),h=new Map;if(a.some(w=>w.objectApiName===$e)){let w=await this.averageEmailBytes(e,d.get($e)??[]);w!==void 0&&h.set($e,w)}let m=g?w=>p.target.active.has(w)?void 0:g(w):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let R=Date.now(),b;try{b=await yp({source:{pages:(w,A)=>Vt(this.deps,s,w,void 0,void 0,A),count:async(w,A)=>{let S=this.deps.countRecords;if(S)return A?S(s,w,A):S(s,w);let v=0,j=w.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let F of Vt(this.deps,s,j,void 0,void 0,A))v+=F.length;return v}},objects:u,order:a.map(w=>w.objectApiName),excluded:new Map([...o.excludedObjects].map(w=>[w,null])),referenceData:o.referenceDataObjects,fieldsOf:w=>d.get(w)?.filter(A=>A.queryable).map(A=>({name:A.name,...A.type!==void 0?{type:A.type}:{},...A.groupable!==void 0?{groupable:A.groupable}:{},...A.sortable!==void 0?{sortable:A.sortable}:{},...A.aggregatable!==void 0?{aggregatable:A.aggregatable}:{}})),filterOf:w=>o.objectSoqlFilters?.[w],options:i,budget:f,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(w,A)=>{let S=l.get(w),v=it(A);return S?.lacking.has(v)?"recordTypeNotInTarget":S?.closed.has(v)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...m?{priceCurrencyWrittenIn:m}:{},...h.size>0?{averageBytes:h}:{},now:R,labelsOf:async(w,A)=>{if(A.toLowerCase()!=="recordtypeid")return;let S=(await this.objectInfoOf(s,w))?.recordTypes??[],v=new Map(S.map(j=>[it(j.recordTypeId),j.developerName]));return j=>typeof j=="string"?v.get(it(j)):void 0},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(w){throw w instanceof gp?new ir("SAMPLE_TOO_LARGE",`${w.message} Or draw among fewer roots: a window of dates (--fit-window) or a filter on the roots of the large objects (--fit-where).`):w instanceof mp||this.isAborted?new be("Forge execution was aborted by user request. Remaining objects were not processed."):w}let{cut:k}=b;if(k.kind==="cannotFit"){let w=k.heaviest.map(B=>`${B.objectApiName} (${B.rows} records${B.whole?", copied whole":""})`).join(", "),A=b.strataFloors,S=k.noRoot?"the objects copied whole and the first root drawn with the records it brings":A?`the objects copied whole and the roots kept of each object and of each value of its strata (${A.roots} roots for the floors of ${A.values} values)`:"the objects copied whole and the roots kept of each object",v=k.noRoot?"Leave objects out (--exclude-object)":A?"Keep no root of each object and value (--fit-floor 0), stratify fewer objects (--fit-strata), leave objects out (--exclude-object)":"Keep no root of each object (--fit-floor 0), leave objects out (--exclude-object)",j=nw[k.limitedBy],F=k.limitedBy==="storage"||k.limitedBy==="within";throw new jd(`No sample of the whole org fits: ${S} take ${k.rows} records, ${(k.storageBytes/1048576).toFixed(1)} MB, ${j.past}; the heaviest are ${w}. ${or} ${v}${j.more}.`,k.heaviest,{limitedBy:k.limitedBy,...F?{needMB:Th(k.storageBytes,"up"),budgetMB:Th(k.limitedBy==="storage"&&f.storageBytes!==void 0?f.storageBytes:f.budget.bytes,"down")}:{},heaviest:k.heaviest.map(B=>B.objectApiName)})}let O=Rp({...b,cut:k},i,f.budget);return up(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:O,...b.newestByIds.length>0?{newestByIds:b.newestByIds}:{},...b.oldestByIds.length>0?{oldestByIds:b.oldestByIds}:{},ids:[...k.ids].map(([w,A])=>({objectApiName:w,ids:A})),counts:{personAccounts:Object.fromEntries(k.personAccounts),byThePlatform:k.byThePlatform.map(w=>({...w}))}})}async averageEmailBytes(e,t){let n=og(t,e.config.fieldExclusions[$e]);if(n.length===0)return;let o=this.filterOf(e,$e);try{let s=await this.readWholeOf(e,$e,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${$e}${o?` WHERE ${o}`:""} LIMIT ${Xw}`);if(s.length===0)return;let i=0;for(let a of s)for(let[d,c]of Object.entries(a))d!=="Id"&&typeof c=="string"&&(i+=Buffer.byteLength(c,"utf8"));return Math.ceil(i/s.length)}catch(s){Ye.warn("[forge] the size of the emails could not be read before the sample was drawn: "+V(s));return}}async runSampleOf(e,t){let{manifest:n}=t,o=new Set(n.sample.whole.map(d=>d.objectApiName)),s=new Set([...e.writtenObjects].filter(d=>!o.has(d)&&!e.config.referenceDataObjects.has(d))),i=new Map,a=new Map;for(let d of s){let c=new Set;for await(let f of t.ids(d))for(let p of f)c.add(it(p));i.set(d,c);let l=c.values().next().value?.slice(0,3)??(await this.objectInfoOf(e.sourceOrgId,d))?.keyPrefix??e.sourceKeyPrefixes.get(d);l&&a.set(d,l)}return{plan:t,report:{...n.sample,plan:t.place},drawn:s,ids:i,prefixes:a,counts:n.counts??{personAccounts:{},byThePlatform:[]},gone:new Map,changed:new Map,leftEmpty:new Map,reads:new Map,withoutStandard:new Set}}drawnObjectNamed(e,t,n){let o=t.filter(s=>e.drawn.has(s));if(o.length!==0)return t.length===1?o[0]:o.find(s=>{let i=e.prefixes.get(s);return i!==void 0&&n.startsWith(i)})}inThePlan(e,t,n){return e.ids.get(t)?.has(it(n))===!0}outsideTheSample(e,t,n){let o=e.sample;if(!o)return!1;let s=this.drawnObjectNamed(o,t,n);return s===void 0?!1:!this.inThePlan(o,s,n)||o.gone.get(s)?.has(it(n))===!0}secondPassOfTheSample(e){let t=e.sample;return t?{outsideTheSample:n=>{let o=n.sourceRefId,s=[...t.drawn].find(i=>{let a=t.prefixes.get(i);return a!==void 0&&o.startsWith(a)});return s!==void 0&&this.outsideTheSample(e,[s],o)},onLeftOutsideTheSample:(n,o)=>this.noteLeftOutsideTheSample(e,n,o)}:{}}noteLeftOutsideTheSample(e,t,n){let o=e.sample;if(!o)return;let s=o.leftEmpty.get(t)??new Map;s.set(n,(s.get(n)??0)+1),o.leftEmpty.set(t,s)}async countToWriteOfThePlan(e,t,n){let o=t.objectApiName,s=e.config.stream?.resumeAfter.get(o),i=n.ids.get(o)??new Set,a=s&&Ft.test(s.lastId)?s.lastId:void 0,d=O=>a===void 0||Mr(O,a)>0,c=0;if(!s?.done)for(let O of i)d(O)&&c++;let u=Math.min(c,await this.writtenBeforeOf(e,t,s)),l=e.standardPricebookId,f=o===Ut&&l&&i.has(it(l))&&d(l)&&!e.config.writtenBefore.has(l)?Math.min(1,c-u):0,p=Math.max(0,c-u-f),g=Math.min(p,n.counts.personAccounts[o]??0),h=0;o===ce&&g>0&&await this.personAccountsInTarget(e)===!0&&(h=g);let m=n.counts.byThePlatform.find(O=>O.objectApiName===o);m&&(h+=Math.min(p-h,m.inPlan)),p-=h;let R=O=>n.report.dropped.filter(w=>w.objectApiName===o&&w.reason===O).reduce((w,A)=>w+A.rows,0),b={...u>0?{writtenBefore:u}:{},...f>0?{linkedToTarget:f}:{},...h>0?{byThePlatform:h}:{},...R("noParentInSource")>0?{noParentInSource:R("noParentInSource")}:{},...R("outsideFilter")>0?{outsideFilter:R("outsideFilter")}:{}},k=o===ce&&h>0?0:g;return{read:c,counted:{rows:p,...k>0?{personAccounts:Math.min(k,p)}:{}},...Object.keys(b).length>0?{leftOut:b}:{}}}async personContactsBeyondThePlan(e,t){if(!e.sample?.drawn.has(ce))return;let n=t.find(i=>i.objectApiName===ce),o=t.find(i=>i.objectApiName===Se)?.counted.personAccounts??0;if(!n||o<=0||await this.personAccountsInTarget(e)!==!0)return;let s=n.leftOut?.byThePlatform??0;o<=s||(n.leftOut={...n.leftOut,byThePlatform:o})}async readOfThePlan(e,t,n,o){let s=n.objectApiName,i=t.reads.get(s);if(i)return i;let a=await this.deps.describeFields(e.sourceOrgId,s),d=wp({objectApiName:s,columns:zt(a.filter(c=>!xn(c)),e.config.fieldExclusions[s]),sourceRows:n.recordCount,planRows:o});return t.reads.set(s,d),d}planRowsAfter(e,t,n){let o=e.ids.get(t);if(!o)return 0;if(n===void 0)return o.size;let s=0;for(let i of o)Mr(i,n)>0&&s++;return s}async*pagesOfThePlanByIds(e,t,n,o,s,i=!1){let a=Be(n),d=this.filterOf(e,a),c=Math.max(1,uu(a,du(o),d?`(${d})`:void 0));for await(let u of t.plan.ids(a,{...s!==void 0?{after:s}:{},size:c})){if(this.isAborted)return;let l=u.filter(g=>Ft.test(g));if(l.length===0)continue;let f=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${l.map(g=>`'${g}'`).join(", ")})`,p=await this.readWholeOf(e,a,f);if(p.sort((g,h)=>Mr(String(g.Id),String(h.Id))),i){let g=new Set(p.map(m=>it(String(m.Id)))),h=t.gone.get(a)??new Set;for(let m of l)g.has(it(m))||h.add(it(m));h.size>0&&t.gone.set(a,h)}yield p}}async rowsOfThePlan(e,t,n,o,s,i=!1){let a=[];for await(let d of this.pagesOfThePlanByIds(e,t,n,o,s,i))for(let c of d)a.push(c);return a}async*pagesOfThePlan(e,t,n,o,s){let i=n.objectApiName,a=o.lastId??o.resumeAfter,d=await this.readOfThePlan(e,t,n,this.planRowsAfter(t,i,a)),c=/^SELECT (.+?) FROM /.exec(s)?.[1]?.split(", ")??["Id"],u=d.by==="ids"?this.pagesOfThePlanByIds(e,t,i,c,a,!0):this.cursorKeptToThePlan(e,t,i,s,a);yield*js(u,e.config.stream?.writeWindow??e.config.stream?.pageSize)}async*cursorKeptToThePlan(e,t,n,o,s){let i=t.ids.get(n)??new Set,a=new Set,d=Vt(this.deps,e.sourceOrgId,o,void 0,()=>e.truncatedObjects.add(n),this.readOptionsOf(e,n));try{for await(let u of d){let l=u.filter(f=>{let p=it(String(f.Id));return i.has(p)?(a.add(p),!0):!1});l.length>0&&(yield l)}}finally{await d.return(void 0)}let c=t.gone.get(n)??new Set;for(let u of i)!a.has(u)&&(s===void 0||Mr(u,s)>0)&&c.add(u);c.size>0&&t.gone.set(n,c)}sampleResultOf(e){let t=e.sample;if(!t||e.simulated)return;let n=new Map(e.remapper.countsByObject().map(i=>[i.objectApiName,i])),o=t.report,s=bp(o.roots);return{seed:o.seed,draw:o.draw,share:o.share,sha256:o.plan.sha256,drawnAt:o.plan.drawnAt,drawnBy:o.plan.drawnBy,...s?{roots:s}:{},objects:o.objects.map(i=>{let a=n.get(i.objectApiName),d=a?a.created+(a.linked??0):0,c=e.store?.earlierRecordsOf(i.objectApiName)??0;return{...i,written:Math.min(i.kept,d+c),goneSinceTheSample:t.gone.get(i.objectApiName)?.size??0,changedSinceTheSample:t.changed.get(i.objectApiName)??0}}),...t.leftEmpty.size>0?{leftEmpty:[...t.leftEmpty].flatMap(([i,a])=>[...a].map(([d,c])=>({objectApiName:i,field:d,rows:c})))}:{}}}async countBeforeWrite(e,t){let{config:n}=e,o=n.beforeWrite;if(!o)return;let s=n.stream?.everything===!0,i=[],a=[],d=new Set,c=[],u=[];for(let A of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let S=A.objectApiName;if(!A.included||!e.writtenObjects.has(S))continue;let v=s&&!this.streamsNode(A,e);if(n.referenceDataObjects.has(S)){v&&c.push({objectApiName:S,rows:await this.rowsOf(e,A)});continue}let{read:j,counted:F,leftOut:B,capped:E,partial:_}=e.sample?.drawn.has(S)?await this.countToWriteOfThePlan(e,A,e.sample):await this.countToWrite(e,A);e.counted.set(S,j),E&&a.push(S),_&&d.add(S),v&&!e.sample?.drawn.has(S)&&c.push({objectApiName:S,rows:j}),s&&u.push({node:A,read:j,whole:v}),i.push({objectApiName:S,rows:[],counted:F,...B?{leftOut:B}:{}})}let l=e.sample?.drawn.has(ze)?void 0:i.find(A=>A.objectApiName===ze),f=i.find(A=>A.objectApiName===We),p=l?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(l&&p!==void 0&&p>0){let A=Math.min(p,l.counted.rows);l.counted={...l.counted,rows:l.counted.rows-A},l.leftOut={...l.leftOut,byThePlatform:A}}let g=f?.leftOut?.writtenBefore??0,h=l?this.rolesThePlatformMayWriteOfTheCounts(e,l.counted.rows,(p===void 0?f?.counted.rows??0:0)+g):0;if(l&&h>0&&(l.mayBeByThePlatform=p!==void 0?{rows:h,before:!0}:{rows:h}),await this.personContactsBeyondThePlan(e,i),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=s?await this.heldAtTheGate(e,t,i):void 0;m&&(m.requests+=await this.pricesReplacedAtTheGate(e,i)),m&&(m.requests+=await this.directRelationsAtTheGate(e,i,d));let R=s?await this.measureTheWholeOrg(e,i,c,u,m):void 0,b=R&&e.sample?{...R,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:R;if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let k=xs(n),O=n.dryRun&&!s?0:await this.readBackRequests(e,i),w=await o({objects:i,...k!==void 0&&a.length>0?{capped:{perObject:k,objects:a}}:{},...O>0?{readBack:O}:{},...b?{wholeOrg:b}:{},dryRun:n.dryRun});await this.afterTheGate(e,w,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(h=>h.included&&e.writtenObjects.has(h.objectApiName)&&!o.referenceDataObjects.has(h.objectApiName)),i=new Map(s.map((h,m)=>[h.objectApiName,m])),a=new Map,d=new Map,c=new Map,u=$h,l=new Map,f=(h,m,R)=>{let b=a.get(h)??new Map;b.has(m)||u<=0||(b.set(m,R),a.set(h,b),u--)},p={requests:0,lookups:new Map},g=async(h,m)=>{let R=await this.idsUnder(e,h,m);return p.requests+=Math.max(1,Math.ceil((R?.length??0)/Dn)),R};for(let h of s){if(this.isAborted)break;let m=h.objectApiName;if(e.sample?.drawn.has(m))continue;if(u>0&&this.streamsNode(h,e)){let b=await this.recordTypesOfTable(e,h);if(b&&b.closed.length>0&&this.typesHeldRowByRow(e,b)){let k=new Set(b.lackingInSource);for(let[O,w]of[[b.closedInSource.filter(A=>!k.has(A)),d],[b.lackingInSource,c]]){let A=O.map(v=>`'${v}'`).join(", ");if(!A)continue;let S=a.get(m)?.size??0;for(let v of await g(m,`RecordTypeId IN (${A})`)??[])f(m,v,"held");w.set(m,(a.get(m)?.size??0)-S)}}}let R=await this.deps.describeFields(e.sourceOrgId,m).catch(()=>[]);for(let b of R){let[k]=b.referenceTo??[],O=k===void 0?void 0:i.get(k);if(!b.isReference||(b.referenceTo??[]).length!==1||O===void 0||O>=(i.get(m)??0)||!b.createable||(o.fieldExclusions[m]??[]).includes(b.name)||!Qe(m,b.name,b.nillable)||(p.lookups.set(m,(p.lookups.get(m)??0)+1),u<=0))continue;let w=Be(b.name),A=await g(m,`${w} != null AND ${w} NOT IN (SELECT Id FROM ${Be(k)})`);for(let F of A??[])f(m,F,{field:b.name,parentObject:k,reason:fd(b.name,k)});let S=a.get(k);if(!S||S.size===0)continue;let v=[...S].filter(([,F])=>F==="held").map(([F])=>F),j=[...S].filter(([,F])=>F!=="held").map(([F])=>F);for(let[F,B]of[[v,"held"],[j,{field:b.name,parentObject:k,reason:Eh(b.name,k)}]])for(let E of kn(F)){if(u<=0)break;for(let _ of await g(m,`${w} IN (${E})`)??[])f(m,_,B)}}for(let b of R){if(!b.isReference||b.name==="RecordTypeId"||!b.createable||(o.fieldExclusions[m]??[]).includes(b.name)||(b.referenceTo??[]).length===1&&Qe(m,b.name,b.nillable))continue;let k=new Set;for(let w of b.referenceTo??[]){let A=w===m?void 0:a.get(w);if(!(!A||A.size===0))for(let S of kn([...A.keys()])){let v=await g(m,`${Be(b.name)} IN (${S})`);for(let j of v??[])k.add(j)}}for(let w of a.get(m)?.keys()??[])k.delete(w);if(k.size===0)continue;let O=l.get(m)??[];O.push({field:b.name,rows:k.size}),l.set(m,O)}}for(let h of n){let m=l.get(h.objectApiName);m&&(h.leftEmpty=m)}for(let h of n){let m=a.get(h.objectApiName);if(!m||m.size===0)continue;let R=d.get(h.objectApiName)??0,b=c.get(h.objectApiName)??0,k=[...m.values()].filter(S=>S==="held").length,O=m.size-k,w=Math.max(0,h.counted.rows-m.size),A=h.counted.personAccounts;h.counted={rows:w,...A!==void 0&&Math.min(A,w)>0?{personAccounts:Math.min(A,w)}:{}},h.leftOut={...h.leftOut,...R>0?{heldBack:(h.leftOut?.heldBack??0)+R}:{},...b>0?{recordTypeNotInTarget:(h.leftOut?.recordTypeNotInTarget??0)+b}:{},...k-R-b>0?{withoutParent:k-R-b}:{},...O>0?{noParentInSource:O}:{}}}for(let h of a.values())for(let[m,R]of h)e.heldInTheOrg.set(m,R);return p}async pricesReplacedAtTheGate(e,t){let n=t.find(h=>h.objectApiName===et);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(et)??0)>$h)return 0;let o=await this.deps.describeFields(e.sourceOrgId,et).catch(()=>[]);if(!o.some(h=>h.name===mt))return 0;let s=["Id",tn,Pn,mt,...o.some(h=>h.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(h=>h.name===Hn)?[Hn]:[]],i=this.filterOf(e,et),a=e.sample,d;try{d=a?.drawn.has(et)?await this.rowsOfThePlan(e,a,et,s):await this.readWholeOf(e,et,`SELECT ${s.join(", ")} FROM ${et}`+(i?` WHERE ${i}`:""))}catch(h){return Ye.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${V(h)}`),1}let c=Math.max(1,Math.ceil(d.length/Dn)),u=e.currencies===void 0,l=d.filter(h=>!e.heldInTheOrg.has(String(h.Id))),f=await this.priceCurrencyInput(e,l,o),p=c+(u&&e.currencies!==void 0?dw:0);if(!f){let h=e.oneCurrency===void 0,m=await this.pricesKeyOf(e);if(!m.oneCurrency)return p;let R=Math.min(n.counted.rows,wi(l,m).standsFor.length);return R>0&&(n.counted={...n.counted,rows:n.counted.rows-R},n.leftOut={...n.leftOut,currencyReplaced:R}),p+(h&&this.deps.orgCurrency?1:0)}let g=Math.min(n.counted.rows,Ca(f,[]).standsFor.size);return g===0||(n.counted={...n.counted,rows:n.counted.rows-g},n.leftOut={...n.leftOut,currencyReplaced:g}),p}async directRelationsAtTheGate(e,t,n){if(e.sample?.drawn.has(Cn))return 0;let o=t.find(p=>p.objectApiName===Cn);if(!o||o.counted.rows<=0||!t.some(p=>p.objectApiName===ce)||n.has(ce)||n.has(Cn))return 0;let s=this.deps.countRecords;if(!s)return 0;let i=e.config.stream?.resumeAfter.get(Cn),a=this.filterOf(e,Cn),d=[...a?[`(${a})`]:[],...i&&Ft.test(i.lastId)?[`Id > '${i.lastId}'`]:[],"IsDirect = true"],c;try{c=await s(e.sourceOrgId,`SELECT COUNT() FROM ${Cn} WHERE ${d.join(" AND ")}`)}catch(p){return Ye.warn(`[forge] the relations the platform writes with the contacts could not be counted at the gate: ${V(p)}`),1}let u=o.leftOut,l=(u?.writtenBefore??0)+(u?.withoutParent??0)+(u?.noParentInSource??0),f=Math.max(0,Math.min(c-l,o.counted.rows));return f===0||(o.counted={...o.counted,rows:o.counted.rows-f},o.leftOut={...u,byThePlatform:(u?.byThePlatform??0)+f}),1}async idsUnder(e,t,n){let o=e.config.stream?.resumeAfter.get(t),s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...o&&Ft.test(o.lastId)?[`Id > '${o.lastId}'`]:[],n];try{return(await this.readWholeOf(e,t,`SELECT Id FROM ${Be(t)} WHERE ${i.join(" AND ")}`)).map(d=>String(d.Id))}catch(a){Ye.warn(`[forge] the ${t} records held back could not be counted at the gate: ${V(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:k})=>k>a).map(({objectApiName:k,rows:O})=>({objectApiName:k,rows:O,bound:a})),c=new Set(o.filter(k=>k.whole).map(k=>k.node.objectApiName)),{writes:u,restOnly:l}=await this.writesOfTheWholeOrg(e,t,c),f=o.find(({node:k})=>k.objectApiName===$e&&k.included),p=t.find(k=>k.objectApiName===$e)?.counted?.rows??0,g=f&&p>0?await this.emailBytesOf(e,f.node):void 0,h=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o),R=t.find(k=>k.objectApiName===Se)?.counted?.personAccounts??0,b=R>0&&await this.personAccountsInTarget(e)===!1?R:0;return{writes:u,...l?{restOnly:l}:{},...g!==void 0?{emailTextBytes:g}:{},...i.files?{files:h??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,h)+cw(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{},...b>0?{personAccountsAsBusiness:b}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=e.bulk?.restOnly??new Set;if(s&&!e.bulk){let c=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});i=new Set([...os,...c??sa])}let a=o.stream?.writeWindow??o.stream?.pageSize??Dn,d=t.map(({objectApiName:c,counted:u})=>{let l=Math.max(0,u?.rows??0),f=s&&!i.has(c),p=n.has(c)?[l]:[...Array.from({length:Math.floor(l/a)},()=>a),...l%a>0?[l%a]:[]],g=0,h=0;for(let m of f?p:[])for(let R=0;R<m;R+=Dr){let b=Math.min(Dr,m-R);b<2e3||(g++,h+=b)}return{objectApiName:c,rows:l,jobs:g,jobRows:h,restRows:l-h}});return s?{writes:d,restOnly:i}:{writes:d}}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Dn)),i=new Map;for(let{node:c,read:u}of t)i.set(c.objectApiName,u);for(let{objectApiName:c,rows:u}of n)i.set(c,u);let a=0;for(let[c,u]of i){let l=t.find(f=>f.node.objectApiName===c)?.node;a+=e.sample?.drawn.has(c)&&l?(await this.readOfThePlan(e,e.sample,l,u)).requests:s(u)}let d=t.find(({node:c})=>c.objectApiName===$e);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===ut)){let c=await this.countOf(e,$e,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=Sd.length+Math.ceil(c/Dn),a+=Math.ceil(c/kd)+c}return a}async rowsOf(e,t){return await this.countOf(e,t.objectApiName)??t.recordCount}async countOf(e,t,n){let o=this.deps.countRecords;if(!o)return;let s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...n?[n]:[]],a=i.length>0?` WHERE ${i.join(" AND ")}`:"",d=`SELECT COUNT() FROM ${Be(t)}${a}`,c=this.readOptionsOf(e,t);try{return await(c?o(e.sourceOrgId,d,c):o(e.sourceOrgId,d))}catch{return}}async emailBytesOf(e,t){let n=t.objectApiName;try{let o=await this.deps.describeFields(e.sourceOrgId,n),s=og(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let g=0,h=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of h)for(let[R,b]of Object.entries(m))R!=="Id"&&typeof b=="string"&&(g+=Buffer.byteLength(b,"utf8"));return g}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&Ft.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],u=c.length>0?` WHERE ${c.join(" AND ")}`:"",l=["Id",...s.map(g=>g.name)].join(", "),f=0,p=Vt(this.deps,e.sourceOrgId,`SELECT ${l} FROM ${Be(n)}${u} ORDER BY Id`,e.config.stream?.pageSize,void 0,this.readOptionsOf(e,n));try{for await(let g of p){for(let h of g)for(let[m,R]of Object.entries(h))m!=="Id"&&typeof R=="string"&&(f+=Buffer.byteLength(R,"utf8"));if(this.isAborted)break}}finally{await p.return(void 0)}return f}catch(o){Ye.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+V(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of Sd){let c=[d,`${a} <= ${t}`].filter(Boolean).join(" AND "),u=[d,`${a} > ${t}`].filter(Boolean).join(" AND "),l=await this.sumOfFiles(e,i,a,c);if(!l)return;n+=l.bytes,o+=l.count;let f=await this.deps.countRecords?.(e.sourceOrgId,`SELECT COUNT() FROM ${i} WHERE ${u}`).catch(()=>{});s+=f??0}return{bytes:n,count:o,overCeiling:s}}async sumOfFiles(e,t,n,o){try{let[s]=await this.deps.queryRecords(e.sourceOrgId,`SELECT SUM(${n}) total, COUNT(Id) n FROM ${t} WHERE ${o}`),i=Number(s?.total??0),a=Number(s?.n??0);if(Number.isFinite(i)&&Number.isFinite(a))return{bytes:i,count:a}}catch{}try{let s=0,i=0,a=Vt(this.deps,e.sourceOrgId,`SELECT Id, ${n} FROM ${t} WHERE ${o} ORDER BY Id`,e.config.stream?.pageSize);try{for await(let d of a){for(let c of d){let u=c[n];s+=typeof u=="number"&&Number.isFinite(u)?u:0,i++}if(this.isAborted)break}}finally{await a.return(void 0)}return{bytes:s,count:i}}catch(s){Ye.warn(`[forge] the files of ${t} could not be measured: ${V(s)}`);return}}async phoneNumbersPastTheFiction(e,t){let n=0;for(let{node:o,read:s}of t){if(s===0||this.isAborted)continue;let i=o.objectApiName,a=new Set(e.config.fieldExclusions[i]??[]),c=(await this.deps.describeFields(e.sourceOrgId,i).catch(()=>[])).filter(u=>u.createable&&!a.has(u.name));for(let u of Ea(c)){if(u.kind!=="phone")continue;let l=await this.countOf(e,i,`${Be(u.name)} != null`);n+=Math.min(l??s,s)}}return Math.max(0,n-$f)}async countToWrite(e,t){let n=t.objectApiName,o=this.streamsNode(t,e),s=o?e.config.stream?.resumeAfter.get(n):void 0,i=this.filterOf(e,n),a=this.readOptionsOf(e,n),d=this.deps.countRecords,c=async z=>{if(!d)return;let J=[...i?[`(${i})`]:[],...z?[z]:[],...s&&Ft.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],Me=J.length>0?` WHERE ${J.join(" AND ")}`:"",ke=`SELECT COUNT() FROM ${Be(n)}${Me}`;try{return await(a?d(e.sourceOrgId,ke,a):d(e.sourceOrgId,ke))}catch{return}},u=this.readBound(e,t),l=u===void 0?void 0:Math.max(0,u-(s?.read??0)),f=await c(),p=f??t.recordCount,g=l===void 0?p:Math.min(p,l),h=xs(e.config),m=h===void 0?void 0:Math.max(0,h-(s?.read??0)),R=m!==void 0&&l===m&&p>m,b=o?await this.recordTypesOfTable(e,t):void 0;if(b&&b.closed.length>0&&!this.typesHeldRowByRow(e,b))return{read:g,counted:{rows:0},...g>0?{leftOut:xh(b.closed,g)}:{}};let k=Math.min(g,await this.writtenBeforeOf(e,t,s)),O=n===Ut?Math.min(g-k,await this.standardBookOfTheTable(e,c)):0,w=g-k-O,A=k>0||O>0?{...k>0?{writtenBefore:k}:{},...O>0?{linkedToTarget:O}:{}}:void 0,S=z=>z===void 0?{rows:w}:{rows:w,personAccounts:z},v=g<p,j=z=>({read:g,counted:S(z),...A?{leftOut:A}:{},...R?{capped:!0}:{},...v?{partial:!0}:{}});if(n!==Se&&n!==ce||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(z=>z.name==="IsPersonAccount"))return j();let B=await c("IsPersonAccount = true"),E=B===void 0?void 0:Math.min(B,w);if(n!==ce||B===void 0||f===void 0)return j(E);let _=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(_===void 0)return j(E);let ee=Math.max(0,B-_-(f-g)-k);if(ee===0)return j(E);let X=(E??0)-ee;return{read:g,counted:{rows:w-ee,...X>0?{personAccounts:X}:{}},leftOut:{...A,byThePlatform:ee},...R?{capped:!0}:{},...v?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!Ft.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,Ut)?Math.min(1,await t(`Id = '${n}'`)??0):1}async personContactsTakenAsBusinessAtTheGate(e,t){if(await this.personAccountsInTarget(e)!==!0)return;let n=await this.personRecordTypesInTarget(e);if(!n)return 0;let{config:o}=e;if(!((await this.deps.describeFields(e.sourceOrgId,Se).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[Se]??[]).includes("RecordTypeId")&&o.fieldMappings[Se]?.RecordTypeId===void 0)){let d=xa((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes);return d!==void 0&&!n.has(d.slice(0,15))?void 0:0}let a=(o.recordTypeMappings??[]).filter(d=>!n.has(d.targetId.slice(0,15))).map(d=>d.sourceId);if(a.length===0)return 0;if(a.every(d=>Ft.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return Hf({lookups:t.filter(s=>s.isReference&&o(s.name)),rows:n,ownerMappings:e.config.ownerMappings,outsideTheRun:s=>this.isOutsideTheRun(e,s),mapped:s=>e.remapper.get(s)!==void 0,known:e.targetHolds,refused:e.targetReadsRefused,inactive:e.inactiveUsers,query:s=>this.deps.queryRecords(e.targetOrgId,s),neverCopied:s=>vs(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=Kf(t,e.inactiveUsers,e.config.ownerMappings);if(o.size!==0&&!await e.writesInactiveOwners())return o}isOutsideTheRun(e,t){return!e.writtenObjects.has(t)&&!e.failedObjects.has(t)&&!e.notInTarget.has(t)}noteLookupsOutsideTheRun(e,t,n,o){let s=wd(new Map,o);if(s.size===0)return;let i=e.lookupsOutsideTheRun.get(t)??new Map;for(let[a,d]of s){let c=n.find(l=>l.name===a)?.referenceTo?.[0]??a,u=i.get(a)??{parent:c,rows:0};u.rows+=d,i.set(a,u)}e.lookupsOutsideTheRun.set(t,i)}async noteLookupsHeldBack(e,t,n,o){let s=bd(new Map,o);if(s.size===0)return;let i=e.lookupsHeldBack.get(t)??new Map;for(let[a,d]of s){let c=i.get(a)??{parent:await this.parentNamed(e,n,a,o),rows:0};c.rows+=d,i.set(a,c)}e.lookupsHeldBack.set(t,i)}async parentNamed(e,t,n,o){let s=t.find(d=>d.name===n)?.referenceTo??[];if(s.length===1)return s[0];let i=o.find(d=>d.lookupsHeldBack?.includes(n))?.source[n],a=s.filter(d=>e.writtenObjects.has(d));if(typeof i=="string"&&a.length>0){let c=(await this.sourceKeyPrefixes(e,new Set(a))).get(i.slice(0,3));if(c)return c}return s[0]??n}async rowsWhoseParentTheTargetLacks(e,t,n,o,s){let i=new Map,{config:a}=t;if(a.referenceFallback!=="keep"||a.expandOrphanParents)return i;let d=n.filter(u=>{let l=u.referenceTo??[];return u.isReference&&s(u.name)&&l.length===1&&!vs(t,l[0])&&this.isOutsideTheRun(t,l[0])&&Qe(e.objectApiName,u.name,u.nillable)});if(d.length===0||o.length===0)return i;let c=await this.idsTheTargetLacks(t,d,o,()=>!0);return c.size===0||o.forEach((u,l)=>{for(let f of d){let p=u[f.name];if(!(typeof p!="string"||!c.has(p)||t.remapper.get(p))){i.set(l,{field:f.name,parentObject:(f.referenceTo??[])[0],notInTarget:!0});return}}}),i}rowsOfClosedTypes(e,t,n,o){let{config:s}=e,i=new Map(o.map(c=>[c.recordTypeId,c])),a=n.map(c=>({RecordTypeId:s.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));e.recordTypeMapper&&s.recordTypeMappings&&(a=e.recordTypeMapper.apply(a,s.recordTypeMappings));let d=new Map;return n.forEach((c,u)=>{let l=a[u]?.RecordTypeId,f=typeof l=="string"?i.get(l):void 0;f&&d.set(c,{field:"RecordTypeId",parentObject:f.developerName,recordType:{...f,objectApiName:t.objectApiName}})}),d}async rowsHeldInTheWholeOrg(e,t,n,o,s){let i=new Map,a=new Map;if(t.config.stream?.everything!==!0||o.length===0)return{held:i,aside:a};let d=fw(t,e.objectApiName,n,s),c=new Set,u=new Map;o.forEach((l,f)=>{let p=t.heldInTheOrg.get(String(l.Id));if(p!==void 0&&p!=="held"){a.set(f,p);return}if(t.sample?.withoutStandard.has(it(String(l.Id)))){i.set(f,{field:Pn,parentObject:et,reason:Zw}),c.add(f);return}for(let{field:g,parent:h}of d){let m=l[g];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let R=t.sample;if(R?.drawn.has(h)){this.inThePlan(R,h,m)?R.gone.get(h)?.has(it(m))?a.set(f,{field:g,parentObject:h,reason:lw(g,h)}):i.set(f,{field:g,parentObject:h}):(i.set(f,{field:g,parentObject:h,reason:uw(g,h)}),c.add(f));return}let b=t.heldInTheOrg.get(m);if(b==="held"){i.set(f,{field:g,parentObject:h});return}if(b){let O=b===vh?fd(g,h):Eh(g,h);a.set(f,{field:g,parentObject:h,reason:O});return}let k=u.get(h)??new Map;k.set(m,[...k.get(m)??[],{index:f,field:g}]),u.set(h,k)}});for(let[l,f]of u){let p=await this.idsInTheSource(t,l,[...f.keys()]);for(let[g,h]of f){let m=p===void 0||p.has(g.slice(0,15));m||t.heldInTheOrg.set(g,vh);for(let{index:R,field:b}of h)i.has(R)||a.has(R)||(m?i.set(R,{field:b,parentObject:l}):a.set(R,{field:b,parentObject:l,reason:fd(b,l)}))}}for(let l of i.keys())a.delete(l);if(c.size>0&&t.sample){let l=e.objectApiName;t.sample.changed.set(l,(t.sample.changed.get(l)??0)+c.size)}return{held:i,aside:a}}async idsInTheSource(e,t,n){let o=new Set;try{for(let s of kn(n)){let i=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Be(t)} WHERE Id IN (${s})`);for(let a of i)o.add(String(a.Id).slice(0,15))}return o}catch(s){Ye.warn(`[forge] whether the source holds the ${t} records named could not be read: ${V(s)}`);return}}async writtenBeforeOf(e,t,n){let{writtenBefore:o}=e.config,s=t.objectApiName,i=e.store?.earlierRecordsOf(s,n!==void 0)??0;if(e.store&&i>0)return i;if(o.size===0||n)return 0;let a=(await this.objectInfoOf(e.sourceOrgId,s))?.keyPrefix??e.sourceKeyPrefixes.get(s);if(!a)return 0;let d=[];for(let p of o.keys())p.startsWith(a)&&d.push(p);let c=e.config.objectSoqlFilters?.[s],u=this.deps.countRecords;if(!c||d.length===0||!u)return d.length;let l=this.readOptionsOf(e,s),f=this.filterOf(e,s)??c;try{let p=0;for(let g of kn(d)){let h=`SELECT COUNT() FROM ${Be(s)} WHERE (${f}) AND Id IN (${g})`;p+=await(l?u(e.sourceOrgId,h,l):u(e.sourceOrgId,h))}return p}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===$e&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(zo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:Hm(),...n?{pass:n}:{}},d=n?void 0:this.readBound(t,e);if(i?.done||d!==void 0&&a.read>=d)return;let c=n?void 0:await this.recordTypesOfTable(t,e);if(c&&c.closed.length>0&&!this.typesHeldRowByRow(t,c)){let f=d===void 0?c.rows:Math.min(c.rows,d-a.read);this.holdBackTableForRecordTypes(e,t,c,f);return}let u=n?n.expected:t.counted.get(o)??Sh(e,d);a.carry.rowsLeft=n?()=>Math.max(0,u-a.carry.rows):()=>Math.max(0,u-(a.read-(i?.read??0)));let l=n?.stopped??`Stopped ${e.objectApiName}`;t.cursors.set(o,a);try{let f=n?void 0:await this.keysOfTheTable(t,e,a);for(f&&(a.carry.tableKeys=f);;){if(this.isAborted)throw a.carry.pages>0&&a.carry.rowsLeft()>0?this.stopStreamedNode(e,t,a.carry,0,l):a.carry.pages>0&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!await this.readNode(e,t,!1,!0))break;let p=n?t.preread.get(o)?.records??[]:void 0;if(await this.writeNode(e,t,p,a.carry),o===Se&&await this.mapContactsOfPersonAccounts(t),s&&await this.linkTasksOfTheEmailsWritten(t),await this.tellPage(t,e,a),a.ended)break}}finally{t.cursors.delete(o),await a.pages?.return(void 0)}t.store&&a.ended&&!a.failed&&a.lastId!==void 0&&t.store.checkpoint(o,{lastId:a.lastId,read:a.read,done:!0},n?.name),a.carry.pages>0&&!a.failed&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),this.releaseRows(t,o)}endOfAStreamedNode(e,t,n){if(n)return{...n.end,again:!0};if(t!==$e||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${$s(o)}`}:{}}}recordTypesOfTable(e,t){let n=t.objectApiName,o=e.tableRecordTypes.get(n);return o||(o=this.countRecordTypesOfTable(e,t),e.tableRecordTypes.set(n,o)),o}async countRecordTypesOfTable(e,t){let{config:n,sourceOrgId:o,targetOrgId:s}=e,i=t.objectApiName,a=await this.targetObjectInfoOf(e,i),d={closed:[],rows:0,target:a,closedInSource:[],lackingInSource:[]};if(!a||!a.recordTypes.some(c=>!c.available&&!c.master)&&!await this.mayLackRecordTypes(e,i,a)||(n.fieldExclusions[i]??[]).includes("RecordTypeId")||n.fieldMappings[i]?.RecordTypeId)return d;try{let[c,u]=await Promise.all([this.deps.describeFields(o,i),an(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(F=>F.name==="RecordTypeId"&&F.createable)||u&&!u.creatable.has("RecordTypeId"))return d;let f=n.stream?.resumeAfter.get(i),p=this.filterOf(e,i),g=[...p?[`(${p})`]:[],...f&&Ft.test(f.lastId)?[`Id > '${f.lastId}'`]:[]],h=g.length>0?` WHERE ${g.join(" AND ")}`:"",m=`FROM ${Be(i)}${h}`,R=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),b=R.reduce((F,B)=>F+(typeof B.n=="number"&&B.n>0?B.n:0),0),k=vu(R),O=async F=>[...$u(i,F,a.recordTypes),...await this.typesTheTargetLacks(e,i,F,a)],w=await O(this.recordTypesAsSent(e,k)),A=F=>{let B=new Set(F.map(E=>E.recordTypeId));return[...k.keys()].filter(E=>[...this.recordTypesAsSent(e,[[E,1]]).keys()].some(_=>B.has(_)))},S=(F,B)=>({closed:F,rows:B,target:a,closedInSource:A(F),lackingInSource:A(F.filter(E=>E.unmapped))}),v=this.readBound(e,t),j=v===void 0?void 0:Math.max(0,v-(f?.read??0));if(w.length>0&&j!==void 0&&b>j){let F=await this.recordTypesOfTheRowsRead(e,i,m,j);if(F)return S(await O(this.recordTypesAsSent(e,F.counts)),F.rows)}return S(w,b)}catch{return}}recordTypesAsSent(e,t){let{config:n}=e,o=new Map;for(let[s,i]of t){if(n.recordTypeDecisions.get(s)?.to===null)continue;let a=s;e.recordTypeMapper&&n.recordTypeMappings&&(a=e.recordTypeMapper.apply([{RecordTypeId:s}],n.recordTypeMappings)[0]?.RecordTypeId),typeof a=="string"&&o.set(a,(o.get(a)??0)+i)}return o}async typesTheTargetLacks(e,t,n,o){if(!e.recordTypeMapper||!e.config.recordTypeMappings)return[];if(!o||o.recordTypes.length===0)return[];if(Lo(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),Lo(t,n,o.recordTypes,i)}async mayLackRecordTypes(e,t,n){if(!e.recordTypeMapper||!e.config.recordTypeMappings||n.recordTypes.length===0)return!1;let s=((await this.objectInfoOf(e.sourceOrgId,t))?.recordTypes??[]).filter(a=>!a.master);if(s.length===0)return!1;let i=this.recordTypesAsSent(e,s.map(a=>[a.recordTypeId,1]));return Lo(t,i,n.recordTypes,[]).length>0}async recordTypesOfTheRowsRead(e,t,n,o){let s=!1;try{let i=await this.readWholeOf(e,t,`SELECT RecordTypeId ${n} ORDER BY Id LIMIT ${o}`,()=>{s=!0});if(s)return;let a=new Map;for(let d of i){let c=d.RecordTypeId;typeof c=="string"&&c!==""&&a.set(c,(a.get(c)??0)+1)}return{counts:a,rows:i.length}}catch{return}}typesHeldRowByRow(e,t){if(e.config.stream?.everything!==!0)return!1;let n=t.closed.reduce((o,s)=>o+s.recordCount,0);return t.rows>n}holdBackTableForRecordTypes(e,t,n,o){let s=e.objectApiName;t.gaps?.knowRecordTypes(s,"target",n.target?.recordTypes??[]);for(let i of n.closed)t.gaps?.add(Ph(i,n.target));t.failedObjects.add(s),t.failedCount+=o,t.errors.push({objectApiName:s,stage:"scope",failedCount:o,attemptedCount:0,samples:n.closed.map(i=>({recordSummary:`RecordType=${i.developerName} (${i.recordCount} record${i.recordCount===1?"":"s"})`,messages:[Do(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${$n(s,o,Qt(t,s))}: `+n.closed.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."})}async nextPage(e,t,n,o,s){if(n.ended)return[];let i=e.sample?.drawn.has(t.objectApiName)?e.sample:void 0,a=f=>i?this.pagesOfThePlan(e,i,t,n,f):Vt(this.deps,e.sourceOrgId,f,e.config.stream?.writeWindow??e.config.stream?.pageSize,()=>e.truncatedObjects.add(t.objectApiName),this.readOptionsOf(e,t.objectApiName));n.pages??=a(o);let d=e.config.stream?.everything===!0?ld:0,c;for(let f=0;;f++)try{c=await n.pages.next();break}catch(p){let g=Kh(p);if(!g&&!Vh(p)||f>=d||this.isAborted)throw p;let h=n.lastId===void 0?o:s?.(n.lastId);if(h===void 0)throw p;g||await Jh(Rh*2**f),Ye.warn(`[forge] ${t.objectApiName}: the source ${g?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${f+1}/${d}): `+V(p)),n.pages=a(h)}if(c.done)return n.ended=!0,[];n.taken++;let u=c.value;n.room!==void 0&&(u.length>n.room&&(u=u.slice(0,n.room),n.ended=!0,(n.cutBy==="cap"?e.cappedObjects:e.truncatedObjects).add(t.objectApiName)),n.room-=u.length),n.read+=u.length;let l=u[u.length-1]?.Id;return typeof l=="string"&&(n.lastId=l),u}async readWhole(e,t,n){let o=e.sample;if(o?.drawn.has(t)){let d=/^SELECT (.+?) FROM /.exec(n)?.[1]?.split(", ")??["Id"];return this.rowsOfThePlan(e,o,t,d,void 0,!0)}let s=!1,i=()=>{s=!0,e.truncatedObjects.add(t)},a=await this.readWholeRows(e,n,i);if(s&&e.config.stream?.everything===!0)throw new Cs(t,e.config.stream.wholeReadBound);return a}async readWholeRows(e,t,n){let{stream:o}=e.config,s=o?.pageSize;if(s===void 0||!this.deps.queryPages)return this.deps.queryRecords(e.sourceOrgId,t,n);let i=(o?.everything===!0?o.wholeReadBound:o?.ceiling)??5e4,a=[],d=Vt(this.deps,e.sourceOrgId,t,s);try{for await(let c of d)if(a.push(...c),a.length>i)return n(),a.slice(0,i)}finally{await d.return(void 0)}return a}pagedLimit(e,t){let n=xs(e.config),o=n===void 0?void 0:n-t.read,s=e.config.stream?.ceiling,i=s===void 0?void 0:s-t.read;if(i===void 0&&o===void 0)return;let a=i!==void 0&&(o===void 0||i<o);return t.room=Math.max(0,(a?i:o)??0),t.cutBy=a?"ceiling":"cap",Math.max(1,t.room)}async tellPage(e,t,n){e.store&&n.lastId!==void 0&&e.store.checkpoint(t.objectApiName,{lastId:n.lastId,read:n.read},n.pass?.name);let o=e.config.stream?.onPage;if(!o)return;let s=e.preread.get(t.objectApiName)?.records??[],i=e.simulated?[]:s.flatMap(a=>{let d=a.Id;if(typeof d!="string"||!e.remapper.isCreated(d))return[];let c=e.remapper.get(d);return c?[{sourceId:d,targetId:c}]:[]});await o({objectApiName:t.objectApiName,...n.lastId!==void 0&&!n.pass?{checkpoint:{lastId:n.lastId,read:n.read}}:{},created:i})}endStreamedNode(e,t,n,o={}){let{config:s}=t,i=o.say??t.onProgress,a=e.objectApiName;this.mergePageReports(t,a,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=o.again?[]:Qt(t,a),c=o.again?void 0:t.heldForExclusions.get(a),u=[...ud(n),...d],l=_n(u),f=v=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:v})};if(n.heldWhole!==void 0){f(`${$n(a,n.heldWholeRows,d)}: ${n.heldWhole} Objects that cannot be written without it will be skipped.`);return}if(n.rows===0&&c&&c.size>0){f(zr(a,c));return}let p=wh(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){f(`${$n(a,n.personContactsUnlinked,d)}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`);return}if(p===0&&n.failed===0&&n.sent===0&&n.withoutParent>0){f(`${$n(a,n.withoutParent,d)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`);return}let g=p+n.failed,h=g>0?n.failed/g:0,m=n.failed>0&&n.alreadyExists===n.failed,R=n.failed>0&&!m&&(p===0||h>.5),b=Vo(n.picklists.list())+No(n.currencies.list())+gd(n.lookupsNotCarried)+Rd(n.ownersInactive)+md(n.lookupsOutsideTheRun)+yd(n.lookupsHeldBack)+Td(t,a),k=ss(n.writtenWithoutFields),O=tg(t,a),w=Oh(t,a),A=Bh(n.sentOnTheirOwn);if(R){p>0&&t.failedInPart.add(a),f(p===0?`Failed all ${a} records: ${n.failed+l} failed${cn(u)}${A}${b}${w}`:`${n.failed+l}/${g+l} ${a} records failed (>50%)${cn(u)}${A}${b}${k}${O}${w}`+Fh);return}let S=yh(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${hd(s,n,u,pd(t,a))}${o.note??""}${A}${S}${b}${k}${O}${Ps(t,a)}${w}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();Od(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...ud(n),...Qt(t,i)],c=wh(n),u=c+n.failed,l=n.failed>0&&n.alreadyExists!==n.failed&&(c===0||n.failed/u>.5);l&&t.failedObjects.add(i),l&&c>0&&t.failedInPart.add(i),t.onProgress({objectName:i,status:l?"error":"stopped",progress:100,message:`${s}: ${hd(t.config,n,d,pd(t,i))}, ${a} not sent${Bh(n.sentOnTheirOwn)}${yh(n)}${Vo(n.picklists.list())}${No(n.currencies.list())}${gd(n.lookupsNotCarried)}${Rd(n.ownersInactive)}${md(n.lookupsOutsideTheRun)}${yd(n.lookupsHeldBack)}${Td(t,i)}${ss(n.writtenWithoutFields)}${Ps(t,i)}`})}mergePageReports(e,t,n){if(n.withoutParent>0&&!n.withoutParentSaid){let i={objectApiName:t,stage:"scope",failedCount:n.withoutParent,attemptedCount:0,samples:$d(n.withoutParentGroups,e.failedObjects)},a=e.errors.findIndex(d=>d.objectApiName===t&&d.stage==="insert");a===-1?e.errors.push(i):e.errors.splice(a,0,i),n.withoutParentSaid=!0}let o=e.errors.filter(i=>i.objectApiName===t&&i.stage==="insert");if(o.length>0){let[i]=o,a={...i,failedCount:o.reduce((u,l)=>u+l.failedCount,0),attemptedCount:n.succeeded+n.updated+n.linked+n.failed,samples:o.flatMap(u=>u.samples).slice(0,Tw)},d=e.errors.indexOf(i),c=e.errors.filter(u=>!o.includes(u));c.splice(d,0,a),e.errors.splice(0,e.errors.length,...c)}let s=e.existingRecords.filter(i=>i.objectApiName===t);if(s.length>1){let i=s.reduce((u,l)=>u+(l.linkedToCreated??0),0),a={objectApiName:t,linked:s.reduce((u,l)=>u+l.linked,0),...i>0?{linkedToCreated:i}:{},unidentified:s.reduce((u,l)=>u+l.unidentified,0)},d=e.existingRecords.indexOf(s[0]),c=e.existingRecords.filter(u=>!s.includes(u));c.splice(d,0,a),e.existingRecords.splice(0,e.existingRecords.length,...c)}}async startAsDrafts(e,t,n){let o=new Map;if(e.config.dryRun)return o;let s=await this.lifecycleOf(e,t);return s&&n.forEach((i,a)=>{let d=To(i.Status,s);d&&(o.set(a,String(i.Status)),i.Status=d)}),o}async oweStatusesFoundAfterStop(e,t,n){let{store:o}=e;if(!o)return;let s=n.filter(a=>{let d=a.Id;return typeof d=="string"&&o.wasFoundAfterStop(d)});if(s.length===0)return;let i=await this.lifecycleOf(e,t);if(i)for(let a of s){if(!To(a.Status,i))continue;let d=e.config.writtenBefore.get(String(a.Id));d&&this.oweStatus(e,t,d,String(a.Status))}}async lifecycleOf(e,t){let n=tu[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=nu(s=>this.deps.queryRecords(e.targetOrgId,s),n),e.lifecycles.set(t,o)),o}async notePastDraft(e,t,n){if(!([...e.statusChildren.values()].some(({parent:a})=>a===t)||e.config.excludedObjects.size>0&&Ar[t]!==void 0))return;let s=await this.lifecycleOf(e,t);if(!s)return;let i=e.pastDraft.get(t)??new Map;for(let a of n){let d=a.Id;typeof d=="string"&&To(a.Status,s)&&i.set(d,String(a.Status))}e.pastDraft.set(t,i)}async restoreStatuses(e){let t=this.deps.updateRecords;if(t&&e.store){await this.restoreStatusesFromTheJournal(e,t);return}if(!t||e.deferredStatuses.length===0)return;let n=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[o,s]of ng(n)){let i=0,a=[];for(let d=0;d<s.length;d+=is.rest){let c=s.slice(d,d+is.rest),u;try{u=await t(e.targetOrgId,o,c.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=c.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}c.forEach(({id:l,status:f},p)=>{let g=u[p];g?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${l} Status=${f}`,messages:g?.errors??["No result returned for the status update"]}))})}e.onProgress({objectName:o,status:i>0?"error":"done",progress:100,message:`Restored the status of ${s.length-i}/${s.length} ${o} records written as drafts`}),i>0&&e.errors.push({objectApiName:o,stage:"insert",failedCount:i,attemptedCount:s.length,samples:a})}}async restoreStatusesFromTheJournal(e,t){let{store:n}=e;if(!n||e.statusesGiven||n.statusesOwed().size===0)return;e.statusesGiven=!0;let o=new Map,s=new Map,i=async a=>{let d=s.get(a)??[];if(s.set(a,[]),d.length===0)return;let c=o.get(a);if(!c)return;let u;try{u=await t(e.targetOrgId,a,d.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=d.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}d.forEach(({id:l,status:f},p)=>{let g=u[p];if(g?.success){n.gaveStatus(a,l);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${l} Status=${f}`,messages:g?.errors??["No result returned for the status update"]})})};for(let{objectApiName:a,id:d,status:c}of n.statusLines()){if(e.leftDrafts.has(d)||n.statusGiven(d))continue;let u=o.get(a)??{entries:0,failed:0,samples:[]};u.entries++,o.set(a,u);let l=s.get(a)??[];l.push({id:d,status:c}),s.set(a,l),l.length>=is.rest&&await i(a)}for(let[a,{entries:d,failed:c,samples:u}]of o)await i(a),e.onProgress({objectName:a,status:c>0?"error":"done",progress:100,message:`Restored the status of ${d-c}/${d} ${a} records written as drafts`}),c>0&&e.errors.push({objectApiName:a,stage:"insert",failedCount:c,attemptedCount:d,samples:u})}reportDraftsExclusionsLeave(e){let t=e.config.excludedObjects;if(t.size===0)return;let n=new Set;for(let[s,i]of Object.entries(Ar)){let a=e.pastDraft.get(s);if(!a||a.size===0)continue;let d=e.statusChildrenRead.get(s),c=[];for(let[u,l]of a){let f=e.remapper.get(u);if(!e.config.dryRun&&!f)continue;let p;if(t.has(i.object))p=`${i.object} is excluded from this run`;else if(d&&!d.kept.has(u)){let h=d.held.get(u);h&&(p=`none of its ${i.object} records can be written without ${h.excluded}`+(h.target?Kr(h.target):", which is excluded from this run"))}if(!p)continue;f&&n.add(f);let g=f!==void 0&&!e.simulated?.has(f)?f:u;c.push({recordSummary:`${s} ${g} Status=${l}`,messages:[`Left a draft: the platform gives ${s} this status only with ${i.object} records under it, and ${p}.`]})}c.length!==0&&e.errors.push({objectApiName:s,stage:"insert",failedCount:c.length,attemptedCount:c.length,samples:c.slice(0,3)})}if(n.size===0)return;for(let s of n)e.leftDrafts.add(s);let o=e.deferredStatuses.splice(0,e.deferredStatuses.length);e.deferredStatuses.push(...o.filter(({id:s})=>!n.has(s)))}reportDraftsLeft(e){if(e.store){if(e.statusesGiven)return;e.statusesGiven=!0;for(let[n,{count:o,samples:s}]of e.store.statusesOwed())e.errors.push({objectApiName:n,stage:"insert",failedCount:o,attemptedCount:o,samples:s.map(({id:i,status:a})=>({recordSummary:`${n} ${i} Status=${a}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))});return}let t=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[n,o]of ng(t))e.errors.push({objectApiName:n,stage:"insert",failedCount:o.length,attemptedCount:o.length,samples:o.slice(0,3).map(({id:s,status:i})=>({recordSummary:`${n} ${s} Status=${i}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))})}async skipForFailedParent(e,t,n,o){let s=u=>iw(e.objectApiName,t.graph,u).filter(l=>t.failedObjects.has(l)&&!t.failedInPart.has(l)),i=s(n??[]);if(i.length===0)return!1;if(!n)try{if(i=s(await this.deps.describeFields(t.sourceOrgId,e.objectApiName)),i.length===0)return!1}catch{}t.skippedCount++,t.failedObjects.add(e.objectApiName);let a=o?.filter(u=>!dn(t.config,u)).length??t.counted.get(e.objectApiName);a!==0&&(t.failedCount+=a??0,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:a??0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:[...i.map(u=>`Not written: its records cannot be written without ${u}, which failed in this run.`),...a===void 0?["Skipped before its records were read: how many there were is not known."]:[]]}]}));let d=Qt(t,e.objectApiName),c=(a??0)+_n(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${cn(d)}`:"")}),!0}async rowsWithoutTheirParent(e,t,n,o){let s=new Map;o.forEach((u,l)=>{for(let f of n){let[p]=f.referenceTo??[];if(!f.isReference||(f.referenceTo??[]).length!==1||p===e.objectApiName||!t.failedInPart.has(p)||!Qe(e.objectApiName,f.name,f.nillable))continue;let g=u[f.name];if(typeof g=="string"&&g&&!t.remapper.get(g)){s.set(l,{field:f.name,parentObject:p});return}}});let i=n.filter(u=>u.isReference&&(u.referenceTo??[]).length>1&&Qe(e.objectApiName,u.name,u.nillable)),a=[];if(o.forEach((u,l)=>{for(let f of i){let p=u[f.name];typeof p=="string"&&p&&!t.remapper.get(p)&&a.push({index:l,field:f.name,id:p})}}),a.length===0)return s;let d=new Set(t.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName));d.delete(e.objectApiName);let c=await this.sourceKeyPrefixes(t,new Set(i.flatMap(u=>(u.referenceTo??[]).filter(l=>d.has(l)))));for(let{index:u,field:l,id:f}of a){let p=c.get(f.slice(0,3));p&&!s.has(u)&&s.set(u,{field:l,parentObject:p})}return s}async sourceKeyPrefixes(e,t){let n=[];for(let s of t){if(e.sourceKeyPrefixes.has(s))continue;let i=e.preread.get(s)?.records.find(a=>typeof a.Id=="string");i?e.sourceKeyPrefixes.set(s,String(i.Id).slice(0,3)):n.push(s)}for(let s=0;s<n.length;s+=6){let i=n.slice(s,s+6),a=await Promise.all(i.map(d=>this.objectInfoOf(e.sourceOrgId,d)));i.forEach((d,c)=>{let u=a[c]?.keyPrefix;u&&e.sourceKeyPrefixes.set(d,u)})}let o=new Map;for(let s of t){let i=e.sourceKeyPrefixes.get(s);i&&!o.has(i)&&o.set(i,s)}return o}async keyPrefixesNamedBy(e,t){let n=new Set(e.graph.nodes.map(s=>s.objectApiName)),o=new Set;for(let s of t){let i=s.isReference?s.referenceTo??[]:[];if(!(i.length<2))for(let a of i)n.has(a)&&!e.keyPrefixesAsked.has(a)&&o.add(a)}if(o.size>0){for(let s of o)e.keyPrefixesAsked.add(s);await this.sourceKeyPrefixes(e,o)}return e.sourceKeyPrefixes}async excludedByKeyPrefix(e,t,n){let o=e.config.excludedObjects;if(o.size===0)return new Map;let s=new Set;for(let d of n){let c=d.isReference?d.referenceTo??[]:[];if(!(c.length<2||!Qe(t,d.name,d.nillable)))for(let u of c)o.has(u)&&s.add(u)}let i=new Set([...s].filter(d=>!e.keyPrefixesAsked.has(d)));if(i.size>0){for(let d of i)e.keyPrefixesAsked.add(d);await this.sourceKeyPrefixes(e,i)}let a=new Map;for(let d of s){let c=e.sourceKeyPrefixes.get(d);c&&!a.has(c)&&a.set(c,d)}return a}async objectOfSourceId(e,t,n){let o=t.slice(0,3),s=n.find(u=>e.sourceKeyPrefixes.get(u)===o);if(s)return s;let i=new Set(e.graph.nodes.map(u=>u.objectApiName)),a=n.filter(u=>!e.sourceKeyPrefixes.has(u)),d=a.filter(u=>!i.has(u)),c=[a.filter(u=>i.has(u))];for(let u=0;u<d.length;u+=6)c.push(d.slice(u,u+6));for(let u of c){let l=(await this.sourceKeyPrefixes(e,new Set(u))).get(o);if(l)return l}}writeOrderOf(e){return this.orderByFields(e,new Map([...e.preread].map(([t,n])=>[t,n.fieldInfos])))}orderByFields(e,t){let n=e.parentsOutside.size>0?{...e.graph,nodes:[...e.graph.nodes,...e.parentsOutside.values()]}:e.graph,o=new Set(n.nodes.filter(c=>c.included).map(c=>c.objectApiName)),s=[],i=[];for(let[c,u]of t){Jm(u)&&i.push(c);for(let l of u)if(!(!l.isReference||!Tr(l)||!Qe(c,l.name,l.nillable)))for(let f of l.referenceTo??[])f===c||!o.has(f)||s.push({sourceObject:f,targetObject:c,relationshipName:l.name,type:"lookup",required:!0})}let a=Nl(o,i),d=t.get(et)?.some(c=>c.name===mt);return ra(ts(n,t),[...s,...a,...d?Mf(o,i,[...s,...a]):[],...Ti(o),...ji(o,t),..._f(o,t),...xi(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>gt(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(Se)&&o.has(ce)&&(await Promise.allSettled([Se,ce].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([Se,ce][d],a.value)}),ra(ts(e.graph,s),[...Ti(o),...ji(o,s),...xi(o)])}let n=new Map;for(let o=0;o<t.length&&!this.isAborted;o+=6){let s=t.slice(o,o+6);(await Promise.allSettled(s.map(a=>this.deps.describeFields(e.sourceOrgId,a.objectApiName)))).forEach((a,d)=>{a.status==="fulfilled"&&n.set(s[d].objectApiName,a.value)})}return this.orderByFields(e,n)}async withWhatStatusesNeed(e,t,n){let o=new Set(e.nodes.map(d=>d.objectApiName)),s=new Map,i=[],a=[];for(let d of e.nodes){if(this.isAborted)break;let c=Ar[d.objectApiName];if(!d.included||!c||o.has(c.object)||s.has(c.object)||n.has(c.object))continue;let u;try{u=await this.deps.describeFields(t,c.object)}catch{continue}let l=u.find(f=>f.name===c.lookup&&f.isReference&&(f.referenceTo??[]).includes(d.objectApiName));l&&(s.set(c.object,{parent:d.objectApiName,lookup:c.lookup}),i.push(Ur(c.object,u,d.level+1)),a.push({sourceObject:d.objectApiName,targetObject:c.object,relationshipName:l.name,type:"lookup",required:Qe(c.object,l.name,l.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...a]},added:s}}async withWhatItsRecordsComeWith(e,t,n){let o=new Set(e.nodes.map(a=>a.objectApiName)),s=[],i=[];for(let a of e.nodes){if(this.isAborted)break;let d=zm[a.objectApiName];if(!a.included||!d||o.has(d.object)||n.has(d.object))continue;let c;try{c=await this.deps.describeFields(t,d.object)}catch{continue}let u=c.find(l=>l.name===d.lookup&&l.isReference&&(l.referenceTo??[]).includes(a.objectApiName));u&&(o.add(d.object),s.push(Ur(d.object,c,a.level+1)),i.push({sourceObject:a.objectApiName,targetObject:d.object,relationshipName:u.name,type:"lookup",required:Qe(d.object,u.name,u.nillable)}))}return s.length===0?e:{...e,nodes:[...e.nodes,...s],edges:[...e.edges,...i]}}async withTheCatalogItNeeds(e,t,n){let o=Il(e,n);if(o.size===0)return e;let s=new Set(e.edges.map(u=>`${u.sourceObject}|${u.targetObject}`)),i=new Map,a=new Map,d=[],c=e.nodes.filter(u=>u.included);for(;c.length>0&&!this.isAborted;){let u=[];for(let l=0;l<c.length&&!this.isAborted;l+=6){let f=c.slice(l,l+6);(await Promise.allSettled(f.map(({objectApiName:g})=>this.deps.describeFields(t,g)))).forEach((g,h)=>{if(g.status!=="fulfilled")return;let{objectApiName:m,level:R}=f[h];a.set(m,g.value);for(let b of g.value){let k=b.referenceTo??[];if(!b.isReference||k.length!==1)continue;let[O]=k;O===m||!(o.has(O)||i.has(O))||El(m,b)&&(o.delete(O)&&(i.set(O,R+1),u.push({objectApiName:O,level:R+1})),!s.has(`${O}|${m}`)&&(s.add(`${O}|${m}`),d.push({sourceObject:O,targetObject:m,relationshipName:b.name,type:"lookup",required:Qe(m,b.name,b.nillable)})))}})}c=u}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([u,l])=>Ur(u,a.get(u)??[],l))],edges:[...e.edges,...d]}}async withSellingModelOptions(e,t,n){let o=u=>e.nodes.find(l=>l.included&&l.objectApiName===u),s=o(Zo),i=o(jr);if(!o(et)||!s||!i||n.has(Gt)||e.nodes.some(u=>u.objectApiName===Gt))return e;let a;try{a=await this.deps.describeFields(t,Gt)}catch{return e}let d=Ur(Gt,a,Math.max(s.level,i.level)+1),c=(u,l)=>({sourceObject:u,targetObject:Gt,relationshipName:l,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(Zo,"Product2Id"),c(jr,"ProductSellingModelId")]}}summaryOf(e){let t=this.deps.requestsSent?.(),{simulated:n}=e,o=e.config.stream?.summaryBound;if(e.store&&o!==void 0&&e.remapper.count>o)return this.summaryOfTheJournal(e,t);let s=e.remapper.toJSON();if(n)for(let[c,u]of Object.entries(s))n.has(u)&&delete s[c];let i=c=>c in s,a=Gh(e),d=[...e.mayHaveBeenWritten].map(([c,u])=>({objectApiName:c,sourceIds:[...u]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0&&!n?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...kw(e),...yw(e),...Ew(e),...Iw(e),...Pw(e),...Gw(e)],truncatedObjects:[...e.truncatedObjects],...jh(e),...e.fieldExclusionsUnmatched.length>0?{fieldExclusionsUnmatched:[...e.fieldExclusionsUnmatched]}:{},...ow(e),remapTable:s,existingRecords:[...e.existingRecords],existingSourceIds:e.remapper.existingSourceIds().filter(i),updatedSourceIds:e.remapper.updatedSourceIds().filter(i),...a.length>0&&!n?{withTheirRecordSourceIds:a}:{},...e.writtenByThePlatform.size>0?{writtenByThePlatform:[...e.writtenByThePlatform].map(([c,u])=>({objectApiName:c,rows:u}))}:{},...e.leftEmptyByFilter.size>0&&!n?{lookupsLeftEmptyByFilter:[...e.leftEmptyByFilter].flatMap(([c,u])=>[...u].map(([l,{records:f,ids:p}])=>({objectApiName:c,field:l,records:f,recordIds:[...p]})))}:{},remapByObject:n?[]:e.remapper.countsByObject(),...e.notSent.size>0?{notSentByObject:[...e.notSent].map(([c,u])=>({objectApiName:c,notSent:u}))}:{},createdByObject:n?[]:e.remapper.createdByObject(),readByObject:[...e.readByObject].map(([c,u])=>({objectApiName:c,read:u,...this.originOf(e,c,u)})),failedReads:[...e.failedReads],...e.files?{files:structuredClone(e.files)}:{},...e.fileContentFieldsLeftOut.size>0?{fileContentFieldsLeftOut:[...e.fileContentFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.encryptedFieldsLeftOut.size>0?{encryptedFieldsLeftOut:[...e.encryptedFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.picklistChanges.size>0?{picklistValuesChanged:e.picklistChanges.list()}:{},...e.currencyChanges.size>0?{currenciesReplaced:e.currencyChanges.list()}:{},...e.recordTypesGiven.size>0?{recordTypesGiven:[...e.recordTypesGiven].map(([c,u])=>Yw(c,u))}:{},...e.writtenWithoutFields.size>0?{writtenWithoutFields:[...e.writtenWithoutFields].map(([c,{rows:u,fields:l}])=>({objectApiName:c,rows:u,fields:l.map(f=>({...f}))}))}:{},contactPoints:e.contactPoints?e.contactPoints.report():{neutralized:!1,fields:[],values:0},...e.writtenBetween?{writtenBetween:{...e.writtenBetween}}:{},...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},...n?{dryRun:!0}:{},...e.gaps?{gaps:e.gaps.list(e.config.decisions.ignoredGaps)}:{},...e.decisionsApplied.size>0?{decisionsApplied:e.decisionsApplied.list()}:{},...d.length>0?{mayHaveBeenWritten:d}:{},...ey(this.sampleResultOf(e)),...e.roots?{roots:this.rootsResultOf(e,e.roots)}:{},...e.roots&&e.readRequests!==void 0?{reads:{source:e.readRequests}}:{}}}originOf(e,t,n){let o=e.roots;if(!o)return{};let s=t===e.config.rootObjectApiName,i=0;if(s)for(let u of o.ids)e.idsRead.has(u)&&i++;i=Math.min(i,n);let a=0;for(let u of e.scopeCache?.reachedOf(t)??[])s&&o.ids.has(u)||a++;let d=Math.min(a,n-i),c=e.readUnder.get(t);return{origin:{roots:i,under:d,named:n-i-d},...c&&c.size>0?{readUnder:[...c]}:{}}}rootsResultOf(e,t){let n=[],o=[],s=0,i=0,a=0,d=e.errors.find(m=>m.objectApiName===t.objectApiName)?.samples.flatMap(m=>m.messages)[0]??"not written",c=new Set(e.remapper.updatedSourceIds()),u=new Set(Gh(e)),l=new Map((e.preread.get(t.objectApiName)?.records??[]).map(m=>[String(m.Id),m])),f=m=>{let R=l.get(m);return e.simulated!==null&&t.objectApiName===ce&&R!==void 0&&rn(R)&&!e.contactsOnTheirOwn.has(m)&&typeof R.AccountId=="string"&&e.remapper.wasCreated(R.AccountId)},p=0,g=[],h=(m,R)=>{if(g.length>=bn)return;let b=R&&e.simulated===null?e.remapper.get(m):void 0;g.push(b!==void 0?{source:m,target:b}:{source:m})};for(let m of t.ids){if(!e.idsRead.has(m)){n.push(m),h(m,!1);continue}s++,e.remapper.wasCreated(m)||c.has(m)?(i++,h(m,!0)):u.has(m)||f(m)?(i++,p++,h(m,!0)):e.remapper.isExisting(m)?(a++,h(m,!0)):(o.push({id:m,reason:d}),h(m,!1))}return{objectApiName:t.objectApiName,from:t.from,...t.query?{query:{...t.query}}:{},cap:t.cap,asked:t.ids.size,read:s,gone:n,written:i,linked:a,failed:o,sha256:t.sha256,readAt:t.readAt,...t.readAgain?{readAgain:{...t.readAgain}}:{},...p>0?{withTheirAccount:p}:{},ids:g,...t.ids.size>g.length?{idsLeftOut:t.ids.size-g.length}:{},...t.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}summaryOfTheJournal(e,t){let n=this.summaryOf({...e,config:{...e.config,stream:e.config.stream&&{...e.config.stream,summaryBound:void 0}},remapper:new qr,store:void 0,withTheirRecord:new Set,linkedToCreatedCount:0}),o=e.store?.withTheirRecordCount??0,s=e.store?.linkedToCreatedCount()??0;return{...n,remapCount:e.remapper.count,...o>0?{withTheirRecordCount:o}:{},...s>0?{linkedToCreatedCount:s}:{},remapByObject:e.remapper.countsByObject(),...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},remapInJournal:!0}}async prepareFiles(e){let{config:t,onProgress:n}=e,o=t.files,s=this.fileCopyDeps();if(!o||!s)return[];let i=await Yf({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=Xf(i);if(a&&!t.dryRun)throw new jn(`${a} Nothing was written.`,"FILES_UNREAD");e.errors.push(...i.errors);let d=await this.filesCopiedBefore(e,i.files,s),c={...i,files:d.filter(p=>p.into?.unchanged!==!0)},u;if(c.files.length>0)try{u=await np(s,e.targetOrgId)}catch(p){let g=`The file storage the target has left could not be read (${V(p)}), so the files could not be checked against it.`;if(!t.dryRun)throw new jn(`${g} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(qa(g))}e.files=rp(c,o.maxFileBytes,u),a&&(e.files.lookupFailure=a);let l=ep(c.files),f=u===void 0?null:tp(l,u);if(f&&u!==void 0&&!t.dryRun)throw new jn(`${f} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:l,remainingBytes:u});if(f&&e.errors.push(qa(f)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:p,sourceId:g,name:h,bytes:m})=>({objectApiName:p,sourceId:g,name:h,bytes:m}));for(let p of e.files.objects)n({objectName:p.objectApiName,status:"done",progress:100,message:op(p)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await Zf({files:t,targetOrgId:e.targetOrgId,copiedBefore:i=>{let a=o.mapping(i);return a?.earlier&&a.kind==="created"&&a.objectApiName?{objectApiName:a.objectApiName,targetId:a.targetId}:void 0},queryRecords:n.queryRecords});return e.errors.push(...s.errors),s.files}async writeFiles(e,t){let n=this.fileCopyDeps();if(!n||!e.files)return;let{remapper:o}=e;e.failedCount+=await Ua({files:t,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:s=>o.wasCreated(s),get:s=>o.get(s),add:(s,i,a)=>o.add(s,i,a),persist:()=>o.persist()},deps:n,report:e.files,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:e.onProgress,...e.store?{calls:Es(e.store)}:{}})}async copyFilesOfTheOrg(e,t){let n=this.fileCopyDeps();if(!n)return;e.files??={maxFileBytes:t,objects:[],links:0,leftOut:[]};let o=e.files,s=0,i=(d,c)=>e.onProgress({objectName:d,status:"running",progress:50,message:c}),a=e.config.stream?.pageSize??Cw;for(let d of Sd){let{counted:c}=d,u=e.config.stream?.resumeAfter.get(zo(c,zh));if(u?.done)continue;let f=`SELECT ${d.object==="ContentVersion"?"Id, ContentDocumentId, Title, PathOnClient, ContentSize, SharingPrivacy":"Id, ParentId, Name, ContentType, BodyLength, IsPrivate"} FROM ${d.object} WHERE `+[d.where,`${d.size} <= ${t}`].filter(Boolean).join(" AND "),p=u?.read??0,g=u&&Ft.test(u.lastId)?u.lastId:void 0;for(let h=!1;!h;){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,f,g,a);if(!m)break;h=m.length<a;let R=!0;for(let k=0;k<m.length;k+=kd){let O=m.slice(k,k+kd),w=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,O):Mw(e,O);if(!w){R=!1;break}if(w.length===0)continue;let A=await this.filesCopiedBefore(e,w,n);for(let v of A){if(v.into?.unchanged)continue;let j=Hh(o,v.objectApiName);j.planned++,j.plannedBytes+=v.bytes}s+=A.filter(v=>v.into?.unchanged).length,e.failedCount+=await Ua({files:A,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:v=>e.remapper.wasCreated(v),get:v=>e.remapper.get(v),add:(v,j,F)=>e.remapper.add(v,j,F),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:Es(e.store)}:{}});let S=Hh(o,c);i(c,`Copying files: ${S.copied} of ${S.planned} copied so far`)}if(!R)break;p+=m.length;let b=m[m.length-1]?.Id;typeof b=="string"&&(g=b),g!==void 0&&e.store?.checkpoint(c,{lastId:g,read:p,...h?{done:!0}:{}},zh)}}for(let d of o.objects){let c=d.objectApiName==="Attachment"?"attachment":"file";e.onProgress({objectName:d.objectApiName,status:d.failed>0&&d.copied===0?"error":"done",progress:100,message:`Copied ${d.copied} ${c}${d.copied===1?"":"s"} of ${d.planned}`+(d.failed>0?`, ${d.failed} failed`:"")})}s>0&&Ye.info(`[forge] ${s} file(s) copied by the run this one takes up: linked to the records they lacked`)}async filesPageAfter(e,t,n,o,s){let i=n+(o?` AND Id > '${o}'`:"")+` ORDER BY Id LIMIT ${s}`;try{return await this.readOnPassingFailure(t,()=>this.deps.queryRecords(e.sourceOrgId,i))}catch(a){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:o?`(files after ${o})`:"(files)",messages:[`Not read, so not copied \u2014 a run taken up reads them again: ${V(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=Kh(o);if(!s&&!Vh(o)||n>=ld||this.isAborted)throw o;s||await Jh(Rh*2**n),Ye.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${ld}): ${V(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&Ft.test(c)&&n.set(c,d)}if(n.size===0)return[];let o=new Map,s=d=>{e.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(links of ${n.size} files)`,messages:[d]}]})},i=!1;try{let d=await this.readOnPassingFailure("ContentDocumentLink",()=>this.deps.queryRecords(e.sourceOrgId,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE ContentDocumentId IN (${[...n.keys()].map(c=>`'${c}'`).join(", ")})`,()=>i=!0));for(let c of d){let u=c.ContentDocumentId,l=c.LinkedEntityId;if(typeof u!="string"||typeof l!="string"||!e.remapper.wasCreated(l))continue;let f=o.get(u)??[];if(f.some(h=>h.id===l))continue;let p=c.ShareType,g=c.Visibility;f.push({id:l,...typeof p=="string"?{shareType:p}:{},...typeof g=="string"?{visibility:g}:{}}),o.set(u,f)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${V(d)}`);return}i&&s("More links than the source reads at once: the files were copied onto the records of the run among those read, and may lack a link to the others.");let a=[];for(let[d,c]of o){let u=n.get(d),l=u?.Id;if(!u||typeof l!="string")continue;let f=u.Title,p=typeof f=="string"&&f!==""?f:d,g=u.PathOnClient,h=u.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:l},name:p,bytes:typeof h=="number"&&Number.isFinite(h)?h:0,hosts:c,fields:{Title:p,PathOnClient:typeof g=="string"&&g!==""?g:p,...u.SharingPrivacy==="P"?{SharingPrivacy:"P"}:{}}})}return a}async readInTurn(e,t){t.turnsAhead.delete(e.objectApiName),await this.readNode(e,t,!0,!1),![...t.waitingFor.values()].some(o=>o.includes(e))&&(await this.readUnderWhatWaited(e.objectApiName,t,"at its turn"),await this.endTurn(e.objectApiName,t))}async readUnderWhatWaited(e,t,n){let o=t.scopeCache,s=t.readAgainUnder.get(e);if(!(!o||!s||!o.isRead(e))){t.readAgainUnder.delete(e);for(let{node:i,fieldInfos:a,whileWaiting:d}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");t.failedObjects.has(i.objectApiName)||n==="at its turn"&&!d||n==="after the catalog"&&!d&&!sg(i.objectApiName,a).includes(e)||await this.readAgainUnderRowsOf(t,i,[...a],e)&&await this.readUnderRowsAdded(i.objectApiName,t,1)}}}async readAgainUnderRowsOf(e,t,n,o){let s=on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:e.config.objectSoqlFilters?.[t.objectApiName],fieldsLeftOut:e.config.fieldExclusions[t.objectApiName],readObjects:e.readObjects,catalog:Ke,under:new Set([o])});return s.kind!=="query"?!1:(await this.readMore(e,t,n,s.statements,`under the ${o} records read after it`)).length>0}async readUnderRowsAdded(e,t,n){let o=t.scopeCache;if(!o||n>=Xm)return;let{config:s}=t,i=new Set(t.graph.edges.filter(a=>a.sourceObject===e&&a.targetObject!==e).map(a=>a.targetObject));for(let a of t.graph.nodes){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(!a.included||!i.has(d)||!o.isRead(d)||d===s.rootObjectApiName||Ke.has(d)||s.referenceDataObjects.has(d)||t.failedObjects.has(d)||t.notCreatable.has(d))continue;let c=await this.fieldsReadAgain(t,a);!c||!await this.readAgainUnderRowsOf(t,a,c.fields,e)||(c.described&&this.withoutFileContent(t,d,c.described,!0),await this.readUnderRowsAdded(d,t,n+1))}}async readWhatTheyCannotBeWrittenWithout(e,t,n,o){let s=e.scopeCache;if(!s||o.length===0)return;let{config:i}=e,a=new Set(i.fieldExclusions[t]??[]),d=new Map;for(let c of n){let u=c.referenceTo??[];if(!c.isReference||u.length!==1||a.has(c.name)||!Tr(c)||!Qe(t,c.name,c.nillable))continue;let[l]=u;if(l===t||l===i.rootObjectApiName||Ke.has(l)||i.referenceDataObjects.has(l)||!e.readObjects.has(l)||e.failedObjects.has(l)||e.notCreatable.has(l)||!s.isRead(l))continue;let f=s.scopeOf(l),p=e.askedForRowsThatNeedThem.get(l),g=e.heldForExclusions.get(l);for(let h of o){let m=h[c.name];typeof m!="string"||m===""||f?.has(m)||p?.has(m)||g?.has(m)||e.remapper.get(m)||e.leftToThePlatform.has(m)||d.set(l,(d.get(l)??new Set).add(m))}}for(let[c,u]of d){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let l=e.graph.nodes.find(m=>m.included&&m.objectApiName===c);if(!l)continue;let f=e.askedForRowsThatNeedThem.get(c)??new Set;for(let m of u)f.add(m);e.askedForRowsThatNeedThem.set(c,f);let p=await this.fieldsReadAgain(e,l);if(!p)continue;let g=zt(p.fields,i.fieldExclusions[c]);(await this.readMore(e,l,p.fields,new Sn().buildById({objectApiName:c,selectFields:g.length>0?g:["Id"],ids:u,extraWhere:i.objectSoqlFilters?.[c]}),`which the ${t} records read after it cannot be written without`)).length!==0&&(p.described&&this.withoutFileContent(e,c,p.described,!0),await this.readUnderRowsAdded(c,e,0))}}async readParentsOutsideTheGraph(e){let{config:t}=e;if(!e.scopeCache||t.referenceFallback!=="nullify")return!1;let n=new Map(e.graph.nodes.map(d=>[d.objectApiName,d])),o=new Map,s=new Map,i=!1,a=[...e.preread].filter(([d])=>!e.failedObjects.has(d)).map(([d,c])=>({objectApiName:d,fieldInfos:c.fieldInfos,records:c.records}));for(let d=0;d<ew&&a.length>0;d++){let c=this.parentsWanted(e,a,d>0,n);c.size>0&&(i=!0);let u=[];for(let[f,p]of c){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let g=await this.refusalOf(e,f,n.get(f),o);g?await this.holdBackForARefusedParent(e,f,g,p,s):u.push([f,p])}let l=[];for(let[f,p]of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let g=tw(e,p);if(g.ids.size===0)continue;let h=await this.readParentsById(e,f,n.get(f),g);h&&l.push(h)}a=l}return i}parentsWanted(e,t,n,o){let{config:s}=e,i=new Map,a=new Map,d=c=>{let u=a.get(c);return u||(u=new Set((e.preread.get(c)?.records??[]).flatMap(l=>typeof l.Id=="string"?[l.Id]:[])),a.set(c,u)),u};for(let{objectApiName:c,fieldInfos:u,records:l}of t){let f=new Set(s.fieldExclusions[c]??[]);for(let p of u){let g=p.referenceTo??[];if(!p.isReference||g.length!==1||f.has(p.name)||!Tr(p)||!Qe(c,p.name,p.nillable))continue;let[h]=g;if(h===c||h===s.rootObjectApiName||Ke.has(h)||s.referenceDataObjects.has(h)||s.excludedObjects.has(h)||vs(e,h))continue;let m=o.get(h);if(m&&(!n||!m.included||e.failedObjects.has(h)))continue;let R=e.askedForRowsThatNeedThem.get(h),b=e.heldForExclusions.get(h);for(let k of l){let O=k[p.name];if(typeof O!="string"||O===""||dn(s,k)||e.remapper.get(O)||e.leftToThePlatform.has(O)||R?.has(O)||b?.has(O)||d(h).has(O))continue;let w=i.get(h);w||(w={ids:new Set,neededBy:new Set,rows:[]},i.set(h,w)),w.ids.add(O),w.neededBy.add(c),w.rows.push({objectApiName:c,row:k,field:p.name})}}}return i}async refusalOf(e,t,n,o){if(n)return e.notInTarget.has(t)?"not-in-target":e.notCreatable.has(t)?"not-creatable":void 0;let s=o.get(t);if(s!==void 0)return s??void 0;let i,a=this.deps.isObjectCreatable;if(a)try{await a(e.targetOrgId,t)||(i="not-creatable")}catch(d){nr(d)?i="not-in-target":e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${d instanceof Error?d.message:String(d)}`]}]})}return o.set(t,i??null),i}async holdBackForARefusedParent(e,t,n,o,s){let i=new Map;for(let{objectApiName:a,row:d,field:c}of o.rows){let u=d.Id;if(typeof u!="string"||i.get(a)?.has(u)||!await this.carriesTheLookup(e,a,c,s))continue;let l=i.get(a)??new Map;l.set(u,{row:d,why:{field:c,excluded:t,target:n}}),i.set(a,l)}for(let[a,d]of i){let c=e.preread.get(a);if(!c)continue;let u=c.records.filter(l=>typeof l.Id!="string"||!d.has(l.Id));this.holdBackRowsRead(e,a,c,u,[...d].map(([l,{row:f,why:p}])=>({id:l,row:f,why:p})))}}async carriesTheLookup(e,t,n,o){if(e.config.fieldMappings[t]?.[n])return!0;let s=o.get(t);if(s===void 0){try{s=await an(this.deps.describeFields,e.targetOrgId,t)}catch{s=null}o.set(t,s)}return s===null||s.creatable.has(n)}async readParentsById(e,t,n,o){let{config:s}=e,i=[...o.neededBy].sort().join(", "),a=s.maxRecordsPerObject?Math.floor(s.maxRecordsPerObject):0,d=a>0?a-(e.readByObject.get(t)??0):0;if(a>0&&d<=0){o.ids.size>0&&e.cappedObjects.add(t);return}let c=e.preread.get(t),u,l;if(c)u=[...c.fieldInfos];else{try{l=await this.deps.describeFields(e.sourceOrgId,t)}catch(S){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(describe, for the ${i} records that cannot be written without its records)`,messages:[V(S)]}]});return}u=l.filter(S=>!xn(S))}let f=e.askedForRowsThatNeedThem.get(t)??new Set;for(let S of o.ids)f.add(S);e.askedForRowsThatNeedThem.set(t,f);let p=zt(u,s.fieldExclusions[t]),g=new Sn().buildById({objectApiName:t,selectFields:p.length>0?p:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]});this.holdTheRootsReading(e,t,g.length);let h;try{h=await Wr(d>0?oa(g,d,{byIdCount:g.length}):{kind:"query",statements:g,byIdCount:g.length},S=>this.deps.queryRecords(e.sourceOrgId,S,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(S){if(S instanceof be)throw S;e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(read by id, for the ${i} records that cannot be written without them)`,messages:[V(S)]}]});return}Gr(e,h);let m=new Set((c?.records??[]).flatMap(S=>typeof S.Id=="string"?[S.Id]:[])),R=h.filter(S=>typeof S.Id!="string"||!m.has(S.Id)),b=S=>(e.graph.nodes.find(v=>v.objectApiName===S)??e.parentsOutside.get(S))?.level??0,k=n??e.parentsOutside.get(t)??Ur(t,u,1+Math.max(0,...[...o.neededBy].map(b))),O=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,k,u,R,void 0,await this.excludedByKeyPrefix(e,t,u));let w=[...e.heldForExclusions.get(t)??[]].filter(([S])=>!O.has(S));if(this.leaveToThePlatform(e,t,R,u),R.length===0&&w.length===0)return;let A=c?.createableSet??new Set(u.filter(S=>S.createable).map(S=>S.name));if(R.length>0){e.preread.set(t,c?{...c,records:[...c.records,...R]}:{fieldInfos:u,createableSet:A,records:R,targetSetsPending:null}),l&&this.withoutFileContent(e,t,l,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,k),e.writtenObjects.add(t));let S=R.find(j=>typeof j.Id=="string")?.Id;typeof S=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,S.slice(0,3));let v=e.readAsParents.get(t)??{count:0,neededBy:new Set};v.count+=R.length;for(let j of o.neededBy)v.neededBy.add(j);e.readAsParents.set(t,v)}else if(!n){let S=e.heldForExclusions.get(t);S&&e.onProgress({objectName:t,status:"error",progress:100,message:zr(t,S,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+R.length+w.length),this.holdTheRootsRows(e,t),s.dryRun){let S=R.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,R,A):0,v=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${R.length-S} ${v}record(s) would be inserted`+(S>0?`, ${S} ${v}would be written by the platform with ${Qn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+Ns(Fs(w.map(([,j])=>j)),c!==void 0)})}return R.length>0?{objectApiName:t,fieldInfos:u,records:R}:void 0}async endTurn(e,t){t.turnsAhead.delete(e);let n=t.waitingFor.get(e);if(n){t.waitingFor.delete(e);for(let o of n){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.readInTurn(o,t)}}}async readNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,onProgress:d,remapper:c}=t;t.readAtItsTurn.delete(e.objectApiName);let u=t.cursors.get(e.objectApiName);try{(!u||u.taken===0)&&d({objectName:e.objectApiName,status:"scanning",progress:0,message:`Querying ${e.objectApiName} records...`});let l=u?.described??await this.deps.describeFields(i,e.objectApiName);u&&(u.described=l);let f=l.filter(E=>!xn(E)),p=new Set(f.filter(E=>E.createable).map(E=>E.name));if(await this.skipForFailedParent(e,t,f))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let E=Qm(e.objectApiName,f,t.turnsAhead);if(E)return t.waitingFor.set(E,[...t.waitingFor.get(E)??[],e]),!1}let g={node:e,edges:t.graph.edges,fieldInfos:f,scopedBuilder:t.scopedBuilder,scopeCache:t.scopeCache,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:t.roots?.ids,extraWhere:Bw(this.filterOf(t,e.objectApiName),u?.pass),fieldsLeftOut:s.fieldExclusions[e.objectApiName],maxRecordsPerObject:u?t.sample?.drawn.has(e.objectApiName)?void 0:this.pagedLimit(t,u):s.maxRecordsPerObject,...u?{inIdOrder:u.resumeAfter!==void 0?{afterId:u.resumeAfter}:{}}:{},readObjects:t.readObjects,catalog:Ke,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},h=on(g);if(n&&this.waitsForWhatPointsAtIt(e,h,t))return t.catalogNodes.push({node:e,fieldInfos:f}),!1;if(h.kind==="skip"){if(n&&h.reason===na)return t.deferredNodes.push(e),!1;let E=t.heldForExclusions.get(e.objectApiName);return E&&E.size>0?(t.readByObject.set(e.objectApiName,E.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,E,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${h.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let E=on({...g,maxRecordsPerObject:1}),_=E.kind==="query"?await Wr(E,ee=>this.deps.queryRecords(i,ee)):[];return this.reportNotCreatable(e,t,_.length>0),!1}if(this.holdTheRootsReading(t,e.objectApiName,h.statements.length),t.roots&&h.readUnder){let E=t.readUnder.get(e.objectApiName)??new Set;for(let _ of h.readUnder)E.add(_);t.readUnder.set(e.objectApiName,E)}let R=o&&!s.referenceDataObjects.has(e.objectApiName)?u?.targetSets??an(this.deps.describeFields,a,e.objectApiName).then(E=>({ok:!0,sets:E}),E=>({ok:!1,error:E})):null;u&&(u.targetSets=R);let b=t.scopeCache?new Set:void 0,k=u?E=>{let _=on({...g,maxRecordsPerObject:u.room===void 0?void 0:Math.max(1,u.room),inIdOrder:{afterId:E}});return _.kind==="query"&&_.statements.length===1?_.statements[0]:void 0}:void 0,O=await Wr(h,E=>u?this.nextPage(t,e,u,E,k):this.readWhole(t,e.objectApiName,E),b,()=>t.cappedObjects.add(e.objectApiName));if(u?.ended&&O.length===0&&u.taken>0)return!1;let w=u?.pass?O.filter(u.pass.keep):O;Gr(t,w),this.keepWhatStatusesNeed(t,e,w,b);let A=this.holdBackWhatExclusionsCost(t,e,f,w,b,await this.excludedByKeyPrefix(t,e.objectApiName,f));b&&t.scopeCache?.addReached(e.objectApiName,b);let S=w.find(E=>typeof E.Id=="string")?.Id;if(typeof S=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,S.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,w.length);let E=await t.referenceDataMapper.resolve(e.objectApiName,w,a);for(let _ of E.mappings)c.addExisting(_.sourceId,_.targetId);return E.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:E.unmatched.length,attemptedCount:w.length,referenceData:!0,samples:rw(e.objectApiName,E.unmatched)}),t.scopeCache&&Ml(t.scopeCache,e.objectApiName,w),t.linkedCount+=E.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${E.mappings.length} resolved, ${E.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,w,f),e.objectApiName===Ut&&t.standardPricebookId){let E=t.standardPricebookId,_=w.filter(ee=>ee.Id!==E);_.length!==w.length&&(w.length=0,w.push(..._))}let v=t.scopeCache;if(n&&v&&Ke.has(e.objectApiName))return rs(v,e.objectApiName,w,f,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),t.catalogNodes.push({node:e,fieldInfos:f}),t.readAtItsTurn.set(e.objectApiName,{records:w,fieldInfos:f}),!1;let j=t.heldForExclusions.get(e.objectApiName);if(A>0&&w.length===0&&j&&!u)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,j.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,j)}),!1;if(gt(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,w,f);let E=t.sample;if(E?.drawn.has(e.objectApiName)){let ee=w.filter(J=>this.inThePlan(E,e.objectApiName,String(J.Id)));w.length=0,w.push(...ee);let X=t.standardPricebookId,z=new Set(w.filter(J=>J[tn]===X).map(J=>Ad(J,t.sellingModels)));for(let J of w)J[tn]!==X&&(z.has(Ad(J,t.sellingModels))||E.withoutStandard.add(it(String(J.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,w,f);let _=await this.keptPrices(t,w);_.length!==w.length&&(w.length=0,w.push(..._))}t.scopeCache&&rs(t.scopeCache,e.objectApiName,w,f,{keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),await this.notePastDraft(t,e.objectApiName,w);let F=e.objectApiName===s.rootObjectApiName||Ke.has(e.objectApiName)?[]:Ym(e.objectApiName,f,t),B=new Set(n?[...t.waitingFor.values()].flat().map(E=>E.objectApiName):[]);for(let E of F){let _=t.readAgainUnder.get(E)??[];t.readAgainUnder.set(E,[..._,{node:e,fieldInfos:f,whileWaiting:B.has(E)}])}if(s.files&&s.stream?.everything!==!0){let E=w.flatMap(_=>typeof _.Id=="string"&&!s.writtenBefore.retried(_.Id)?[_.Id]:[]);t.fileScope.set(e.objectApiName,E)}if(this.withoutFileContent(t,e.objectApiName,l,w.length>0),u&&(u.carry.rows+=w.length),u?.pass||t.readByObject.set(e.objectApiName,(u?u.carry.rows:w.length)+(j?.size??0)),this.holdTheRootsRows(t,e.objectApiName),t.preread.set(e.objectApiName,{fieldInfos:f,createableSet:p,records:w,targetSetsPending:R}),s.dryRun){let E=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,w,p),_=w.length-E;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${_} record(s) would be inserted`+(E>0?`, ${E} would be written by the platform with ${Qn(e.objectApiName)}`:"")+Ch(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,f,w),!0}catch(l){if(l instanceof be||l instanceof Cs||Ta(l))throw l;if(t.notCreatable.has(e.objectApiName))return this.reportNotCreatable(e,t,!0),!1;t.failedObjects.add(e.objectApiName),t.failedReads.add(e.objectApiName),u&&(u.failed=!0);let f=s.isScoped?0:Math.max(0,Sh(e,s.maxRecordsPerObject)-(u?.read??0));return t.failedCount+=f,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:f,attemptedCount:f,samples:[{recordSummary:"(stage failed before insert)",messages:[V(l)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(l)}`}),!1}}holdBackWhatExclusionsCost(e,t,n,o,s,i){let a=e.config.excludedObjects;if(a.size===0)return 0;let d=t.objectApiName,c=n.filter(O=>O.isReference&&Qe(d,O.name,O.nillable)),u=c.filter(O=>{let w=O.referenceTo??[];return w.length===1&&w[0]!==d&&a.has(w[0])}),l=c.filter(O=>{let w=O.referenceTo??[];return w.length>1&&w.some(A=>a.has(A))}),f=d===et&&e.sellingModels&&a.has(Gt),p=Dh(d),g=c.length>0&&e.heldForExclusions.size>0;if(u.length===0&&l.length===0&&!g&&!f&&!p)return 0;let h=O=>{for(let S of u){let v=O[S.name];if(typeof v=="string"&&v!==""&&!e.remapper.get(v))return{field:S.name,excluded:(S.referenceTo??[])[0]}}for(let S of l){let v=O[S.name];if(typeof v!="string"||v===""||e.remapper.get(v))continue;let j=i.get(v.slice(0,3));if(j!==void 0&&(S.referenceTo??[]).includes(j))return{field:S.name,excluded:j}}let w=g?Mh(e,O,c):void 0;if(w)return w;let A=O[Hn];if(f&&typeof A=="string"&&A!=="")return{field:Hn,excluded:Gt}},m=e.heldForExclusions.get(d)??new Map,R=p?e.statusChildrenRead.get(p.parent)??{kept:new Set,held:new Map}:void 0,b=[];for(let O of o){let w=h(O),A=p?O[p.lookup]:void 0;if(!w){b.push(O),R&&typeof A=="string"&&R.kept.add(A);continue}R&&typeof A=="string"&&!R.held.has(A)&&R.held.set(A,w);let S=O.Id;typeof S=="string"&&(s?.delete(S),!m.has(S)&&(m.set(S,w),e.failedCount++))}R&&p&&e.statusChildrenRead.set(p.parent,R),m.size>0&&e.heldForExclusions.set(d,m);let k=o.length-b.length;return k>0&&(o.length=0,o.push(...b)),k}holdBackWhatHeldRowsCost(e){let{config:t}=e;if(e.heldForExclusions.size!==0)for(let n=!0;n&&!this.isAborted;){n=!1;for(let[o,s]of[...e.preread]){let i=s.fieldInfos.filter(c=>c.isReference&&Qe(o,c.name,c.nillable));if(i.length===0)continue;let a=[],d=[];for(let c of s.records){let u=c.Id,l=typeof u=="string"&&!dn(t,c)?Mh(e,c,i):void 0;typeof u=="string"&&l?d.push({id:u,row:c,why:l}):a.push(c)}d.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,a,d))}}}holdBackWhatOnlyRowsHeldBackName(e){if(!e.scopeCache||e.namedByRowsHeldBack.size===0)return!1;let t=Lh(e),n=!1;for(let[o,s]of[...e.preread]){if(!Ke.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,u=typeof c=="string"?Wh(e,o,c,t):void 0;typeof c=="string"&&u?a.push({id:c,row:d,why:u}):i.push(d)}a.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,i,a))}return n}leaveOutWhatOnlyRowsHeldBackName(e,t){let n=e.scopeCache,o=n?.get(t);if(!n||!o||o.size===0||e.namedByRowsHeldBack.size===0)return;let s=Lh(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=Wh(e,t,d,s);c&&(a.push(d),!i.has(d)&&(i.set(d,c),e.failedCount++))}a.length!==0&&(e.heldForExclusions.set(t,i),n.forget(t,a))}holdBackRowsRead(e,t,n,o,s){let{config:i,onProgress:a}=e,d=e.heldForExclusions.get(t)??new Map;for(let{id:f,why:p}of s)d.set(f,p);e.heldForExclusions.set(t,d),e.failedCount+=s.length;let c=n.fieldInfos.filter(f=>f.isReference);for(let{row:f,why:p}of s)for(let g of c){let h=f[g.name];typeof h!="string"||h===""||e.namedByRowsHeldBack.has(h)||e.namedByRowsHeldBack.set(h,{field:g.name,excluded:p.excluded,namedBy:t})}let u=new Set(s.map(({id:f})=>f)),l=e.fileScope.get(t)??[];if(l.length>0&&e.fileScope.set(t,l.filter(f=>!u.has(f))),this.noteStatusRowsHeld(e,t,o,s),i.dryRun&&a({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${s.length} fewer would be inserted`+Ns(Fs(s.map(({why:f})=>f)))}),o.length>0){e.preread.set(t,{...n,records:o});return}e.preread.delete(t),e.failedObjects.add(t),a({objectName:t,status:"error",progress:100,message:zr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=Dh(t);if(!s)return;let i=e.statusChildrenRead.get(s.parent),a=new Map(i?.held??[]);for(let{row:c,why:u}of o){let l=c[s.lookup];typeof l=="string"&&!a.has(l)&&a.set(l,u)}let d=new Set;for(let c of n){let u=c[s.lookup];typeof u=="string"&&d.add(u)}e.statusChildrenRead.set(s.parent,{kept:d,held:a})}keepWhatStatusesNeed(e,t,n,o){let s=e.statusChildren.get(t.objectApiName);if(!s)return;let i=e.pastDraft.get(s.parent),a=[];for(let d of n){let c=d[s.lookup];typeof c=="string"&&i?.has(c)===!0?a.push(d):typeof d.Id=="string"&&o?.delete(d.Id)}a.length!==n.length&&(n.length=0,n.push(...a))}leaveToThePlatform(e,t,n,o){let s=e.leftToThePlatform.keep(t,n,$w(t,o)),i=n.length-s.length;return i>0&&(n.length=0,n.push(...s)),i}leaveWhatHangsFromThePlatform(e,t,n,o){let s=[...o],i=this.leaveToThePlatform(e,t.objectApiName,s,n),a=e.readByObject.get(t.objectApiName);return i>0&&a!==void 0&&e.readByObject.set(t.objectApiName,a-i),s}holdEmailsForTheirTask(e,t){if(e.taskTurnOver||!e.graph.nodes.some(s=>s.included&&s.objectApiName===ut))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(ut)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)Oo(s)&&(n===void 0||n.has(String(s.ActivityId)))?e.emailsInTwoPasses?e.emailsLeftForTheirTask++:e.emailsAfterTheirTask.push(s):o.push(s);return o}async writeEmailsAfterTheirTask(e){if(e.emailsInTwoPasses){await this.streamEmailsAfterTheirTask(e);return}e.taskTurnOver=!0;let t=e.emailsAfterTheirTask.splice(0,e.emailsAfterTheirTask.length),n=e.graph.nodes.find(o=>o.objectApiName===$e);n&&t.length>0&&!this.isAborted&&(e.emailsAllWaiting=void 0,await this.writeNode(n,e,t)),this.endBeforeTheEmailsThatWaited(e,t.length,this.isAborted)}async streamEmailsAfterTheirTask(e){if(e.taskTurnOver)return;e.taskTurnOver=!0;let t=e.emailsLeftForTheirTask;e.emailsLeftForTheirTask=0;let n=e.graph.nodes.find(u=>u.included&&u.objectApiName===$e),o=e.config.stream?.resumeAfter,s=o?.has($e)===!0||o?.has(zo($e,bh))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has($e)&&e.graph.nodes.some(u=>u.included&&u.objectApiName===ut))||this.isAborted){this.endBeforeTheEmailsThatWaited(e,t,this.isAborted);return}let a=e.emailsWrittenFirst!==void 0,d=e.config.dryRun?"Simulated":"Completed";try{await this.streamNode(n,e,{name:bh,where:"ActivityId != null",keep:u=>Oo(u),expected:t,stopped:`Stopped ${$e} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${$e} after their task`}})}catch(u){throw e.emailsWrittenFirst=void 0,u}let c=e.emailsWrittenFirst;c&&(e.emailsWrittenFirst=void 0,e.onProgress(c))}endBeforeTheEmailsThatWaited(e,t,n){let o=e.emailsWrittenFirst??e.emailsAllWaiting;e.emailsWrittenFirst=void 0,e.emailsAllWaiting=void 0,o&&(Od(e,$e,t),e.onProgress(Fw(o,t,n,Ch(e,$e))))}endOfTheEmails(e,t){return n=>{if(n.status!=="done"&&n.status!=="error"&&n.status!=="stopped"){e.onProgress(n);return}if(!t){if(e.emailsAfterTheirTask.length===0&&e.emailsLeftForTheirTask===0){e.onProgress(n);return}e.emailsWrittenFirst=n,e.onProgress({...n,status:"running"});return}let o=e.emailsWrittenFirst;e.emailsWrittenFirst=void 0,e.onProgress(o?{...n,status:o.status==="error"?"error":n.status,message:`${o.message}; ${n.message}`}:n)}}async linkTasksWrittenWithEmails(e,t){if(e.emailsInTwoPasses)return this.tasksLinkedBeforeTheirTurn(e,t);let n=new Map;for(let c of e.preread.get($e)?.records??[]){let u=c.ActivityId,l=c.Id;if(typeof u!="string"||u===""||typeof l!="string"||!e.remapper.isCreated(l))continue;let f=e.remapper.get(l);f&&n.set(u,f)}let o=[...new Set(t.flatMap(c=>n.get(String(c.Id))??[]))];if(o.length===0)return{rows:t,linked:0};let s,{simulated:i}=e;try{s=i?new Map(o.map(c=>[c,i.idFor(null)])):await Ai(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:ut,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(c)}`]}]}),{rows:t,linked:0}}let a=t.filter(c=>{let u=String(c.Id),l=n.get(u),f=l===void 0?void 0:s.get(l);return f===void 0?!0:(e.remapper.addExisting(u,f,ut),ur(e,u),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),cr(e,ut,d),{rows:a,linked:d}}tasksLinkedBeforeTheirTurn(e,t){let n=t.filter(s=>{let i=s.Id;return typeof i!="string"||e.remapper.get(i)===void 0}),o=t.length-n.length;return o>0&&(e.linkedCount+=o),cr(e,ut,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get($e)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||Oo(i)||!e.remapper.isCreated(d))continue;let c=e.remapper.get(d);c&&t.set(c,a)}if(t.size===0)return;let n=[...t.keys()],{simulated:o}=e,s;try{s=o?new Map(n.map(i=>[i,o.idFor(null)])):await Ai(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:ut,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(i)}`]}]});return}for(let[i,a]of s){let d=t.get(i);d===void 0||e.remapper.get(d)!==void 0||(e.remapper.addExisting(d,a,ut),ur(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!So(t)||n.length===0)return{rows:n,lookups:new Map,held:new Map,linked:0,owners:0,values:i};let{config:a,remapper:d,simulated:c}=e,u=$i[t],l=a.decisions.defaultOf(t,u),f=c?await this.writesAs(e):void 0,p=await Pi(t,n,{source:R=>this.deps.queryRecords(e.sourceOrgId,R),target:R=>this.deps.queryRecords(e.targetOrgId,R),targetIdOf:R=>d.get(R),mappedUser:R=>a.ownerMappings[R],...l!==void 0?{defaultUser:l}:{},written:s,...c?{simulated:{ownerOf:R=>a.ownerMappings[R]??(f??=c.idFor(rg)),idFor:()=>c.idFor(o)}}:{}});p.defaulted.size>0&&l!==void 0&&e.decisionsApplied.add({kind:"set_default",objectApiName:t,field:u,to:l},p.defaulted.size);for(let[,{field:R,parentObject:b}]of p.held)b==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:R,rows:1,detail:{type:"reference"},decisions:[...Eu.required_field_missing??[]]});let g=0,h=0;for(let[R,{id:b,owners:k,notKept:O,unread:w=[]}]of p.linked){let A=String(R.Id);d.addExisting(A,b,t),d.isCreated(String(R.OpportunityId))&&(ur(e,A),h++),k&&g++;for(let S of O)i.notKept.set(S,(i.notKept.get(S)??0)+1);for(let S of w)i.unread.set(S,(i.unread.get(S)??0)+1)}let m=p.linked.size;return m>0&&(e.linkedCount+=m),cr(e,t,h),m>h&&e.existingRecords.push({objectApiName:t,linked:m-h,unidentified:0}),{rows:m>0?n.filter(R=>!p.linked.has(R)):n,lookups:p.lookups,held:p.held,linked:m,owners:g,values:i}}async takeTheSyncCopies(e,t,n,o,s){let i={taken:0,given:0};if(!e.readsEverythingFirst)return i;let{remapper:a,simulated:d,config:c}=e,u=h=>a.wasCreated(h)||c.writtenBefore.has(h),l=[];if(t.forEach(({source:h},m)=>{let R=h[Wa],b=h[Da];if(typeof R!="string"||typeof b!="string"||!u(R)||!u(b))return;let k=a.get(R),O=a.get(b);k&&O&&l.push({index:m,quote:k,product:O})}),l.length===0)return i;let f=h=>s.updatable?s.updatable.has(h):s.fields?.find(m=>m.name===h)?.updateable!==!1,p;if(d)p=this.copiesASimulationFinds(e,t,l,s.keyPrefix);else{let h=k=>s.fields===void 0||s.fields.some(O=>O.name===k&&O.queryable!==!1),m=[...new Set(l.flatMap(({index:k})=>Object.keys(n[k]??{})))].filter(k=>f(k)&&h(k)),R;try{R=await qf(k=>this.deps.queryRecords(e.targetOrgId,k),l,m)}catch(k){return e.errors.push({objectApiName:rr,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(quote lines the platform copied from their opportunity products)",messages:[`Not looked up, so written as read: a quote that syncs with its opportunity may hold a line twice. ${V(k)}`]}]}),i}let b=new Set;for(let k of o){let O=a.get(String(k.Id));O&&b.add(O.slice(0,15))}p=Uf(l,R,b)}if(p.size===0)return i;let g=d?0:await this.giveTheCopiesTheirFields(e,t,n,p,f);for(let[h,m]of p){let R=t[h],b=typeof R.source.Id=="string"?R.source.Id:void 0,k=String(m.Id);b!==void 0&&a.add(b,k,rr),R.nullifiedFks.length>0&&this.oweToTheSecondPass(e,R.nullifiedFks.map(O=>({objectApiName:rr,newId:k,sourceId:b,fieldName:O.field,sourceRefId:O.sourceRefId,...O.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let h of[...p.keys()].sort((m,R)=>R-m))t.splice(h,1),n.splice(h,1);return{taken:p.size,given:g}}copiesASimulationFinds(e,t,n,o){let s=new Map,{simulated:i}=e;if(!i)return s;let a=l=>typeof l=="string"&&l!==""?l.slice(0,15):void 0,d=new Map;for(let l of e.pendingFkUpdates){let f=a(l.sourceId),p=a(l.sourceRefId);l.objectApiName===We&&l.fieldName===ys&&f&&p&&d.set(f,p)}if(d.size===0)return s;let c=new Map;for(let l of e.preread.get(Df)?.records??[]){let f=a(l.Id),p=a(l.OpportunityId);f&&p&&c.set(f,p)}let u=new Set;for(let{index:l}of n){let{source:f}=t[l],p=a(f[Da]),g=a(f[Wa]),h=p?c.get(p):void 0;!p||!g||!h||d.get(h)!==g||u.has(p)||(u.add(p),s.set(l,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:rr,recordSummary:"(quote lines the platform copied from their opportunity products)",leftAs:"Taken, and left as the platform copied them, without the fields of the source's lines"}){let a=[];for(let[l,f]of o){let p=new Set(t[l].nullifiedFks.map(h=>h.field)),g=Gf(n[l]??{},f,s,p);Object.keys(g).length>0&&a.push({Id:f.Id,...g})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],u=0;for(let l=0;l<a.length;l+=Xh){let f=a.slice(l,l+Xh);if(!d||this.isAborted){c.push(`${f.length} not sent: ${d?"the run was cancelled first":"the run sends no update"}`);continue}try{let p=await d(e.targetOrgId,i.objectApiName,f);f.forEach((g,h)=>{let m=p[h];m?.success?u++:c.push(`${String(g.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(p){c.push(`${f.length} not updated: ${V(p)}`)}}return c.length>0&&e.errors.push({objectApiName:i.objectApiName,stage:"insert",failedCount:0,attemptedCount:a.length,samples:[{recordSummary:i.recordSummary,messages:[`${i.leftAs}: ${c.slice(0,3).join(" | ")}`]}]}),u}async linkTheRolesThePlatformWrote(e,t,n,o){let s={linked:0,given:0};if(t.length===0)return s;let{remapper:i,simulated:a,config:d}=e,c=new Map;if(d.writtenBefore.size>0&&t.forEach(({source:R},b)=>{let k=R.OpportunityId,O=n[b]?.[Le];typeof k!="string"||typeof O!="string"||O===""||vi(R)&&d.writtenBefore.has(k)&&c.set(k,O)}),e.contactSentWith.size===0&&c.size===0)return s;let u=Ir(t.map(({source:R},b)=>({OpportunityId:R.OpportunityId,[Le]:n[b]?.[Le],IsPrimary:R.IsPrimary})),R=>i.isCreated(R)?e.contactSentWith.get(R):c.get(R));if(u.length===0)return s;let l=R=>o.updatable?o.updatable.has(R):o.fields?.find(b=>b.name===R)?.updateable!==!1,f=a?u.filter(R=>i.isCreated(String(t[R].source.OpportunityId))):[],p=u.filter(R=>!f.includes(R)),g=new Map(f.map(R=>[R,{Id:a?.idFor(o.keyPrefix)??""}]));if(p.length>0){let R=S=>o.fields===void 0||o.fields.some(v=>v.name===S&&v.queryable!==!1),b=a?[]:[...new Set(p.flatMap(S=>Object.keys(n[S]??{})))].filter(S=>l(S)&&R(S)),k=new Map(p.map(S=>[S,{opportunity:String(i.get(String(t[S].source.OpportunityId))),contact:String(n[S]?.[Le])}])),O;try{O=await Ei(S=>this.deps.queryRecords(e.targetOrgId,S),[...new Set([...k.values()].map(({opportunity:S})=>S))],b)}catch(S){e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[`Not looked up, so written as read: an opportunity may hold the role of its contact twice. ${V(S)}`]}]}),O=[]}let{found:w,alike:A}=Ii(k,O);for(let[S,v]of w)g.set(S,v);if(A.length>0){for(let S of A)e.contactSentWith.delete(String(t[S].source.OpportunityId));e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[Zc(A.length)]}]})}}if(g.size===0)return s;let h=a?0:await this.giveTheCopiesTheirFields(e,t,n,g,l,{objectApiName:ze,recordSummary:"(contact roles the platform wrote with their opportunities)",leftAs:"Linked, and left as the platform wrote them, without the fields of the source's roles"}),m=0;for(let[R,b]of g){let k=t[R],O=typeof k.source.Id=="string"?k.source.Id:void 0,w=String(b.Id);if(O===void 0)continue;let A=String(k.source.OpportunityId);e.contactSentWith.delete(A),i.addExisting(O,w,ze),i.wasCreated(A)&&(ur(e,O),m++),k.nullifiedFks.length>0&&this.oweToTheSecondPass(e,k.nullifiedFks.map(S=>({objectApiName:ze,newId:w,sourceId:O,fieldName:S.field,sourceRefId:S.sourceRefId,...S.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let R of[...g.keys()].sort((b,k)=>k-b))t.splice(R,1),n.splice(R,1);return e.linkedCount+=g.size,cr(e,ze,m),g.size>m&&e.existingRecords.push({objectApiName:ze,linked:g.size-m,unidentified:0}),{linked:g.size,given:h}}async mapContactsOfPersonAccounts(e,t=e.preread.get(Se)?.records??[]){let n=new Map;for(let i of t){let a=i[Er],d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||e.remapper.get(a))continue;let c=e.remapper.get(d);c&&n.set(c,{contact:a,account:d})}if(n.size===0||await this.personAccountsInTarget(e)===!1)return;let{simulated:o}=e;if(o){for(let[,{contact:i,account:a}]of n)e.contactsOnTheirOwn.has(i)||(e.remapper.addExisting(i,o.idFor(null),ce),e.remapper.isCreated(a)&&this.contactWithItsAccount(e,i));return}let s;try{s=await Xc(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:Se,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contacts the platform wrote with the person accounts)",messages:[`Not looked up, so what points at them is left empty: ${V(i)}`]}]});return}for(let[i,{contact:a,account:d}]of n){let c=s.get(i);if(!c){e.contactsOnTheirOwn.add(a);continue}e.remapper.addExisting(a,c,ce),e.remapper.isCreated(d)&&this.contactWithItsAccount(e,a)}}contactWithItsAccount(e,t){ur(e,t);let n=e.sample;(n?.drawn.has(ce)?this.inThePlan(n,ce,t):e.writtenObjects.has(ce))||(e.linkedCount++,cr(e,ce,1),n?.drawn.has(ce)&&e.personContactsOutsideTheSample++)}writesAs(e){let{runningUser:t}=this.deps;return e.writesAs??=t?t(e.targetOrgId).then(n=>typeof n=="string"&&n!==""?n:void 0,()=>{}):Promise.resolve(void 0),e.writesAs}personAccountsInTarget(e){return e.personAccountsInTarget??=this.deps.describeFields(e.targetOrgId,Se).then(t=>t.some(n=>n.name===Er),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${Se}'`).then(t=>t.length===0?void 0:new Set(t.filter(n=>n.IsPersonType===!0||n.IsPersonType==="true").map(n=>String(n.Id).slice(0,15))),()=>{}),e.personRecordTypes}async takenAsBusinessAccounts(e,t,n){let o=t.filter(rn);if(o.length===0)return new Set;let s=await this.personAccountsInTarget(e);if(s!==!0)return new Set(s===!1?o:[]);let i=await this.personRecordTypesInTarget(e);if(!i)return new Set;let a=new Map((e.config.recordTypeMappings??[]).map(u=>[u.sourceId,u.targetId])),d=u=>{let l=u.RecordTypeId;return n&&typeof l=="string"&&l!==""?l:void 0},c=o.some(u=>d(u)===void 0)?xa((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes):void 0;return new Set(o.filter(u=>{let l=d(u),f=l===void 0?c:a.get(l);return f!==void 0&&!i.has(f.slice(0,15))}))}async noteContactsOfBusinessAccounts(e,t,n){let o=n.has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[Er];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if(So(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!dn(e.config,a)).map(a=>String(a.Id)));return n.length===0||i.size===0?0:(await this.teamThePlatformWrites(e,t,n,i)).size}if(t===ze)return(await this.rolesThePlatformWritesOfTheRead(e,e.preread.get(We)?.records??[],e.preread.get(ce)?.records??[],n)).size;if(t===Se)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==ce)return 0;let s=n.filter(i=>rn(i)&&!e.contactsOnTheirOwn.has(String(i.Id))).length;return s>0&&await this.personAccountsInTarget(e)!==!1?s:0}async personContactsOnTheirOwn(e,t){if(t.length===0)return{rows:new Set,why:""};let n=await this.personAccountsInTarget(e);return{rows:new Set(t.filter(i=>n===!1||e.contactsOnTheirOwn.has(String(i.Id)))),why:n===!1?"the target has no person accounts":"their account is no person account in the target"}}saySentOnTheirOwn(e,t,n){t!==0&&e.errors.push({objectApiName:ce,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`IsPersonAccount=true (${t} record${t===1?"":"s"})`,messages:[`Sent as contacts of their own: ${n}, and wrote no contact with it.`]}]})}linkPersonContacts(e,t){let n=0,o=0,s=0,i=0;for(let c of t){let u=String(c.Id),l=e.remapper.get(u);if(l){e.remapper.addExisting(u,l,ce),n++,Nw(e,u)&&o++;continue}let f=c.AccountId;typeof f=="string"&&e.remapper.get(f)?i++:s++}n>0&&(e.linkedCount+=n),cr(e,ce,o),n>o&&e.existingRecords.push({objectApiName:ce,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:Nh.accountNotWritten}]:[],...i>0?[{count:i,why:Nh.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:ce,stage:"scope",failedCount:d,attemptedCount:0,samples:a.map(({count:c,why:u})=>({recordSummary:`IsPersonAccount=true (${c} record${c===1?"":"s"})`,messages:[`Not written: ${u.replace(/^not sent: /,"")}.`]}))})),{linked:n,notSent:a}}reportNotCreatable(e,t,n){t.skippedCount++,n&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not createable on target org"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:n?`Skipped ${e.objectApiName} (target org rejects inserts on this entity)`:`Skipped ${e.objectApiName} (target org rejects inserts on this entity; the clone holds none of its records)`})}async reportNotInTargetOfTheScope(e){for(let t of e.notInTargetPutOff?.splice(0)??[]){let n=await this.deps.describeFields(e.sourceOrgId,t.objectApiName).catch(()=>{}),o=n&&on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,readObjects:e.readObjects,catalog:Ke});if(o?.kind!=="skip"||o.reason!==na){this.reportNotInTarget(t,e);continue}e.skippedCount++,e.onProgress({objectName:t.objectApiName,status:"skipped",progress:100,message:`Skipped ${t.objectApiName} (not in the target org; nothing the run read names its records)`})}}reportNotInTarget(e,t){t.skippedCount++,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not in the target org, or the user the run writes as cannot see it: none of its records can be written there"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (not in the target org)`})}waitsForWhatPointsAtIt(e,t,n){return!n.scopeCache||!Ke.has(e.objectApiName)?!1:t.kind==="skip"||!Cl(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=vl.flatMap(d=>e.catalogNodes.filter(({node:c})=>c.objectApiName===d)).filter(({node:d})=>!e.failedObjects.has(d.objectApiName)&&!e.notCreatable.has(d.objectApiName)&&!o.referenceDataObjects.has(d.objectApiName));if(!s.some(({node:d})=>kh(n,d.objectApiName).size>0))return;let i=new Map([...n.entries()].map(([d,c])=>[d,new Set(c)])),a=new Set;for(let{node:d,fieldInfos:c}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let u=d.objectApiName,l=[...c],f=o.objectSoqlFilters?.[u],p=async m=>u===Ut&&e.standardPricebookId?m.filter(R=>R.Id!==e.standardPricebookId):gt(u)&&e.standardPricebookId?(await this.addStandardPricebookEntries(d,e,m,l),e.readsEverythingFirst||await this.pricesInTheCurrencyWritten(d,e,m,l),this.keptPrices(e,m)):m;if(u===Gt){if(!a.has(Zo)&&!a.has(jr))continue;let m=on({node:d,edges:e.graph.edges,fieldInfos:l,scopedBuilder:e.scopedBuilder,scopeCache:n,rootObjectApiName:o.rootObjectApiName,rootRecordId:o.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:f,fieldsLeftOut:o.fieldExclusions[u],readObjects:e.readObjects,catalog:Ke});if(m.kind!=="query")continue;(await this.readMore(e,d,l,m.statements,"named by records read after the catalog",p)).length>0&&a.add(u);continue}let g=zt(l,o.fieldExclusions[u]),h=new Set;for(let m=0;m<Zm;m++){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let R=[...kh(n,u)].filter(k=>!h.has(k));if(R.length===0)break;for(let k of R)h.add(k);if((await this.readMore(e,d,l,new Sn().buildById({objectApiName:u,selectFields:g.length>0?g:["Id"],ids:new Set(R),extraWhere:f}),m===0?"named by records read after the catalog":"named by its own records read before them",p)).length===0)break;a.add(u)}}a.size>0&&await this.readAfterTheCatalogAgain(e,t,i)}async readAfterTheCatalogAgain(e,t,n){let o=e.scopeCache;if(!o)return;let{config:s}=e,i=new Set;for(let a of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(e.failedObjects.has(d)||e.notCreatable.has(d)||s.referenceDataObjects.has(d))continue;let c=n.get(d),u=o.isRead(d)?o.scopeOf(d):void 0,l=new Set([...o.get(d)??[]].filter(b=>!c?.has(b)&&!u?.has(b))),f=new Set(e.graph.edges.filter(b=>b.targetObject===d&&i.has(b.sourceObject)).map(b=>b.sourceObject));if(l.size===0&&f.size===0)continue;let p=await this.fieldsReadAgain(e,a);if(!p)continue;let{fields:g}=p,h=s.objectSoqlFilters?.[d],m=[];if(l.size>0){let b=zt(g,s.fieldExclusions[d]);m.push(...new Sn().buildById({objectApiName:d,selectFields:b.length>0?b:["Id"],ids:l,extraWhere:h}))}if(f.size>0){let b=on({node:a,edges:e.graph.edges,fieldInfos:g,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:h,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:Ke,under:f});b.kind==="query"&&m.push(...b.statements)}m.length===0||(await this.readMore(e,a,g,m,"for what the catalog read again brought")).length===0||(i.add(d),p.described&&this.withoutFileContent(e,d,p.described,!0))}}async fieldsReadAgain(e,t){let n=e.preread.get(t.objectApiName);if(n)return{fields:[...n.fieldInfos]};try{let o=await this.deps.describeFields(e.sourceOrgId,t.objectApiName);return{fields:o.filter(s=>!xn(s)),described:o}}catch{return}}async readMore(e,t,n,o,s,i=async a=>a){let a=e.scopeCache;if(!a)return[];let{config:d}=e,c=t.objectApiName,u=d.maxRecordsPerObject?Math.floor(d.maxRecordsPerObject):0,l=u>0?u-(e.readByObject.get(c)??0):0;if(u>0&&l<=0)return o.length>0&&e.cappedObjects.add(c),[];let f=a.isRead(c),p=new Set(f?a.scopeOf(c)??[]:[]),g=m=>typeof m.Id!="string"||!p.has(m.Id);this.holdTheRootsReading(e,c,o.length);let h;try{let m=await Wr(l>0?oa(o,l,{byIdCount:o.length}):{kind:"query",statements:o,byIdCount:o.length},B=>this.deps.queryRecords(e.sourceOrgId,B,()=>e.truncatedObjects.add(c)),void 0,()=>e.cappedObjects.add(c));Gr(e,m);let R=m.filter(g);this.keepWhatStatusesNeed(e,t,R,void 0);let b=e.heldForExclusions.get(c),k=0;for(let B of b?R:[]){let E=B.Id;typeof E!="string"||b?.get(E)?.namedBy===void 0||(b.delete(E),k++)}k>0&&(b?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=k,e.readByObject.set(c,(e.readByObject.get(c)??k)-k));let O=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,R,void 0,await this.excludedByKeyPrefix(e,c,n));let w=[...e.heldForExclusions.get(c)??[]].filter(([B])=>!O.has(B));if(this.leaveToThePlatform(e,c,R,n),h=(await i(R)).filter(g),rs(a,c,h,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,h.flatMap(B=>typeof B.Id=="string"?[B.Id]:[])),await this.notePastDraft(e,c,h),h.length===0&&w.length===0)return[];if(d.files&&d.stream?.everything!==!0){let B=h.flatMap(E=>typeof E.Id=="string"?[E.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...B])}f||e.skippedCount--;let A=e.preread.get(c),S=A?.records??[],v=gt(c)?await this.keptPrices(e,[...S,...h]):[...S,...h],j=v.length-S.length,F=A?.createableSet??new Set(n.filter(B=>B.createable).map(B=>B.name));if(e.preread.set(c,A?{...A,records:v}:{fieldInfos:n,createableSet:F,records:v,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+j+w.length),this.holdTheRootsRows(e,c),d.dryRun){let B=await this.writtenWithTheirAccountOnADryRun(e,c,gt(c)?[]:h,F);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${j-B} more record(s) would be inserted`+(B>0?`, ${B} more would be written by the platform with ${Qn(c)}`:"")+`, ${s}`+Ns(Fs(w.map(([,E])=>E)),!0)})}}catch(m){if(m instanceof be||Ta(m))throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[V(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,h),h}async keptPrices(e,t){let n=await this.pricesKeyOf(e),{kept:o,standsFor:s}=wi(t,n);if(this.pricesStandFor(e,s),n.oneCurrency)for(let i of o){let a=i.Id,d=i[mt];typeof a=="string"&&typeof d=="string"&&d!==""&&e.pricesKeptAsRead.set(a,{from:d,to:n.oneCurrency.code})}return o}async pricesKeyOf(e){e.oneCurrency??=(async()=>{let n=a=>this.deps.describeFields(a,et).catch(()=>[]),[o,s]=await Promise.all([n(e.sourceOrgId),n(e.targetOrgId)]),i=a=>a.some(d=>d.name===mt);if(!(s.length===0||!i(o)||i(s)))try{let a=await this.deps.orgCurrency?.(e.targetOrgId);return typeof a=="string"&&/^[A-Z]{3}$/.test(a)?{code:a}:{}}catch(a){return Ye.warn(`[forge] the target's one currency could not be read: ${V(a)}`),{}}})();let t=await e.oneCurrency;return{sellingModel:e.sellingModels,...t?{oneCurrency:t}:{}}}pricesStandFor(e,t){for(let{left:n,kept:o}of t){let s=n.Id,i=o.Id;if(typeof s!="string"||typeof i!="string"||s===i||e.prices.standsFor.get(s)===i)continue;e.remapper.alias(s,i),e.prices.standsFor.set(s,i);for(let[c,u]of e.prices.standsFor)u===s&&(e.remapper.alias(c,i),e.prices.standsFor.set(c,i));let a=n[mt],d=o[mt];typeof a=="string"&&typeof d=="string"&&a!==d&&e.pricesSwappedSaid.push({from:a,to:d,how:"replaced",forLines:!1})}}async addStandardPricebookEntries(e,t,n,o){let s=t.standardPricebookId;if(!s)return;let i=u=>Ad(u,t.sellingModels),a=new Set,d=new Set,c=new Set;for(let u of n){let l=u.Id;if(typeof l=="string"&&c.add(l),u[tn]===s)continue;let f=u[Pn];typeof f=="string"&&f&&(a.add(f),d.add(i(u)))}if(a.size!==0)try{let u=new Sn().buildJoining({objectApiName:e.objectApiName,selectFields:zt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Pn,ids:a},whole:{field:tn,ids:new Set([s])}}),l=0;for(let f of u)for(let p of await this.deps.queryRecords(t.sourceOrgId,f)){let g=p.Id;typeof g=="string"&&c.has(g)||d.has(i(p))&&(n.push(p),Gr(t,[p]),l++)}l>0&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:`Added ${l} standard price book entr${l===1?"y":"ies"} the custom prices depend on`})}catch(u){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book entries)",messages:[V(u)]}]})}}async pricesInTheCurrencyWritten(e,t,n,o,s){let i=await this.priceCurrencyInput(t,n,o);if(!i)return;let a={...i,...s?{wanted:s}:{}},d=s?t.pricesTheGateCounted:void 0,c=Na(a).filter(h=>!d||d.has(Fa(h))),u=[],l=[...new Set(c.map(({currency:h})=>h))].filter(h=>/^[A-Z]{3}$/.test(h));if(l.length>0)try{let h=new Sn().buildJoining({objectApiName:e.objectApiName,selectFields:zt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Pn,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:tn,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${mt} IN (${l.map(m=>`'${m}'`).join(", ")})`});for(let m of h)u.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(h){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[V(h)]}]});return}let f=t.sample;if(f?.drawn.has(e.objectApiName)){let h=u.filter(m=>this.inThePlan(f,e.objectApiName,String(m.Id)));u.length=0,u.push(...h)}let p=Ca(a,d?u.filter(h=>d.has(Pa(Bf(h,t.sellingModels),String(h[mt])))):u),g=new Set(n);n.length=0,n.push(...p.rows),Gr(t,p.rows.filter(h=>!g.has(h)));for(let[h,m]of p.standsFor)t.remapper.alias(h,m),t.prices.standsFor.set(h,m);for(let[h,m]of t.prices.standsFor){let R=p.standsFor.get(m);R!==void 0&&(t.remapper.alias(h,R),t.prices.standsFor.set(h,R))}for(let[h,m]of p.convertedInto)t.prices.convertedInto.set(h,m);for(let[h,m]of p.written)t.prices.written.set(h,m);for(let[h,m]of p.keys)t.prices.keys.set(h,m);t.pricesSwappedSaid.push(...p.said),!(p.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:Ma(p.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===mt)||!t.some(d=>typeof d[mt]=="string"))return;let s=await this.runCurrencies(e);if(!s)return;let{target:i}=s,a=this.priceCurrencyWrittenIn(e,i);return{prices:t,standardBookId:o,sellingModels:e.sellingModels,writtenIn:a,active:i.active}}priceCurrencyWrittenIn(e,t){return n=>{let o={[mt]:n};e.config.decisions.applyToRow(et,o,void 0,new Xi);let s=o[mt];return typeof s=="string"&&t.active.has(s)?s:bu(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(et);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=Na({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(Fa)),o.length}currenciesTheirLinesMayWant(e,t,n){let o=new Set(t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[])),{decisions:s}=e.config,i=d=>{if(s.changesRowsOf(d))return!0;if(!Po(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(u=>u.name===Ru[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:u}]of Object.entries(ms)){let l=i(c);for(let f of e.preread.get(d)?.records??[]){let p=f[_r];if(typeof p!="string"||typeof f[u]!="string")continue;let g=e.prices.standsFor.get(p)??p;if(!o.has(g))continue;let h=f[He],m=!l&&typeof h=="string"&&n.has(h)?[h]:[...n],R=a.get(g)??new Set;for(let b of m)R.add(b);a.set(g,R)}}return a}currenciesTheirLinesWant(e,t){let n=new Set(t.flatMap(s=>typeof s.Id=="string"?[s.Id]:[])),o=new Map;for(let[s,{field:i}]of Object.entries(ms))for(let a of e.preread.get(s)?.records??[]){let d=a[_r];if(typeof d!="string")continue;let c=e.prices.standsFor.get(d)??d;if(!n.has(c))continue;let u=this.currencyTheirRecordWentIn(e,a,i);if(u===void 0)continue;let l=o.get(c)??new Set;l.add(u),o.set(c,l)}return o}currencyTheirRecordWentIn(e,t,n){let o=t[n];if(typeof o!="string"||e.remapper.get(o)===void 0)return;let s=e.currencyChangesById.get(o)?.to;if(s!==void 0)return s;let i=t[He];return typeof i=="string"&&i!==""?i:void 0}pricedInTheirRecordsCurrency(e,t,n){let o=ms[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[_r];if(typeof i!="string")return s;let a=e.prices.standsFor.get(i)??i,d=e.prices.keys.get(a),c=d?this.currencyTheirRecordWentIn(e,s,o):void 0;if(d===void 0||c===void 0)return s;let u=e.prices.written.get(Pa(d,c));return u===void 0||u===a||u===i||e.remapper.get(u)===void 0?s:{...s,[_r]:u}})}async objectInfoOf(e,t){if(!this.deps.describeObject)return null;try{return await this.deps.describeObject(e,t)}catch{return null}}async toWriteAtTheGate(e,t,n,o=0){let s=n.records.filter(u=>!dn(e.config,u)),i=n.records.length-s.length,a=s.length>0?await this.heldBackAtTheGate(e,t,n,s):[],d=a.length>0,c={...i>0?{writtenBefore:i}:{},...d?xh(a,s.length):{}};return{objectApiName:t,rows:d?[]:s,...Object.keys(c).length>0?{leftOut:c}:{},...o>0&&!d?{mayAdd:o}:{}}}async withoutWhatThePlatformWrites(e,t){let n=u=>t.find(l=>l.objectApiName===u)?.rows??[],o=new Map,s=new Set(n("Opportunity").map(u=>String(u.Id)));for(let u of t)if(!(!So(u.objectApiName)||u.rows.length===0)){if(s.size===0)break;o.set(u.objectApiName,await this.teamThePlatformWrites(e,u.objectApiName,u.rows,s))}let i=await this.personContactsThePlatformWrites(e,n(Se),n(ce));i.size>0&&o.set(ce,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(We),n(ce),n(ze)),d=await this.rolesOfOpportunitiesWrittenBefore(e,n(ze).filter(u=>!a.has(u))),c=new Set([...a,...d.linked]);return c.size>0&&o.set(ze,c),t.map(u=>{let l=o.get(u.objectApiName),f=u.objectApiName===ze&&d.mayBe>0?{mayBeByThePlatform:{rows:d.mayBe,before:!0}}:{};return!l||l.size===0?{...u,...f}:{...u,rows:u.rows.filter(p=>!l.has(p)),leftOut:{...u.leftOut,byThePlatform:l.size},...f}})}async withoutWhatTheTargetHoldsByValue(e,t){let{config:n}=e,o=[];for(let s of t){let{objectApiName:i,rows:a}=s,d=e.preread.get(i);if(a.length===0||s.counted||!d){o.push(s);continue}let c=await(d.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,i).then(w=>({ok:!0,sets:w}),w=>({ok:!1,error:w})));if(!c.ok){o.push(s);continue}let u=dr(d.createableSet,c.sets.creatable),l=new Set(n.fieldExclusions[i]??[]),f=n.fieldMappings[i]??{},p=new Set(Object.values(f)),g=new Set(await e.maskedSourceFields(i).catch(()=>[])),h=n.anonymization,m=new Set(e.anonymize&&h?h.fields[i]??this.detectedPersonalFields(e,h,i,d.fieldInfos):[]),R=new Set(e.contactPoints?Ea(d.fieldInfos).map(({name:w})=>w):[]),b=n.decisions.truncatedFieldsOf(i),k=c.sets.fields.filter(({name:w,unique:A,externalId:S})=>A===!0&&u.has(w)&&!(n.upsertMode==="auto"&&S===!0)&&!l.has(w)&&f[w]===void 0&&!p.has(w)&&!g.has(w)&&!m.has(w)&&!R.has(w)&&!b.has(w)&&!(i===Se&&w.endsWith("__pc"))),O=new Map;for(let w of k){let{name:A}=w,S=new Map;for(let F of a){let B=F[A];if(typeof B!="string"||B===""||Zh.test(B))continue;let E=Mn(w,B);S.has(E)||S.set(E,B)}let v=[...S.values()];if(v.length===0)continue;let j=new Set;try{let F=Be(i),B=Be(A);for(let E of kn(v,Yh)){let _=await this.deps.queryRecords(e.targetOrgId,`SELECT ${B} FROM ${F} WHERE ${B} IN (${E})`);for(let ee of _){let X=ee[A];typeof X=="string"&&j.add(Mn(w,X))}}}catch{continue}for(let F of a){let B=F[A];typeof B=="string"&&j.has(Mn(w,B))&&!O.has(F)&&O.set(F,A)}}if(O.size===0){o.push(s);continue}o.push({...s,rows:a.filter(w=>!O.has(w)),leftOut:{...s.leftOut,linkedByValue:{rows:O.size,fields:[...new Set(O.values())]}}})}return o}async rolesOfOpportunitiesWrittenBefore(e,t){let{config:n}=e,o={linked:new Set,mayBe:0};if(n.writtenBefore.size===0)return o;let s=u=>u.slice(0,15),i=new Map;for(let u of t){let l=u.OpportunityId,f=u[Le];typeof l!="string"||typeof f!="string"||f===""||vi(u)&&n.writtenBefore.has(l)&&i.set(s(l),f)}if(i.size===0)return o;let a=Ir(t,u=>i.get(s(u))),d=u=>typeof u=="string"&&u!==""?n.writtenBefore.get(u)??e.remapper.get(u):void 0,c=new Map;for(let u of a){let l=d(t[u].OpportunityId),f=d(t[u][Le]);l!==void 0&&f!==void 0&&c.set(u,{opportunity:l,contact:f})}if(c.size===0)return{...o,mayBe:a.length};try{let u=await Ei(f=>this.deps.queryRecords(e.targetOrgId,f),[...new Set([...c.values()].map(({opportunity:f})=>f))]),{found:l}=Ii(c,u);return{linked:new Set([...l.keys()].map(f=>t[f])),mayBe:a.length-c.size}}catch{return{...o,mayBe:a.length}}}async rolesThePlatformWritesOfTheTables(e,t,n,o){let{config:s}=e,i=new Set(n.map(u=>u.objectApiName));if(!i.has(We)||(s.fieldExclusions[We]??[]).includes(Le)||s.fieldMappings[We]?.[Le]!==void 0)return 0;if([We,ze,ce].some(u=>o.has(u)))return;let d=u=>t.findIndex(l=>l.objectApiName===u),c=i.has(ce)&&d(ce)<d(We);try{if(!(await this.deps.describeFields(e.sourceOrgId,We)).some(w=>w.name===Le&&w.createable)||!(await an(this.deps.describeFields,e.targetOrgId,We)).creatable.has(Le))return 0;let f=w=>s.objectSoqlFilters?.[w],p=s.stream?.resumeAfter.get(ze),g=f(We),h=f(ce),m=[...f(ze)?[`(${f(ze)})`]:[],`Opportunity.${Le} != null`,...p&&Ft.test(p.lastId)?[`Id > '${p.lastId}'`]:[],...g?[`OpportunityId IN (SELECT Id FROM ${We} WHERE (${g}))`]:[],...c&&h?[`${Le} IN (SELECT Id FROM ${ce} WHERE (${h}))`]:[]],R=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${Le}, IsPrimary, Opportunity.${Le} FROM ${ze} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${mh+1}`);if(R.length>mh)return;let b=w=>c||s.writtenBefore.has(w)||e.remapper.get(w)!==void 0,k=w=>{let A=w.Opportunity,S=A!==null&&typeof A=="object"?A[Le]:void 0;return typeof S=="string"&&S!==""?S:void 0},O=new Map;for(let w of R){let A=w.OpportunityId,S=k(w);typeof A!="string"||S===void 0||s.writtenBefore.has(A)||!b(S)||O.set(A.slice(0,15),S)}return Ir(R,w=>O.get(w.slice(0,15))).length}catch{return}}rolesThePlatformMayWriteOfTheCounts(e,t,n){let{config:o}=e;return(o.fieldExclusions[We]??[]).includes(Le)||o.fieldMappings[We]?.[Le]!==void 0?0:Math.min(t,n)}async rolesThePlatformWritesOfTheRead(e,t,n,o){if(o.length===0||t.length===0)return new Set;let{config:s,remapper:i}=e;if((s.fieldExclusions[We]??[]).includes(Le)||s.fieldMappings[We]?.[Le]!==void 0)return new Set;let a=e.preread.get(We);if(!a?.createableSet.has(Le))return new Set;let d=await(a.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,We).then(f=>({ok:!0,sets:f}),f=>({ok:!1,error:f})));if(!d.ok||!d.sets.creatable.has(Le))return new Set;let c=f=>f.slice(0,15),u=new Set(n.map(f=>c(String(f.Id)))),l=new Map;for(let f of t){let p=f.Id,g=f[Le];typeof p!="string"||typeof g!="string"||g===""||dn(s,f)||!u.has(c(g))&&i.get(g)===void 0||l.set(c(p),g)}return l.size===0?new Set:new Set(Ir(o,f=>l.get(c(f))).map(f=>o[f]))}async teamThePlatformWrites(e,t,n,o){let{config:s}=e,i=s.decisions.defaultOf(t,$i[t]),a=await this.writesAs(e);try{let d=await Pi(t,n,{source:c=>this.deps.queryRecords(e.sourceOrgId,c),target:c=>this.deps.queryRecords(e.targetOrgId,c),targetIdOf:c=>o.has(c)?c:void 0,mappedUser:c=>s.ownerMappings[c],...i!==void 0?{defaultUser:i}:{},written:[],simulated:{ownerOf:c=>s.ownerMappings[c]??a??`${rg}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>rn(d)&&!e.contactsOnTheirOwn.has(String(d.Id)));if(o.length===0)return new Set;if(await this.personAccountsInTarget(e)===!1)return new Set;let i=(e.preread.get(Se)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[Er])));return new Set(o.filter(d=>!a.has(String(d.Id))))}async heldBackAtTheGate(e,t,n,o){let s=e.graph.nodes.find(u=>u.objectApiName===t);if(!s)return[];let i=await this.objectInfoOf(e.targetOrgId,t);if(!i||i.recordTypes.length===0)return[];if(!(e.recordTypeMapper!==null&&e.config.recordTypeMappings!==void 0)&&!i.recordTypes.some(u=>!u.available&&!u.master))return[];let d=await(n.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,t).then(u=>({ok:!0,sets:u}),u=>({ok:!1,error:u}))),c=d.ok?dr(n.createableSet,d.sets.creatable):n.createableSet;return this.recordTypesHeldBack(s,o,i,c,e)}async recordTypesHeldBack(e,t,n,o,s){let{config:i}=s;if(!n||n.recordTypes.length===0)return[];if(!o.has("RecordTypeId"))return[];if((i.fieldExclusions[e.objectApiName]??[]).includes("RecordTypeId"))return[];if(i.fieldMappings[e.objectApiName]?.RecordTypeId)return[];let a=t.map(c=>({RecordTypeId:i.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));s.recordTypeMapper&&i.recordTypeMappings&&(a=s.recordTypeMapper.apply(a,i.recordTypeMappings));let d=new Map;for(let c of a){let u=c.RecordTypeId;typeof u=="string"&&d.set(u,(d.get(u)??0)+1)}return[...ju(e.objectApiName,a,n.recordTypes),...await this.typesTheTargetLacks(s,e.objectApiName,d,n)]}oweToTheSecondPass(e,t){let n=this.withoutSyncedQuotes(e,t);if(e.secondPassInStore&&e.store){for(let o of n)e.store.owe(o);return}if(e.store)for(let o of n)e.store.owe(o);e.pendingFkUpdates.push(...n)}withoutSyncedQuotes(e,t){if(e.config.stream?.everything!==!0)return t;let n=t.filter(o=>o.objectApiName!==We||o.fieldName!==ys);return e.syncedQuotesLeft+=t.length-n.length,n.length===t.length?t:n}saySyncedQuotesLeft(e){let t=e.syncedQuotesLeft;t!==0&&(e.syncedQuotesLeft=0,e.errors.push({objectApiName:We,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(${We}.${ys})`,messages:[`Left empty on ${t} opportunit${t===1?"y":"ies"}: filled in, the target syncs the quote at once and writes its lines over the opportunity's products the run copied. Start the sync in the target to fill it in.`]}]}))}patchedInTheJournal(e){let{store:t}=e;if(!(!t||e.secondPassInStore))return eg(t)}oweStatus(e,t,n,o){e.store?e.store.oweStatus(t,n,o):e.deferredStatuses.push({objectApiName:t,id:n,status:o})}countWrites(e,t,n){e.simulated?e.wouldInsertCount+=n.successCount:e.successCount+=n.successCount,e.updatedCount+=n.updatedCount,n.mayHaveBeenWritten&&n.mayHaveBeenWritten.length>0&&e.mayHaveBeenWritten.set(t,[...e.mayHaveBeenWritten.get(t)??[],...n.mayHaveBeenWritten]),e.linkedCount+=n.linkedExistingCount,e.linkedToCreatedCount+=n.linkedToCreatedCount??0,e.failedCount+=n.failureCount,this.oweToTheSecondPass(e,n.pendingFkUpdates),n.writtenWithoutFields&&this.countWrittenWithoutFields(e,t,n.writtenWithoutFields);for(let{field:o,recordId:s}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,o,s);for(let o of n.withTheirRecord??[])ur(e,o);(n.linkedExistingCount>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:n.linkedExistingCount,...n.linkedToCreatedCount?{linkedToCreated:n.linkedToCreatedCount}:{},unidentified:n.unidentifiedExistingCount}),n.failureCount>0&&e.errors.push({objectApiName:t,stage:"insert",failedCount:n.failureCount,attemptedCount:n.successCount+n.updatedCount+n.linkedExistingCount+n.failureCount,samples:n.errorSamples})}countWrittenWithoutFields(e,t,n){e.writtenWithoutFields.set(t,ia(e.writtenWithoutFields.get(t),n))}noteLeftEmptyByFilter(e,t,n,o){let s=e.leftEmptyByFilter.get(t);s||(s=new Map,e.leftEmptyByFilter.set(t,s));let i=s.get(n)??{records:0,ids:[]};i.records++,i.ids.length<Km&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[fl(n)]})}oweLookupsOfRowsWrittenBefore(e,t,n,o,s){let{config:i}=e,a=new Set(e.graph.nodes.filter(l=>l.included).map(l=>l.objectApiName)),d=new Set(i.fieldExclusions[t.objectApiName]??[]),c=i.fieldMappings[t.objectApiName]??{},u=o.filter(l=>l.isReference&&l.name!=="RecordTypeId"&&!d.has(l.name)&&dd(l,s,c[l.name])&&(l.referenceTo??[]).some(f=>a.has(f)));if(u.length!==0)for(let l of n){let f=l.Id;if(typeof f!="string")continue;let p=i.writtenBefore.get(f);if(p)for(let g of u){let h=l[g.name];if(typeof h!="string"||!h||i.writtenBefore.has(h)&&!e.store?.owesUntold(f))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:p,sourceId:f,fieldName:c[g.name]??g.name,sourceRefId:h}]);m&&(e.secondPassInStore&&e.store?e.store.owe(m,!0):e.owedToRowsWrittenBefore.push(m))}}}owedNowWritten(e){if(e.owedToRowsWrittenBefore.length===0)return[];let t=[],n=[];for(let o of e.owedToRowsWrittenBefore)e.remapper.get(o.sourceRefId)?t.push(o):n.push(o);return e.owedToRowsWrittenBefore=n,t}sayLookupsOutsideTheClone(e,t){let n=new Map,o=this.keepLookupsInTheClone(e,t,n);return this.sayLeftEmpty(e,n),o}keepLookupsInTheClone(e,t,n){let o=[];for(let s of t){if(e.remapper.get(s.sourceRefId)||e.idsRead.has(s.sourceRefId)){o.push(s);continue}let i=this.objectPointedAt(e,s);if(i!==void 0&&(e.failedObjects.has(i)||e.notCreatable.has(i)||e.notInTarget.has(i))){o.push(s);continue}let a=n.get(s.objectApiName)??new Map,d=`${s.fieldName}|${i??""}`,c=a.get(d)??{field:s.fieldName,parent:i,count:0};c.count++,a.set(d,c),n.set(s.objectApiName,a)}return o}sayLeftEmpty(e,t){for(let[n,o]of t)e.errors.push({objectApiName:n,stage:"scope",failedCount:0,attemptedCount:0,samples:[...o.values()].sort((s,i)=>i.count-s.count).slice(0,3).map(({field:s,parent:i,count:a})=>({recordSummary:`${i===void 0?s:`${s} \u2192 ${i}`} (${a} record${a===1?"":"s"})`,messages:[`Written with the lookup empty: the ${i===void 0?"":`${i} `}record it points at is not in the clone.`]}))})}async secondPassFromTheJournal(e){let{store:t}=e;if(!t)return null;let n=new Qf({remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:e.targetOrgId,enabled:!e.config.dryRun,onProgress:e.onProgress,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:eg(t),onAnswered:()=>t.flush(),onRefusedByFilter:(l,f,p)=>this.noteLeftEmptyByFilter(e,l,f,p),...this.secondPassOfTheSample(e)}),o=new Map,s=e.config.stream?.secondPassPageSize??Vm,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=l=>t.wasPatched(l.newId,l.fieldName),d=new Jf;for(let l of i)d.note(0,l.newId);let c=1;for(let l of t.owedPages(s)){for(let{update:f}of l)a(f)||d.note(c,f.newId);c++}let u=l=>d.spans(l.newId);await n.patch(this.keepLookupsInTheClone(e,i,o),u);for(let l of t.owedPages(s)){let f=l.filter(({update:p,toRowWrittenBefore:g})=>!a(p)&&(!g||e.remapper.get(p.sourceRefId)!==void 0)).map(({update:p})=>p);await n.patch(this.keepLookupsInTheClone(e,f,o),u)}return await n.sendHeld(),this.sayLeftEmpty(e,o),n.finish()}objectPointedAt(e,t){let n=e.config.fieldMappings[t.objectApiName]??{},s=e.preread.get(t.objectApiName)?.fieldInfos.find(a=>a.isReference&&(n[a.name]??a.name)===t.fieldName)?.referenceTo??[];if(s.length===1)return s[0];let i=t.sourceRefId.slice(0,3);return s.find(a=>e.sourceKeyPrefixes.get(a)===i)}applyRecordTypeDecisions(e,t,n,o){let{config:s}=e,i=new Map,a=e.recordTypeMapper&&s.recordTypeMappings?new Set(s.recordTypeMappings.map(d=>d.sourceId)):void 0;return o.forEach((d,c)=>{let u=n[c]?.cleaned.RecordTypeId;if(typeof u!="string"||u===""||!("RecordTypeId"in d))return;let l=s.recordTypeDecisions.get(u);if(l){l.to===null&&delete d.RecordTypeId,e.decisionsApplied.add({kind:"map_record_type",objectApiName:t,from:l.from,...l.to!==null?{to:l.to}:{}});return}!e.simulated||!a||Dw.test(u)||a.has(u)||i.set(u,(i.get(u)??0)+1)}),i}simulateWrite(e,t,n,o,s,i,a,d,c=new Map){let{simulated:u}=e;if(!u)return;let l=t.objectApiName,f=new Set,p=0;i({objectName:l,status:"running",progress:0,recordCount:n.records.length,message:`Simulating the write of ${n.records.length} ${l} records: nothing is sent...`});for(let[g,h]of n.cleaned.entries()){let m=n.records[g]??{},R=d?Pu(l,m,h.source,d):[];if(R.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:Gl(m),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${R.map(w=>w.name).join(", ")}]`]});continue}let b=u.idFor(o),k=typeof h.source.Id=="string"?h.source.Id:void 0,O=c.get(m);if(O!==void 0){s.linkedExistingCount++,p++,f.add(O),k!==void 0&&e.remapper.addExisting(k,b,l);continue}s.successCount++,a&&!Dl(n.records[g]??{})&&a(h),k!==void 0&&e.remapper.add(k,b,l);for(let w of h.nullifiedFks)s.pendingFkUpdates.push({objectApiName:l,newId:b,sourceId:k,fieldName:w.field,sourceRefId:w.sourceRefId,...w.insertOnly?{insertOnly:!0}:{}})}p>0&&i({objectName:l,status:"running",progress:0,message:`[dry-run] ${l}: ${p} fewer would be inserted, linked to the record${p===1?"":"s"} the target holds under the same ${[...f].join(", ")}, which its refusal of the row names`})}holdBackSkippedRows(e,t,n,o,s){let{config:i}=e;if(!i.decisions.skipsRowsOf(t.objectApiName))return n;let a=new Set(i.fieldExclusions[t.objectApiName]??[]),d=new Map(Object.entries(i.fieldMappings[t.objectApiName]??{}).map(([l,f])=>[f,l])),c=n.filter(l=>{let f=l.RecordTypeId;return!i.decisions.holdsBack(t.objectApiName,p=>{let g=d.get(p)??p;return a.has(g)?void 0:l[g]},Qh(i,typeof f=="string"?f:void 0),e.decisionsApplied,s)}),u=n.length-c.length;return u>0&&o({objectName:t.objectApiName,status:"running",progress:0,message:`${t.objectApiName}: ${u} record${u===1?"":"s"} held back, as decided on the gaps`}),c}async findGaps(e,t,n){let{gaps:o}=e;if(!o)return new Map;let s=t.objectApiName,i=new Map([...n.recordTypes?.values()??[]].map(d=>[d.recordType,d]));for(let{picklistChanges:d=[]}of n.cleanedRecords){let c=xu(s,d,u=>{if(u.recordType!==void 0)return i.get(u.recordType)?.picklists.get(u.field)?.values;let l=n.picklistValuesByField?.get(u.field);return l?[...l]:void 0});for(let u of c)o.add(u)}if(n.unmapped.size>0){let d=await this.sourceRecordTypesOf(e,s);o.knowRecordTypes(s,"source",d);for(let[c,u]of n.unmapped){let l=d.find(f=>f.recordTypeId.slice(0,15)===c.slice(0,15))?.developerName??c;o.add(Di("record_type_unmapped",s,l,u,lg(n.targetObject)))}}let a=n.targetFields;return a?(Fu({objectApiName:s,rows:n.recordsToInsert.map((d,c)=>{let u=n.cleanedRecords[c]?.cleaned.RecordTypeId;return{payload:d,source:n.cleanedRecords[c]?.source??{},typed:typeof u=="string"&&n.recordTypes?.has(u)===!0}}),targetFields:a,picklistValuesByField:n.picklistValuesByField,picklistFields:n.picklistFields??new Map},o),await this.currencyGaps(e,s,a,n.cleanedRecords),this.uniqueValueGaps(e,s,a,n.recordsToInsert)):new Map}sourceRecordTypesOf(e,t){let n=e.sourceRecordTypes.get(t);if(!n){let o=this.deps.describeObject;n=o?o(e.sourceOrgId,t).then(s=>this.namedRecordTypes(e.recordTypeRows,e.sourceOrgId,s.recordTypes),()=>[]):Promise.resolve([]),e.sourceRecordTypes.set(t,n)}return n}currenciesFor(e,t,n,o){return t?.some(i=>i.name===He&&i.createable)===!0&&o(He)&&n.some(i=>typeof i[He]=="string"&&i[He]!=="")?this.runCurrencies(e):Promise.resolve(void 0)}async parentCurrenciesFor(e,t,n,o){if(e.currencyChangesById.size===0)return;let s=n?.find(a=>a.name===He);if(!s||s.createable&&!Po(t)||!o.some(a=>typeof a[He]=="string"&&a[He]!==""))return;let i=await e.currencies;return{changeOf:a=>e.currencyChangesById.get(a),...i?{currencies:i}:{}}}runCurrencies(e){let t=this.deps.queryTooling;return e.currencies??=yu(n=>this.deps.queryRecords(e.sourceOrgId,n),n=>this.deps.queryRecords(e.targetOrgId,n),t?{source:n=>t(e.sourceOrgId,n),target:n=>t(e.targetOrgId,n)}:{}),e.currencies}async currencyGaps(e,t,n,o){if(!n.some(d=>d.name===He&&d.createable))return;let s=new Map,i=new Map;for(let{source:d,currencyChange:c}of o){let u=d[He];if(typeof u!="string"||u===""||(s.set(u,(s.get(u)??0)+1),!c||c.chosenBy==="decision"))continue;let l=i.get(u)??{to:new Set,fields:new Set,kept:!1};l.to.add(c.to);for(let f of c.fields)l.fields.add(f);c.notConverted&&(l.kept=!0),i.set(u,l)}if(s.size===0)return;let a=(await e.currencies)?.target.active;if(!(!a||a.size===0))for(let[d,c]of s){if(a.has(d))continue;let u=i.get(d);e.gaps?.add(Nu(t,d,c,u&&{to:[...u.to].sort(),converted:[...u.fields].sort(),asRead:u.kept}))}}async uniqueValueGaps(e,t,n,o){let s=new Map,i=n.filter(a=>a.unique===!0&&a.createable&&!(e.config.upsertMode==="auto"&&a.externalId===!0));for(let a of i){let d=new Map;for(let f of o){let p=f[a.name];if(typeof p!="string"||p===""||Zh.test(p))continue;let g=Mn(a,p),h=d.get(g);h?h.rows++:d.set(g,{value:p,rows:1})}if(d.size===0)continue;let c=new Set;try{let f=Be(t),p=Be(a.name),g=[...d.values()].map(({value:h})=>h);for(let h of kn(g,Yh)){let m=await this.deps.queryRecords(e.targetOrgId,`SELECT ${p} FROM ${f} WHERE ${p} IN (${h})`);for(let R of m){let b=R[a.name];typeof b=="string"&&c.add(Mn(a,b))}}}catch{continue}let u=0,l=0;for(let[f,{rows:p}]of d)c.has(f)&&(u+=p,l++);u>0&&e.gaps?.add(Cu(t,a.name,u,l));for(let f of o){let p=f[a.name];typeof p=="string"&&c.has(Mn(a,p))&&!s.has(f)&&s.set(f,a.name)}}return s}async writeNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,remapper:d}=t;o&&o.pages++;let c=e.objectApiName===$e?this.endOfTheEmails(t,n!==void 0):t.onProgress,u=s.dryRun?"Simulated":"Completed",l=n===void 0?`${u} ${e.objectApiName}`:t.emailsWrittenFirst?"after their task":`${u} ${e.objectApiName} after their task`,f=n===void 0?`Stopped ${e.objectApiName}`:t.emailsWrittenFirst&&!o?"stopped after their task":`Stopped ${e.objectApiName} after their task`,p=t.preread.get(e.objectApiName);if(!p)return;let{fieldInfos:g,createableSet:h,targetSetsPending:m}=p;if(gt(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,p.records,g,this.currenciesTheirLinesWant(t,p.records));let j=await this.keptPrices(t,p.records);j.length!==p.records.length&&(p.records.length=0,p.records.push(...j))}let R=n??p.records,b=R.filter(j=>dn(s,j)),k=e.objectApiName===ce?R.filter(j=>rn(j)&&!dn(s,j)):[],O=await this.personContactsOnTheirOwn(t,k),w=new Set(k.filter(j=>!O.rows.has(j))),A=b.length>0||w.size>0?R.filter(j=>!dn(s,j)&&!w.has(j)):R,S=A,v=[];try{let j=null,F,B=null,E,_,ee=await(m??an(this.deps.describeFields,a,e.objectApiName).then($=>({ok:!0,sets:$}),$=>({ok:!1,error:$})));if(ee.ok)j=ee.sets.creatable,F=ee.sets.updateable,B=ee.sets.picklistValuesByField,E=ee.sets.picklistFields,_=ee.sets.fields;else{let $=ee.error;t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed \u2014 falling back to source schema)",messages:[$ instanceof Error?$.message:String($)]}]})}let X=j?dr(h,j):h,z=this.linkPersonContacts(t,[...w]);if(o&&(o.withTheirAccount+=z.linked,cd(o,z.notSent),z.linked===0&&(o.personContactsUnlinked+=w.size)),w.size>0&&z.linked===0&&A.length===0&&b.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,w.size,Qt(t,e.objectApiName))}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`});return}if(b.length>0&&(t.linkedCount+=b.length,o&&(o.writtenBefore+=b.length),this.oweLookupsOfRowsWrittenBefore(t,e,b,g,F),await this.oweStatusesFoundAfterStop(t,e.objectApiName,b),A.length===0&&w.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: 0 succeeded, ${Ed(s,b.length)}, 0 failed`});return}let J=await this.targetObjectInfoOf(t,e.objectApiName),Me=Lw(J);t.gaps?.knowRecordTypes(e.objectApiName,"target",J?.recordTypes??[]);let ke=await this.recordTypesHeldBack(e,A,J,X,t),ue=ke.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,A,ke):void 0,H=ue!==void 0&&ue.size>0&&(o!==void 0||ue.size<A.length);if(H){S=A.filter(W=>!ue.has(W)),t.failedCount+=ue.size;for(let W of ue.keys())t.heldInTheOrg.set(String(W.Id),"held");let $=[...ue.values()];if(v.push(...$),o?(o.withoutParent+=$.length,Hr($,o.withoutParentGroups),cd(o,Ih($))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:$.length,attemptedCount:0,samples:$d(Hr($),t.failedObjects)}),o&&S.length===0)return}else if(o?.heldWhole!==void 0&&ke.length===0){t.failedCount+=A.length,o.heldWholeRows+=A.length;return}if(ke.length>0&&!H){for(let W of ke)t.gaps?.add(Ph(W,J));if(t.failedObjects.add(e.objectApiName),t.failedCount+=A.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:A.length,attemptedCount:0,samples:ke.map(W=>({recordSummary:`RecordType=${W.developerName} (${W.recordCount} record${W.recordCount===1?"":"s"})`,messages:[Do(W)]}))}),o){o.heldWhole??=ke.map(Wo).join(" "),o.heldWholeRows+=A.length;return}let $=Qt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,A.length,$)}: `+ke.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."});return}S=this.holdBackSkippedRows(t,e,S,c,Me),S=this.leaveWhatHangsFromThePlatform(t,e,g,S);let Q=0;if(e.objectApiName===$e&&n===void 0){let $=this.holdEmailsForTheirTask(t,S);if(Q=S.length-$.length,S=$,Q>0&&S.length===0){let W={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${$s(Q)}`};c(W),o||(t.emailsAllWaiting={...W,status:"done",progress:100});return}}let pe=0;if(e.objectApiName===ut){let $=await this.linkTasksWrittenWithEmails(t,S);S=$.rows,pe=$.linked,o&&(o.withTheirEmail+=$.linked)}let we=new Set(s.fieldExclusions[e.objectApiName]??[]),Ee=s.fieldMappings[e.objectApiName]??{},ae=await this.teamOfTheOpportunities(t,e.objectApiName,S,J?.keyPrefix,g.flatMap($=>!$.isReference&&X.has($.name)&&!we.has($.name)&&Ee[$.name]===void 0?[$.name]:[]));S=ae.rows,o&&(o.teamOwners+=ae.owners,o.teamOthers+=ae.linked-ae.owners,jw(o.teamValues,ae.values));let D=await this.rowsWithoutTheirParent(e,t,g,S);for(let[$,W]of await this.rowsWhoseParentTheTargetLacks(e,t,g,S,me=>X.has(me)&&!we.has(me)&&Ee[me]===void 0))D.has($)||D.set($,W);let L=await this.rowsHeldInTheWholeOrg(e,t,g,S,$=>X.has($)&&!we.has($)&&Ee[$]===void 0);for(let[$,W]of L.held)D.has($)||D.set($,W);if(L.aside.size>0){for(let fe of D.keys())L.aside.delete(fe);gw(t,e.objectApiName,L.aside.values()),S.forEach((fe,Ce)=>{let ot=L.aside.get(Ce);ot&&t.heldInTheOrg.set(String(fe.Id),ot)});let $=S.filter((fe,Ce)=>!L.aside.has(Ce)),W=new Map;S.forEach((fe,Ce)=>{L.aside.has(Ce)||W.set(Ce,W.size)});let me=new Map;for(let[fe,Ce]of D){let ot=W.get(fe);ot!==void 0&&me.set(ot,Ce)}D.clear();for(let[fe,Ce]of me)D.set(fe,Ce);S=$}if(S.forEach(($,W)=>{let me=ae.held.get($);me&&!D.has(W)&&D.set(W,{field:me.field,parentObject:me.parentObject,reason:me.why})}),D.size>0&&(s.stream?.everything===!0&&S.forEach(($,W)=>{D.has(W)&&t.heldInTheOrg.set(String($.Id),"held")}),S=S.filter(($,W)=>!D.has(W)),t.failedCount+=D.size,o?(o.withoutParent+=D.size,Hr(D.values(),o.withoutParentGroups),cd(o,[{count:D.size,why:vd}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:D.size,attemptedCount:0,samples:aw(D,t.failedObjects)}),S.length===0&&ae.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let $=Q===0?Qt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,D.size,$)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`});return}await t.orphanExpander.expandForNode({node:e,fieldInfos:g,records:S,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?($,W,me,fe)=>this.anonymizeRows(t,$,[W],[me],fe,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:($,W)=>this.withoutFileContent(t,$,W,!0),startAsDraft:async($,W)=>(await this.startAsDrafts(t,$,[W])).get(0),oweStatus:($,W,me)=>this.oweStatus(t,$,W,me),objectOf:($,W)=>this.objectOfSourceId(t,$,W),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:($,W)=>this.sayRecordTypeNote(t,$,W),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:($,W)=>this.countWrittenWithoutFields(t,$,W),linkPersonContacts:$=>this.mapContactsOfPersonAccounts(t,$),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:$=>t.maskedSourceFields($),onMaskedLeftOut:($,W)=>this.noteEncryptedLeftOut(t,$,W),businessAccountsAmong:($,W)=>this.takenAsBusinessAccounts(t,$,W),contactOnItsOwn:$=>t.contactsOnTheirOwn.has($),...t.store?{calls:Es(t.store)}:{}}),S=this.leaveWhatHangsFromThePlatform(t,e,g,S);let Re=s.fieldMappings[e.objectApiName]??{},Ne=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),S,$=>X.has($)||Re[$]!==void 0),Ie=E?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:S,fields:E,written:$=>X.has($)&&!Ne.has($)&&Re[$]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:_!==void 0&&!_.some($=>$.name==="RecordTypeId")}):void 0;for(let $ of Ie?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,$);let ge=X.has("RecordTypeId")&&!Ne.has("RecordTypeId")&&Re.RecordTypeId===void 0,K=e.objectApiName===Se?await this.takenAsBusinessAccounts(t,S,ge):void 0,te=Po(e.objectApiName)?void 0:await this.currenciesFor(t,_,S,$=>X.has($)&&!Ne.has($)&&Re[$]===void 0),M=te?void 0:await this.parentCurrenciesFor(t,e.objectApiName,_,S);S=this.pricedInTheirRecordsCurrency(t,e.objectApiName,S);let q=gt(e.objectApiName)?$=>t.prices.convertedInto.get(String($.Id)):void 0,G=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,g,S,$=>X.has($)&&!Ne.has($)&&Re[$]===void 0):void 0,Te=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,S,X.has("OwnerId")&&!Ne.has("OwnerId")&&Re.OwnerId===void 0):void 0,ie=lh({objectApiName:e.objectApiName,records:S,...q?{pricedIn:q}:{},fieldInfos:g,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:$=>vs(t,$),ownerMappings:s.ownerMappings,...ae.lookups.size>0?{resolvedLookups:ae.lookups}:{},...G&&G.size>0?{targetLacks:G}:{},...Te?{inactiveOwners:Te}:{},...t.sample?{outsideTheSample:($,W)=>this.outsideTheSample(t,$.referenceTo??[],W)||t.heldInTheOrg.has(W)}:s.stream?.everything===!0?{heldByTheRun:$=>t.heldInTheOrg.has($)}:{},excludedFields:Ne,fieldRename:Re,creatableFields:X,updatableFields:F,picklistValuesByField:B,picklistFields:E,recordTypeValues:Ie?.byRecordType,businessAccounts:K,contactPoints:t.contactPoints??void 0,decide:($,W)=>s.decisions.applyToRow(e.objectApiName,$,Qh(s,W),t.decisionsApplied,Me),...te||M?{currencyFields:Io(_??[])}:{},...te?{currencies:te}:{},...M?{parentCurrencies:M}:{}}),ne=new Ko,U=new Fo;for(let{picklistChanges:$=[],currencyChange:W,source:me}of ie){ne.add(e.objectApiName,$),t.picklistChanges.add(e.objectApiName,$),o?.picklists.add(e.objectApiName,$),U.add(e.objectApiName,W),t.currencyChanges.add(e.objectApiName,W),o?.currencies.add(e.objectApiName,W);let fe=me.Id;W&&typeof fe=="string"&&t.currencyChangesById.set(fe,W)}let Oe=Vo(ne.list())+No(U.list())+gd(_h(new Map,ie))+Rd(Uh(ie))+md(wd(new Map,ie))+yd(bd(new Map,ie))+(o?"":Td(t,e.objectApiName));o&&(_h(o.lookupsNotCarried,ie),wd(o.lookupsOutsideTheRun,ie),bd(o.lookupsHeldBack,ie),o.ownersInactive+=Uh(ie)),this.noteLookupsOutsideTheRun(t,e.objectApiName,g,ie),await this.noteLookupsHeldBack(t,e.objectApiName,g,ie);for(let $ of ie)for(let W of $.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,W);xw(t,e.objectApiName,ie);let ye=ie.map($=>$.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(ye=t.recordTypeMapper.apply(ye,s.recordTypeMappings,$=>hs(e.objectApiName,$)));let le=this.applyRecordTypeDecisions(t,e.objectApiName,ie,ye);ye=this.anonymizeRows(t,e.objectApiName,ye,ie.map($=>String($.source.Id??"")),g,s.fieldMappings[e.objectApiName]??{});let Nt=new Map((_??[]).flatMap($=>$.length!==void 0&&$.length>0?[[$.name,$.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let $ of ye)s.decisions.truncate(e.objectApiName,$,Nt,t.decisionsApplied);let ft=new Map;t.gaps&&(ft=await this.findGaps(t,e,{cleanedRecords:ie,recordsToInsert:ye,targetFields:_,targetObject:J,picklistValuesByField:B,picklistFields:E,recordTypes:Ie?.byRecordType,unmapped:le}));let Tt=e.objectApiName===rr?await this.takeTheSyncCopies(t,ie,ye,b,{fields:_,updatable:F,keyPrefix:J?.keyPrefix}):{taken:0,given:0};e.objectApiName===We&&Aw(t,ie,ye);let wt=e.objectApiName===ze?await this.linkTheRolesThePlatformWrote(t,ie,ye,{fields:_,updatable:F,keyPrefix:J?.keyPrefix}):{linked:0,given:0},nt=await this.startAsDrafts(t,e.objectApiName,ye),At=new Map;if(t.store)for(let[$,W]of nt){let me=ie[$];me&&At.set(me,W)}let dt=[];if(gt(e.objectApiName)&&t.standardPricebookId){let $=ie.map((fe,Ce)=>Ce),{standard:W,custom:me}=Fc($.map(fe=>({index:fe,[tn]:ie[fe].source[tn]})),t.standardPricebookId);for(let fe of[W,me])fe.length!==0&&dt.push({records:fe.map(Ce=>ye[Ce.index]),cleaned:fe.map(Ce=>ie[Ce.index])})}dt.length===0&&(ye.length>0||Tt.taken===0&&wt.linked===0)&&dt.push({records:ye,cleaned:ie});let Xt=await this.recordTypeCounter(t,e.objectApiName,J,ge),Ae=ql();Ae.successCount+=Tt.taken;let yt;try{for(let $ of dt){if(t.simulated){this.simulateWrite(t,e,$,J?.keyPrefix,Ae,c,Xt,_,ft);continue}await t.batchWriter.writeNode({node:e,records:$.records,cleanedRecords:$.cleaned,fieldInfos:g,creatableFields:X,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:J?.keyPrefix,picklistFields:E,remapper:d,...t.store?{oweLookups:W=>this.oweToTheSecondPass(t,W)}:{},...t.store?{calls:Es(t.store)}:{},...At.size>0?{onWritten:(W,me)=>{let fe=At.get(W);fe!==void 0&&(At.delete(W),this.oweStatus(t,e.objectApiName,me,fe))}}:{},...Xt?{onCreatedWithoutRecordType:Xt}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(W=>W.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},Ae)}}catch($){if(!($ instanceof be))throw $;yt=$}finally{for(let[$,W]of nt){let me=ie[$];if(me&&t.store&&!At.has(me))continue;let fe=me?.source.Id;if(typeof fe!="string")continue;let Ce=d.get(fe);!Ce||d.isExisting(fe)||this.oweStatus(t,e.objectApiName,Ce,W)}this.countWrites(t,e.objectApiName,Ae)}let _e=Ae.successCount,pt=Ae.updatedCount,$t=Ae.linkedExistingCount,x=Ae.failureCount,Y=Ae.unidentifiedExistingCount;if(o){let $=dt.reduce((ot,zn)=>ot+zn.records.length,0),W=dt.flatMap(ot=>ot.cleaned);o.sent+=$,o.succeeded+=_e,o.updated+=pt,o.linked+=$t,o.linkedToCreated+=Ae.linkedToCreatedCount??0,o.failed+=x,o.alreadyExists+=Ae.alreadyExistsCount,o.unidentified+=Y,o.rolesOfTheirOpportunity+=wt.linked,o.rolesGiven+=wt.given,o.writtenWithoutFields=Ae.writtenWithoutFields?ia(o.writtenWithoutFields,Ae.writtenWithoutFields):o.writtenWithoutFields,Ae.flagsNotKept&&(o.flagsNotKept=eu(o.flagsNotKept,Ae.flagsNotKept));let me=yt?$-(_e+pt+$t+x):0,fe=W.slice(0,$-me).filter(ot=>O.rows.has(ot.source)).length;o.sentOnTheirOwn+=fe,fe>0&&(o.onTheirOwnWhy=O.why);let Ce=[...ud(o),...Qt(t,e.objectApiName)];if(yt)throw this.stopStreamedNode(e,t,o,me,f),yt;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${hd(s,o,Ce)}`});return}let re=_e+pt+$t+b.length+z.linked+ae.linked+wt.linked,ve=re+x,oe=ve>0?x/ve:0,se=x>0&&Ae.alreadyExistsCount===x,rt=x>0&&!se&&(re===0||oe>.5),he=ag($t,Ae.linkedToCreatedCount??0),qe=pt>0?`, ${pt} updated through their external id`:"",Ve=Y>0?` (${Y} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",bt=$=>[...Ih(v),...D.size>0?[{count:D.size,why:vd}]:[],...z.notSent,...$?Qt(t,e.objectApiName):[]],Zt=bt(Q===0),In=pe>0?`, ${pe} written by the platform with their email`:"",Ct=ig(z.linked,pd(t,e.objectApiName)),Un=dg(ae.owners,ae.linked-ae.owners)+cg(wt.linked,wt.given),vt=dt.flatMap($=>$.cleaned),Je=$=>vt.slice(0,$).filter(W=>O.rows.has(W.source)).length,en=$=>$>0?`, ${$} ${$===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",Xe=en(Je(vt.length)),Dt=b.length>0?`, ${Ed(s,b.length)}`:"",Mt=Q>0?`, ${$s(Q)}`:"",Rt=[Fi(Ae.flagsNotKept),ug(ae.values)].flatMap($=>$?[`, ${$}`]:[]).join(""),ct=ss(Ae.writtenWithoutFields),De=tg(t,e.objectApiName),Et=Ps(t,e.objectApiName),hn=n===void 0?Oh(t,e.objectApiName):"",eo=s.dryRun?"would be inserted":"succeeded",Gn=Tt.taken>0?` (${zf(Tt.taken,Tt.given,s.dryRun)})`:"",to=$=>`${_e} ${eo}${Gn}${qe}${he}${In}${Ct}${Un}${Dt}, ${x+_n($)} failed${Ve}${cn($)}`,gn=`${Xe}${Mt}${Rt}${Oe}${ct}${De}${Q===0?Et:""}${hn}`;if(yt){let $=dt.reduce((Ce,ot)=>Ce+ot.records.length,0),W=$-(_e+pt+$t+x)+Q;Od(t,e.objectApiName,W);let me=Q>0?` (${$s(Q)})`:"",fe=Je($-W+Q);throw this.saySentOnTheirOwn(t,fe,O.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:rt?"error":"stopped",progress:100,message:`${f}: ${to(bt(!0))}, ${W} not sent${me}${en(fe)}${Rt}${Oe}${ct}${De}${Et}`}),yt}if(this.saySentOnTheirOwn(t,Je(vt.length),O.why),rt){t.failedObjects.add(e.objectApiName),re>0&&t.failedInPart.add(e.objectApiName);let $=_n(Zt);c({objectName:e.objectApiName,status:"error",progress:100,message:re===0?`Failed all ${e.objectApiName} records: ${x+$} failed${cn(Zt)}${Xe}${Oe}${hn}`:`${x+$}/${ve+$} ${e.objectApiName} records failed (>50%)${cn(Zt)}${Xe}${Oe}${ct}${De}${hn}${Fh}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: ${to(Zt)}${gn}`})}catch(j){if(j instanceof be)throw j;t.failedObjects.add(e.objectApiName),t.failedCount+=S.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:S.length,attemptedCount:S.length,samples:[{recordSummary:"(stage failed before insert)",messages:[V(j)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(j)}`})}}};function ny(r,e){if(r.sample===void 0){if(e===void 0)return;throw new Error("A sample was handed to a run whose config copies every record, or walks from a record: run it as its config says, or ask the sample in its config. Nothing was read or written.")}if(r.inputMode!=="org"||e===void 0)throw new Error("The config asks a sample of the whole org, and the run was handed nothing to keep or take up its plan with: it would have copied every record. Nothing was read or written.");return{...e,options:r.sample}}function Pd(r,e,t,n){let o=t?.recordTypeMappings,s=Rs(e.anonymizePII,r,t?.anonymizationRules,n),i=t?.files?{maxFileBytes:t.files.maxFileSizeMB*1048576,acceptedAsIs:t.files.acceptedAsIs}:void 0,a=t?.writtenBefore,d=t?.beforeWrite,c=e.inputMode==="org",u=t?.stream,l=ny(e,u?.sample),f=c?{...u,everything:!0,writeWindow:xd,secondPassPageSize:xd,ceiling:void 0,wholeReadBound:u?.wholeReadBound??u?.ceiling??fo,...l?{sample:l}:{}}:u,p=[...new Set([...r.nodes.filter(Wc).map(O=>O.objectApiName),...e.excludedObjects??[]])],g=p.length>0?p:void 0,h=e.dryRun===!0?!0:void 0,m=Jo(e),R=e.keepContactPoints===!0?!0:void 0,b=ry(r,e,t?.roots);return b||e.inputMode==="record"&&typeof e.recordId=="string"?{...b?{roots:b}:{rootRecordId:e.recordId},rootObjectApiName:b?.objectApiName??r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:g,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:R,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:h,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||g||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||R||i||a||d||f||h||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:g,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:R,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:h,decisions:m}:void 0}function ry(r,e,t){let n=e.maxRoots??kr,o=r.nodes.find(a=>a.level===0)??r.nodes[0],s={...t?.plan?{plan:t.plan}:{},...t?.plan&&t.planOfTheRunRetried?{planOfTheRunRetried:!0}:{},...t?.keepAt!==void 0?{keepAt:t.keepAt}:{},...t?.fingerprint!==void 0?{fingerprint:t.fingerprint}:{},...t?.sourceRequestsLeft!==void 0?{sourceRequestsLeft:t.sourceRequestsLeft}:{},...t?.readTotal!==void 0?{readTotal:t.readTotal}:{}};if(e.inputMode==="record"&&t?.ids!==void 0){let a=o?.objectApiName;return a===void 0?void 0:{objectApiName:a,ids:[...t.ids],cap:n,...s}}if(!jc(e)||e.inputMode!=="soql")return;let i=wl(e.soqlQuery??"");if("issue"in i)throw Pe.of(Yo(i.issue,o?.objectApiName));return{objectApiName:o?.objectApiName??i.objectApiName,query:i.query,cap:n,...s}}var Jr="--checkpoint-first",Fd={switches:[Jr],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},oy=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function pg(r){return[` --checkpoint-first ${r.step??""}take a checkpoint of what ${r.run} writes before its`," first write: each object it writes, and each the"," target's flows that still run create as it writes"," them, held whole, as every checkpoint holds an object."," Its cost is that of the tables, not of the records",` written, and is said first. A rewind to it takes ${r.run}`," back (sandforge checkpoint rewind), and the work of"," anyone else on those objects since with it. Refused",` \u2014 another run writing, a limit, the disk \u2014 ${r.run}`," writes nothing, exit 1; deleted again when it writes",` nothing; with ${r.simulation}, says what it would hold and`," cost, and takes nothing (default: off)",...(r.note??[]).map(t=>` ${t}`)," --checkpoint-keep-days <n>"," the days that checkpoint is kept on this machine,"," 0 to 3650, 0 until it is deleted (default: 7)"," --checkpoint-exclude-object <ApiName>"," leave an object out of that checkpoint, named; a"," rewind leaves its records as they are; repeat for more"].join(`
|
|
8
8
|
`)}function Vr(r){process.stderr.write(`${r}
|
|
9
|
-
`),process.exit(2)}function hg(r,e=[]){let t=a=>{let d=[];for(let c=0;c<r.length;c++)r[c]===a&&c+1<r.length&&d.push(r[c+1]);return d},n=t("--checkpoint-keep-days"),o=t("--checkpoint-exclude-object");if(!r.includes(Jr)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Vr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${Jr}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Vr(`${Jr} does not go with ${a}: ${d}`);n.length>1&&Vr(`--checkpoint-keep-days is given ${n.length} times: give it once.`);let s;if(n.length===1){let a=n[0];s=/^\d{1,4}$/.test(a)?Number(a):Number.NaN;try{fa(s,void 0)}catch{Vr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)oy.test(a)||Vr(`--checkpoint-exclude-object takes an object's API name, not "${a}".`),i.some(d=>d.toLowerCase()===a.toLowerCase())||i.push(a);return{...s!==void 0?{keepDays:s}:{},...i.length>0?{excluded:i}:{}}}function fg(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function sy(r){let e=r.self??Vu,t=r.elsewhere??(s=>Ju(s,e)),n=`A SandForge run is writing to ${r.orgName}: start this run once it has ended. No record was read.`,o=s=>s.writer!==void 0&&s.writer.pid===e.pid&&Date.parse(s.writer.hostStartedAt)===Date.parse(e.startedAt);return async s=>{let i=r.envLock?.(s);if(i!==void 0)return`${i}: start this run once it has ended. No record was read.`;for(let a of r.runs)for(let d of await a.list()){if(d.end!==void 0||!(fg(d.targetOrganizationId,s)||fg(d.targetOrgId,s)||d.targetOrgId===r.alias))continue;let u=r.own?.runId!==void 0&&d.runId===r.own.runId;if(o(d)?!u:t(d))return n}}}function gg(r,e){return{id:e.id,orgType:Mc({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function iy(r){let e=r.reason==="notAFolder"?"it is a file, not a folder":r.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${r.detail!==void 0?` (${r.detail})`:""}`;return`the checkpoints cannot be kept in ${r.path}: ${e}`}function ay(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${af(t)}`))}}function mg(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-
|
|
9
|
+
`),process.exit(2)}function hg(r,e=[]){let t=a=>{let d=[];for(let c=0;c<r.length;c++)r[c]===a&&c+1<r.length&&d.push(r[c+1]);return d},n=t("--checkpoint-keep-days"),o=t("--checkpoint-exclude-object");if(!r.includes(Jr)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Vr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${Jr}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Vr(`${Jr} does not go with ${a}: ${d}`);n.length>1&&Vr(`--checkpoint-keep-days is given ${n.length} times: give it once.`);let s;if(n.length===1){let a=n[0];s=/^\d{1,4}$/.test(a)?Number(a):Number.NaN;try{fa(s,void 0)}catch{Vr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)oy.test(a)||Vr(`--checkpoint-exclude-object takes an object's API name, not "${a}".`),i.some(d=>d.toLowerCase()===a.toLowerCase())||i.push(a);return{...s!==void 0?{keepDays:s}:{},...i.length>0?{excluded:i}:{}}}function fg(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function sy(r){let e=r.self??Vu,t=r.elsewhere??(s=>Ju(s,e)),n=`A SandForge run is writing to ${r.orgName}: start this run once it has ended. No record was read.`,o=s=>s.writer!==void 0&&s.writer.pid===e.pid&&Date.parse(s.writer.hostStartedAt)===Date.parse(e.startedAt);return async s=>{let i=r.envLock?.(s);if(i!==void 0)return`${i}: start this run once it has ended. No record was read.`;for(let a of r.runs)for(let d of await a.list()){if(d.end!==void 0||!(fg(d.targetOrganizationId,s)||fg(d.targetOrgId,s)||d.targetOrgId===r.alias))continue;let u=r.own?.runId!==void 0&&d.runId===r.own.runId;if(o(d)?!u:t(d))return n}}}function gg(r,e){return{id:e.id,orgType:Mc({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function iy(r){let e=r.reason==="notAFolder"?"it is a file, not a folder":r.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${r.detail!==void 0?` (${r.detail})`:""}`;return`the checkpoints cannot be kept in ${r.path}: ${e}`}function ay(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${af(t)}`))}}function mg(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-FZF23M6R.mjs"),{openCheckpointStore:i}=await import("./chunk-XK5W7BVE.mjs"),{nodeSyncRunCreations:a}=await import("./chunk-LXDSRP2W.mjs"),{nodeSeedRunCreations:d}=await import("./chunk-CZLJZQCS.mjs"),{envLockHolder:c,envLockLine:u}=await import("./chunk-VQJMP3DC.mjs"),l=i({root:r.storeRoot??o(r.journalDir,"checkpoints"),...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in l)throw new Error(iy(l.refusal));let{store:f}=l,{session:p}=r,g=r.connect(p),h={id:r.org.id,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,orgType:r.org.orgType,metadata:{apiVersion:g.version,...r.org.edition!==void 0?{edition:r.org.edition}:{}}},m={log:R=>{R.startsWith("[WARN] ")&&r.say(`warning: ${R.slice(7)}`)},orgManager:{getOrg:R=>R===h.id?h:void 0},orgRegistry:{getCredentials:async R=>R===h.id?{accessToken:p.accessToken,instanceUrl:p.instanceUrl}:void 0}};return{deps:{org:s(g),store:f,handler:m,runWriting:sy({orgName:p.alias,alias:p.alias,runs:[a(r.journalDir),d(r.journalDir)],envLock:R=>{let b=c(f.locksDir,R);return b!==void 0?u(b):void 0},...r.own?{own:r.own}:{}}),...r.freeBytes?{freeBytes:r.freeBytes}:{}},org:{orgId:r.org.id,orgName:p.alias,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,registered:{orgType:r.org.orgType,...r.org.edition!==void 0?{metadata:{edition:r.org.edition}}:{}}}}})(),n=o=>({module:r.module,written:o.written,running:o.running,request:r.request,operationId:r.operationId,tool:"cli",keepDays:fa(r.request.keepDays,void 0)});return{async scope(o){let s=await import("./chunk-NLB3RGIY.mjs"),{deps:i,org:a}=await t();return s.scopeBeforeRun(i,a,n(o))},async take(o,s,i={}){let a=await import("./chunk-NLB3RGIY.mjs"),{deps:d,org:c}=await t();return a.takeBeforeRun({...d,...i.signal?{signal:i.signal}:{},onProgress:ay(r.say)},c,n(o),s)},async settle(o,s){let i=await import("./chunk-NLB3RGIY.mjs"),{deps:a}=await t(),d=await i.settleBeforeRun(a.store,o,s);return d.notDeleted!==void 0&&r.say(`warning: ${d.notDeleted}`),d.info}}}function Nd(r){return tl(r).map(e=>` ${e}`)}var dy=new Set(["TOO_MANY_RECORDS","API_BUDGET","DISK"]);function Ms(r){let e=r.message.replace(/\s*No record was read\.$/,""),t=dy.has(r.code)?"leave an object out of it (--checkpoint-exclude-object <ApiName>), ":"";return`The checkpoint before the run was refused: ${e} Fix what refuses it, ${t}or run without ${Jr} to write without one.`}function Cd(r){return r.code!==Tn?lf:r.refusal!==void 0?`${Ms(r.refusal)} Nothing was written.`:r.message}function cy(r){return r===null?"kept until it is deleted":`kept until ${r.slice(0,10)}`}function wg(r,e,t){return[`checkpoint before the run: ${r.checkpointId} '${r.name}', ${r.objects.length} object(s), ${r.records} record(s), ${cy(r.expiresAt)}`,` rewind to it: ${qt("checkpoint")} rewind --org ${e} --checkpoint ${r.checkpointId}${t?" --mute-automation":""}`,...r.notHeld.map(({objectApiName:n,reason:o})=>` not in the checkpoint: ${n} \u2014 ${o}`)]}function Md(r){return r.state==="deleted"?[sf]:[]}async function DS(r,e,t,n,o){try{let s=await r.settle(e,t);for(let i of Md(s))o(i);return s}catch(s){return o(`warning: the checkpoint '${e.name}' taken before the run, which wrote nothing, could not be deleted (${s instanceof Error?s.message:String(s)}): delete it with ${qt("checkpoint")} delete --org ${n} --checkpoint ${e.checkpointId}`),e}}var Bs="--leave-undeletable",Bd="UNDELETABLE_NOT_LEFT";function uy(r,e){let t=r.map(o=>`${o.objectApiName} (${o.records} records)`).join(", "),n=St(Bs)?`run again with ${Bs}`:`run ${at(Bs,"removal")}`;return{code:Bd,message:`The user SandForge connects as may not delete the records of ${t} in ${e}. Nothing was removed. Give that user Delete on those objects, or ${n} to remove the rest and leave them.`}}function yg(r,e,t,n=o=>process.stderr.write(`${o}
|
|
10
10
|
`)){return async o=>{if(!r)return t(uy(o,e)),!1;let s=o.map(i=>`${i.objectApiName} (${i.records} records)`).join(", ");return n(`The user SandForge connects as may not delete the records of ${s} in ${e}.`),n(`Those stay, with the records they hang from; the rest is removed (${Bs}).`),!0}}function bg(r,e){let t;return async n=>{let o=await r.describeObject?.(e,n);return!o||!o.recordTypes.some(s=>!s.master)?o?.recordTypes:(t??=r.queryRecords(e,Co).then(Mo,()=>[]),Bo(o.recordTypes,await t))}}var oc=`sandforge clone \u2014 Forge a clone of one record, or of whole tables, from a source org
|
|
11
11
|
to a target sandbox, or remove what a run of it created.
|
|
12
12
|
|