sandforge 1.80.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-pipeline.mjs +12 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/chunk-2JZGCCPG.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
- package/lib/chunk-3C2ZZIFN.mjs +7 -0
- package/lib/chunk-3CX7GPCR.mjs +7 -0
- package/lib/chunk-3HEMJTAP.mjs +925 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
- package/lib/chunk-3XG25GTF.mjs +7 -0
- package/lib/chunk-42BFLWHR.mjs +7 -0
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/chunk-5K2I2DMP.mjs +11 -0
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/chunk-6KP6WETK.mjs +9 -0
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/chunk-7PY3VQP3.mjs +7 -0
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/chunk-7WSLT5VX.mjs +8 -0
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/chunk-AUS6NFLZ.mjs +8 -0
- package/lib/chunk-BMTNTBBM.mjs +7 -0
- package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/chunk-CCEH7L53.mjs +7 -0
- package/lib/chunk-CELEBWEZ.mjs +7 -0
- package/lib/chunk-CV47FDQW.mjs +7 -0
- package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/chunk-DBBPDSFN.mjs +7 -0
- package/lib/chunk-DIL62SUN.mjs +7 -0
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/chunk-FOIWWK7G.mjs +156 -0
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/chunk-G2JR3F63.mjs +7 -0
- package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/chunk-HIHCYMSL.mjs +7 -0
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/chunk-IRZJU2PG.mjs +22 -0
- package/lib/chunk-ISSP2FZ5.mjs +7 -0
- package/lib/chunk-IVZJSDJD.mjs +7 -0
- package/lib/chunk-J24TIGSI.mjs +10 -0
- package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
- package/lib/chunk-JFNLKHY6.mjs +8 -0
- package/lib/chunk-JH27IKCO.mjs +9 -0
- package/lib/chunk-JJITOWZK.mjs +7 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/chunk-JQZTMFO7.mjs +7 -0
- package/lib/chunk-KIMQQ6JQ.mjs +7 -0
- package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/chunk-KP5G6FUC.mjs +7 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/chunk-LXDSRP2W.mjs +7 -0
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
- package/lib/chunk-MUEQRIK7.mjs +9 -0
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/chunk-O2PUGRNW.mjs +10 -0
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-P55MKIZX.mjs +37 -0
- package/lib/chunk-P63WJMXQ.mjs +7 -0
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PE435FVH.mjs +15 -0
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/chunk-PWVDNN2C.mjs +7 -0
- package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/chunk-SAMWHL22.mjs +13 -0
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/chunk-SZGGFST2.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/chunk-XK5W7BVE.mjs +7 -0
- package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/chunk-XU25YA46.mjs +9 -0
- package/lib/chunk-XZISAZA6.mjs +7 -0
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/chunk-YAIIRFKJ.mjs +8 -0
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/chunk-YMDFF657.mjs +10 -0
- package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/chunk-ZUOPC4W2.mjs +7 -0
- package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +186 -140
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-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 +18 -3
- package/lib/chunk-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MFG4MUIO.mjs +0 -9
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QR3WELJQ.mjs +0 -7
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{c as Jt,d as Ts,e as Ms,f as Vt}from"./chunk-ZXFL2MSN.mjs";import{b as ut,c as pt,d as Qt,e as en,f as Ws,g as tn}from"./chunk-VYOYXTCU.mjs";import{b as Gs,d as Us}from"./chunk-C3LNYAVJ.mjs";import{a as zs,c as qs}from"./chunk-GJ6SZVHT.mjs";import{a as ze,b as Fs,c as js,d as vs,f as Ns,g as xs,h as Ds,i as Ls,j as $s,l as Q,n as Xt,o as Zt,p as Bs,q as _s,s as qe}from"./chunk-52EXDVPN.mjs";import{Dc as Cr}from"./chunk-ISSP2FZ5.mjs";import{a as ve,c as Ht}from"./chunk-BOGNK4LV.mjs";import{$a as Ps,F as ps,G as fs,Ga as ys,Ha as ws,L as gs,M as hs,O as ms,Oa as Ss,Pa as Rs,Qa as bs,Ra as ks,Sa as Os,Ua as As,Va as Cs,Xa as Is,ab as Es,g as ds,i as Yt}from"./chunk-P55MKIZX.mjs";import{k as us}from"./chunk-PYRZFUVU.mjs";import{i as Ir,o as vr}from"./chunk-O2PUGRNW.mjs";import{G as Or,N as Ar,m as qt,r as kr}from"./chunk-7SDZR6SR.mjs";import{l as cs,m as ls}from"./chunk-TEIBWMJM.mjs";import{l as br}from"./chunk-54HYHHVL.mjs";import{f as Nr,h as xr,i as Ue,k as Dr,l as Lr,m as $r,o as Br,p as _r,q as Wr,r as Gr,s as Ur}from"./chunk-WSUKC2U3.mjs";import{a as Kt}from"./chunk-QSRAEUGZ.mjs";import{h as Fr,j as jr}from"./chunk-SAMWHL22.mjs";import{b as Tr,f as Mr}from"./chunk-HKUWHVI7.mjs";import{b as Ut,c as Ge,d as ee}from"./chunk-VPDEJGPS.mjs";import{f as Pr,g as Er}from"./chunk-JQZTMFO7.mjs";import{$a as Yr,Ac as as,Ra as qr,Sa as Kr,Wb as Qr,Zb as es,_a as Hr,_b as ts,ac as ns,bb as we,db as at,eb as Jr,ec as rs,fb as dt,fc as ss,gb as Vr,hb as Xr,ib as ct,jb as lt,kc as is,lb as Zr,lc as os,mc as xe,zb as Ne}from"./chunk-JFNLKHY6.mjs";import{q as zr}from"./chunk-VZVICK7Q.mjs";import{a as mr,d as yr,e as wr,f as Sr,g as Rr}from"./chunk-HFUDCNU5.mjs";import{A as Ie,B as dr,C as _t,D as ot,E as Wt,G as Gt,H as cr,I as lr,J as je,n as Xn,o as Fe,q as Zn,r as Qn,s as er,t as tr,u as nr,v as rr,w as sr,y as ar,z as We}from"./chunk-XZISAZA6.mjs";import{a as Yn}from"./chunk-EADHKH3A.mjs";import{F as X,G as oe,I as Bt,N as Kn,P as Hn,f as it,g as zn,m as qn,r as $t}from"./chunk-KIMQQ6JQ.mjs";import{f as Un,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{c as ur,d as pr,f as fr,h as gr,j as hr,k as zt}from"./chunk-ZUTUYBNW.mjs";import{a as Jn,w as Vn}from"./chunk-ICIYL45C.mjs";import{c as ir,d as or}from"./chunk-PR74GYVI.mjs";import{$c as $n,Ed as Gn,Hc as rt,Ib as vn,Jb as et,Mc as xn,Td as Lt,Uc as st,Vb as Nn,Zc as Dn,_c as Ln,ad as Bn,bd as _n,cd as Wn,g as Fn,i as Dt,ic as tt,j as jn,k as fe,rc as Me,sc as ge,wc as nt}from"./chunk-ZQO5PDX5.mjs";import{b as _e,k as vt,l as Nt,u as Tn,v as Mn,z as xt}from"./chunk-WZQEK4WT.mjs";var ft=class{classify(e){let t=et(e.statusCode),s=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:s}}classifyBatch(e){let t=e.map(a=>this.classify(a)),s={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},r={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";s[d]=(s[d]??0)+1,r[a.originalError.statusCode]=(r[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:s,byErrorCode:r,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return et(e).retryable}hasBlockingError(e){return e.some(t=>et(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys(vn).length}getSuggestedAction(e,t){return t.suggestUpsert?"Consider using upsert with external ID":t.suggestTruncate?"Truncate field values to fit within limits":t.blockAll?"Operation blocked: resolve storage/limit issue first":t.strategy==="reauth_then_retry"?"Re-authenticate and retry":t.strategy==="reduce_batch"?"Reduce batch size and retry":t.retryable?`Retry after ${t.delay??0}ms`:`Fix ${e} error and retry manually`}};function Vi(n,e){return new Promise(t=>{if(e?.aborted){t();return}let s=()=>{clearTimeout(r),e?.removeEventListener("abort",s),t()},r=setTimeout(s,n);e?.addEventListener("abort",s,{once:!0})})}var gt=class{constructor(e={}){this.options=e;this.strategy=new Lr({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new ft}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),s,r=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:r}}catch(o){s=o instanceof Error?o:new Error(String(o));let a=Xi(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:s,attempts:i+1,totalDelay:r};if(i<t.maxRetries){let c={success:!1,error:s,attempts:i+1,totalDelay:r,cancelled:!0};if(this.options.signal?.aborted)return c;let l=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,l),r+=l,await Vi(l,this.options.signal),this.options.signal?.aborted)return{...c,totalDelay:r}}}return{success:!1,error:s,attempts:t.maxRetries+1,totalDelay:r}}async executeBatch(e,t){let s=[...e],r=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;s.length>0&&o<=a;){let d=await t(s);r.push(...d.successes);let c=[];for(let l of d.failures)this.classifier.classify(l.error).classification.retryable&&o<a?c.push(l.record):i.push(l);if(s=c,s.length>0){let l=this.options.retryConfig?.initialDelay??1e3,u=this.options.retryConfig?.maxDelay??3e4,f=l*Math.pow(2,o);await new Promise(p=>setTimeout(p,Math.min(f,u))),o++}}return{successes:r,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function Xi(n){if(typeof n!="object"||n===null)return{statusCode:"UNKNOWN_ERROR",message:String(n)};let e=n,t=[e.errorCode,e.statusCode,e.name].find(r=>typeof r=="string"&&r.length>0&&r!=="Error"),s=e.fields??e.data?.fields;return{statusCode:t??"UNKNOWN_ERROR",errorCode:typeof e.errorCode=="string"?e.errorCode:void 0,message:typeof e.message=="string"?e.message:String(n),fields:Array.isArray(s)?s.filter(r=>typeof r=="string"):void 0}}var Zi=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Qi(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function eo(n,e,t,s=()=>Date.now()){let r=await br(n,e,{now:s,successfulOnly:!0});return r.state==="running"?{state:"running"}:r.state!=="ended"?r:{state:"ended",created:(r.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!Zi.test(a)?[]:t&&Qi(o.sf__Created)!==!0?[]:[a]}),...typeof r.info.systemModstamp=="string"?{at:r.info.systemModstamp}:{}}}async function cd(n,e,t,s,r=()=>new Date){let i,o=()=>(i??=(async()=>{if(!s)return 0;try{let d=r().getTime(),c=Date.parse(await s());return Number.isFinite(c)?c-(d+r().getTime())/2:0}catch{return 0}})(),i),a=[];for(let d of e.jobs??[]){if(d.job===void 0)continue;let c={job:d.job,objectApiName:d.objectApiName},l=await eo(t,d.job,d.upsert===!0,()=>r().getTime());if(l.state==="running"||l.state==="unread"){a.push({...c,read:l,answered:!1});continue}let u=r().toISOString();l.state==="ended"&&l.at!==void 0&&Number.isFinite(Date.parse(l.at))?u=new Date(Date.parse(l.at)-await o()).toISOString():e.lastWrittenAt!==void 0&&(u=e.lastWrittenAt);let f=l.state==="ended"?l.created:[],p=await n.answerInFlight(e.runId,d.objectApiName,f,u,d.job);a.push({...c,read:l,answered:p})}return a}function ld(n,e){return e.map(({job:t,read:s})=>{let r=`${n}, job ${t}`;switch(s.state){case"ended":return`[INFO] ${r}: the job no line of the run answered ended in the org; ${s.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${r}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${r}: the job is still running in the org; read again later`;default:return`[WARN] ${r}: the job could not be read back: ${s.reason}`}})}var Le=5e3,rn=200,ht=_e().refine(n=>Ge(n),"not a record id"),to=Nt({sourceOrgId:_e().min(1).max(200),targetOrgId:_e().min(1).max(200),objectApiName:_e().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:Tn(["document","attachment"]),sourceId:ht,targetId:ht,sourceVersionId:ht.optional(),sourceModifiedAt:xt.datetime().optional(),linked:vt(ht).max(rn),copiedAt:xt.datetime()}),no=Nt({version:Mn(1),entries:vt(to).max(Le)});function Hs(n){if(n==null)return{kind:"none"};let e=no.safeParse(n);if(e.success)return{kind:"stored",map:e.data};let t=e.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"map"}: ${t.message}`}}function kd(n,e,t){return n?n.check({orgId:e,orgTier:xn(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var le=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Ke=class extends Error{};function ro(){return{copied:0,versions:0,bytes:0,links:0,unchanged:0,tooLarge:0,pastRunCap:0,external:0,recordNotWritten:0,failed:0}}function te(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function mt(n,e){let t=n;for(let s of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[s]}return Wt(t)}function De(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function so(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function He(n,e,t){return`${n}|${e}|${t}`}function io(n,e){let t=e.load(n.id);if(t===null)throw new le("Files are copied by a saved configuration only: it keeps which file it copied where, so that running it again copies none of them twice. Save the configuration, then run it. Nothing was read or written.");if(t.kind==="unreadable")throw new le(`The record of the files this configuration copied could not be read (${t.issue}), so a run could copy them a second time. Turn the files off, or save the configuration again under a new name. Nothing was read or written.`);let s=new Map;if(t.kind==="stored")for(let r of t.map.entries)s.set(He(r.sourceOrgId,r.targetOrgId,r.sourceId),r);return s}var nn="ContentDocument.LatestPublishedVersion.SystemModstamp";async function oo(n,e,t,s){let r=rt(t.objectApiName),i=t.where?.trim()?` WHERE (${Un(t.where)})`:"",o=`SELECT Id FROM ${r}${i}`,a=_t(s),d=new Set,c,l=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${nn} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${nn} > ${a})`);for(let f of l){let p=te(f,"LinkedEntityId");p&&Ge(p)&&d.add(p),c=De(De(c,mt(f,"SystemModstamp")),mt(f,nn))}let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT ParentId, LastModifiedDate FROM Attachment WHERE ParentId IN (${o}) AND LastModifiedDate > ${a}`);for(let f of u){let p=te(f,"ParentId");p&&Ge(p)&&d.add(p),c=De(c,mt(f,"LastModifiedDate"))}return{ids:[...d],...c!==void 0?{newest:c}:{}}}async function ao(n,e,t){let s=new Map;for(let r of ee(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${r})`);for(let o of i){let a=te(o,"Id"),d=Wt(o.LastModifiedDate);a&&d&&s.set(a,d)}}return s}function co(n,e,t){return e===void 0||n.targetId===n.sourceId?!1:n.sourceModifiedAt!==void 0?n.sourceModifiedAt!==e:t!==void 0&&Date.parse(e)>Date.parse(t)}async function lo(n,e,t,s,r,i){let o=[...r.values()].filter(l=>l.kind==="document"&&l.objectApiName===t&&l.sourceOrgId===e.sourceOrgId&&l.targetOrgId===e.targetOrgId&&!i.has(l.sourceId)).map(l=>l.sourceId),a=_t(s),d=[],c;for(let l of ee(o)){let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SystemModstamp FROM ContentVersion WHERE ContentDocumentId IN (${l}) AND IsLatest = true AND SystemModstamp > ${a}`);for(let f of u){c=De(c,mt(f,"SystemModstamp"));let p=te(f,"ContentDocumentId"),h=te(f,"Id");if(!p||!h||(te(f,"ContentLocation")??"S")!=="S")continue;let y=te(f,"Title")??p;d.push({objectApiName:"ContentDocument",sourceId:p,body:{objectApiName:"ContentVersion",id:h},name:y,bytes:so(f,"ContentSize"),hosts:[],fields:{Title:y,PathOnClient:te(f,"PathOnClient")??y}})}}return{files:d,...c!==void 0?{newest:c}:{}}}async function uo(n,e,t,s){let r=new Map,i=new Date().toISOString(),o=(l,u,f)=>({sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:t,kind:l,sourceId:u,targetId:u,linked:[],copiedAt:i,...f}),a=s.filter(l=>l.objectApiName==="ContentDocument").map(l=>l.sourceId);for(let l of ee(a)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");if(!p)continue;let h=te(f,"LatestPublishedVersionId");r.set(p,o("document",p,h?{sourceVersionId:h}:{}))}}let d=[...r.keys()];for(let l of ee(d)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${l})`);for(let f of u){let p=te(f,"ContentDocumentId"),h=te(f,"LinkedEntityId"),y=p?r.get(p):void 0;y&&h&&Ge(h)&&y.linked.length<rn&&y.linked.push(h)}}let c=s.filter(l=>l.objectApiName==="Attachment").map(l=>l.sourceId);for(let l of ee(c)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id FROM Attachment WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");p&&r.set(p,o("attachment",p,{}))}}return r}async function Ys(n){let{config:e,option:t,objects:s,deps:r}=n,i=io(e,r.store),o;try{o=await gs(r.copy,e.targetOrgId)}catch(p){throw new le(`The file storage the target has left could not be read (${K(p)}), so the files could not be measured against it. Nothing was written.`)}let a=t.maxFileSizeMB*1048576,d=t.maxRunMB*1048576,c=0,l=0,u=new Set,f={objects:new Map,storage:{remainingBytes:o,plannedBytes:0}};for(let{objectConfig:p,changedSince:h,filesSeen:y}of s){if(p.operation==="delete")continue;let m=p.objectApiName,R=await r.sourceIds(p,h),S=[],b=h===void 0?void 0:y!==void 0&&Date.parse(y)>Date.parse(h)?dr(y):h,k=h===void 0?void 0:y,g=new Map;if(b!==void 0)try{let j=new Set(R),D=await oo(r,e,p,b);k=De(k,D.newest);let _=D.ids.filter(z=>!j.has(z));if(_.length>0){let z=n.tie?await n.tie(p,_):{held:new Map};g=z.held;let H=_.filter(G=>!g.has(G)).length;H>0&&S.push(`${H} record(s) whose files changed since the last run, and nothing else of them, could not be tied to their copy in the target`+(z.refused?` (${z.refused})`:"")+": their new files are copied when the record changes, or on a full read.")}}catch(j){throw new le(`${m}: the files its records gained since the last run could not be looked up (${K(j)}). Run it again, or turn the files off. Nothing was written.`)}let w=[...R,...g.keys()],M=await ps({scope:new Map([[m,w]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:r.copy.queryRecords});if(fs(M)){let j=new Set(M.errors.flatMap(D=>D.samples.flatMap(_=>_.messages)));throw new le(`${m}: the files of its records could not all be looked up in the source (${[...j].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let A=ro();for(let j of M.leftOut)j.reason==="too-large"?A.tooLarge++:j.reason==="external"&&A.external++;A.tooLarge>0&&S.push(`${A.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let O=M.files,E=[],F=new Map;try{if(b!==void 0){let _=new Set(O.map(H=>H.sourceId)),z=await lo(r,e,m,b,i,_);k=De(k,z.newest);for(let H of z.files)H.bytes>a?A.tooLarge++:O=[...O,H]}let j=O.filter(_=>!i.has(He(e.sourceOrgId,e.targetOrgId,_.sourceId)));if(j.length>0)for(let[_,z]of await uo(r,e,m,j))i.set(He(e.sourceOrgId,e.targetOrgId,_),z),E.push(z);let D=O.filter(_=>_.objectApiName==="Attachment");D.length>0&&(F=await ao(r,e,D.map(_=>_.sourceId)))}catch(j){throw new le(`${m}: the files an earlier run copied could not be looked up (${K(j)}), so a run could copy them twice. Nothing was written.`)}let N=[],$=new Map,T=0,v=0;for(let j of O){if(u.has(j.sourceId)){A.unchanged++,N.push(j);continue}let D=i.get(He(e.sourceOrgId,e.targetOrgId,j.sourceId)),_=D?.kind==="attachment"&&co(D,F.get(j.sourceId),h);if(_&&!r.deleteFromTarget){v++;continue}if(D&&!_&&(D.kind==="attachment"||D.sourceVersionId===j.body.id)){A.unchanged++,D.kind==="document"&&N.push({...j,into:{documentId:D.targetId,linked:D.linked,unchanged:!0}});continue}if(!D&&l>=Le-i.size){T++,A.pastRunCap++;continue}if(c+j.bytes>d){A.pastRunCap++;continue}c+=j.bytes,A.bytes+=j.bytes,u.add(j.sourceId),D&&_?(A.replaced=(A.replaced??0)+1,$.set(j.sourceId,D.targetId),N.push(j)):D?(A.versions++,N.push({...j,into:{documentId:D.targetId,linked:D.linked}})):(l++,A.copied++,N.push(j))}A.pastRunCap>T&&S.push(`${A.pastRunCap-T} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),v>0&&S.push(`${v} legacy attachment(s) the source changed since they were copied were left as copied: replacing one deletes its earlier copy, and this run may not delete in the target.`),T>0&&S.push(`${T} file(s) were not copied: this configuration keeps the record of ${Le} copied files at most, which it holds already. Removing an earlier run of it frees the entries of the files that run copied: Remove what this run created on its History entry, or --remove on the command line.`),f.objects.set(m,{scope:new Set(w),files:N,outcome:A,notes:S,shared:E,held:g,replacing:$,attachmentsChangedAt:F,...k!==void 0?{filesSeen:k}:{}})}return f.storage={remainingBytes:o,plannedBytes:c,...c>o?{shortfall:`The files to copy take ${st(c)} and the target has ${st(Math.max(0,o))} of file storage left. Lower the largest file or the most a run copies, or leave the files out.`}:{}},f}function po(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function Js(n){let{config:e,option:t,objectApiName:s,planned:r,written:i,deps:o,signal:a}=n,d={...r.outcome,copied:0,versions:0,bytes:0,...r.outcome.replaced!==void 0?{replaced:0}:{}},c=[...r.notes],l=[...i.keys()].filter(g=>!r.scope.has(g)).length;l>0&&c.push(`${l} record(s) written were not in the source when the files were looked up: their files are copied by the next run.`);try{for(let g of r.shared)o.store.record(e.id,g)}catch(g){c.push(`The files the target already held could not be recorded (${K(g)}): the next run looks them up again.`)}if(r.files.length===0)return{outcome:d,notes:c,unplanned:l,cancelled:!1};let u=o.store.load(e.id),f=new Map((u?.kind==="stored"?u.map.entries:[]).filter(g=>g.sourceOrgId===e.sourceOrgId&&g.targetOrgId===e.targetOrgId).map(g=>[g.sourceId,g])),p=r.files.map(g=>{let w=g.into?void 0:f.get(g.sourceId);return w&&w.kind==="document"?{...g,into:{documentId:w.targetId,linked:w.linked,unchanged:!0}}:g}),h=hs({files:p.filter(g=>!g.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),y=[],m,R=!1,S=[],b={ids:[],note:void 0},k=(g,w)=>{let M=He(e.sourceOrgId,e.targetOrgId,g.sourceId),A=[...new Set([...g.into?.linked??[],...w.linked])].slice(0,rn),O=g.objectApiName==="ContentDocument",E=r.replacing.get(g.sourceId),F=r.attachmentsChangedAt.get(g.sourceId);w.asVersion?(d.versions++,d.bytes+=g.bytes):E!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=g.bytes):g.into?.unchanged||(d.copied++,d.bytes+=g.bytes),!w.asVersion&&!g.into&&n.onCreated?.(O?"ContentDocument":"Attachment",w.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:s,kind:O?"document":"attachment",sourceId:g.sourceId,targetId:w.targetId,...O?{sourceVersionId:g.body.id}:{},...!O&&F!==void 0?{sourceModifiedAt:F}:{},linked:A,copiedAt:new Date().toISOString()}),E!==void 0&&E!==w.targetId&&S.push(E)}catch(N){m=`${K(N)} (${M})`}};try{await ms({files:p,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:g=>i.has(g)||r.held.has(g),get:g=>i.get(g)??r.held.get(g),add:()=>{}},deps:o.copy,report:h,errors:y,waitIfPaused:async()=>{if(m!==void 0)throw new Ke;if(await n.waitIfPaused?.(),a?.aborted)throw new Ke},onProgress:g=>{g.status==="running"&&o.onProgress?.(g.progress,`${s}: ${g.message}`)},onCopied:k})}catch(g){if(!(g instanceof Ke))throw g;R=m===void 0}finally{S.length>0&&(b=await fo(o,S))}return d.links=h.links,d.failed=h.objects.reduce((g,w)=>g+w.failed,0)+b.ids.length,d.recordNotWritten=h.leftOut.filter(g=>g.reason==="record-not-created").length,c.push(...po(y)),b.note!==void 0&&c.push(b.note),d.recordNotWritten>0&&c.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),m!==void 0&&(d.failed++,c.push(`A copied file could not be recorded, so no more files were copied: ${m}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:c,unplanned:l,cancelled:R}}var Ks=200;async function fo(n,e){let t=[],s=new Set;for(let r=0;r<e.length;r+=Ks){let i=e.slice(r,r+Ks);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let c=o[d];c?.success||(t.push(a),s.add(c?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),s.add(K(o))}}return t.length===0?{ids:[],note:void 0}:{ids:t,note:`${t.length} earlier copy(ies) of an attachment replaced could not be deleted from the target (${[...s].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function Od(n){let e=t=>{let s=n[t];if(!s)throw new Error(`No connection for the org ${t}.`);return s};return{queryRecords:async(t,s)=>(await Yn(e(t).pages,s)).records,readFileBody:(t,s,r)=>Ss(e(t).transport,s,r),insertFile:(t,s,r)=>Rs(e(t).transport,s,r),insertRecords:async(t,s,r)=>hr(await e(t).create(s,r),s).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>bs(e(t).transport)}}function Ad(n){let e=0,t=0,s=0;for(let r of n)e+=r.copied+r.versions+(r.replaced??0),t+=r.bytes,s+=r.tooLarge+r.pastRunCap;return`${e} file(s), ${st(t)} copied, ${s} skipped past the caps`}var sn="sync:config:",Vs="syncConfigs",Je="sync:delta:",on="syncDelta",yt="sync:files:",Xs="syncFiles",Zs=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${sn}${e.id}`,e,Vs)}load(e){return this.configStore.get(`${sn}${e}`)}isSaved(e){return this.load(e)!==void 0}deltaStore(){return{load:e=>this.isSaved(e)?this.loadDelta(e):null,record:(e,t)=>this.recordWatermark(e,t)}}fileStore(){return{load:e=>this.isSaved(e)?this.loadFiles(e):null,record:(e,t)=>this.recordFile(e,t)}}list(){let e=this.configStore.getByCategory(Vs);return Object.values(e).sort((s,r)=>r.updatedAt.localeCompare(s.updatedAt))}delete(e){return this.configStore.delete(`${Je}${e}`),this.configStore.delete(`${yt}${e}`),this.configStore.delete(`${sn}${e}`)}loadDelta(e){return ar(this.configStore.get(`${Je}${e}`))}recordWatermark(e,t){let s=this.loadDelta(e),o={version:1,entries:[...(s.kind==="stored"?s.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...s.kind==="stored"&&s.state.resetAt?{resetAt:s.state.resetAt}:{}};this.configStore.set(`${Je}${e}`,o,on)}loadFiles(e){return Hs(this.configStore.get(`${yt}${e}`))}recordFile(e,t){let s=this.loadFiles(e);if(s.kind==="unreadable")throw new Error(`the record of copied files does not read: ${s.issue}`);let i=(s.kind==="stored"?s.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=Le)throw new Error(`the record of copied files holds ${Le} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${yt}${e}`,o,Xs)}forgetFiles(e,t,s){let r=this.loadFiles(e);if(r.kind!=="stored"||s.length===0)return[];let i=new Set(s.map(d=>d.slice(0,15))),o=[],a=r.map.entries.filter(d=>{let c=d.sourceOrgId===t.sourceOrgId&&d.targetOrgId===t.targetOrgId&&i.has(d.targetId.slice(0,15));return c&&o.push(d),!c});if(o.length>0){let d={version:1,entries:a};this.configStore.set(`${yt}${e}`,d,Xs)}return o}markRemoved(e,t,s,r){let i=this.loadDelta(e);if(i.kind!=="stored"||s.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!s.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:r}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${Je}${e}`,d,on)}return o}clearDelta(e){let t=this.loadDelta(e),s=t.kind==="stored"?t.state.entries.length:0,r={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${Je}${e}`,r,on),s}};async function go(n,e,t){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=ye(i);for(let d of ee(o)){if(t?.aborted)return;let c=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${a} WHERE Id IN (${d})`);for(let l of c.records){let u=Date.parse(String(l.CreatedDate??""));Number.isFinite(u)&&(s=Math.min(s,u),r=Math.max(r,u))}}}if(!(!Number.isFinite(s)||!Number.isFinite(r)))return{first:new Date(s).toISOString(),last:new Date(r).toISOString()}}async function Nd(n,e){let t=r=>({note:`What the duplicate rules of the target reported of the run could not be read (${K(r)}): the empty DuplicateRecordSet records it left, if any, stay.`}),s=new Set;try{for(let{ids:r}of e)for(let i of ee(r)){let{records:o}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE RecordId IN (${i})`);for(let a of o){let d=a.DuplicateRecordSetId;typeof d=="string"&&s.add(d)}}}catch(r){return{take:async()=>t(r)}}return{take:async(r=[])=>{let i=new Set(r.map(l=>l.slice(0,15))),o=[...s].filter(l=>!i.has(l.slice(0,15)));if(o.length===0)return{};let a=new Set;try{for(let l of ee(o)){let{records:u}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${l})`);for(let f of u)a.add(String(f.DuplicateRecordSetId))}}catch(l){return t(l)}let d=o.filter(l=>!a.has(l));if(d.length===0)return{};let c={objectApiName:"DuplicateRecordSet",planned:d.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let l=0;l<d.length;l+=Ut){let u=d.slice(l,l+Ut);for(let f of await kr(n,c.objectApiName,u))f.kind==="deleted"?c.deleted+=1:f.kind==="gone"?c.alreadyGone+=1:(c.refused+=1,c.reasons.includes(f.reason)||c.reasons.push(f.reason))}return{object:c}}}}async function ho(n,e){if(!n||!e)return n;let t=Date.parse(e.at),s=Date.parse(e.lastAt??""),r=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(s))return n;let o=await Qs(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(r,t+o):r,d=Number.isFinite(s)?Math.max(i,s+o):i;return a===r&&d===i?n:{first:a===r?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function Qs(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),s=Date.parse(await n.serverTime());return Number.isFinite(s)?s-(t+e().getTime())/2:void 0}catch{return}}async function mo(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),s=await Qs(n);if(s===void 0)return;let r=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+s).toISOString(),last:new Date(r+s).toISOString()}}var yo=50,wo=3,ei=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function So(n,e,t,s){let r=Date.parse(t.first)-ks,i=Date.parse(t.last)+Os;if(!Number.isFinite(r)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:c}of e){if(a>=wo||o.size>1||s?.aborted)break;let l=c.slice(0,yo);if(l.length===0)continue;let u;try{let[p]=ee(l,l.length);u=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${ye(d)} WHERE Id IN (${p})`)).records}catch{continue}let f=!1;for(let p of u){let{LastModifiedById:h,LastModifiedDate:y}=p??{},m=typeof y=="string"?Date.parse(y):Number.NaN;typeof h!="string"||!ei.test(h)||!(m>=r&&m<=i)||(o.has(h.slice(0,15))||o.set(h.slice(0,15),h),f=!0)}f&&a++}return o.size===1?[...o.values()][0]:void 0}async function xd(n,e,t,s,r,i,o){let a=e.some(({ids:p})=>p.length>0),d=a?await ho(await go(n,e,s),r):await mo(r),c=o.runUserId!==void 0&&ei.test(o.runUserId)?o.runUserId:void 0,l=n.query?.bind(n),u=!c&&!a&&d&&l?await So({query:l},i,d,s):void 0,f=i.filter(({ids:p})=>p.length>0);return{writtenBetween:d,created:e,remap:new Set([...e,...i].flatMap(({ids:p})=>p.map(h=>h.slice(0,15)))),automation:As(t),...c?{runUserId:c}:{},...u?{user:u}:{},ties:{...o.ties,...f.length>0?{writtenOver:f}:{}},...s?{signal:s}:{}}}var wt={status:"cancelled",objects:[],unread:[],handWork:[]};function zd(n,e,t){return{...Ar(n,e),counts:Cs(jr(Fr(n),t))}}async function qd(n,e){let t=Date.parse(n.writtenBetween?.first??""),s=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(s))return n;let{created:r}=n,i=new Set(r.flatMap(({ids:c})=>c.map(l=>l.slice(0,15)))),o=await Or(e,{has:c=>i.has(c),start:t,end:s,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},r.filter(c=>c.objectApiName==="Quote").flatMap(({ids:c})=>c),new Set(r.map(c=>c.objectApiName))),a=new Set(o.flatMap(c=>c.copies.map(l=>l.id.slice(0,15))));if(a.size===0)return n;let{remap:d}=n;return{...n,remap:{has:c=>d.has(c)||a.has(c)}}}async function Kd(n){let e,t,s;try{let o=await n.input();"refused"in o?s={...wt,status:"refused",refusal:o.refused}:t=Is(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:c}=await Cr(n.guard,{...n.guardOf,objectName:Es(a).join(", "),recordCount:Ps(a)});if(e=c,c==="refused")return`Operation blocked by Production Guard: ${d.blockedReason??d.impactSummary}`;if(c==="declined")return"Operation cancelled by user (confirmation declined)."}})}catch(o){s={...wt,status:"failure",refusal:K(o)}}let r=async o=>{if(!t||s)return!1;try{return await o(t)}catch(a){return s={...t.result(),status:"failure",refusal:K(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await r(async o=>(await o.ask(),!1))},get takes(){return s?[]:t?.takes??[]},first:o=>r(a=>a.first(o)),afterRemoval:o=>r(a=>a.afterRemoval(o)),result:()=>s??t?.result()??wt,settle:()=>(i??=(async()=>{let o=s??t?.result()??wt;return n.onGuardDecision(o,e),t&&(t.made.size>0||t.late.size>0||t.gone.size>0)&&await n.keepMade?.(t.made,t.late,t.gone).catch(()=>{}),o})(),i)}}function Hd(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var ti=6e4;function ko(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&Oo(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function Oo(n,e){let t=Date.parse(n?.first??""),s=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(s)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=s+9e5+ti&&Math.max(e.from,e.to)>=t-2e3-ti}var Ao=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function Yd(n,e){return n.filter(t=>Ao.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let s=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:s,to:s}})}function Co(n){let e=Date.parse(n.firstWrittenAt??n.startedAt),t=Date.parse(n.lastWriteAt??n.lastWrittenAt??n.end?.at??n.startedAt);return{ids:[...n.created,...n.overwritten??[]].flatMap(({ids:s})=>s),from:e,to:Number.isFinite(t)?t:e}}function Io(n,e,t){return n.filter(s=>s.targetOrgId===e&&s.runId!==t).map(Co)}async function Jd(n,e,t,s){let r=await s(n.targetOrgId,e).catch(()=>[]),i=Po(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:ko(e,[...Io(t,n.targetOrgId,n.runId),...r]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function Vd(n,e,t,s=[]){let r=[...s],i=Kt(n.madeEarlier,e,r),o=Kt(n.lateEarlier,t,r),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function Po(n){let e;for(let t of n??[]){let s=Date.parse(t.first);Number.isFinite(s)&&(!e||s<e.at)&&(e={at:s,first:t.first})}return e?.first}var ae=class extends Error{constructor(t,s,r){super(t);this.result=s;this.cause=r;this.name="SyncRunFailure"}result;cause},$e=class extends ae{constructor(t,s,r){super(t,s);this.code=r;this.name="SyncRunRefused"}code};function Qd(n){return typeof n!="number"||!Number.isFinite(n)?5e4:Math.min(5e4,Math.max(1,Math.floor(n)))}var Eo=/\b(QUERY_TIMEOUT|OPERATION_TOO_LARGE)\b/;function an(n){return Eo.test(n)?" Salesforce gave up on the count: filter the object on an indexed field (CreatedDate, SystemModstamp, Id, Name or an External ID) or on a narrower range of CreatedDate, then run it again. A user with View All Data reads the source without its sharing, which is what slows such a count most.":""}var To={raise:"the sandforge.sync.maxRecordsPerObject setting",sample:"Forge, with Depth ALL and Records per object set to A sample that fits the target"};function Mo(n,e,t){let s=e<5e4?`raise ${t.raise} (50000 at most), or `:"";return n==="target"?`To compare every record, ${s}narrow the object's filter.`:`To copy the rest, ${s}read it in slices: a filter on CreatedDate, one range per run. To copy a sample of the source that fits the target instead, use ${t.sample}.`}function ec(n){let e=n.cutAtReadCap??[];if(!(n.readCap===void 0||e.length===0))return`the read of the source stopped at ${n.readCap} records of ${e.join(", ")} (sandforge.sync.maxRecordsPerObject): the run copied part of ${e.length===1?"it":"each"}. `+Mo("source",n.readCap,To)}var Fo=2e3,jo=5e3,St=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??Fo,this.pollIntervalMs=e.pollIntervalMs??jo,this.signal=e.signal}async executeChunked(e,t,s,r,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:s,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,c={id:d,operation:s,object:t,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString(),totalRecords:i};e.bulkManager.registerJob(c);try{await a.open();let l=wr(a);l!==void 0&&e.onOpened?.(l);let u=[];for await(let w of r){if(this.signal?.aborted)break;for(let M of w)u.push(M);e.onProgress?.(u.length,i)}let f,p=0;if(this.signal?.aborted||(f=mr(s,u,o),await a.uploadData(f.text),p=u.length),this.signal?.aborted||f===void 0)return await Rr(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(p);await a.close();let h=await a.check();for(;h.state==="InProgress"||h.state==="UploadComplete";)e.bulkManager.updateJobState(d,h.state),e.onProgress?.(h.numberRecordsProcessed??0,i),await new Promise(w=>setTimeout(w,this.pollIntervalMs)),h=await a.check();let y=await a.getAllResults(),m=yr(y,f,Sr(h)),R=m.outcomes,S=[],b=[],k=m.unattributedSuccessIds.length;for(let w of R)w.success?(k++,w.id!==void 0&&S.push(w.id)):b.push(w.error??"Unknown error");S.push(...m.unattributedSuccessIds),b.push(...m.unattributedFailures);let g=h.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,g),e.bulkManager.updateJobCounts(d,h.numberRecordsProcessed??i,b.length),{totalRecords:p,successCount:k,failureCount:b.length,successIds:S,errors:b,aborted:!1,outcomes:R,...m.unattributedSuccessIds.length>0?{unmatchedIds:m.unattributedSuccessIds}:{}}}catch(l){throw e.bulkManager.updateJobState(d,"Failed"),l}}async*createChunkGenerator(e,t){let s=t??this.chunkSize;for(let r=0;r<e.length;r+=s)yield e.slice(r,r+s)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var vo=1e4,ni=fe.REST_API_BATCH_SIZE;function No(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function xo(n){return!n.success&&Br(n.errors,n.errorDetails)}function Do(n,e){let[t,...s]=n.errors;return t===void 0?n:{...n,errors:[Wr(t,e),...s]}}function dn(n){return typeof n.created=="boolean"?{created:n.created}:{}}function ii(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function ri(n){let e=n===void 0?void 0:pr(n);return e?ii([e]):{}}function cn(n,e){return n!=="insert"&&n!=="upsert"?[]:e.flatMap(t=>t.success&&typeof t.id=="string"&&t.id!==""&&(n==="insert"||t.created===!0)?[t.id]:[])}function Lo(n,e){return!n||!e?n??e:{before:async(t,s,r,i)=>await n.before?.(t,s,r,i)??await e.before?.(t,s,r,i),sending:(t,s,r)=>{n.sending(t,s,r),e.sending(t,s,r)},opened:(t,s,r,i)=>{n.opened?.(t,s,r,i),e.opened?.(t,s,r,i)},answered:(t,s,r,i)=>{n.answered(t,s,r,i),e.answered(t,s,r,i)}}}function pc(n,e){let t=s=>s==="insert"||s==="upsert";return{...e?{before:(s,r,i,o)=>e.before(s,r,i,o)}:{},sending:(s,r,i)=>{t(r)?n.sending?.(s,i,r==="upsert"?{upsert:!0}:void 0):n.writing?.(s,i)},opened:(s,r,i,o)=>{t(r)&&n.sending?.(s,i,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(s,r,i)=>{t(r)?n.answered?.(s,cn(r,i)):i.length>0&&n.writing?.(s,i.length),e?.answered(s,r,i)}}}var si=class{constructor(e){this.deps=e;this.wait=e.wait??(t=>_r(t,e.signal)),this.retryOp=new gt({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,s,r)=>{e.log(`[RETRY] sync attempt=${t} code=${s.originalError.statusCode} delay=${r}ms`)}})}deps;retryOp;wait;async insert(e,t,s,r){let i=Lo(this.deps.calls,r),o=l=>this.deps.connection.sobject(e).create(l,{headers:tt()}),a="Insert failed after retries",d=await this.tryStreaming("insert",e,t,void 0,i)??await this.tryBulk("insert",e,t,void 0,i),c=d?await this.duplicatesAgain("insert",e,t,d,o,a,i):await this.executeRestBatches("insert",e,t,s,o,a,i);return this.locksAgain("insert",e,t,c,o,a,i)}async upsert(e,t,s,r){let i=c=>this.deps.connection.sobject(e).upsert(c,t,{headers:tt()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,s,t)??await this.tryBulk("upsert",e,s,t),d=a?await this.duplicatesAgain("upsert",e,s,a,i,o,this.deps.calls,t):await this.executeRestBatches("upsert",e,s,r,i,o,this.deps.calls,t);return this.locksAgain("upsert",e,s,d,i,o,this.deps.calls,t)}async update(e,t,s){let r=d=>this.deps.connection.sobject(e).update(d,{headers:tt()}),i="Update failed after retries",o=await this.tryStreaming("update",e,t)??await this.tryBulk("update",e,t),a=o?await this.duplicatesAgain("update",e,t,o,r,i):await this.executeRestBatches("update",e,t,s,r,i);return this.locksAgain("update",e,t,a,r,i)}async delete(e,t,s){let r=d=>this.deps.connection.sobject(e).destroy(d),i="Delete failed after retries",o=t.map(d=>({Id:d})),a=await this.tryBulk("delete",e,o)??await this.executeRestBatches("delete",e,t,s,r,i);return this.locksAgain("delete",e,t,a,r,i)}async tryStreaming(e,t,s,r,i=this.deps.calls){if(s.length<=vo)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o=await this.refusedBefore(i,t,e,s,r);if(o)return o;let a=new St({signal:this.deps.signal});i?.sending(t,e,s.length);let d={connection:qt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(u,f)=>{this.deps.onProgress(u,f,`Streaming ${e} ${t}`)},onOpened:u=>i?.opened?.(t,e,s.length,u)},c=await a.executeChunked(d,t,e,a.createChunkGenerator(s),s.length,r);if(c.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Streaming ${e} ${t}`,c.unmatchedIds);let l=(c.outcomes??[]).map(u=>this.withExistingRecord(t,{id:u.id,success:u.success,errors:u.success?[]:[u.error??"Streaming error"],...dn(u),...u.success?{}:ri(u.error)}));return i?.answered(t,e,l),l}async tryBulk(e,t,s,r,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(s.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o={connection:qt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(l,u)=>{this.deps.onProgress(l,u,`Bulk ${e} ${t}`)},signal:this.deps.signal,onOpened:l=>i?.opened?.(t,e,s.length,l)},a=await this.refusedBefore(i,t,e,s,r);if(a)return a;i?.sending(t,e,s.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,s,r);if(d.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Bulk ${e} ${t}`,d.unmatchedIds);let c=d.outcomes.map(l=>this.withExistingRecord(t,{id:l.id,success:l.success,errors:l.success?[]:[l.error??"Bulk error"],...dn(l),...l.success?{}:ri(l.error)}));return i?.answered(t,e,c),c}async refusedBefore(e,t,s,r,i){if(s==="delete"||!e?.before)return;let o=await e.before(t,s,r,i);if(o!==void 0)return this.deps.log(`[WARN] ${s} ${t}: ${r.length} row(s) not sent: ${o}`),r.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,s,r,i,o,a=this.deps.calls,d){let c=r.flatMap((p,h)=>h<s.length&&No(p)?[h]:[]);if(c.length===0||this.deps.signal?.aborted)return r;let l;try{l=await this.executeRestBatches(e,t,c.map(p=>s[p]),ni,i,o,a,d,c)}catch(p){if(!(p instanceof Q))throw p;l=p.written}let u=[...r];l.forEach((p,h)=>{u[c[h]]=p});let f=l.filter(p=>p.success).length;return this.deps.log(`[INFO] ${e} ${t}: ${c.length} row(s) a duplicate rule refused in the Bulk API job, which cannot carry the header that lets a rule's matches be saved, went again through REST with it: ${f} saved`+(l.length<c.length?`, ${c.length-l.length} not sent (cancelled)`:"")),u}async locksAgain(e,t,s,r,i,o,a=this.deps.calls,d){let c=new Map,l=await Gr({outcomes:r.slice(0,s.length),locked:xo,written:p=>p.success,send:async p=>{let h;try{h=await this.executeRestBatches(e,t,p.map(y=>s[y]),ni,i,o,a,d,p)}catch(y){if(!(y instanceof Q))throw y;h=y.written}for(let y of p.slice(0,h.length))c.set(y,(c.get(y)??0)+1);return h},note:Do,wait:p=>this.wait(p),stopped:()=>this.deps.signal?.aborted===!0}),u=Ur("row(s)",l);return u===void 0?r:(this.deps.log(`[INFO] ${e} ${t}: ${u}`),[...l.outcomes.map((p,h)=>{let y=c.get(h);return y===void 0?p:{...p,lockResends:y}}),...r.slice(s.length)])}logUnmatched(e,t){t&&t.length>0&&this.deps.log(`[WARN] ${e}: the job wrote ${t.length} record(s) no row was matched to: ${t.join(", ")}`)}withExistingRecord(e,t){if(t.success)return t;let s=zt(t,this.deps.keyPrefixOf?.(e));return s.kind==="linked"?{...t,existingId:s.id}:t}async executeRestBatches(e,t,s,r,i,o,a=this.deps.calls,d,c){let l=[];for(let u=0;u<s.length;u+=r){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t,l);let f=s.slice(u,u+r);if(e!=="delete"){let y=await this.refusedBefore(a,t,e,f,d);if(y){l.push(...y);continue}if(this.deps.signal?.aborted)throw new Q(t,l)}a?.sending(t,e,f.length);let p=await this.retryOp.execute(()=>i(f));if(p.cancelled)throw a?.answered(t,e,[],c&&[]),new Q(t,l);let h=[];if(p.success&&p.result)for(let y of Array.isArray(p.result)?p.result:[p.result])h.push(this.restOutcome(t,y));else h.push(...f.map(()=>({success:!1,errors:[p.error?.message??o]})));l.push(...h),a?.answered(t,e,h,c?.slice(u,u+f.length))}return l}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...dn(t)};let s=t.errors??[],r=s.map(fr),i={id:t.id,success:!1,errors:[r[0]??"Unknown error"],...ii(s.map(ur))},o=zt({success:!1,errors:r,duplicateMatchIds:s.flatMap(a=>gr(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};function oi(n,e){if(n.operation==="delete")return[];let t=or(n.fieldMappings,n.excludedFields??[]),s=new Set([...ir(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),r=i=>!t.has(i.toLowerCase())||s.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&r(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function ai(n,e){let t=[...n].sort((b,k)=>b.insertOrder-k.insertOrder),s=new Map(t.map((b,k)=>[b.objectApiName,k])),r=new Set(t.filter(b=>b.operation!=="delete").map(b=>b.objectApiName)),i=new Map([...r].map(b=>[b.toLowerCase(),b])),o=[],a=new Set;for(let b of t){let k=b.objectApiName;if(r.has(k))for(let{field:g,referenceTo:w}of e.get(k)??[])for(let M of w){let A=i.get(M.toLowerCase());if(A===void 0||A===k)continue;let O=`${A}>${k}`;a.has(O)||(a.add(O),o.push({parent:A,child:k,field:g}))}}let d=$o(t.map(b=>b.objectApiName),o),c=new Map;d.forEach((b,k)=>{for(let g of b)c.set(g,k)});let l=d.map(b=>[...b].sort((k,g)=>(s.get(k)??0)-(s.get(g)??0))),u=l.map(b=>s.get(b[0])??0),f=l.map(()=>new Set);for(let{parent:b,child:k}of o){let g=c.get(b)??0,w=c.get(k)??0;g!==w&&f[w].add(g)}let p=new Set,h=[];for(;p.size<l.length;){let b;if(l.forEach((k,g)=>{p.has(g)||[...f[g]].some(w=>!p.has(w))||(b===void 0||u[g]<u[b])&&(b=g)}),b===void 0)break;p.add(b),h.push(...l[b])}let y=new Map(t.map(b=>[b.objectApiName,b])),m=h.flatMap(b=>{let k=y.get(b);return k?[k]:[]}),R=new Map(h.map((b,k)=>[b,k])),S=[];for(let b of m){let k=b.objectApiName,g=o.filter(w=>w.child===k&&(s.get(w.parent)??0)>(s.get(k)??0)&&(R.get(w.parent)??0)<(R.get(k)??0)).sort((w,M)=>(R.get(M.parent)??0)-(R.get(w.parent)??0));g.length>0&&S.push({objectApiName:k,after:g[0].parent,field:g[0].field})}return{ordered:m,order:{objects:h,moved:S,cycles:l.filter(b=>b.length>1)}}}function $o(n,e){let t=new Map(n.map(l=>[l,[]]));for(let{parent:l,child:u}of e)t.get(l)?.push(u);let s=0,r=new Map,i=new Map,o=[],a=new Set,d=[],c=l=>{r.set(l,s),i.set(l,s),s++,o.push(l),a.add(l);for(let p of t.get(l)??[])r.has(p)?a.has(p)&&i.set(l,Math.min(i.get(l)??0,r.get(p)??0)):(c(p),i.set(l,Math.min(i.get(l)??0,i.get(p)??0)));if(i.get(l)!==r.get(l))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;a.delete(f),u.push(f)}while(f!==l);d.push(u)};for(let l of n)r.has(l)||c(l);return d}var Bo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,de=n=>n.toLowerCase();function Rt(n){return n==="insert"||n==="upsert"}function _o(n,e){let t=de(e);if(n.addOnFields.some(r=>de(r.fieldApiName)===t)||n.transformRules.some(r=>r.field&&de(r.field)===t))return;let s=n.fieldMappings.find(r=>r.type!=="exclude"&&de(r.targetField)===t);return s?(s.type==="direct"||s.type==="rename")&&(s.transformRules??[]).length===0?s.sourceField:void 0:e}function Wo(n){return n!==void 0&&[...n.source.active].some(e=>!n.target.active.has(e))}async function di(n){let e=new Map,t=new ze(n.earlier),s=new Set,r=new Set([...n.leftOut].map(de)),i,o=async l=>{let u=await n.read(l);return u.length>0&&ut(l.objectApiName,u)&&(i=await n.standardPricebooks?.(),i&&t.noteMatched(i.source,i.target)),u},a=n.matched,d=(l,u)=>{a&&u>0&&a.set(l,(a.get(l)??0)+u)},c=(l,u)=>{let f=i?.source;return l===ge&&f!==void 0?u.filter(p=>p.Id===f).length:0};for(let l of n.ordered){let u=l.objectApiName;if(r.has(de(u))){if(!Rt(l.operation))continue;let A=await o(l);for(let O of A){let E=O.Id;typeof E=="string"&&E!==""&&t.noteRefused(E,u)}d(u,c(u,A)),s.add(de(u));continue}if(l.operation==="delete")continue;let f=(n.lookups.get(u)??[]).flatMap(({field:A,referenceTo:O})=>{let F=O.filter(N=>de(N)!==de(u)&&s.has(de(N))).length>0?_o(l,A):void 0;return F!==void 0?[{field:A,source:F}]:[]}),p=a!==void 0&&Rt(l.operation),h=p&&u===ge&&await n.standardPricebooks?.()!==void 0,y=p&&u===Me&&await n.standardPricebooks?.()?await n.currencies?.():void 0,m=Wo(y);if(f.length===0&&!h&&!m)continue;let R=new Map,S=A=>{let O=`${A.parent}|${A.field}`,E=R.get(O);E?E.rows++:R.set(O,{...A,rows:1})},b=n.copied?.get(u),k=(await o(l)).filter(A=>{let O=A.Id;return!(b&&typeof O=="string"&&b.has(O.slice(0,15)))}),g=new Map;for(let A of f.length>0?k:[]){let O=A.Id,E=f.find(({source:N})=>{let $=A[N];return typeof $=="string"&&Bo.test($)&&t.refusedObjectOf($)!==void 0});if(!E)continue;let F={parent:t.refusedObjectOf(A[E.source])??"",field:E.field};S(F),typeof O=="string"&&O!==""&&g.set(O,F),Rt(l.operation)&&typeof O=="string"&&O!==""&&t.noteRefused(O,u)}if(h&&d(u,c(u,k)),m){let A=pt(Me,{records:k,sources:k,sourceIds:k.map(E=>typeof E.Id=="string"?E.Id:void 0)},i,y,E=>t.refusedObjectOf(E)!==void 0),O=0;for(let[E,F]of A.standsFor){if(g.has(E))continue;let N=t.refusedObjectOf(F)!==void 0?g.get(F):void 0;if(N){S(N),g.set(E,N),t.noteRefused(E,u);continue}O++}d(u,O)}let w=[...R.values()],M=w.reduce((A,O)=>A+O.rows,0);M>0&&(e.set(u,{objectApiName:u,rows:M,parent:w[0].parent,field:w[0].field,parents:w}),Rt(l.operation)&&s.add(de(u)))}return e}var ci=Symbol("not written");function Go(n,e){if(n==="delete")return{rules:[],onChange:[]};let t=[],s=[];for(let{onChangeOnly:r,...i}of e)r&&n==="insert"?s.push(i.name):t.push(i);return{rules:t,onChange:s}}function Uo(n){return`${n.length} active validation rule(s) of the target left out of what may refuse these inserts: their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is \u2014 ${n.join(", ")}`}var zo=/^012000000000000(AAA)?$/;function qo(n){let e=n.RecordTypeId;return typeof e=="string"&&e.length>=15&&!zo.test(e)}function un(n){let e=n?.[Jn];return typeof e=="string"&&e!==""}async function li(n,e,t,s){let r=e.some(qo)?await n.recordTypes():void 0,i=t.some(un)||e.some(un)?await n.currencies():void 0,o=n.later?.get(s),a=n.recordTypesUnderTheLease?.get(s);return{links:n.links,sources:t,...r?{recordTypes:r}:{},...i?{currencies:i,currencyChangesById:n.currencyChangesById}:{},...n.contactPoints?{contactPoints:n.contactPoints}:{},...o&&o.size>0?{later:o}:{},...a?{recordTypesUnderTheLease:a}:{},...n.createdWithoutRecordType?{createdWithoutRecordType:n.createdWithoutRecordType}:{}}}function ui(n){let e=new Map;for(let t of n?.cycles??[])t.forEach((s,r)=>{r<t.length-1&&e.set(s,new Set(t.slice(r+1)))});return e}function Ko(n,e,t){return{...n,...e.set?{lookupsSetAfter:{...e.set,after:[...t]}}:{},...e.leftOut.length>0?{lookupsLeftOut:[...n.lookupsLeftOut??[],...e.leftOut]}:{}}}function pi(n,e){return e.flatMap((t,s)=>{let r=n[s];return t.success&&r!==void 0?[r]:[]})}function fi(n,e){let t=e.encryptedLeftOut??[];return t.length>0?{...n,encryptedLeftOut:[...t]}:n}function re(n){return n.slice(0,15)}function Ho(n,e){if(!e)return n;if(e.unread!==void 0)return{...n,errors:[...n.errors,`The contact roles the platform wrote with the run's opportunities were not looked up, so written as read: an opportunity may hold the role of its contact twice. ${e.unread}`]};let{records:t,given:s,refusal:r,alike:i}=e,o=i!==void 0?{...n,errors:[...n.errors,Kn(i)]}:n;return t===0?o:{...o,skipped:o.skipped+t,writtenByThePlatform:{records:t,given:s,...r!==void 0?{refusal:r}:{}}}}function Yo(n,e,t){if(n.objectApiName!==X||!ue(n.operation)||!t.sentWithAContact||e.records.length===0)return{prepared:e,linked:0};let s=a=>typeof a=="string"&&a!==""?t.targetOf(a):void 0,r=e.records.map((a,d)=>({OpportunityId:s(a.OpportunityId),[oe]:s(a[oe]),IsPrimary:e.sources[d]?.IsPrimary??a.IsPrimary})),i=new Set(Bt(r,a=>t.contactSentWith(a)));if(i.size===0)return{prepared:e,linked:0};for(let a of i){t.roleLinkedFor(String(r[a].OpportunityId));let d=e.sourceIds[a];d!==void 0&&t.noteWritten(d,d)}let o=(a,d)=>!i.has(d);return{prepared:{...e,records:e.records.filter(o),sourceIds:e.sourceIds.filter(o),sources:e.sources.filter(o),unsettled:e.unsettled.length===e.records.length?e.unsettled.filter(o):e.unsettled},linked:i.size}}var Jo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ln=200;function Vo(n,e,t){let s=c=>{let l=t?.fields?.find(u=>u.name===c);return l?.nillable===!1&&l.defaultedOnCreate!==!0},r=[],i=new Set,o=new Set,a=0;for(let[c,l]of n){let u=e[c]==="insert"?l.filter(s):[];if(u.length>0){r.push(c);for(let f of u)i.add(f);continue}a++;for(let f of l)o.add(f)}let d=[];return a>0&&d.push(`${a} record(s) would be written without ${[...o].sort().join(", ")}: a lookup held an id from the source org that the target does not have, which the run learns from its first refusal and sends the record again without the lookups it did not settle.`),r.length>0&&d.push(`${r.length} record(s) would be refused: a lookup held an id from the source org that the target does not have, and sent again without the lookups the run did not settle, the record lacks ${[...i].sort().join(", ")}, which the target requires (REQUIRED_FIELD_MISSING).`),{refused:r,notes:d}}function Xo(n){return`${n} record(s) would be linked to the contact role the platform writes with their opportunity, for its contact, not written.`}function pn(n){let e=n.alreadyLinked,t=n.alreadyCopied-e;return{...t>0?{alreadyCopied:t}:{},...e>0?{alreadyLinked:e}:{}}}function Zo(n,e){return e.alreadyCopied===0?n:{...n,skipped:n.skipped+e.alreadyCopied,...pn(e)}}function gi(n,e){return`What earlier runs of this configuration copied could not be read (${n}), and ${e.map(t=>t.objectApiName).join(", ")} ${e.length===1?"is":"are"} inserted: the records they copied would be copied a second time. Nothing was written.`}var Qo="SYNC_EARLIER_UNREAD",ea=new Set(["account","contact"]);function ue(n){return n==="insert"||n==="upsert"}function hi(n,e,t,s=new Map,r=new Set,i=new Map,o=new Map,a=new Set,d,c={}){let l=0,u=0,f=n.map(g=>{let w=g.objectApiName,M=e.get(w)??{rows:0},A=t.get(w)??new Set,O=A.size,E=Math.min(O,M.rows),F=Math.min([...A].filter(v=>a.has(v)).length,E);u+=F,l+=E-F;let $=(s.has(w)?0:i.get(w)?.rows??0)+(o.get(w)??0),T=c.keys?.get(w);return{objectApiName:w,operation:g.operation,rows:Math.max(0,M.rows-O-$),...M.personAccounts!==void 0?{personAccounts:M.personAccounts}:{},batchSize:g.batchSize,...T?{overwriteKey:T}:{}}}),p=f.flatMap(g=>{let w=s.get(g.objectApiName);return w?[{...g,why:w.why,...w.key?{key:w.key}:{}}]:[]}),h=f.find(g=>g.objectApiName===X),y=h&&d!==void 0?Math.min(d,h.rows):0;h&&y>0&&(h.rows-=y);let m=f.filter(g=>!s.has(g.objectApiName)),R=m.filter(g=>g.rows>0&&ue(g.operation)&&r.has(g.objectApiName)).length,S=[...i.values()].filter(({objectApiName:g})=>!s.has(g)),b=d===void 0?ta(n,m):0,k=m.filter(g=>c.typed?.has(g.objectApiName)).length;return{objects:m,alreadyCopied:l,...u>0?{alreadyLinked:u}:{},...p.length>0?{unwritable:p}:{},...S.length>0?{heldBack:S}:{},...R>0?{readBack:R}:{},...b>0?{rolesByThePlatform:b}:{},...y>0?{rolesLinked:y}:{},...k>0?{describedAgain:k}:{}}}var Ee="Opportunity";function ta(n,e){let t=o=>e.find(a=>a.objectApiName===o&&ue(a.operation)),s=t(Ee),r=t(X);return!s||!r||n.find(o=>o.objectApiName===Ee)?.excludedFields.includes(oe)?0:Math.min(s.rows,r.rows)}function na(n,e,t){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:t,conflictCount:0,errors:[`${e.message} Left out of the run, as confirmed before it wrote.`]}}function mi(n,e,t){if(ue(e.operation))for(let s of t){let r=s?.Id;typeof r=="string"&&r!==""&&n.noteRefused(r,e.objectApiName)}}function bt(n,e,t){let s=[];for(let[r,i]of t){let o=n.targetOf(i);o!==void 0?n.noteMatched(r,o):ue(e.operation)&&n.refusedObjectOf(i)!==void 0&&(n.noteRefused(r,e.objectApiName),s.push(r))}return s}function yi(n,e,t){let s=Qt(e,t),r=tn(n,{...e,prices:s});return t.length===0?r:{...r,processed:r.processed+t.length,failed:r.failed+t.length,errors:[...r.errors,en(n.objectApiName,t.length)]}}function wi(n){let e=Ln(n.objects);return e.length>0?`${$n(e)} Nothing was read or written.`:void 0}function Si(n){let e=_n(n.objects);return e.length>0?`${Wn(e)} Nothing was read or written.`:void 0}var Ri=class{deps;constructor(e){this.deps=e}async execute(e){let t=Date.now(),s=`sync-${Date.now()}`,r=[],i=wi(e);if(i!==void 0)throw new $e(i,{...se(e.id,s,[],t,"failure"),error:i},Dn);let o=Si(e);if(o!==void 0)throw new $e(o,{...se(e.id,s,[],t,"failure"),error:o},Bn);let{ordered:a,order:d,refused:c,typed:l,lookups:u,keys:f}=await this.writeOrderOf(e.objects),p=ui(d),h=this.deps.queryTargetRows?l:new Set,y=this.deltaLoadOf(e),m=(C,I)=>new $e(C,{...se(e.id,s,[],t,"failure"),error:C},I),R;try{R=await this.planFiles(e,a,y)}catch(C){let I=C instanceof Error?C.message:String(C);throw new ae(I,se(e.id,s,[],t,"failure"),C)}if(R?.storage.shortfall)throw new ae(`${R.storage.shortfall} Nothing was written.`,{...se(e.id,s,[],t,"failure"),files:R.storage});let S=await this.earlierLinks(e),b=a.filter(C=>C.operation==="insert");if(S.unread!==void 0&&b.length>0)throw m(gi(S.unread,b),Qo);let k;try{k=await this.alreadyCopiedOf(e,a,S.links)}catch(C){let I=`What earlier runs of this configuration copied could not be looked up in the target (${C instanceof Error?C.message:String(C)}), so nothing was written.`;throw new ae(I,{...se(e.id,s,[],t,"failure"),error:I},C)}let g=await this.countRun(e,a,y,this.deps.writeGate!==void 0);if(this.deps.writeGate&&"unread"in g){let C=`The records to write could not be counted (${g.unread}), so nothing was written.`+an(g.unread);throw new ae(C,{...se(e.id,s,[],t,"failure"),error:C})}let w=new Map,M=this.standardPricebooksOnce(),A=this.currenciesOnce(),O=y===void 0?new Map:void 0;if(this.deps.writeGate&&"counted"in g){let C;try{C=await this.heldBackOfRun(e,a,c,u,y,S.links,k,M,A,O)}catch(B){let q=B instanceof Error?B.message:String(B);throw new ae(q,{...se(e.id,s,[],t,"failure"),error:q},B)}let I=hi(a,g.counted,k,c,h,C.heldBack,C.matched,S.linked,await this.rolesLinkedAtTheGate(e,a,c,C.heldBack,k,S.links,O),{keys:f,...this.deps.describeTargetFieldsAgain?{typed:l}:{}}),{answer:x}=await this.deps.writeGate.hold(I);if(!x.go)throw m(x.message,x.code);for(let B of I.unwritable??[])w.set(B.objectApiName,B.rows)}let E=this.deps.leaseOfTheGate?.(),F=E&&E.assigned>0?await this.recordTypesReadAgain(a.map(C=>C.objectApiName).filter(C=>l.has(C)&&!w.has(C))):void 0,N=new Map,$=async()=>{let C=E;E=void 0,await C?.giveBack().catch(()=>{});for(let[I,x]of await this.readBackRecordTypes(N))for(let B=r.length-1;B>=0;B--)if(r[B].objectApiName===I){r[B]={...r[B],recordTypeGiven:x};break}},T=new ze(S.links),v=this.recordTypesOnce(),j=new Map,D=Ls(e),_=this.deps.idMap,z={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},H=Promise.resolve(),G,ne=(C,I,x)=>{if(!_)return;let B=ra(C.operation,I,x);for(let[q,Y]of[[B.written,!1],[B.linked,!0]])q.length!==0&&(H=H.then(()=>_.record(e.id,z,C.objectApiName,q,Y).catch(pe=>{G??=pe instanceof Error?pe.message:String(pe)})))},Te=0,Se=(C,I)=>{if(I.length===0)return;this.deps.creations?.deleted?.(C,I),Te+=I.length,T.noteDeleted(I);let x=_?.forget?.bind(_);x&&(H=H.then(()=>x(e.id,z,I).then(()=>{},B=>{G??=B instanceof Error?B.message:String(B)})))},V=this.deps.creations,Re=new Map,ie=0,P=(C,I)=>{if(!V)return;let x=cn(C.operation,I);if(x.length===0)return;let B=C.objectApiName;V.noteUnanswered?V.noteUnanswered(B,x):V.note(B,x),Re.set(B,(Re.get(B)??0)+x.length)},W=(C,I)=>{V&&(V.note(C,[I]),ie++)},Z=!1,he=!1,Be=!1,zi=async C=>{let I=await V?.flush();await H;let x=[];return S.unread!==void 0&&!Be&&(Be=!0,x.push(`What earlier runs of this configuration wrote could not be read (${S.unread}): a lookup at a record one of them wrote went as the source holds it.`)),I!==void 0&&!Z&&(Z=!0,x.push(`What this run created could not all be kept (${I}): removing the run may leave some of it in the target.`)),G!==void 0&&!he&&(he=!0,x.push(`Which record of the target each record this run wrote became could not all be kept (${G}): a later run may send a lookup at one of them as the source holds it.`)),x.length===0?C:{...C,errors:[...C.errors,...x]}},ce=async C=>{r.push(await zi(C))},be=new Map,qi=new Set((d?.cycles??[]).map(C=>C[C.length-1])),bn=(C,I)=>{for(let x=r.length-1;x>=0;x--)if(r[x].objectApiName===C){r[x]=Ko(r[x],I,[...p.get(C)??[]]);return}},Xe=new Map,Ki=(C,I)=>{for(let x=r.length-1;x>=0;x--)if(r[x].objectApiName===C){r[x]={...r[x],errors:[...r[x].errors,I]};return}},It=(C,I,x)=>{for(let B=r.length-1;B>=0;B--){let q=r[B];if(q.objectApiName!==C)continue;if(!q.delta)return;let Y=(q.delta.lookupsOwed??0)+I;r[B]={...q,delta:{...q.delta,...x!==void 0?{recorded:x}:{},...Y>0?{lookupsOwed:Y}:{}}};return}},Hi=async()=>{for(let[C,I]of[...be]){be.delete(C),await this.deps.pauseGate?.whilePaused(this.deps.signal);let x=this.deps.signal?.aborted?{leftOut:Zt(I.pending),unset:Xt(I.pending)}:await this.deps.dataSync.setLookups(I.objectConfig,I.pending,T,!0);"set"in x&&x.set&&V?.touched?.(C,x.set.records),bn(C,x);let B=Xe.get(C);if(Xe.delete(C),x.unset===0){let q=B?.();q!==void 0&&It(C,0,q)}else It(C,x.unset)}},Pt=()=>{for(let[C,I]of[...be])be.delete(C),Xe.delete(C),bn(C,{leftOut:Zt(I.pending)}),It(C,Xt(I.pending))},Ze=C=>{let I=$s(D,C.objectResults.some(Y=>Y.success>0)),x={...C,...R?{files:R.storage}:{},...I?{contactPoints:I}:{}},B=V?.overwrittenCount?.()??0,q=V?.deleted?Te:0;return!V||Re.size===0&&ie===0&&B===0&&q===0?x:{...x,created:{runId:V.runId,objects:[...Re].map(([Y,pe])=>({objectApiName:Y,count:pe})),files:ie,...B>0?{overwritten:B}:{},...q>0?{deleted:q}:{}}}},kn="counted"in g?[...g.counted.values()].reduce((C,{rows:I})=>C+I,0):void 0,Et=this.isGrappeActive(kn);Et&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:s,totalPartitions:a.length,totalRecords:kn}});let On=()=>{if(!Et)return;let C=0,I=0;for(let x of r)C+=x.processed,I+=x.failed;this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:s,totalProcessed:C,totalFailed:I}})},ke=async(C,I)=>(Pt(),await $(),On(),await V?.flush(),await H,Ze(ia(e.id,s,r,t,C,I))),Tt=0;for(let[C,I]of a.entries()){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return ke(a.slice(C));let x=c.get(I.objectApiName),B=w.get(I.objectApiName);if(x&&B!==void 0){let L=na(I,x,B);try{await this.noteLeftOutRefused(e,I,y,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...O?{gateReads:O}:{}},k.get(I.objectApiName))}catch(U){let me=U instanceof Error?U.message:String(U);throw await ce({...L,errors:[...L.errors,me]}),Pt(),new ae(me,Ze(se(e.id,s,r,t,"failure")),U)}await ce(L);continue}let q=new it,{plan:Y,mark:pe}=await this.readPlan(e,I,y),Oe={changedSince:Y?.read==="delta"?Ie(Y.since):void 0,rows:0,cut:!1},Ae=(L,U)=>Y?{...L,delta:je(Y,Oe.rows,U)}:L,Qe=R?.objects.get(I.objectApiName),Mt=Qe?new Map:void 0,Ft;try{Ft=await this.syncObject(e,I,q,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...D?{contactPoints:D}:{},later:p,...F?{recordTypesUnderTheLease:F}:{},createdWithoutRecordType:N,...O?{gateReads:O}:{}},Y?Oe:void 0,Mt,V||_?(L,U)=>{P(I,L),ne(I,L,U)}:void 0,k.get(I.objectApiName),(p.get(I.objectApiName)?.size??0)>0?L=>{let U=be.get(I.objectApiName);U?U.pending.push(...L):be.set(I.objectApiName,{objectConfig:I,pending:L})}:void 0)}catch(L){if(L instanceof Q){let U=Pe(qe(I.objectApiName,I.operation,L.written,L.notes,L.lookupsLeftOut,L.writtenWithoutFields),q);return(U.processed>0||U.skipped>0)&&await ce(Ae(U)),ke(a.slice(C))}throw await ce(Ae(Pe({...kt(I),failed:1,errors:[L instanceof Error?L.message:String(L)]},q))),Pt(),new ae(L instanceof Error?L.message:String(L),Ze(se(e.id,s,r,t,"failure")),L)}if(Ft===ci){let L=Pe(kt(I),q);return L.skipped>0&&await ce(Ae(L)),ke(a.slice(C))}let J=Ft,An=!0;if(Qe&&Mt&&e.files){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await ce(Ae(J)),ke(a.slice(C+1),bi(I));let L=await Js({config:e,option:e.files,objectApiName:I.objectApiName,planned:Qe,written:Mt,deps:this.deps.files,signal:this.deps.signal,waitIfPaused:()=>this.deps.pauseGate?.whilePaused(this.deps.signal)??Promise.resolve(),onCreated:W});if(J={...J,files:L.outcome,errors:[...J.errors,...L.notes]},An=L.outcome.failed===0&&L.outcome.pastRunCap===0&&L.unplanned===0,L.cancelled)return await ce(Ae(J)),ke(a.slice(C+1),bi(I))}let Ce;if(Y?.read==="delta"&&e.propagateDeletes===!0&&Oe.changedSince){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await ce(Ae(J)),ke(a.slice(C));try{Ce=await this.carryDeletions(I,Oe.changedSince,L=>Se(I.objectApiName,L))}catch(L){if(!(L instanceof Q))throw L;let U=qe(I.objectApiName,"delete",L.written);return await ce(Ae({...J,errors:[...J.errors,...U.errors,...L.notes]},{deleted:U.success,deleteFailed:U.failed,notes:[],complete:!1})),ke(a.slice(C))}J={...J,errors:[...J.errors,...Ce.notes]}}let Cn=Oe.lookupsUnset??0,Ji=J.failed===0&&An&&!Oe.cut&&Cn===0&&(Ce===void 0||Ce.deleteFailed===0&&Ce.error===void 0&&Ce.complete),In=(L,U,me)=>{let En=Qe?.filesSeen;try{return this.deps.deltaStore?.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:I.objectApiName,watermark:L,fingerprint:U,recordedAt:new Date().toISOString(),...En!==void 0?{filesSeen:En}:{}}),L}catch(jt){me(`The watermark could not be saved, so the next run reads from the previous one: ${jt instanceof Error?jt.message:String(jt)}`);return}},Pn;if(Y&&pe!==null&&Ji){let{fingerprint:L}=Y,U=I.objectApiName;be.has(U)?Xe.set(U,()=>In(pe,L,me=>Ki(U,me))):Pn=In(pe,L,me=>{J={...J,errors:[...J.errors,me]}})}Y&&(J={...J,delta:je(Y,Oe.rows,Ce,Pn,Cn)}),await ce(J),qi.has(I.objectApiName)&&await Hi(),Et&&(Tt++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`sync-partition-${Tt}`,percentage:Math.round(Tt/a.length*100),processedRecords:J.processed}}))}await $();let Yi=ki(r);return On(),await V?.flush(),await H,Ze(se(e.id,s,r,t,Yi))}async recordTypesReadAgain(e){let t=this.deps.describeTargetFieldsAgain,s=new Map;return t&&await Promise.all(e.map(async r=>{try{s.set(r,(await t(r)).recordTypes??[])}catch{}})),s}async readBackRecordTypes(e){let t=this.deps.queryTargetRows,s=new Map;return await Promise.all([...e].map(async([r,{given:i,types:o,ids:a}])=>{if(!t||a.length===0){s.set(r,i);return}try{let d=await t(cs(r,a));s.set(r,{...i,readBack:ls(d,o)})}catch(d){let c=d instanceof Error?d.message:String(d);s.set(r,{...i,readBack:{read:0,types:[],unread:c}})}})),s}async earlierLinks(e){let t=this.deps.idMap;if(!t)return{};try{let s={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},r=await t.load(e.id,s);if(!r)return{};let i=await t.linked?.(e.id,s);return{links:r,...i!==void 0&&i.size>0?{linked:i}:{}}}catch(s){return{unread:s instanceof Error?s.message:String(s)}}}recordTypesOnce(){let e;return()=>{let t=this.deps.recordTypes;return t?(e??=t().catch(s=>{throw new Error(`The record types of the two orgs could not be read, so none of these records was sent: ${s instanceof Error?s.message:String(s)}`)}),e):Promise.resolve(void 0)}}currenciesOnce(){let e;return()=>{let t=this.deps.currencies;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}standardPricebooksOnce(){let e;return()=>{let t=this.deps.standardPricebooks;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}async pricesSettled(e,t,s){let r=e.objectApiName,i=e.operation!=="delete"&&ut(r,t.sources)?await s.standardPricebooks?.():void 0;i&&s.links.noteMatched(i.source,i.target);let o=i&&r===Me&&t.sources.some(un)?await s.currencies():void 0;return pt(r,t,i,o,a=>s.links.refusedObjectOf(a)!==void 0)}deltaLoadOf(e){if(e.mode==="delta")return!this.deps.deltaStore||!this.deps.deltaReads?null:this.deps.deltaStore.load(e.id)}async readPlan(e,t,s){if(s===void 0)return{plan:null,mark:null};let r=We(e,t,s),i=this.deps.deltaReads;if(!i||r.read==="full"&&r.reason==="not_saved")return{plan:r,mark:null};try{return{plan:r,mark:await i.latestModstamp(t.objectApiName)}}catch{return{plan:{read:"full",reason:"no_modstamp",fingerprint:r.fingerprint},mark:null}}}async carryDeletions(e,t,s){let r=await this.tallyObjectDeletions(e,t);if("error"in r)return{deleted:0,deleteFailed:0,error:r.error,notes:[r.error],complete:!1};let{tally:i,notes:o}=r;if(i.ids.length===0)return{deleted:0,deleteFailed:0,notes:o,complete:!i.truncated};let a={...e,operation:"delete",fieldMappings:[],transformRules:[],addOnFields:[]},d;try{d=await this.deps.dataSync.write(a,i.ids.map(l=>({Id:l})))}catch(l){throw l instanceof Q&&s(pi(i.ids,l.written)),l}s(pi(i.ids,d.outcomes));let c=qe(e.objectApiName,"delete",d.outcomes,d.notes);return{deleted:c.success,deleteFailed:c.failed,notes:[...c.errors,...o],complete:!i.truncated}}async tallyObjectDeletions(e,t){let s=this.deps.deltaReads;if(!s)return{error:"Deletions need the source's recycle bin, and none was given."};let r=Gt(e);if("refused"in r)return{error:r.refused};let i=ot(e.where,t)??"";try{let o=await cr(s,e,r,i,a=>{if(r.sourceField==="Id")return a.Id;let d=this.deps.fieldMapping.apply(a,e.fieldMappings,e.excludedFields);return this.deps.transformPipeline.transformRecord(d,e)[r.keyField]});return{tally:o,notes:lr(o,r.keyField)}}catch(o){if(this.deps.signal?.aborted)throw new Q(e.objectApiName,[]);return{error:`The source's deletions could not be read, so none was carried; the next run looks for them again: ${o instanceof Error?o.message:String(o)}`}}}async countRun(e,t,s,r){let i=this.deps.countSource;if(!r&&!this.deps.grappeConfig?.enabled||!i)return{none:!0};let o=new Map;try{for(let a of t){let d=s===void 0?null:We(e,a,s),c=d?.read==="delta"?{changedSince:Ie(d.since)}:void 0,l=c?await i(e.sourceOrgId,a,c):await i(e.sourceOrgId,a);if(!Number.isFinite(l)||l<0)throw new Error(`the source answered no count of ${a.objectApiName}`);let u=r&&l>0&&this.deps.countPersonAccounts&&ea.has(a.objectApiName.toLowerCase())?await this.deps.countPersonAccounts(a,c):void 0;o.set(a.objectApiName,{rows:l,...u!==void 0&&u>0?{personAccounts:u}:{}})}}catch(a){return{unread:a instanceof Error?a.message:String(a)}}return{counted:o}}async alreadyCopiedOf(e,t,s){let r=new Map,i=this.deps.readSourceIds,o=this.deps.findInTarget;if(!s||s.size===0||!i||!o)return r;for(let a of t){if(a.operation!=="insert")continue;if(this.deps.signal?.aborted)break;let d=new Map;for(let f of await i(a)){let p=s.get(re(f));p!==void 0&&d.set(re(f),p)}if(d.size===0)continue;let c=await o(e.targetOrgId,a,"Id",[...new Set(d.values())]),l=new Set([...c.keys()].map(f=>f.slice(0,15))),u=new Set;for(let[f,p]of d)l.has(p.slice(0,15).toLowerCase())&&u.add(f);u.size>0&&r.set(a.objectApiName,u)}return r}async writeOrderOf(e){let t=this.deps.describeTargetFields,s=new Map,r=new Set,i=new Map;if(!t)return{ordered:[...e].sort((d,c)=>d.insertOrder-c.insertOrder),refused:s,typed:r,lookups:new Map,keys:i};let o=new Map,a=[];for(let d of e){if(d.operation==="delete"){a.push(d);continue}let c=await Ds(t,d.objectApiName,d.operation,d.externalIdField);"refused"in c&&s.set(d.objectApiName,c.refused);let l="target"in c&&c.target?xs(Ns(d,c.target),c.target):d;a.push(l),!("refused"in c)&&(l.operation==="update"||l.operation==="upsert"||l.objectApiName===X)&&i.set(d.objectApiName,Ms(l.operation==="upsert"?l.externalIdField??"Id":"Id","target"in c?c.target:void 0)),"target"in c&&c.target&&(o.set(d.objectApiName,oi(l,c.target)),ue(d.operation)&&(c.target.recordTypes??[]).some(u=>!u.master)&&r.add(d.objectApiName))}return{...ai(a,o),refused:s,typed:r,lookups:o,keys:i}}async heldBackOfRun(e,t,s,r,i,o,a,d,c,l){let u=new Map,f=t.some(h=>ue(h.operation)&&(h.objectApiName===ge||h.objectApiName===Me));return s.size===0&&!f?{heldBack:new Map,matched:u}:{heldBack:await di({ordered:t,lookups:r,leftOut:new Set(s.keys()),...o?{earlier:o}:{},copied:a,standardPricebooks:d,currencies:c,matched:u,read:async h=>{let y=i===void 0?null:We(e,h,i);if(y?.read==="delta")return this.deps.querySource(e.sourceOrgId,h,{changedSince:Ie(y.since)});let m=await this.deps.querySource(e.sourceOrgId,h);return l?.set(h.objectApiName,m),m}}),matched:u}}async rolesLinkedAtTheGate(e,t,s,r,i,o,a){let d=m=>t.find(R=>R.objectApiName===m),c=d(Ee),l=d(X);if(!c||!l||!ue(l.operation))return;if(!this.deps.queryTargetRows||c.excludedFields.includes(oe))return 0;if(!a||c.operation!=="insert")return;let u=m=>m.fieldMappings.length===0&&m.addOnFields.length===0&&m.transformRules.length===0;if(!u(c)||!u(l)||[Ee,X,$t].some(m=>s.has(m)||r.has(m)))return;let p=await this.deps.describeTargetFields?.(Ee).catch(()=>{});if(!p)return;if(!p.creatable.has(oe))return 0;let h=async m=>{let R=a.get(m.objectApiName);if(R)return R;let S=await this.deps.querySource(e.sourceOrgId,m);return a.set(m.objectApiName,S),S},y=m=>typeof m.Id=="string"&&m.Id!==""?m.Id:void 0;try{let m=new Set([...o?.keys()??[]].map(re)),R=d($t);if(R&&ue(R.operation)&&t.indexOf(R)<t.indexOf(c))for(let g of await h(R)){let w=y(g);w&&m.add(re(w))}let S=g=>i.get(g)??new Set,b=new Map;for(let g of await h(c)){let w=y(g),M=g[oe];!w||typeof M!="string"||M===""||S(Ee).has(re(w))||!m.has(re(M))||b.set(re(w),M)}if(b.size===0)return 0;let k=(await h(l)).filter(g=>{let w=y(g);return w!==void 0&&!S(X).has(re(w))});return Bt(k,g=>b.get(re(g))).length}catch{return}}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&e!==void 0&&e>=t.autoActivateThreshold)}async simulate(e){let t=wi(e);if(t!==void 0)throw new Error(t);let s=Si(e);if(s!==void 0)throw new Error(s);let r=Date.now(),i=[],{ordered:o,order:a,refused:d,typed:c,lookups:l,keys:u}=await this.writeOrderOf(e.objects),f,p,h,y=await this.validationRulesOf(o),m=(F={})=>({configId:e.id,operationId:`sync-simulation-${r}`,direction:e.direction,conflictStrategy:e.conflictStrategy,objects:i,duration:Date.now()-r,timestamp:new Date().toISOString(),...f?{files:f.storage}:{},...y.unread!==void 0?{validationRulesUnread:y.unread}:{},...a?{writeOrder:a}:{},...p?{writeCheck:p}:{},...h!==void 0?{writeCheckUnread:h}:{},...F}),R=this.deltaLoadOf(e);try{f=await this.planFiles(e,o,R)}catch(F){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:F instanceof Error?F.message:String(F)})}let S=await this.earlierLinks(e),b=o.filter(F=>F.operation==="insert");if(S.unread!==void 0&&b.length>0)return m({error:gi(S.unread,b)});let k;try{k=await this.alreadyCopiedOf(e,o,S.links)}catch(F){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:F instanceof Error?F.message:String(F)})}let g=this.deps.writeGate,w=this.standardPricebooksOnce(),M=this.currenciesOnce(),A=R===void 0?new Map:void 0,O=g?await this.countRun(e,o,R,!0):void 0;if(g&&O&&"unread"in O&&(h=`${O.unread}${an(O.unread)}`),g&&O&&"counted"in O)try{let F=await this.heldBackOfRun(e,o,d,l,R,S.links,k,w,M,A);p=await g.measure(hi(o,O.counted,k,d,this.deps.queryTargetRows?c:new Set,F.heldBack,F.matched,S.linked,await this.rolesLinkedAtTheGate(e,o,d,F.heldBack,k,S.links,A),{keys:u,typed:c}))}catch(F){h=F instanceof Error?F.message:String(F)}let E={links:new ze(S.links),...S.linked?{earlierLinked:S.linked}:{},recordTypes:this.recordTypesOnce(),currencies:M,currencyChangesById:new Map,standardPricebooks:w,later:ui(a),...A?{gateReads:A}:{}};for(let[F,N]of o.entries()){if(this.deps.signal?.aborted)return m({cancelled:!0});this.deps.onSimulationProgress?.(F,o.length,N.objectApiName);try{let $=await this.simulateObject(e,N,R,E,k.get(N.objectApiName),d.get(N.objectApiName)),T=f?.objects.get(N.objectApiName),{rules:v,onChange:j}=Go(N.operation,y.byObject.get(N.objectApiName)??[]),D=[...$.notes,...T?.notes??[],...j.length>0?[Uo(j)]:[]];i.push({...$,...T?{files:T.outcome}:{},notes:D,...v.length>0?{validationRules:v}:{}})}catch($){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:$ instanceof Error?$.message:String($),failedObject:N.objectApiName})}}if(p){let F=new Set([...p.objects.map(G=>G.objectApiName),...(p.rolesLinked??0)>0?[X]:[]]),N=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.operation==="delete"?ne.delete:ne.insert+ne.update),0),$={...p};delete $.rolesByThePlatform,delete $.rolesLinked;let T=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.writtenByThePlatform??0),0),v=(p.rolesLinked??0)-T,j=p.total+v,D=j-N,_={objectApiName:X,rows:0},z=$.objects.some(G=>G.objectApiName===X)?$.objects:[...$.objects,_],H=j>0&&N===0;p={...$,objects:z.map(G=>G.objectApiName===X?{...G,rows:Math.max(0,G.rows+v)}:G).filter(G=>G.rows>0),total:j,...T>0?{rolesLinked:T}:{},...D>0?{notWritten:D}:{},...H?{total:0}:{},...H&&$.verdict==="writes"?{verdict:"nothing"}:{}}}return m()}async validationRulesOf(e){let t=this.deps.readValidationRules,s=e.filter(i=>i.operation!=="delete").map(i=>i.objectApiName),r=new Map;if(!t||s.length===0)return{byObject:r};try{for(let{objectApiName:i,...o}of await t(s))r.set(i,[...r.get(i)??[],o]);return{byObject:r}}catch(i){return{byObject:r,unread:i instanceof Error?i.message:String(i)}}}async simulateObject(e,t,s,r,i,o){let a=this.deps.findInTarget;if(!a)throw new Error("A simulation needs to look records up in the target org.");let d=new it,{plan:c}=await this.readPlan(e,t,s),l={changedSince:c?.read==="delta"?Ie(c.since):void 0,rows:0,cut:!1},u=await this.prepare(e,t,d,c?l:void 0,i,r.gateReads,r.earlierLinked),f=u.records.length>0?await this.pricesSettled(t,u,r):void 0,p=f?{...u,...f}:u;if(o&&p.records.length>0){mi(r.links,t,p.sources);let P=f?bt(r.links,t,f.standsFor):[];return fi({objectApiName:t.objectApiName,operation:t.operation,read:p.read,insert:0,update:0,delete:0,skipped:p.alreadyCopied,...pn(p),refused:p.records.length+P.length,conflicts:0,conflictFields:[],notes:[o.message]},p)}let h=Yo(t,p,r.links),y=h.prepared,m=null;if(y.records.length>0&&this.deps.describeTargetFields)try{let P=await this.deps.describeTargetFields(t.objectApiName);m=P.creatable.size>0?P:null}catch{m=null}let R=await li(r,y.records,y.sources,t.objectApiName),S=vs({config:{...t,fieldMappings:[],addOnFields:[]},records:y.records,target:m,run:R}),b=S.sentAt.map(P=>y.records[P]),k=Xn(t),g=new Map;if(k!==null){let P=new Map;for(let W of b){let Z=W[k],he=Fe(Z);he!==null&&P.set(he,Z)}P.size>0&&(g=await a(e.targetOrgId,t,k,[...P.values()]))}let w=b.map(P=>Qn(t,P,g)),M=t.operation==="upsert"&&k!==null&&k.toLowerCase()!=="id"?tr(k,b.map(P=>Fe(P[k])),w,er(b.length,t.batchSize,this.deps.bulkThreshold??fe.REST_API_BATCH_SIZE)):void 0;for(let P of M?.updated??[])w[P]="update";let A=w.flatMap((P,W)=>(P==="insert"||P==="update")&&M?.refused.has(W)!==!0?[W]:[]),O=m?.fields!==void 0&&A.length>0?rr(t.objectApiName,A.map(P=>({payload:S.payloads[P],source:y.sources[S.sentAt[P]]??{},creates:w[P]==="insert"})),m.fields):{refused:new Set,notes:[],refusedFor:[]},E=new Set([...[...O.refused].map(P=>A[P]),...M?.refused??[]]),F=await this.lookupsTheTargetLacks(A.filter(P=>!E.has(P)),S.payloads,S.settled,m),N=Vo(F,w,m);for(let P of N.refused)E.add(P);let $=A.filter(P=>w[P]==="insert"&&!E.has(P)),T=t.operation==="insert"?(m?.fields??[]).filter(P=>P.unique===!0&&P.createable):[],v=new Map;for(let P of T){let W=new Map;for(let Z of $){let he=S.payloads[Z][P.name],Be=Fe(he);Be!==null&&W.set(Be,he)}W.size!==0&&v.set(P.name,await a(e.targetOrgId,t,P.name,[...W.values()]))}let j=sr($.map(P=>S.payloads[P]),v);for(let P of j.refused)E.add($[P]);let D=new Set([...j.linked].map(P=>$[P])),_=b.flatMap((P,W)=>E.has(W)||D.has(W)?[]:[W]),z=new Set(_.map(P=>S.sentAt[P])),H=y.unsettled.filter((P,W)=>z.has(W)),G=nr({objectConfig:t,read:y.read,records:_.map(P=>b[P]),leftOut:d.counts(t.objectApiName),inTarget:g,simulated:_.map(P=>w[P]),conflicts:y.conflicts,unsettled:H,matchField:y.matchField,writable:m?.creatable??null}),ne=t.operation==="insert"||t.operation==="upsert",Te=P=>{let W=y.sources[P]?.Id;return typeof W=="string"&&W!==""?W:void 0},Se=[];if(t.operation!=="delete"){for(let{index:P}of S.held){let W=Te(P);W&&ne&&r.links.noteRefused(W,t.objectApiName)}if(S.sentAt.forEach((P,W)=>{let Z=Te(P);Z&&(E.has(W)||Zn.has(w[W])?ne&&r.links.noteRefused(Z,t.objectApiName):r.links.noteWritten(Z,Z))}),t.objectApiName===Ee&&ne)for(let P of _){let W=Te(S.sentAt[P]),Z=S.payloads[P]?.[oe];w[P]!=="insert"||!W||typeof Z!="string"||Z===""||r.links.noteSentWithContact(W,Z)}f&&(Se=bt(r.links,t,f.standsFor))}let V=Fs(t.objectApiName,_.flatMap(P=>{let W=w[P]==="insert"?S.withoutRecordType.get(S.sentAt[P]):void 0;return W?[W]:[]}),js(m?.recordTypes??[],R.recordTypes)),Re=[...M?.refusedFor??[],...O.refusedFor,...j.refusedFor],ie={...G,skipped:G.skipped+D.size+y.alreadyCopied+h.linked,...pn(y),...h.linked>0?{writtenByThePlatform:h.linked}:{},...y.encryptedLeftOut?{encryptedLeftOut:[...y.encryptedLeftOut]}:{},...V?{recordTypeGiven:V}:{},refused:G.refused+S.held.length+E.size+Se.length,...Re.length>0?{refusedFor:Re}:{},notes:[...f?.standardMatched?[Ws]:[],...us(f?Qt(f,Se):[]).map(P=>`${P}.`),...h.linked>0?[Xo(h.linked)]:[],...G.notes,...M?.notes??[],...S.notes,...Se.length>0?[en(t.objectApiName,Se.length)]:[],...S.currencies.map(P=>`${Vn(P)}.`),...O.notes,...N.notes,...j.notes]};if(!c)return ie;if(c.read==="delta"&&e.propagateDeletes===!0&&l.changedSince){let P=await this.tallyObjectDeletions(t,l.changedSince);if("error"in P)return{...ie,notes:[...ie.notes,P.error],delta:je(c,l.rows,{deleted:0,deleteFailed:0,error:P.error})};let W=P.tally.ids.length;return{...ie,delete:ie.delete+W,notes:[...ie.notes,...P.notes],delta:je(c,l.rows,{deleted:W,deleteFailed:0})}}return{...ie,delta:je(c,l.rows)}}async lookupsTheTargetLacks(e,t,s,r){let i=this.deps.queryTargetRows,o=new Map;if(!i||!r?.fields||r.references.size===0)return o;let a=new Map,d=new Map;for(let u of e){let f=t[u]??{},p=[];for(let[h,y]of Object.entries(f)){if(h==="RecordTypeId"||!r.references.has(h)||s[u]?.has(h)||typeof y!="string"||!Jo.test(y))continue;p.push({field:h,id:y});let m=r.fields.find(R=>R.name===h)?.referenceTo??[];for(let R of m)d.set(R,(d.get(R)??new Set).add(y))}p.length>0&&a.set(u,p)}if(a.size===0)return o;let c=new Set,l=new Set;for(let[u,f]of d){let p=[...f];for(let[h,y]of ee(p,ln).entries())try{let m=await i(`SELECT Id FROM ${ye(u)} WHERE Id IN (${y})`);for(let R of m){let S=R.Id;typeof S=="string"&&c.add(S.slice(0,15))}}catch{let m=h*ln;for(let R of p.slice(m,m+ln))l.add(R.slice(0,15))}}for(let[u,f]of a)f.some(({id:h})=>!c.has(h.slice(0,15))&&!l.has(h.slice(0,15)))&&o.set(u,f.map(({field:h})=>h).sort());return o}async noteLeftOutRefused(e,t,s,r,i){if(!ue(t.operation))return;let{plan:o}=await this.readPlan(e,t,s),a={changedSince:o?.read==="delta"?Ie(o.since):void 0,rows:0,cut:!1},d=await this.prepare(e,t,new it,o?a:void 0,i,r.gateReads,r.earlierLinked);if(d.records.length===0)return;let c=await this.pricesSettled(t,d,r);mi(r.links,t,c.sources),bt(r.links,t,c.standsFor)}async syncObject(e,t,s,r,i,o,a,d,c){let l=await this.prepare(e,t,s,i,d,r.gateReads,r.earlierLinked),u=await this.rolesWrittenWithTheirOpportunity(t,l,r,a),f=u.prepared,p=w=>Ho(fi(Zo(w,f),f),u.said);if(f.records.length===0)return p(Pe(kt(t),s));let h=await this.pricesSettled(t,f,r),{records:y,sourceIds:m,sources:R}=h;if(y.length===0)return p(Pe(tn(kt(t),h),s));let S={...await li(r,y,R,t.objectApiName),...h.standardFirst>0?{standardFirst:h.standardFirst}:{}},b=()=>bt(r.links,t,h.standsFor);if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return ci;if(o||a||c||i){let w=M=>{M.forEach((A,O)=>{let E=m[O];o&&A.success&&A.id&&E&&o.set(E,A.id)}),a?.(M,m)};try{let{outcomes:M,notes:A,currencies:O,lookupsLeftOut:E,writtenWithoutFields:F,lookupsToSet:N,lookupsUnset:$}=await this.deps.dataSync.write({...t,fieldMappings:[],addOnFields:[]},y,S);i&&$!==void 0&&(i.lookupsUnset=$),w(M);let T=b();return N&&c?.(N),p(Pe(yi(_s(qe(t.objectApiName,t.operation,M,A,E,F),O),h,T),s))}catch(M){throw M instanceof Q&&w(M.written),M}}let k=await this.deps.dataSync.sync({...t,fieldMappings:[],addOnFields:[]},y,S),g=b();return p(Pe(yi(k,h,g),s))}async rolesWrittenWithTheirOpportunity(e,t,s,r){let i=this.deps.queryTargetRows;if(e.objectApiName!==X||e.operation!=="insert"&&e.operation!=="upsert"||!i||!s.links.sentWithAContact||t.records.length===0)return{prepared:t};let o=g=>typeof g=="string"&&g!==""?s.links.targetOf(g):void 0,a=t.records.map((g,w)=>({OpportunityId:o(g.OpportunityId),[oe]:o(g[oe]),IsPrimary:t.sources[w]?.IsPrimary??g.IsPrimary})),d=await this.deps.describeTargetFields?.(X).catch(()=>{}),c=g=>g!=="Id"&&g!=="OpportunityId"&&g!==oe&&(d?.creatable.has(g)??!0),l=[...new Set(t.records.flatMap(g=>Object.keys(g)))].filter(c),u;try{u=await Hn(async g=>await i(g),a,g=>s.links.contactSentWith(g),l)}catch(g){return{prepared:t,said:{records:0,given:0,unread:g instanceof Error?g.message:String(g)}}}let{found:f,alike:p}=u;for(let g of p)s.links.roleLinkedFor(String(a[g].OpportunityId));let h=p.length>0?{alike:p.length}:{};if(f.size===0)return p.length>0?{prepared:t,said:{records:0,given:0,...h}}:{prepared:t};let y=[];for(let[g,w]of f){let M=Object.entries(t.records[g]??{}).filter(([A,O])=>c(A)&&O!==null&&O!==void 0&&String(w[A]??"")!==String(O));M.length>0&&y.push({Id:String(w.Id),...Object.fromEntries(M)})}let m=0,R;if(y.length>0)try{let g=await this.deps.dataSync.updateRecords(X,y,e.batchSize);y.forEach((w,M)=>{let A=g[M];A?.success?m++:R??=`${String(w.Id)}: ${A?.errors[0]??"not updated"}`})}catch(g){R=g instanceof Error?g.message:String(g)}let S=[],b=[];for(let[g,w]of f){let M=t.sourceIds[g],A=String(w.Id);s.links.roleLinkedFor(String(a[g].OpportunityId)),M!==void 0&&(s.links.noteWritten(M,A),S.push(M),b.push({success:!1,errors:[],existingId:A}))}r?.(b,S);let k=(g,w)=>!f.has(w);return{prepared:{...t,records:t.records.filter(k),sourceIds:t.sourceIds.filter(k),sources:t.sources.filter(k)},said:{records:f.size,given:m,...R!==void 0?{refusal:R}:{},...h}}}async prepare(e,t,s,r,i,o,a){let d=r?void 0:o?.get(t.objectApiName);d&&o?.delete(t.objectApiName);let c=r?await this.deps.querySource(e.sourceOrgId,t,{changedSince:r.changedSince,onBoundReached:()=>{r.cut=!0}}):d??await this.deps.querySource(e.sourceOrgId,t);r&&(r.rows=c.length);let l=t.externalIdField??"Id",u=this.deps.maskedSourceFields,p=(c.length>0&&u?await u(t.objectApiName).catch(()=>[]):[]).filter(O=>c.some(E=>Object.prototype.hasOwnProperty.call(E,O)));for(let O of c)for(let E of p)delete O[E];let h=p.length>0?{encryptedLeftOut:p}:{},y=t.operation==="insert"||t.operation==="upsert",m=y?s.keep(t.objectApiName,c):c,R=i&&i.size>0&&t.operation==="insert"?m.filter(O=>!(typeof O.Id=="string"&&i.has(re(O.Id)))):m,S=m.length-R.length,b=S>0&&a&&a.size>0?m.filter(O=>typeof O.Id=="string"&&i?.has(re(O.Id))===!0&&a.has(re(O.Id))).length:0;if(R.length===0)return{read:c.length,records:[],sourceIds:[],sources:[],conflicts:[],unsettled:[],matchField:l,alreadyCopied:S,alreadyLinked:b,...h};let g=R.map(O=>{let E=this.deps.fieldMapping.apply(O,t.fieldMappings,t.excludedFields);return this.deps.transformPipeline.transformRecord(E,t)}).map(O=>{let E=this.deps.fieldMapping.applyAddOns(O,t.addOnFields);return y?sa(t.objectApiName,E):E}),w=g,M=[],A=t.operation==="upsert"||t.operation==="update";if(e.direction==="bidirectional"&&A){let O=await this.deps.queryTarget(e.targetOrgId,t);for(let E of O)for(let F of p)delete E[F];if(M=this.deps.conflictResolver.detectConflicts(g,O,l),M.length>0){let E=this.deps.conflictResolver.resolve(M,e.conflictStrategy),F=new Map(E.map(N=>[N.recordId,N.resolvedValues]));w=g.map(N=>{let $=String(N[l]??""),T=F.get($);return T?{...N,...T}:N})}}return{read:c.length,records:w,sourceIds:R.map(O=>typeof O.Id=="string"?O.Id:void 0),sources:R,conflicts:M,unsettled:g,matchField:l,alreadyCopied:S,alreadyLinked:b,...h}}async planFiles(e,t,s){let r=e.files;if(!r)return;let i=this.deps.files;if(!i)throw new le("This session cannot copy files: it reads no file content or file storage. Nothing was read or written.");return Ys({config:e,option:r,deps:i,tie:(o,a)=>this.tieToTarget(e,o,a),objects:t.map(o=>{let a=s===void 0?null:We(e,o,s);return{objectConfig:o,...a?.read==="delta"?{changedSince:Ie(a.since),...a.filesSeen!==void 0?{filesSeen:a.filesSeen}:{}}:{}}})})}async tieToTarget(e,t,s){let r=this.deps.deltaReads,i=this.deps.files;if(!r||!i)return{held:new Map,refused:"the target cannot be asked"};let o=Gt(t);if("refused"in o)return{held:new Map,refused:o.refused};let a=t.objectApiName,d=new Map;if(o.sourceField==="Id")for(let u of s)d.set(u,u);else{let u=rt(a),f=ye(o.sourceField);for(let p of ee(s)){let h=await i.copy.queryRecords(e.sourceOrgId,`SELECT Id, ${f} FROM ${u} WHERE Id IN (${p})`);for(let y of h){let m=this.deps.fieldMapping.apply(y,t.fieldMappings,t.excludedFields),R=this.deps.transformPipeline.transformRecord(m,t)[o.keyField];typeof y.Id=="string"&&Fe(R)!==null&&d.set(y.Id,R)}}}if(d.size===0)return{held:new Map};let c=await r.targetIdsByKey(a,o.keyField,[...new Set(d.values())]),l=new Map;for(let[u,f]of d){let p=c.get(Fe(f))??[];p.length===1&&l.set(u,p[0])}return{held:l}}};function ra(n,e,t){let s=[],r=[];return n!=="insert"&&n!=="upsert"?{written:s,linked:r}:(e.forEach((i,o)=>{let a=t[o];if(a===void 0)return;if(i.success&&typeof i.id=="string"&&i.id!==""){s.push([a,i.id]);return}let d=Bs(n,i);d!==void 0&&r.push([a,d])}),{written:s,linked:r})}function sa(n,e){let t=qn(n,e);if(t.length===0)return e;let s={...e};for(let r of t)delete s[r];return s}function Pe(n,e){let t=e.counts();return t.length===0?n:{...n,skipped:n.skipped+t.reduce((s,{count:r})=>s+r,0),errors:[...n.errors,...t.map(({why:s,count:r})=>zn(r,s))]}}function kt(n){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:0,conflictCount:0,errors:[]}}function ia(n,e,t,s,r,i){let o=ki(t)==="failure"?"failure":"partial",a=r.map(c=>c.objectApiName),d=a.length>0?`Cancelled before ${a.join(", ")} ${a.length===1?"was":"were"} synced.`:"Cancelled.";return{...se(n,e,t,s,o),cancelled:!0,error:i?`${i} ${a.length>0?d:""}`.trim():d}}function bi(n){return`Cancelled while the files of ${n.objectApiName} were copied: those copied stay in the target, the others are copied by the next run.`}function ki(n){return n.length===0?"success":n.every(s=>s.failed>0&&s.success===0)?"failure":n.some(s=>s.failed>0||oa(s.delta)||(s.files?.failed??0)>0)?"partial":"success"}function oa(n){return n!==void 0&&(n.deleteFailed>0||n.deletionError!==void 0)}function se(n,e,t,s,r){let i=0,o=0,a=0,d=0;for(let c of t)i+=c.processed,o+=c.success,a+=c.failed,d+=c.skipped;return{configId:n,operationId:e,status:r,objectResults:t,totalProcessed:i,totalSuccess:o,totalFailed:a,totalSkipped:d,duration:Date.now()-s,timestamp:new Date().toISOString()}}var aa=2;async function Oi(n,e,t,s,r=()=>!1){let i=t.rows;if(!i||i.length!==e.length||t.stopped)return{result:t,unsent:[]};let o=[...i],a=[...e],d=e.map(()=>[]),c=[],l=!1;for(let f=0;f<aa&&!r();f++){let p=[],h=[],y=[];if(o.forEach((S,b)=>{if(S.id)return;let k=Nr(S.errorDetails,a[b],void 0);!k||k.some(({field:g})=>s.has(g))||(p.push(b),h.push(xr(a[b],k)),y.push(k))}),p.length===0)break;let m;try{m=await n(h)}catch(S){let b=[...new Set(y.flat().map(({field:k})=>k))].sort();c.push(`${p.length} record(s) refused on ${b.join(", ")} could not be written again without ${b.length===1?"it":"them"}: ${K(S)}`);break}if(da(m,h.length).forEach((S,b)=>{let k=p[b];o[k]=S,a[k]=h[b],d[k].push(...y[b])}),m.stopped){l=!0;break}}let u;return o.forEach((f,p)=>{!f.id||d[p].length===0||(u=Ue(u,{rows:1,fields:d[p].map(h=>({...h,rows:1}))}))}),{result:{successIds:o.flatMap(f=>f.id?[f.id]:[]),errors:o.flatMap(f=>f.id?[]:[f.error??"Unknown insert error"]),rows:o,...l?{stopped:!0}:{}},...u?{written:u}:{},unsent:c}}function da(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(r=>({id:r})),...n.errors.map(r=>({error:r}))];return(e===1?t:t.map(r=>({...r,unmatched:!0}))).slice(0,e)}var ca=1e4,la=5e5,hn=200;function At(n){let e=Math.floor(la/Math.max(1,n.fieldRules.length));return Math.max(hn,Math.min(ca,e))}var Ai=class{deps;constructor(e){this.deps=e}async execute(e,t,s){let r=s??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return Ti(e.id,r,o.errors.map(l=>l.message),this.deps.now());let a=await Us(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return Ti(e.id,r,a,this.deps.now());let d=e.objects.reduce((l,u)=>l+u.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,r,i):this.executeSequential(e,t,r,i)}preview(e){return this.deps.planBuilder.build(e)}shouldActivateGrappe(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}reportProgress(e,t,s,r=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,r);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:s,percentage:Math.round(i/Math.max(s,1)*100)})}async executeSequential(e,t,s,r){let i=Ci(e,this.platformRolesOf(t),this.deps.onRowIds),o=this.deps.referenceLinker.resolveInsertOrder(e.objects,i.relations),a=e.objects.reduce((d,c)=>d+c.recordCount,0);for(let d of o){if(this.deps.signal?.aborted)return this.stoppedResult(e,s,i,r);let c=await this.readyToWrite(d,i,a);if(!c)continue;let l={},u={successIds:[],errors:[]},f={result:u,unsent:[]},p=Ii(c),h=0,y=0,m=!1,R=At(c.config);for await(let S of this.slicesOf(c,i,R,l)){if(this.deps.signal?.aborted){m=!0;break}h>0&&this.reportProgress(d.objectApiName,i.objectResults,a,u.successIds.length+u.errors.length);let b=await this.insert(t,d,S,c,i);if(h++,Pi(p,c.config.rows,y,S.length,b.result),y+=S.length,ka(f,b),b.result.stopped){m=!0;break}}if(h>0&&Ot(i,d,gn(u,c),[...c.notes,...fn(f)],l,p),m)return this.stoppedResult(e,s,i,r)}return this.ended(e,s,i,r)}async ended(e,t,s,r){let i,o=!1;try{i=await this.deps.knowledge?.({ids:ga(s),results:s.objectResults})}catch(l){o=!0,i={skipped:`The articles were neither published nor linked: ${K(l)}`}}let a=Ei(e.id,t,s.objectResults,r,this.deps.now());if(!i)return a;let d=o||[i.publish,i.links].some(l=>(l?.notDone.length??0)>0),c=this.deps.signal?.aborted===!0;return{...a,knowledge:i,...(d||c)&&a.status==="success"?{status:"partial"}:{},...c?{cancelled:!0}:{}}}async readyToWrite(e,t,s){let r=Dt(e.objectApiName,t.relations),i=jn(e,t.relations).filter(m=>t.wroteNothing.has(m));if(i.length>0)return Ve(t,e.objectApiName,`Skipped: ${i.join(", ")} wrote no records, so there is nothing for ${e.objectApiName} to point at.`);let o=await this.closedObject(e.objectApiName);if(o)return Ve(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,s);let a=vi(e,r),{config:d,dropped:c}=await Mi(a,this.deps.describeCreateableFields),l=await this.whyDropped(e.objectApiName,c),u=m=>m.fieldRules.length===0&&mn(m.rows).length===0;if(u(d)&&!u(a))return Ve(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${l.join("; ")}).`);let{config:f,filled:p}=await Fi(await this.withTheOrgsPicklistValues(d),r,this.deps.describeRequiredFields),h=await this.matchStandardPricebook(f,t);if(h)return Ve(t,e.objectApiName,h);let y;if(r){let m=await this.placeChildren(f,r,t);if("skipped"in m)return Ve(t,e.objectApiName,m.skipped);if(m.parentIds.length===0&&m.unwritten){let{lines:R,keys:S}=m.unwritten;return Ot(t,e,{successIds:[],errors:R},[],{},S),null}y=m}return{relation:r,config:y?{...f,recordCount:y.parentIds.length,...y.rows?{rows:y.rows}:{}}:f,placed:y,...f.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...l.map(m=>`Written without ${m}.`),...p.length>0?[`Written with ${p.join(", ")}, which this org requires and the template names no rule for.`]:[],...y?.notes??[]]}}async placeChildren(e,t,s){let{childObject:r,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(r,i))return{skipped:`Skipped: this org does not let a seed write ${r}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return fa(e.rows??[],t,s.keys.get(o));let a=s.existingIds,d;if(t.parents.kind==="generated")d=a.get(o)??[];else if(t.parents.kind==="records")d=[...t.parents.ids];else{let f=this.deps.readExistingParentIds;if(!f)return{skipped:`Skipped: this run cannot read the ${o} records already in the org, so ${r} has nothing to point at.`};try{d=await f(o,t.parents.where,t.parents.limit)}catch(p){return{skipped:`Skipped: reading the ${o} records already in the org failed (${K(p)}), so ${r} has nothing to point at.`}}}if(d.length===0){let f=t.parents.kind==="existing"?t.parents.where?.trim():"";return{skipped:`Skipped: ${t.parents.kind==="generated"?`${o} wrote no records`:`no ${o} record in the org matches ${f?`"${f}"`:"the relation"}`}, so there is nothing for ${r} to point at.`}}let c=Fn(t.distribution,d.length,this.deps.random),l=c.reduce((f,p)=>f+p,0),u=[];for(let[f,p]of c.entries())for(let h=0;h<p&&u.length<e.recordCount;h++)u.push(d[f]);return u.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${r}.`}:{parentIds:u,notes:l>u.length?[`Stopped at ${u.length} ${r} records, the most the template asks for: the relation spreads ${l} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,s,r){let i=e.config.recordCount,o=Math.max(1,Math.floor(s)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),c=wa(e.config,e.relation)?Sa(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,l=>{r.aiFallback=ba(r.aiFallback,l)},a,e.lengths);Ra(c,e.relation,e.placed,a),yield c,a+=d}while(a<i)}async insert(e,t,s,r,i){let o=f=>this.deps.insert(e,t.objectApiName,f,t.batchSize),a=t.objectApiName===X?await i.platformRoles.link(s):new Map,d=a.size>0?s.filter((f,p)=>!a.has(p)):s,c=d.length===0&&s.length>0?{successIds:[],errors:[],rows:[]}:await o(d),l=await Oi(o,d,c,ua(r),()=>this.deps.signal?.aborted===!0);t.objectApiName===zs&&i.platformRoles.opportunitiesWritten(d,l.result);let u=a.size>0?ha(l,s.length,a):l;return c.notes&&c.notes.length>0?{...u,notes:c.notes}:u}platformRolesOf(e){return new qs({orgId:e,readTarget:this.deps.readTarget,update:this.deps.update,stopped:()=>this.deps.signal?.aborted===!0})}async closedObject(e){if(!this.deps.objectAccess)return;let t;try{t=await this.deps.objectAccess(e)}catch{return}if(t.access==="createable")return;let s=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${s}.`:`Skipped: the user this seed runs as may not create ${e} records${s}`+(t.reason?".":`: give that user Create on ${e} in a permission set.`)}async withTheOrgsPicklistValues(e){if(!this.deps.describePicklistValues||!e.fieldRules.some(i=>i.ruleType==="picklist_random"))return e;let t;try{t=await this.deps.describePicklistValues(e.objectApiName)}catch{return e}let s=!1,r=e.fieldRules.map(i=>{let o=t.get(i.fieldApiName),a=i.config.picklistValues;if(i.ruleType!=="picklist_random"||!o?.length||!a)return i;let d=a.filter(c=>o.includes(c));return d.length===a.length?i:(s=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return s?{...e,fieldRules:r}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>nt(o,t.written))||t.existingIds.has(ge))return;let s=this.deps.readExistingParentIds,r=`${e.objectApiName} points at the org's standard price book`;if(!s)return`Skipped: ${r}, and this run cannot read it.`;let i;try{i=await s(ge,"IsStandard = true",1)}catch(o){return`Skipped: ${r}, and reading it failed (${K(o)}).`}if(i.length===0)return`Skipped: ${r}, and the org shows this user no standard price book (Pricebook2): give that user Read on Price Books in a permission set.`;t.existingIds.set(ge,i)}async orgTakesField(e,t){if(!this.deps.describeCreateableFields)return!0;try{return(await this.deps.describeCreateableFields(e)).has(t)}catch{return!0}}async whyDropped(e,t){if(t.length===0)return[];let s=new Set;try{this.deps.describeVisibleFields&&(s=await this.deps.describeVisibleFields(e))}catch{}let r;try{this.deps.describeComputedFields&&(r=await this.deps.describeComputedFields(e))}catch{}let i=t.filter(c=>s.has(c)&&r?.has(c)===!0),o=t.filter(c=>s.has(c)&&r?.has(c)!==!0),a=t.filter(c=>!s.has(c)),d=(c,l,u)=>c.length===1?l:u;return[...a.length>0?[`${a.join(", ")}: this org does not have ${d(a,"that field","those fields")}, or field-level security hides ${d(a,"it","them")} from the user SandForge connects as`]:[],...i.length>0?[`${i.join(", ")}: ${d(i,"a formula or auto-number field","formula or auto-number fields")}, which the org fills itself and no user sets: take ${d(i,"its rule","their rules")} out of the template`]:[],...o.length>0?[`${o.join(", ")}: ${d(o,"it exists","they exist")}, but the user SandForge connects as may not set ${d(o,"it","them")}`+(r!==void 0?`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set)`:`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set), unless it is a formula or auto-number field, whose rule comes out of the template`)]:[]]}async fieldLengths(e){if(!this.deps.describeFieldLengths)return new Map;try{return await this.deps.describeFieldLengths(e)}catch{return new Map}}async executeWithGrappe(e,t,s,r){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((y,m)=>y+m.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:s,totalPartitions:o.length,totalRecords:a}});let d=Ci(e,this.platformRolesOf(t),this.deps.onRowIds),c=this.deps.referenceLinker.resolveInsertOrder(e.objects,d.relations),l=[],u=0,f=this.deps.grappeConfig?.grappeSize??2e3,p=()=>{let y=d.objectResults.reduce((R,S)=>R+S.recordsCreated,0),m=d.objectResults.reduce((R,S)=>R+S.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:s,totalProcessed:y,totalFailed:m}})},h=()=>(p(),this.stoppedResult(e,s,d,r));for(let y of c){if(this.deps.signal?.aborted)return h();let m=Math.ceil(y.recordCount/f),R=await this.readyToWrite(y,d,a);if(!R){u=this.settleUnusedPartitions(o,u,m,0);continue}let S={},b=Math.max(1,Math.ceil(R.config.recordCount/f)),k=0,g=0,w=[],M=[],A={result:{successIds:[],errors:[]},unsent:[]},O,E=Ii(R),F=0,N=-1;for await(let $ of this.slicesOf(R,d,f,S)){if(N++,this.deps.signal?.aborted){O=N;break}N>0&&this.reportProgress(y.objectApiName,d.objectResults,a,k+g);let T=Date.now(),v=o[u]?.id??this.deps.generateId(),j=await this.insert(t,y,$,R,d),D=j.result;Pi(E,R.config.rows,F,$.length,D),F+=$.length,j.written&&(A.written=Ue(A.written,j.written)),A.unsent.push(...j.unsent);for(let z of j.notes??[])(A.notes??[]).includes(z)||(A.notes=[...A.notes??[],z]);k+=D.successIds.length,g+=D.errors.length,w.push(...D.errors),M.push(...D.successIds),l.push({grappeId:v,status:D.errors.length===0?"success":D.successIds.length>0?"partial":"failure",processedRecords:$.length,successCount:D.successIds.length,failureCount:D.errors.length,errors:D.errors,duration:Date.now()-T}),u++;let _=Math.round(u/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:v,percentage:_,processedRecords:k+g}}),D.stopped){O=N+1;break}}if(O!==void 0)return O>0&&Ot(d,y,gn({successIds:M,errors:w},R),[...R.notes,...fn(A)],S,E),h();u=this.settleUnusedPartitions(o,u,m-b,k+g),Ot(d,y,gn({successIds:M,errors:w},R),[...R.notes,...fn(A)],S,E)}return p(),this.ended(e,s,d,r)}stoppedResult(e,t,s,r){let i=Ei(e.id,t,s.objectResults,r,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,s,r){let i=t;for(let o=s;o>0;o--){let a=e[i]?.id??this.deps.generateId();i++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:a,percentage:Math.round(i/Math.max(e.length,1)*100),processedRecords:r}})}return i}};function Ci(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(s=>s.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function ua(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function fn(n){return[...n.notes??[],...n.written?[Dr(n.written)]:[],...n.unsent]}function Ve(n,e,t,s=!1){let r=Oa(e,t);return n.objectResults.push(s?{...r,optional:!0}:r),n.wroteNothing.add(e),null}function Ot(n,e,t,s,r,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,pa(i)));let o=n.platformRoles.resultOf(e.objectApiName),a=[...t.successIds,...o.linkedIds];n.existingIds.set(e.objectApiName,a),e.recordCount>0&&a.length===0&&n.wroteNothing.add(e.objectApiName),n.objectResults.push({objectApiName:e.objectApiName,recordsCreated:t.successIds.length,recordsFailed:t.errors.length,createdIds:t.successIds,errors:[...t.errors,...s,...o.notes],...r,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function pa(n){let e={};for(let[t,s]of n)"id"in s&&(e[t]=s.id);return e}function fa(n,e,t){let{childObject:s,parentObject:r}=e;if(!t)return{skipped:`Skipped: ${s} is placed by key, and ${r} wrote no rows to place it under.`};let i=[],o=[],a=[],d=new Map;for(let c of n){let l=c.parentKey,u=l===void 0?void 0:t.get(l);if(u&&"id"in u){i.push(u.id),o.push(c);continue}let f=l===void 0?`it names no ${r} row`:`its ${r} ${l} ${u?u.why:`is no ${r} row this run wrote`}`;a.push(`${s} ${c.key} not written: ${f}.`),d.set(c.key,{why:`was not written, as ${f}`})}return{parentIds:i,notes:[],rows:o,unwritten:{lines:a,keys:d}}}function ga(n){let e=new Map;for(let[t,s]of n.keys){let r=new Map;for(let[i,o]of s)"id"in o&&r.set(i,o.id);e.set(t,r)}return e}function Ii(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function Pi(n,e,t,s,r){if(!n||!e)return;let i=r.rows&&(r.rows.length===s||r.stopped)?r.rows:void 0;for(let o=0;o<s;o++){let a=e[t+o];if(!a)continue;let d=i?.[o];i?d?d.id&&d.unmatched?n.set(a.key,{why:"has no id this run can tell: the org did not say which of the ids it answered is its"}):d.id?n.set(a.key,{id:d.id}):n.set(a.key,{why:`was refused (${d.error??"Unknown insert error"})`}):n.set(a.key,{why:"was not sent: the run was stopped before it"}):n.set(a.key,{why:"has no id this run can tell: the insert did not answer record by record"})}}function gn(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function ha(n,e,t){let s=n.result.rows;if(!s)return n;let r=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){r.push({id:String(a.Id)});continue}let d=s[i++];if(!d)break;r.push(d)}return{...n,result:{...n.result,rows:r}}}function mn(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function ma(n){return!n||n.length===0?[]:mn(n).filter(e=>n.every(t=>e in t.values))}function ya(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([s])=>!e.has(s)))}))}async function Mi(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let s=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),r=mn(n.rows).filter(a=>!t.has(a));if(s.length===n.fieldRules.length&&r.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!s.includes(a)).map(a=>a.fieldApiName),...r])],o=n.rows&&ya(n.rows,new Set(r));return{config:{...n,fieldRules:s,...o?{rows:o}:{}},dropped:i}}async function Fi(n,e,t){if(!t)return{config:n,filled:[]};let s;try{s=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let r=new Set([...n.fieldRules.map(o=>o.fieldApiName),...ma(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of s){if(r.has(o.fieldApiName))continue;let a=Nn(o);a.ruleType==="static"&&a.config.staticValue===void 0||i.push({fieldApiName:o.fieldApiName,fieldType:o.type,...a})}return i.length===0?{config:n,filled:[]}:{config:{...n,fieldRules:[...n.fieldRules,...i]},filled:i.map(o=>o.fieldApiName)}}async function ji(n,e,t){let s=Dt(n.objectApiName,e),{config:r}=await Mi(vi(n,s),t.describeCreateableFields),{config:i}=await Fi(r,s,t.describeRequiredFields);return At(i)}function vi(n,e){if(!e)return n;let t=n.fieldRules.filter(s=>s.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function wa(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function Sa(n){return Array.from({length:n},()=>({}))}function Ra(n,e,t,s=0){if(!(!e||!t))for(let[r,i]of n.entries())i[e.lookupField]=t.parentIds[s+r]}function ba(n,e){return n?{fields:[...new Set([...n.fields,...e.fields])],reason:n.reason==="no-answer"&&e.reason==="no-answer"?"no-answer":"short-answer"}:e}function ka(n,e){for(let t of e.result.successIds)n.result.successIds.push(t);for(let t of e.result.errors)n.result.errors.push(t);e.written&&(n.written=Ue(n.written,e.written)),n.unsent.push(...e.unsent);for(let t of e.notes??[])(n.notes??[]).includes(t)||(n.notes=[...n.notes??[],t])}function Oa(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function Ei(n,e,t,s,r){let i=t.reduce((d,c)=>d+c.recordsCreated,0),o=t.reduce((d,c)=>d+c.recordsFailed,0),a=t.some(d=>!d.optional&&d.recordsCreated===0&&d.recordsFailed===0&&d.errors.length>0);return{templateId:n,operationId:e,status:Aa(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-s,timestamp:r}}function Aa(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function Ti(n,e,t,s){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:s}}var Ca=200,Ia=1,Pa=1,yn=2,Ea=2,Di=3,Ta=1,Ma=200,Fa="Campaign";function Li(n,e){if(!n)return;let t=e.toLowerCase();for(let[s,r]of n)if(s.toLowerCase()===t)return r}function ja(n,e){let t=Math.max(1,Math.floor(e)),s=[],r=0;do{let i=Math.max(0,Math.min(t,n-r));s.push(i),r+=i}while(r<n);return s}function va(n,e={}){let t=e.bulkThreshold??Ca,s=!1;return n.objects.flatMap(i=>{let o=Li(e.duplicateRules,i.objectApiName),a=o===!1&&!ys.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??At(i);return ja(i.recordCount,d).map(c=>{let l=we([{rows:c,perCall:i.batchSize}]);if(c<=t||(s=!0,o===!0))return l;let u=we([{rows:c,bulk:!0}]);return a?u:Math.max(u,l)})}).reduce((i,o)=>i+o,0)+(s?Ia:0)+we(Da(n))}function Na(n,e={}){return va(n,e)+xa(n,e)}function xa(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),s=n.objects.some(i=>i.fieldRules.some(o=>nt(o,t))),r=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+we([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/Gs):i,0);return Pa+n.objects.length+yn+(t.has(Fa)?yn+1:0)+r+(s?Ta:0)+(e.typedFirst?Ea:0)+Di+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function ol(n,e,t){let s=new Map;if(t!==void 0)return s;for(let r of n.objects)r.recordCount<=hn||s.set(r.objectApiName,await ji(r,n.relations,e));return s}function al(n,e){return n?.enabled&&e.objects.reduce((s,r)=>s+r.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function Ct(n,e){return n.reduce((t,{objectApiName:s,rows:r,perCall:i,deletes:o})=>{if(r<=e.threshold)return t+we([{rows:r,perCall:i??e.perCall}]);let a=o===!0||Li(e.duplicateRules,s)===!1?0:r;return t+we([{rows:r,bulk:!0},{rows:a}])},0)}function wn(n=0,e=0){return Di+yn+Math.max(0,n)+Math.max(0,e)}function dl(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,s=Math.min(t("Opportunity"),t("OpportunityContactRole")),r=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return Ct(n,e)+(s>0?Math.ceil(s/Ma)+Ct([{objectApiName:"OpportunityContactRole",rows:s}],e):0)+we(r)+wn(n.length,e.automationRead)}function Da(n){let e=s=>n.objects.find(r=>r.objectApiName===s)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function La(n,e){return n.objects.reduce((t,s)=>t+qr(s.objectApiName,{rows:s.recordCount,personAccounts:e.includes(s.objectApiName)?s.recordCount:0}),0)}function ll(n,e){let t=n.automationStarts??[],s=t.filter(a=>a.why!=="leftEmpty"),r=n.automationAtMostMB!==void 0&&n.automationAtMostMB>0&&s.length>0?` (${xe(n.automationAtMostMB)} MB of it at most: ${s.map(a=>`${Ni(a)} ${xi(a)}`).join("; ")})`:"",i=`data storage: about ${xe(n.estimateMB)} MB to write`+(n.automationMB!==void 0&&n.automationMB>0?`, about ${xe(n.automationMB)} MB of it for what the target's automation creates under them${r}`:""),o=t.filter(a=>a.why==="leftEmpty").map(a=>`; nothing counted for ${Ni(a)}: it ${xi(a)}`).join("");return n.verdict==="unread"?`${i}; what ${e} has left could not be read (${n.unread})${o}`:`${i}, ${e} has ${n.remainingMB} MB left of ${n.maxMB} MB`+(n.verdict==="near"?": close to what it has left":"")+o}function Ni(n){return`${n.name} on ${n.objectApiName}`}function xi(n){let e=n.why==="leftEmpty"?"which the seed leaves empty":n.why==="automationMayFill"?"which the seed leaves empty and the target's automation may fill first":"which the seed may leave empty";return`starts only on a record whose ${n.fields.join(" and ")} ${n.fields.length===1?"is":"are"} filled, ${e}`}var ul="SEED_STORAGE_EXCEEDED";async function pl(n,e,t,s,r,i={},o={},a={perRecord:[]}){let d={storageBytes:La(e,t)},c;try{c=await Hr(n)}catch(w){c={unread:K(w)}}let l=new Map(e.objects.map(w=>[w.objectApiName,w.recordCount])),u=w=>l.get(w)??0,f=Yt(a,u),p=a.atMost?Yt({perRecord:a.atMost},u):0,h=Ne(d,c,f),m={...h.verdict==="exceeds"&&p>0&&Ne(d,c,f-p).verdict!=="exceeds"?{...h,verdict:"near"}:h,...p>0?{automationAtMostMB:p/1048576}:{},...a.starts&&a.starts.length>0?{automationStarts:a.starts}:{}},R="unread"in c?await Yr(n).catch(w=>({unread:K(w)})):c.dailyApiRequests,S=at({run:Na(e,o),...ct(r),...i},R),b=lt(r);if(b)return{check:m,api:S,refusal:b.message,refusedFor:"checkpoint",checkpointRefusal:b.refusal};let k=as(m,s);if(k)return{check:m,api:S,refusal:`${k} Nothing was written.`,refusedFor:"storage"};let g=dt(S,s);return g?{check:m,api:S,refusal:g,refusedFor:"apiRequests"}:{check:m,api:S}}function fl(n,e){let{check:t,api:s}=n,r=s.parts??{},i={checkpoint:r.checkpoint??0,mute:r.mute??0,readBack:r.readBack??0,deliverability:r.deliverability??0,fit:r.fit??0};return ds({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB},...e!==void 0?{withinMB:e}:{},api:s.verdict==="unread"?{unread:s.unread}:{max:s.max,remaining:s.remaining},otherRequests:i})}function $a(n){return n==="insert"||n==="upsert"}function _i(n){return n==="update"||n==="upsert"}function Ba(n){return Kr(n.objects.filter(e=>$a(e.operation)).map(({objectApiName:e,rows:t,personAccounts:s})=>({objectApiName:e,rows:[],counted:{rows:t,...s!==void 0?{personAccounts:s}:{}}})))}var Wi=fe.REST_API_BATCH_SIZE;function _a(n,e){return Ct(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:s,rows:r,batchSize:i})=>({objectApiName:t,rows:r,...i!==void 0?{perCall:i}:{},...s==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??Wi,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var Wa="Opportunity",Ga="OpportunityContactRole",Ua=200,za={update:{characters:Jt,wide:!0},upsert:{characters:Ts(),wide:!0}},qa=2,$i=Array.from({length:qa},()=>1),Ka=1;function Ha(n){let e=Math.min(Math.max(0,n),5e4);return Ka+Math.max(1,Math.ceil(e/vr))}function Rn(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(s,r)=>Math.min(t,n-r*t))}function Ya(n,e){if(n.rows<=(e.bulkThreshold??Wi))return Rn(n.rows,n.batchSize??fe.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([s])=>s.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:Rn(n.rows,fe.REST_API_BATCH_SIZE)]}function Ja(n,e){let t=0,s=!1;for(let d of e.targetHeld?.values()??[])t+=Ha(d);for(let d of n.objects)d.rows<=0||d.operation==="delete"||(t+=$i.length,!(d.operation!=="update"&&d.operation!=="upsert")&&(s=!0,t+=Vt([...Ya(d,e),...$i],d.overwriteKey??za[d.operation])));let r=d=>n.objects.find(c=>c.objectApiName===d&&(c.operation==="insert"||c.operation==="upsert")),i=r(Wa),o=r(Ga),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=Rn(a,o.batchSize??fe.REST_API_BATCH_SIZE);s=!0,t+=Math.ceil(a/Ua)+d.length+Vt(d,{characters:Jt,wide:o.overwriteKey?.wide??!0})}return s&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function Gi(n){let e=new Map;for(let{objectApiName:t,operation:s}of n.objects){let r=e.get(t)??new Set;(s==="insert"||s==="upsert")&&r.add("insert"),(s==="update"||s==="upsert")&&r.add("update"),s==="delete"&&r.add("delete"),e.set(t,r)}return(t,s)=>e.get(t)?.has(s)===!0}function Ui(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(s=>t.has(s)),objects:n.objects.filter(s=>t.has(s.objectApiName))}}function Va(n){let e;return t=>{if(e&&t.every(r=>e?.objects.includes(r)))return e.answer.then(r=>Ui(r,t));let s=n(t);return e??={objects:[...t],answer:s},s}}function Ml(n,e){if(n.direction==="bidirectional")return async t=>{let s=n.objects.find(i=>i.objectApiName===t),r=ot(s?.where,void 0);return e(`SELECT COUNT() FROM ${ye(t)}${r?` WHERE ${r}`:""}`)}}async function Xa(n,e){let t=new Set((n.heldBack??[]).filter(({rows:r})=>r>0).map(({objectApiName:r})=>r)),s=new Map;for(let{objectApiName:r,operation:i,rows:o}of n.objects){if(!_i(i)||s.has(r)||o<=0&&!t.has(r))continue;let a=await e(r).catch(()=>5e4);s.set(r,Number.isFinite(a)&&a>=0?a:5e4)}return s}async function Bi(n,e){let t=Ba(n),s=n.objects.filter(T=>T.rows>0).map(({objectApiName:T,rows:v})=>({objectApiName:T,rows:v})).sort((T,v)=>v.rows-T.rows||T.objectApiName.localeCompare(v.objectApiName)),r=s.reduce((T,v)=>T+v.rows,0),i=n.objects.filter(T=>_i(T.operation)).reduce((T,v)=>T+v.rows,0),o=Ne(t,{maxMB:0,remainingMB:0}),a=[],d,c=r>0?Va(e.readAutomation):e.readAutomation,l,u,f,p=Gi(n),h;if(r>0){let T=n.objects.filter(v=>v.rows>0).map(v=>v.objectApiName);if(h=await c(T).catch(v=>({unread:v instanceof Error?v.message:String(v)})),e.checkpointFirst){let v="objects"in h?Lt(h,void 0,p):{firing:[]};try{l=await e.checkpointFirst.scope(T,v)}catch(j){u=zr(j)}}}let y={unread:"not read"};if(r>0){let T=await e.readStorage().catch(v=>({unread:v instanceof Error?v.message:String(v)}));y="unread"in T?await e.readApiBudget().catch(v=>({unread:v instanceof Error?v.message:String(v)})):T.dailyApiRequests,t.totalRows>0&&(o=Ne(t,T))}if(t.totalRows>0){let T=await Qr({plan:t,objects:t.objects.map(v=>v.objectApiName),readAutomation:c,readLimits:e.readLimits});a=T.checks,d=T.unread}h!==void 0&&(f=await Er({...e.emails,read:h,writes:p,readDeliverability:e.readDeliverability,run:"sync"}));let m=r>0&&e.countTarget?await Xa(n,e.countTarget):void 0,R=ss(f?.ofRun),S=e.sentBefore?.(),b=r===0?0:S!==void 0?Math.max(0,S-(R.deliverability??0)):wn(0,h!==void 0?rs(h):0)+(m?.size??0),k=h!==void 0?ws(h):void 0,g=r===0?0:Ja(n,{bulkThreshold:e.bulkThreshold,duplicateRules:k,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...m?{targetHeld:m}:{}}),w=at({run:_a(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:k})+b+g,...ct(l),...Mr(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...R},y),M=e.confirmAboveRecords,A=M>0&&r>M?M:void 0,O=(n.unwritable??[]).map(({objectApiName:T,rows:v,why:j,key:D})=>({...D!==void 0?{key:D}:{},objectApiName:T,rows:v,why:j})),E=(n.heldBack??[]).map(({objectApiName:T,rows:v,parent:j,field:D,parents:_})=>({objectApiName:T,rows:v,parent:j,field:D,..._!==void 0?{parents:_.map(z=>({...z}))}:{}})),F=f?.gate,N=r===0?O.length>0?"refused":"writes":o.verdict==="exceeds"||w.verdict==="exceeds"||u!==void 0||l?.refusal!==void 0?"refused":A!==void 0||O.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(T=>T.verdict!=="fits")||d!==void 0||l!==void 0||F?.verdict==="asks"?"asks":"writes";return{check:{objects:s,total:r,alreadyCopied:n.alreadyCopied,...(n.alreadyLinked??0)>0?{alreadyLinked:n.alreadyLinked}:{},...i>0?{overwrites:i}:{},...(n.rolesByThePlatform??0)>0?{rolesByThePlatform:n.rolesByThePlatform}:{},...(n.rolesLinked??0)>0?{rolesLinked:n.rolesLinked}:{},...A!==void 0?{aboveRecords:A}:{},storage:o.verdict==="unread"?{verdict:"unread",estimateMB:o.estimateMB,unread:o.unread}:t.totalRows===0?{verdict:"fits",estimateMB:0}:{verdict:o.verdict,estimateMB:o.estimateMB,maxMB:o.maxMB,remainingMB:o.remainingMB},emails:a.map(T=>({limit:T.limit,emails:T.emails,verdict:T.verdict,...T.remaining!==void 0?{remaining:T.remaining}:{},...T.max!==void 0?{max:T.max}:{},...T.alertsCounted?{alertsCounted:!0}:{},objects:T.objects.map(({objectApiName:v,perRecord:j})=>({objectApiName:v,perRecord:j})),...T.unread!==void 0?{unread:T.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...F?.deliverability?{deliverability:F.deliverability}:{},...O.length>0?{unwritable:O}:{},...E.length>0?{heldBack:E}:{},...r>0?{apiRequests:w.verdict==="unread"?{verdict:"unread",estimate:w.estimate,unread:w.unread}:{verdict:w.verdict,estimate:w.estimate,remaining:w.remaining,max:w.max}}:{},verdict:N,...u!==void 0?{checkpointUnread:u}:{}},plan:t,storage:o,emails:a,api:w,...l!==void 0?{checkpoint:l}:{},...u!==void 0?{checkpointFailed:u}:{},...f!==void 0?{runEmails:f}:{},emailsAccepted:e.emails.accepted}}function Za(n,e){let{check:t,storage:s,emails:r,plan:i,api:o}=n,a=[],d=t.unwritable??[];if(d.length>0&&(e.policy!=="ask"||t.total===0)&&a.push({code:"SYNC_TARGET_UNWRITABLE",message:td(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:Xr,message:n.checkpointFailed});else{let l=lt(n.checkpoint);l&&a.push(l)}i.totalRows>0&&s.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${xe(s.estimateMB)} MB of data storage, and ${e.org} has ${s.remainingMB} MB left of ${s.maxMB} MB: leave objects out, narrow their filters, or free data storage in ${e.org}. To copy a sample of the source that fits ${e.org} instead, use Forge with Depth ALL and a sample that fits the target (sandforge clone --depth all --fit share). Nothing was written.`});let c=dt(o,e.org,$r);if(c&&a.push({code:Jr,message:c}),e.policy!=="ask"){let l=ns(r,e.org);l&&a.push({code:"SYNC_EMAILS_EXCEEDED",message:`${l} Nothing was written.`});let u=n.runEmails?.gate,f=u?.stop;f&&a.push({code:f.code,message:Ht(f.message,"sync",e.emailsLiftedBy),...ve(u,!1)})}return a}async function Qa(n,e){let{check:t,storage:s,emails:r,api:i}=n,[o]=Za(n,e);if(o)return{go:!1,...o};if(t.total===0)return{go:!0,asked:!1};let a=n.runEmails?.gate;if(e.policy!=="ask")return{go:!0,asked:!1,...ve(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...ve(a,!1)};let c=Ir(e.orgTier),l=r.filter(h=>h.verdict==="exceeds").map(es),u=r.filter(h=>h.verdict==="unread").map(ts),f=e.confirm?await e.confirm({stage:"write",module:"sync",org:e.org,orgTier:e.orgTier,objects:t.objects,total:t.total,...t.aboveRecords!==void 0?{aboveRecords:t.aboveRecords}:{},...c!==void 0&&t.total>c?{largeVolume:c}:{},storage:os(s),counted:!0,...t.overwrites!==void 0?{overwrites:t.overwrites}:{},...l.length>0?{emails:l}:{},...u.length>0?{emailsUnread:u}:{},...t.emailsUnread!==void 0?{emailsUncounted:t.emailsUnread}:{},...t.alreadyCopied>0?{alreadyCopied:t.alreadyCopied}:{},...(t.alreadyLinked??0)>0?{alreadyLinked:t.alreadyLinked}:{},...(t.rolesLinked??0)>0?{rolesLinked:t.rolesLinked}:{},...d.length>0?{unwritable:d}:{},...t.heldBack!==void 0&&t.heldBack.length>0?{heldBack:t.heldBack}:{},...Vr(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(f==="confirmed")return{go:!0,asked:!0,...ve(a,a?.verdict==="asks")};let p=ve(a,!1);return f==="declined"?{go:!1,code:"SYNC_WRITE_DECLINED",message:"The sync was cancelled before it wrote anything. Nothing was written.",...p}:{go:!1,code:"SYNC_CONFIRMATION_UNAVAILABLE",message:"The sync needed a confirmation before it wrote, and there was no one to ask. Nothing was written.",...p}}var ed={notInTarget:n=>`${n} has no such object, or the user the run writes as cannot see it`,notCreateable:n=>`the user the run writes as may not create its records in ${n}`,notUpdateable:n=>`the user the run writes as may not edit its records in ${n}`,unread:n=>`${n} did not describe it, so what it takes could not be told`,notAKey:(n,e)=>`its upsert matches on ${e??"a field"}, neither an External ID nor an idLookup field in ${n}`};function td(n,e,t=[]){let s=n.map(({objectApiName:R,rows:S,why:b,key:k})=>`${R} (${S} record${S===1?"":"s"}): ${ed[b](e,k)}`).join("; "),r=n.length===1?"it":"them",i=n.filter(({why:R})=>R==="notAKey"),o=n.filter(({why:R})=>R!=="notAKey"),a=i.length>0&&o.length>0,d=R=>R.map(({objectApiName:S})=>S).join(" and "),c=`give the user SandForge writes as access to ${a?d(o):r} in ${e}`,l=`match ${a?`${d(i)} `:""}on an External ID field of ${e}`,u=a?`${c}, or ${l}`:i.length>0?`or ${l}`:`or ${c}`,f=new Set(n.map(({objectApiName:R})=>R)),p=({parent:R,field:S})=>`whose ${S} names ${/^[aeiou]/i.test(R)?"an":"a"} ${R} record `+(f.has(R)?"left out":"held back"),h=t.flatMap(({objectApiName:R,rows:S,parent:b,field:k,parents:g})=>(g??[{parent:b,field:k,rows:S}]).map(w=>`${w.rows} ${R} record${w.rows===1?"":"s"}, ${p(w)}`)).join("; "),y=n.filter(({why:R})=>R==="notInTarget"),m=y.length>0?` Where ${e} has not ${d(y)}, Compare deploys ${y.length===1?"it":"them"} from the source: tick Data Model, compare, then Deploy from Diff.`:"";return`${e} would take no record of ${n.length===1?"one object":`${n.length} objects`} the sync writes \u2014 ${s}.`+(h!==""?` Left out, ${r==="it"?"it holds":"they hold"} back ${h}.`:"")+` Leave ${r} out of the run, ${u}.${m} Nothing was written.`}function Fl(n,e){return{measure:async t=>(await Bi(t,n)).check,hold:async t=>{let s=await Bi(t,n),r=await Qa(s,e);return{check:s.check,answer:await nd(s,r,n.checkpointFirst)}}}}async function nd(n,e,t){let s=n.checkpoint;if(!e.go||s===void 0||t===void 0)return e;let r=await Zr(()=>t.take(s));return"stop"in r?{go:!1,...r.stop}:{...e,checkpoint:r.checkpoint}}function jl(n,e){return e==="insert"||e==="update"||e==="delete"}function vl(n,e,t,s,r){let i,o,a,d,c=n(async u=>{let f=i?.automation;return f&&u.every(p=>f.objectsRead.includes(p))?Ui(f,u):e(u)},()=>i?.plan),l=u=>{if(!Tr(u))throw u;return{go:!1,code:u.code,message:u.message}};return{gate:{measure:u=>c.measure(u),hold:async u=>{let f=u.objects.filter(h=>h.rows>0).map(h=>h.objectApiName);if(!i&&f.length>0){d=await e(f).catch(h=>({unread:h instanceof Error?h.message:String(h)}));try{i=await t(d),a=i.muted}catch(h){return{check:await c.measure(u),answer:l(h)}}}let p=await c.hold(u);if(p.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(s),a=o.outcome}catch(b){let{checkpoint:k}=p.answer;return{check:p.check,answer:{...l(b),...k?{checkpoint:k}:{}}}}let{checkpoint:h,emails:y}=p.answer,{deliverability:m}=p.check,R=Gi(u),S=i.plan&&d&&"objects"in d?is({planned:m?.senders??[],held:Gn(Lt(d,Pr(i.plan,o.outcome),R),{writes:R}),...m?{reading:m.reading}:{},accepted:y?.accepted===!0,target:r.target,run:"sync"}):void 0;if(S)return{check:p.check,answer:{go:!1,code:S.code,message:Ht(S.message,"sync",r.liftedBy),...h?{checkpoint:h}:{},...y?{emails:y}:{}}}}return p}},release:async()=>(o&&(a=await o.release()),a),lease:()=>{let u=o;if(u)return{assigned:u.outcome.assigned.length,giveBack:async()=>(a=await u.release(),a)}}}}export{gt as a,St as b,cd as c,ld as d,kd as e,Od as f,Ad as g,Zs as h,go as i,Nd as j,xd as k,zd as l,qd as m,Kd as n,Hd as o,ko as p,Oo as q,Yd as r,Io as s,Jd as t,Vd as u,Po as v,ae as w,$e as x,oi as y,ai as z,Qd as A,To as B,Mo as C,ec as D,cn as E,pc as F,si as G,Ri as H,Ai as I,Li as J,Na as K,ol as L,al as M,Ct as N,wn as O,dl as P,La as Q,ll as R,ul as S,pl as T,fl as U,Ml as V,Bi as W,Za as X,Qa as Y,td as Z,Fl as _,nd as $,jl as aa,vl as ba};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{b as te}from"./chunk-DBBPDSFN.mjs";import{c as nt,d as ot}from"./chunk-GBGHJTPC.mjs";import{i as et,k as tt}from"./chunk-YMDFF657.mjs";import{a as st,b as it,c as rt,d as at,e as ct,f as dt,h as lt}from"./chunk-7WSLT5VX.mjs";import{d as He,j as Ke}from"./chunk-YT22LMF7.mjs";import{c as Oe,d as Ce,p as Ge}from"./chunk-PE435FVH.mjs";import{a as Te}from"./chunk-PWVDNN2C.mjs";import{h as ze,i as Ve}from"./chunk-XU25YA46.mjs";import{A as _e,C as Ue,t as Be,u as We,z as q}from"./chunk-O2PUGRNW.mjs";import{A as qe,B as x,D as ee,G as Ze,b as je,f as Re,h as Ne,i as Q,j as X,k as Fe,n as Le,o as Ie,r as xe,t as Z,u as Je,v as Qe,w as Xe,z as Ye}from"./chunk-SAMWHL22.mjs";import{A as ve,B as I,H as Ee,K as $e,a as De,e as Me,o as Y,z as Pe}from"./chunk-J24TIGSI.mjs";import{f as H}from"./chunk-ZUOPC4W2.mjs";import{E as Se}from"./chunk-XZISAZA6.mjs";import{f as be,g as ke,h as L,m as we,n as ye,o as K,t as Ae,u as J}from"./chunk-L4INJ5TZ.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Hc as F,Va as me,Wa as $,Za as ge,le as he}from"./chunk-ZQO5PDX5.mjs";import{b as pe,k as fe,l as V}from"./chunk-WZQEK4WT.mjs";import{readdir as It,rm as gt,stat as ht}from"node:fs/promises";import{existsSync as xt,readFileSync as Bt,writeFileSync as Wt}from"node:fs";import{hostname as _t}from"node:os";import{join as oe}from"node:path";var Gt=5e5,B=1e6,Ut=100,zt="taking",ut=500;function Xn(e){let t=Ne(e),n=[H(e)];return{get version(){return e.version},request:o=>t.request(o),query:(o,s)=>t.query(o,s),queryMore:o=>t.queryMore(o),describeGlobal:async()=>await e.describeGlobal(),toolingObjects:async()=>{try{return(await e.tooling.describeGlobal()).sobjects.map(s=>s.name)}catch{return[]}},serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp,userId:async()=>(await e.soap.getUserInfo()).userId,requestsSent:()=>n.reduce((o,s)=>o+s(),0),countAlso:o=>{n.push(H(o))}}}function Vt(e){return Fe(ze(e))}var D=class extends Error{constructor(){super("The checkpoint was stopped before it was taken: nothing of it was kept."),this.name="CheckpointTakeStopped"}},W="No record was read.",Ht={excludedByUser:"Left out as asked.",notFound:"The org has no object of this name.",chatter:"Chatter posts, comments and feeds are left out: Salesforce brings a post back only with what it was posted on.",history:"History is left out: it is the org's own trace of changes.",sharing:"Sharing is left out: the org keeps it itself.",changeEvent:"Change events are left out.",unsupportedKind:"Left out: neither the recycle bin nor an update reaches this kind of object as it reaches a record.",customSetting:"Custom settings are left out unless you pick them as custom settings: they are configuration, which a rewind sets back.",notCustomSetting:"Picked as a custom setting: the org has no custom setting of this name.",files:"Documents of the Documents tab are left out: they are shared content kept in folders, as setup is.",heldWithFiles:"Held with its file (ContentDocument): Salesforce neither deletes nor brings back a file's version on its own, and reads the links of a file through the records they tie it to.",setup:"Users, permissions and setup are left out, and so are the org's own logs and jobs.",platformCreated:"Left out: Salesforce alone creates its records, such as approvals, Einstein insights, Data.com clean info and invoices, and no permission lets a user create one.",metadata:"Left out: it is metadata, which a checkpoint doesn't hold.",notWritable:"Left out: the user SandForge connects as may not create, edit and delete its records.",notDescribed:"Left out: the org would not describe it.",noSystemModstamp:"Left out: it has no SystemModstamp, so nothing would tell a record changed since.",noRecycleBin:"Left out: the org deletes its records for good, with no recycle bin, so nothing would tell one deleted since, nor bring it back.",unreadable:"Left out: the org refuses to read it whole.",noViewAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has neither on this one: a record they cannot see would read as deleted since.",noModifyAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has View All on this one, not Modify All: a rewind could not put back what others changed.",activities:"Without View All Data and Modify All Data, tasks and events are left out: Salesforce has no View All for activities, and a private one linked to no record stays out of sight.",catalog:"Without View All Data and Modify All Data, products and price books are left out: Salesforce has no View All or Modify All for them.",filesNotProven:"Without View All Data and Modify All Data, files are left out: nothing proves the user sees every file.",settingNotProven:"Without View All Data and Modify All Data, custom settings are left out: no permission on an object proves the user sees and writes every row.",parentNotSeen:"Without View All Data and Modify All Data, an object with no permissions of its own is held only when the user has View All and Modify All on every record it hangs from, which is not proven here."};function bt(e){let t=Ht[e.reason],n=e.detail===void 0?t:`${t.replace(/\.$/,"")} (${e.detail}).`;return{objectApiName:e.objectApiName,code:e.reason,reason:pt(n),...e.detail===void 0?{}:{detail:pt(e.detail)}}}function Kt(e,t,n){return{objectApiName:e,code:"pastTheLimit",records:t,limit:n,reason:t>B?`${e} has ${t} records, more than any checkpoint holds of one object (${B}): left out of the checkpoint, and a rewind to it does not touch ${e}. Data Export, in Setup, or a Bulk API query keeps a copy of it.`:`${e} has ${t} records, past the checkpoint's limit of ${n} for one object: left out of the checkpoint, as part of it would be taken for all of it.`}}function Jt(e,t){let n=t;for(;;){let o=e.filter(s=>s<=Math.min(n,B)).reduce((s,r)=>s+r,0);if(o<=n)return n;n=o}}function pt(e){return e.length<=ut?e:`${e.slice(0,ut-1)}\u2026`}function kt(e,t){return{code:"RUN_WRITING",message:`${t.operation==="take"?`A checkpoint of ${e} is being taken`:t.operation==="rewind"?`A rewind is writing to ${e}`:t.operation==="undo"?`An undo is writing to ${e}`:t.operation==="empty"?`An emptying of its objects is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${t.pid} on ${t.host}): take the checkpoint once it has ended. ${W}`}}function wt(e){return typeof e!="object"||e===null?void 0:typeof e.errorCode=="string"?v(e):void 0}function _(e,t){return e instanceof Q||e instanceof Te||e instanceof D||t?.aborted===!0}var Qt=V({sobjects:fe(be)}).loose();function M(e){return e.toLowerCase()===ke.toLowerCase()}function Xt(e,t,n){if(e===void 0)return{why:`the org lists no ${L}`};let o=t.get(e);if(o===void 0)return{why:n.get(e)??"it was not described"};let r=o.fields.find(d=>d.name.toLowerCase()==="linkedentityid")?.referenceTo??[];return r.length===0?{why:"its describe names no record a link ties a file to"}:{linkable:new Set(r.map(d=>d.toLowerCase()))}}async function se(e,t,n){let o=new Map,s=new Map,r=0,d=await Promise.allSettled(n.map(p=>t.describe(p)));for(let[p,i]of d.entries()){let c=n[p],l;if(i.status==="fulfilled"&&"body"in i.value)l=i.value.body;else{if(i.status==="rejected"&&i.reason instanceof Q)throw i.reason;r++;try{l=await e.request({method:"GET",url:`/services/data/v${e.version}/sobjects/${F(c)}/describe`})}catch(h){let a=wt(h);if(a===void 0)throw new Error(`The org did not answer the describe of ${c}: ${v(h)}`);s.set(c,a);continue}}let u=He.safeParse(l);u.success?o.set(c,u.data):s.set(c,"its describe does not read as one")}return{describes:o,errors:s,alone:r}}async function yt(e,t,n){let o=Qt.parse(await e.describeGlobal()),s=await e.toolingObjects?.()??[],r=ye(o.sobjects,{mode:n.mode,...n.objects?{objects:n.objects}:{},...n.excluded?{excluded:n.excluded}:{},...n.customSettings?{customSettings:n.customSettings}:{}},s),d=r.candidates.some(M),p=d?o.sobjects.find(m=>m.name.toLowerCase()===L.toLowerCase())?.name:void 0,i=p===void 0?r.candidates:[...r.candidates,p],{describes:c,errors:l,alone:u}=await se(e,t,i),h,a;if(d){let m=Xt(p,c,l);"linkable"in m?h=m.linkable:a=m.why,p!==void 0&&c.delete(p)}let g=Ae(r,c,l);if(a!==void 0){let m=g.objects.find(({objectApiName:C})=>M(C));m!==void 0&&(g=J(g,new Map([[m.objectApiName,`its links to records, ${L}, could not be described: ${a}`]])))}let w=await je(async m=>(await e.query(m)).records),A=new Map(o.sobjects.map(m=>[m.name,ft(m)])),S=o.sobjects.filter(we),f=new Set(S.map(m=>m.name)),k=[...c.values()],y=[];for(let m of g.objects){let C=c.get(m.objectApiName);C&&y.push({scoped:m,label:A.get(m.objectApiName)??m.objectApiName,describe:C,capture:await Ke(C,k,{viewsEncryptedData:w}),...f.has(m.objectApiName)?{customSetting:K(C)}:{}})}return{described:i.length,describedAlone:u,objects:y,leftOut:g.leftOut,addedToPicked:r.addedToPicked,...h!==void 0&&y.some(({scoped:m})=>M(m.objectApiName))?{linkable:h}:{},settings:S.map(m=>({objectApiName:m.name,label:ft(m)}))}}function ft(e){let t=e.label;return typeof t=="string"&&t!==""?t:e.name}async function Yt(e,t,n,o){let s=await ee(t,n.map(({capture:i})=>({objectApiName:i.objectApiName,readMode:i.readMode})),o),r=new Map,d=new Map,p=0;for(let[i,c]of s.entries()){let{objectApiName:l,readMode:u}=n[i].capture;if("count"in c){r.set(l,c.count);continue}p++;let h=Qe(l,u);try{let a=await e.query(h.soql,{scanAll:h.scanAll});if(typeof a.totalSize!="number")throw new Error("The org gave no count of its records.");r.set(l,a.totalSize)}catch(a){let g=wt(a);if(g===void 0)throw new Error(`The org did not count the records of ${l}: ${v(a)}`);d.set(l,g)}}return{counts:r,refused:d,alone:p}}function At(e,t){return t?.has(e.toLowerCase())===!0&&!M(e)}async function qt(e,t,n,o,s){let r=[];for(let{objectApiName:i,records:c}of t){let l=F(i);r.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE IsDeleted = true AND SystemModstamp < ${Z(o)}`,scanAll:!0,counts:"inBin"}),c!==0&&(r.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE SystemModstamp >= ${Je(o)}`,scanAll:!0,counts:"stampedSince"}),At(l,n)&&r.push({...et(l),counts:"links"}))}let d=await Ye(e,r,()=>{},s),p=new Map;return d.forEach((i,c)=>{let{objectApiName:l,counts:u}=r[c],h=i.read?i.totalSize:void 0,a=p.get(l)??{};u==="links"?a.links=h??null:h!==void 0&&(a[u]=h),p.set(l,a)}),{asked:r.length,of:p}}function St({scoped:e,capture:t,customSetting:n,access:o},s,r,d){return{objectApiName:e.objectApiName,records:s,inBin:r,readOrder:e.readOrder,readMode:t.readMode,undeletable:t.undeletable,cascadeParents:t.cascadeParents,restrictParents:t.restrictParents,fingerprint:d,fields:t.fields,leftOutFields:t.leftOutFields,...n!==void 0?{customSetting:n}:{},...o!==void 0?{access:o}:{}}}function Ot(e){return{personAccounts:rt(e.map(({describe:t})=>t)),catalog:at(e.map(({scoped:t})=>t.objectApiName))}}function Zt(e){let t=e?.orgType==="Sandbox"||e?.orgType==="Scratch";return Oe(Ce(t)).defaultQueryLimit}async function Ct(e,t,n,o,s,r,d,p=Tt){let i=n.maxTotal??Gt;if(!Number.isInteger(i)||i<1)throw new RangeError(`Not a number of records: ${i}`);let c=Math.min(i,B),{counts:l,refused:u,alone:h}=await Yt(e,t,o.objects,d),a=J({mode:n.mode,objects:o.objects.map(({scoped:b})=>b),leftOut:o.leftOut,packages:[]},u),g=new Map(o.objects.map(b=>[b.scoped.objectApiName,b])),w=a.leftOut.map(bt),A=[];for(let b of a.objects){let O=g.get(b.objectApiName),P=l.get(b.objectApiName);if(!(O===void 0||P===void 0)){if(P>c){w.push(Kt(b.objectApiName,P,c));continue}A.push({...O,scoped:{...b,readOrder:A.length},records:P,otherGroups:Be(b.objectApiName,O.capture.fields,O.capture.readMode),recount:{}})}}let S=A.some(({scoped:b})=>M(b.objectApiName))?o.linkable:void 0,f=await qt(t,A.map(({scoped:b,records:O})=>({objectApiName:b.objectApiName,records:O})),S,r,d);for(let b of A)b.recount=f.of.get(b.scoped.objectApiName)??{};w.sort((b,O)=>b.objectApiName<O.objectApiName?-1:b.objectApiName>O.objectApiName?1:0);let k={};for(let{scoped:b,describe:O}of A)k[b.objectApiName]=De(O.fields);let y=en(p,We({described:o.described,describedAlone:o.describedAlone,counted:o.objects.length,countedAlone:h,recounted:f.asked,objects:A.map(b=>({records:b.records,otherGroups:b.otherGroups,...b.recount,entry:St(b,b.records,0,k[b.scoped.objectApiName].digest)})),pageRows:Zt(n.registered),leftOut:w,printsBytes:(await $e(k)).length,annexCalls:ct(Ot(A))})),m={...y,apiRequestsLeft:s.remaining},C={objects:A,leftOut:w,estimate:m,objectLimit:c,prints:k,...S!==void 0?{linkable:S}:{}};if(y.records>i){let b=[...A.map(O=>O.records),...w.flatMap(O=>O.code==="pastTheLimit"?[O.records??0]:[])];return{...C,refusal:{code:"TOO_MANY_RECORDS",message:`The objects this checkpoint would keep hold ${y.records} records in ${n.orgName}, past its limit of ${i}: pick fewer objects. ${W}`,holdingLimit:Jt(b,y.records)}}}let R=_e("take",y.apiRequests,s,n.orgName);return R===void 0?C:{...C,refusal:R}}function jt(e){return{query:t=>e.query(t),queryMore:t=>e.queryMore(t)}}var Tt={guard:0,scope:0};function en(e,t){if(e.guard+e.scope===0)return t;let n=t.requestsByPhase;return{...t,apiRequests:t.apiRequests+e.guard+e.scope,...n!==void 0?{requestsByPhase:{...n,guard:n.guard+e.guard,scope:n.scope+e.scope}}:{}}}function tn(e){let t=[...e.mode==="picked"?e.objects??[]:[],...Array.isArray(e.customSettings)?e.customSettings:[]];return new Set(t.map(n=>n.toLowerCase()))}function nn(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}async function Rt(e,t,n,o,s,r){if(s.kind==="org")return{scope:{...o,objects:o.objects.map(f=>({...f,access:"org"}))},reads:Tt};let d=o.objects.map(({scoped:f})=>f.objectApiName),p={grants:s.objects,describes:o.objects.map(({describe:f})=>f),customSettings:o.objects.filter(({customSetting:f})=>f!==void 0).map(({scoped:f})=>f.objectApiName)},i=nt(d,p),c=[],l=0;if(i.length>0)try{let f=await se(e,t,i);c=[...f.describes.values()],l=Math.ceil(i.length/Re)+f.alone}catch(f){if(_(f,r))throw f}let u=ot(d,{...p,describes:[...p.describes,...c]}),h=tn(n),a=[],g=[...o.leftOut],w=[];for(let f of o.objects){let k=f.scoped.objectApiName,y=u.get(k);if(y!==void 0&&"access"in y){a.push({...f,access:y.access});continue}let m={objectApiName:k,reason:y?.reason??"noViewAll",...y?.detail!==void 0?{detail:y.detail}:{}};g.push(m),h.has(k.toLowerCase())&&n.unprovenLeftOut!==!0&&w.push(m)}let A=new Set(a.map(({scoped:f})=>f.objectApiName)),S={scope:{...o,objects:a,leftOut:g,addedToPicked:o.addedToPicked.filter(f=>A.has(f))},reads:{guard:s.requests,scope:l}};if(w.length>0){let f=w.length===1;return{...S,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, and the checkpoint can't hold ${nn(w.map(k=>k.objectApiName))}, asked for by name. ${w.map(k=>`${k.objectApiName}: ${bt(k).reason}`).join(" ")} Leave ${f?"it":"them"} out, or give the user View All Data and Modify All Data. ${W}`}}}return a.length===0&&o.objects.length>0?{...S,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, nor View All and Modify All on any object this checkpoint would hold: without them, a checkpoint holds only the objects its user sees and puts back whole. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. `+W}}:S}function on(e){return e.objects.map(({scoped:t,label:n,capture:o,records:s,customSetting:r,access:d})=>({objectApiName:t.objectApiName,label:n,...t.namespace!==void 0?{namespace:t.namespace}:{},records:s,undeletable:o.undeletable,leftOutFields:o.leftOutFields,...r!==void 0?{customSetting:r}:{},...d!==void 0?{access:d}:{}}))}function Nt(e){let t=e.customSettings;return t!==void 0&&(t==="all"||t.length>0)}async function sn(e,t,n,o,s){let r=new Map(o.objects.map(u=>[u.scoped.objectApiName,u])),d=n.settings.filter(({objectApiName:u})=>!r.has(u)),p=new Map;if(d.length>0)try{({describes:p}=await se(e,t,d.map(({objectApiName:u})=>u)))}catch(u){if(_(u,s))throw u}let i=d.filter(({objectApiName:u})=>p.has(u)),c=await ee(t,i.map(({objectApiName:u})=>({objectApiName:u,readMode:"query"})),s),l=new Map;return c.forEach((u,h)=>{"count"in u&&l.set(i[h].objectApiName,u.count)}),n.settings.map(({objectApiName:u,label:h})=>{let a=r.get(u);if(a?.customSetting!==void 0)return{objectApiName:u,label:h,kind:a.customSetting,records:a.records};let g=p.get(u),w=l.get(u);return{objectApiName:u,label:h,...g!==void 0?{kind:K(g)}:{},...w!==void 0?{records:w}:{}}})}var rn={records:0,apiRequests:0,apiRequestsLeft:0,seconds:0,bytes:0};async function Yn(e,t){let n={mode:t.mode,objects:[],leftOut:[],estimate:rn},o=await te(jt(e.org),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:Nt(t)},{userId:()=>e.org.userId()});if(!o.allowed)return{...n,refusal:o.refusal};let s=e.store.heldBy(o.org.id),r=s===void 0?await e.runWriting?.(o.org.id):void 0,d=X(e.org,e.signal);try{let p=await q(e.org,t.orgName),i=await Rt(e.org,d,t,await yt(e.org,d,t),o.grants,e.signal),{scope:c}=i,l=await e.org.serverTime(),u=await Ct(e.org,d,t,c,p,l,e.signal,i.reads),h={mode:t.mode,objects:on(u),leftOut:u.leftOut,estimate:u.estimate,files:{held:u.objects.some(({scoped:g})=>M(g.objectApiName)),queryAllFiles:o.queryAllFiles,addedToPicked:c.addedToPicked},customSettings:await sn(e.org,d,c,u,e.signal)},a=s!==void 0?kt(t.orgName,s):r!==void 0?{code:"RUN_WRITING",message:r}:i.refusal??u.refusal;return a===void 0?h:{...h,refusal:a}}catch(p){throw _(p,e.signal)?new D:p}}function an(e){let t=e.requestsSent?()=>e.requestsSent?.()??0:void 0,n={guard:0,scope:0,start:0,counts:0,bin:0,snapshot:0,stability:0},o="guard",s=t?.()??0,r=()=>{if(!t)return;let d=t();n[o]+=d-s,s=d};return{enter(d){r(),o=d},requests(){return t?(r(),{total:Object.values(n).reduce((p,i)=>p+i,0),byPhase:{...n}}):void 0}}}async function cn(e,t){if(t.edition!==void 0)return t.edition;let o=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;if(typeof o!="string"||o==="")throw new Error("The org did not say its edition (Organization.OrganizationType).");return o}var dn="Automated Process";async function ln(e){let n=(await e.query("SELECT Id, Name FROM User WHERE UserType = 'AutomatedProcess'")).records.filter(s=>typeof s.Id=="string"),o=n.find(s=>s.Name===dn);return o!==void 0?o.Id:n.length===1?n[0].Id:void 0}function Dt(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function mt(e,t){return e.split(he).join(Dt(t))}function ne(e){let t=Se(e);return t===null?Number.NaN:Date.parse(t)}function Mt(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}async function un(e,t){let n=new Set;for await(let o of x(Y(e,t))){let s=Mt(o.Id);s!==void 0&&n.add(s)}return n}async function pn(e,t,n,o,s,r){let d={changed:0,deleted:0,created:0};if(!o.live&&!o.deleted)return d;let p=await xe.read(e,t,n);if(o.live)for await(let i of x(o.live.file)){let c=ne(i.SystemModstamp);if(!(c<=r))continue;let l=p.stampOf(i.Id);l===void 0?d.created++:l!==c&&d.changed++}if(o.deleted){let i;for await(let c of x(o.deleted.file)){if(!(ne(c.SystemModstamp)<=r))continue;if(p.has(c.Id)){d.deleted++;continue}if(!(ne(c.CreatedDate)<s))continue;i??=await un(e,n);let l=Mt(c.Id);l!==void 0&&!i.has(l)&&d.deleted++}}return d}async function Pt(e){let t=0;for(let n of await It(e,{withFileTypes:!0})){let o=oe(e,n.name);n.isDirectory()?t+=await Pt(o):n.isFile()&&(t+=(await ht(o)).size)}return t}async function fn(e,t){let n=await Pt(e.dir)-(await ht(e.checkpointFile)).size,o=r=>Buffer.byteLength(`${JSON.stringify({...t,bytes:r},null,2)}
|
|
8
|
+
`,"utf8"),s=n+o(n);return s=n+o(s),s}function mn(e){let t=e.snapshotsFile,n=new Ue({getData:()=>xt(t)?JSON.parse(Bt(t,"utf8")):{},setData:o=>Wt(t,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})});return n.initialize(),n}var gn=V({organizationId:pe().optional()}).loose();async function hn(e,t,n,o,s){let r=mn(e),d=0,p={log:n.handler.log,orgManager:n.handler.orgManager,orgRegistry:n.handler.orgRegistry,configStore:r,broker:{postToWebview:c=>{if(c.type!=="operation:progress")return;let l=c.payload;typeof l.percentage=="number"&&typeof l.currentStep=="string"&&s(l.percentage,l.currentStep)}},services:{getSandforgeSetting:(c,l)=>c==="backup.maxRecordsPerObject"?o:l},nextId:()=>`${e.checkpointId}-${++d}`},i=new Ge(p);return i.setBackupRecordStore(new Ve(t)),await i.swept(),{handler:i,config:r}}function bn(e,t){return e.slice(0,15)===t.slice(0,15)}async function qn(e,t){let{org:n,store:o,signal:s}=e,r=e.now??(()=>new Date),d=me.parse([...t.ignoredFields??[]]),p=t.name===void 0?void 0:$.parse(t.name),i=t.nameWithDate;i!==void 0&&$.parse(mt(i,r().toISOString()));let c=t.customSettings==="all"?[]:t.customSettings??[];for(let y of[...t.objects??[],...t.excluded??[],...c])F(y);let l=t.beforeRun===void 0?void 0:ge.parse(t.beforeRun),u=t.keepDays??Me;I(r(),u);let h=(y,m,C=0,R=0)=>e.onProgress?.({percentage:Math.round(y),processedObjects:C,totalObjects:R,step:m});h(0,`Checking ${t.orgName}`);let a=an(n),g=await te(jt(n),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:Nt(t)},{userId:()=>n.userId()});if(!g.allowed)return{taken:!1,refusal:g.refusal};let w=g.org.id,A=ve("ck",r()),S=o.lock(w,"take",A);if("busy"in S)return{taken:!1,refusal:kt(t.orgName,S.busy)};let f,k;try{let y=await e.runWriting?.(w);if(y!==void 0)return{taken:!1,refusal:{code:"RUN_WRITING",message:y}};let m=X(n,s),C=await cn(n,g.org),R=await q(n,t.orgName);h(2,`Reading the objects of ${t.orgName}`),a.enter("scope");let b=await Rt(n,m,t,await yt(n,m,t),g.grants,s);if(b.refusal!==void 0)return{taken:!1,refusal:b.refusal};let{scope:O}=b;a.enter("start");let P=await n.userId(),ie=await ln(n),N=await n.serverTime();h(8,`Counting the records of ${O.objects.length} objects`),a.enter("counts");let T=await Ct(n,m,t,O,R,N,s,b.reads);if(T.refusal!==void 0)return{taken:!1,refusal:T.refusal};if(T.objects.length===0)throw new Error(`None of the objects asked for can be kept in a checkpoint of ${t.orgName}: ${T.leftOut.map(j=>`${j.objectApiName}: ${j.reason}`).join(" ")||"there are none."}`);if(s?.aborted)throw new D;f=await o.create(w,A);let E=`snapshot-${A}`;k={version:1,checkpointId:A,name:p??(i!==void 0?$.parse(mt(i,N)):Dt(N)),org:{organizationId:w,...t.alias!==void 0?{alias:t.alias}:{},username:t.username,instanceUrl:t.instanceUrl,isSandbox:g.org.sandbox,organizationType:C,tier:g.tier,...t.scratchExpiresAt!==void 0?{scratchExpiresAt:t.scratchExpiresAt}:{},...R.dataStorageMaxMB!==void 0?{dataStorageMaxMB:R.dataStorageMaxMB}:{},...t.registered?.staging===!0&&g.org.sandbox?{staging:!0}:{}},takenBy:{userId:P,...ie!==void 0?{automatedProcessUserId:ie}:{},viewAllData:g.grants.kind==="org"||g.grants.viewAllData,modifyAllData:g.grants.kind==="org"||g.grants.modifyAllData,queryAllFiles:g.queryAllFiles},readFrom:N,takenAt:N,scope:{mode:t.mode,leftOut:T.leftOut},objects:[],ignoredFields:d,snapshotId:E,movedWhileTaken:{changed:0,deleted:0,created:0},bytes:0,expiresAt:I(r(),u),status:"taking",takenOn:{host:_t(),pid:process.pid},...l!==void 0?{beforeRun:l}:{}},await o.write(k),h(12,"Reading the recycle bin as it was at the checkpoint"),a.enter("bin");let vt=await qe(m,T.objects.map(({scoped:j})=>({...Xe(j.objectApiName,N),file:Y(f,j.objectApiName)})),s),re=new Map;for(let j of vt){if(!j.read)throw new Error(`The recycle bin of ${j.objectApiName} could not be read whole: ${j.reason}`);re.set(j.objectApiName,j.rows)}a.enter("snapshot");let{records:Et,files:ae}=await kn(f,E,T,t,e,w,m,h);h(88,`Reading the record types, users and queues ${t.orgName} names`);let $t=await wn(f,E,T,m,w,s);h(89,"Reading the time on the org"),a.enter("stability");let ce=await n.serverTime();h(90,`Checking what changed in ${t.orgName} while it was read`);let{movedWhileTaken:Ft,notChecked:Lt}=await yn(f,E,T,m,N,ce,s),{prints:de}=T;await o.writeFingerprints(f,de);let G=T.objects.map(j=>{let z=j.scoped.objectApiName;return St(j,Et.get(z)??0,re.get(z)??0,de[z].digest)});if(s?.aborted)throw new D;let le={...k,takenAt:ce,objects:G,movedWhileTaken:Ft,bytes:0,expiresAt:I(r(),u),status:"ready",...ae!==void 0?{files:ae}:{},replayAnnex:$t},U={...le,bytes:await fn(f,le)};await o.write(U),h(100,`Checkpoint '${U.name}' taken`,G.length,G.length);let ue=a.requests();return{taken:!0,checkpoint:U,notChecked:Lt,...ue!==void 0?{requests:ue}:{},estimate:T.estimate}}catch(y){throw f!==void 0&&await An(o,f,k,e),_(y,s)?new D:y}finally{S.lock.release()}}async function kn(e,t,n,o,s,r,d,p){let i=n.objects.filter(a=>a.records>0),c=new Map,l=(s.snapshotFiles??Vt)(e.dir);if(i.length>0){let a=Math.max(Ut,n.objectLimit),{handler:g,config:w}=await hn(e,l,s,a,(k,y)=>p(15+k*.65,y)),A=await g.backupForPipeline({operationId:t,orgId:o.orgId,objects:i.map(({scoped:k})=>k.objectApiName),fields:new Map(i.map(({scoped:k,capture:y})=>[k.objectApiName,y.fields])),scanAll:i.filter(({capture:k})=>k.readMode==="scanAllLive").map(({scoped:k})=>k.objectApiName),origin:"checkpoint",failWhenTruncated:!0,onConnection:k=>s.org.countAlso?.(k)},s.signal),S=gn.safeParse(w.get(`backup:${t}`)),f=S.success?S.data.organizationId:void 0;if(f===void 0||!bn(f,r))throw new Error(`The snapshot was read from ${f===void 0?"an org that did not say which it is":`another org (${f})`}, not from ${o.orgName}: it is not kept.`);for(let k of A.objects)c.set(k.objectApiName,k.recordCount)}p(82,"Indexing the snapshot",0,n.objects.length);for(let[a,{scoped:g}]of n.objects.entries()){let w=g.objectApiName,A=c.get(w)??0;c.has(w)||(await Pe(oe(e.dir,"backups")),await l.writeFile(Le(e,t,w),""),c.set(w,0));let S=await Ie(e,t,w);if(S.rows!==A)throw new Ee("damaged",`The snapshot of ${w} holds ${S.rows} records where its read kept ${A}: it is not kept.`);p(82+6*(a+1)/n.objects.length,`Indexed ${w}`,a+1,n.objects.length)}let u=n.objects.find(({scoped:a})=>M(a.objectApiName));if(u===void 0||n.linkable===void 0)return{records:c};p(88,"Reading the links of files to the records read");let h=await tt({reader:d,folder:e,snapshotId:t,linked:n.objects.map(({scoped:a})=>a.objectApiName).filter(a=>(c.get(a)??0)>0&&At(a,n.linkable)),documentsInSnapshot:(c.get(u.scoped.objectApiName)??0)>0,...s.signal!==void 0?{signal:s.signal}:{}});return{records:c,files:h}}async function wn(e,t,n,o,s,r){let d=await it(e,t,n.objects.map(({scoped:i,describe:c,capture:l})=>({objectApiName:i.objectApiName,userLookups:st(c,l.fields)}))),p=await dt({reader:o,organizationId:s,users:d,...Ot(n.objects),...r!==void 0?{signal:r}:{}});return lt(e,p)}async function yn(e,t,n,o,s,r,d){let p=oe(e.dir,zt),i={changed:0,deleted:0,created:0},c=[];try{let l=await Ze(o,n.objects.map(({capture:a})=>({objectApiName:a.objectApiName,readMode:a.readMode,held:!1})),s,p,d),u=Date.parse(Z(s)),h=Date.parse(r);for(let a of l){if("unread"in a){c.push({objectApiName:a.objectApiName,reason:a.unread});continue}if(!a.moved)continue;let g=await pn(e,t,a.objectApiName,a,u,h);i.changed+=g.changed,i.deleted+=g.deleted,i.created+=g.created}}finally{await gt(p,{recursive:!0,force:!0})}return{movedWhileTaken:i,notChecked:c}}async function An(e,t,n,o){try{n!==void 0&&await e.write({...n,status:"failed"})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: not marked failed: ${v(s)}`)}try{await gt(t.dir,{recursive:!0,force:!0})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: what its take wrote was not removed: ${v(s)}`)}}export{Gt as a,B as b,Xn as c,D as d,Kt as e,Jt as f,Yn as g,qn as h};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-VZT4E2OJ.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-JQZTMFO7.mjs";import"./chunk-JFNLKHY6.mjs";import"./chunk-VZVICK7Q.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-7PY3VQP3.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{p as actDeliverability,o as actEmailsGate,n as actSendersOf,q as afterLeaseEmailsRefusal,l as checkpointEmails,j as checkpointEmailsUncounted,c as draftedByDiff,d as draftedByPlan,a as emailsOfLimit,m as emailsRefusal,k as emailsUncountedWords,r as pageEmailsRefusal,e as statusBackByDiff,f as statusBackByPlan,b as updatedByDiff,g as writtenByDiff,h as writtenByPlan,i as writtenByUndo};
|
|
@@ -4,4 +4,4 @@ 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{a as T,b as F,d as B,k as R}from"./chunk-
|
|
7
|
+
import{a as T,b as F,d as B,k as R}from"./chunk-3XG25GTF.mjs";import{a as L,f as C,i as $,j as _}from"./chunk-54HYHHVL.mjs";import{b as j,l as x,o as N}from"./chunk-WSUKC2U3.mjs";import{a as I}from"./chunk-4TLYUZD5.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{dd as A}from"./chunk-ZQO5PDX5.mjs";var w=class{byObject=new Map;add(e){let t=this.byObject.get(e.objectApiName);t||(t=new Map,this.byObject.set(e.objectApiName,t));let s=t.get(e.recordId),r=s?.[e.fieldName];if(r!==void 0&&r!==e.value)return{taken:!1,kept:r};let n=s??{Id:e.recordId};return n[e.fieldName]=e.value,t.set(e.recordId,n),{taken:!0}}updates(){return[...this.byObject].map(([e,t])=>[e,[...t.values()]])}};var J="DUPLICATES_DETECTED",X=3,Y=2e3;function Z(i){return new Promise(e=>setTimeout(e,i))}function z(i){let e=i.errorDetails??[];return N(i.errors,e.length===i.errors.length?e:void 0)}function q(i){let e=i.errorDetails;return e?.length!==1||e[0].statusCode===J||z(i)}function Q(i){let e=Object.keys(i).find(s=>s!=="Id"),t=e===void 0?void 0:i[e];return typeof t=="string"?t:""}function U(i){return{objectApiName:i,op:"update"}}function V(i){let e=i.automation??"the target's automation";I.warn(`[forge] ${i.objectApiName}: ${e} hit ${i.limit??"a Salesforce limit"} on an update of ${i.from} records \u2014 sending a record on its own, then smaller calls.`)}function y(i){return Object.keys(i).filter(e=>e!=="Id").length}async function fe(i){if(!i.enabled||!i.updateRecords||i.pendingFkUpdates.length===0)return null;let e=new E(i);return await e.patch(i.pendingFkUpdates),e.finish()}var ee=1024,te=.6;function K(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function M(i){let e=2538058380;for(let t=0;t<i.length;t++)e=Math.imul(e^i.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var H=class{capacity=ee;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);firstPart=new Float64Array(this.capacity);several=new Uint8Array(this.capacity);note(e,t){let s=K(t),r=M(t),n=this.find(s,r);if(n>=0){this.firstPart[n]!==e+1&&(this.several[n]=1);return}this.used+1>this.capacity*te&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=s,this.h2[o]=r,this.firstPart[o]=e+1,this.used++}spans(e){let t=this.find(K(e),M(e));return t>=0&&this.several[t]===1}find(e,t){let s=this.capacity-1;for(let r=t&s;;r=r+1&s){if(this.firstPart[r]===0)return-1;if(this.h1[r]===e&&this.h2[r]===t)return r}}freeSlotFor(e){let t=this.capacity-1,s=e&t;for(;this.firstPart[s]!==0;)s=s+1&t;return s}grow(){let{h1:e,h2:t,firstPart:s,several:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.firstPart=new Float64Array(this.capacity),this.several=new Uint8Array(this.capacity);for(let n=0;n<s.length;n++){if(s[n]===0)continue;let o=this.freeSlotFor(t[n]);this.h1[o]=e[n],this.h2[o]=t[n],this.firstPart[o]=s[n],this.several[o]=r[n]}}},E=class{constructor(e){this.input=e;this.splits=e.splitting!==void 0,this.splitting=e.splitting??L(0),this.bulkUnsupported=e.bulkUnsupported??new Set}input;resolvedCount=0;unresolvedCount=0;insertOnlyLost=0;unresolved=[];pass2Failed=0;pass2Samples=[];notSent=0;notSentObjects=new Set;cancelled=!1;handed=0;held=new w;splitting;splits;bulkUnsupported;backoff=new x({initialDelay:Y});limitOf(e){return this.splits&&e&&!e.success?A(e.errors):void 0}async patch(e,t){let{input:s}=this;if(!s.enabled||!s.updateRecords||e.length===0)return;this.handed+=e.length;let r=new w;for(let n of e)this.take(n,t?.(n)===!0?this.held:r);await this.send(r)}async sendHeld(){await this.send(this.held)}take(e,t){let{input:s}=this,{remapper:r}=s,n=r.get(e.sourceRefId);if(!n){if(s.deferUnresolved){s.stillPending?.push(e);return}if(s.outsideTheSample?.(e)){s.onLeftOutsideTheSample?.(e.objectApiName,e.fieldName);return}this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}=<source ${e.sourceRefId}>`,messages:[`Cycle FK '${e.fieldName}' could not be resolved \u2014 referenced parent (source ${e.sourceRefId}) was not cloned`]});return}if(e.insertOnly){this.insertOnlyLost++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Lookup '${e.fieldName}' left empty: only an insert sets it, and the record it names (source ${e.sourceRefId}) was written after this one`]});return}let o=t.add({objectApiName:e.objectApiName,recordId:e.newId,fieldName:e.fieldName,value:n});if(!o.taken){this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Conflicting cycle FK update for ${e.fieldName}: ${String(o.kept)} vs ${n}`]});return}this.resolvedCount++}async send(e){for(let[t,s]of e.updates()){if(this.jobsFor(t,s.length)){await this.sendAsJobs(t,s);continue}await this.sendObject(t,s)}}jobsFor(e,t){let{input:s}=this;return s.bulkUpdate!==void 0&&t>=2e3&&s.restOnly?.has(e)!==!0&&!this.bulkUnsupported.has(e)}leaveNotSent(e,t){for(let s of t)this.notSent+=y(s);t.length>0&&this.notSentObjects.add(e)}async sendObject(e,t,s,r){let{input:n}=this,{targetOrgId:o}=n,d=n.updateRecords;if(!d||t.length===0)return;let c=()=>(this.cancelled||(this.cancelled=n.stopped?.()===!0),this.cancelled);if(c()){this.leaveNotSent(e,t);return}let l,a=await _(t,{key:U(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,maxSize:B.rest,...r,beforeEachSend:()=>c()?"stop":void 0,send:async p=>{try{return{answers:await d(o,e,[...p])}}catch(h){return l={error:h},{answers:[]}}},limited:p=>this.limitOf(p),settle:(p,h,k,S)=>{let v=l;l=void 0,v?this.callThrew(e,p,v.error):this.settleAnswers(e,p,h,k,S,s),n.onAnswered?.()},onFirstRefusal:V});a.stopped&&this.leaveNotSent(e,[...a.stopped.part,...a.stopped.rest])}settleAnswers(e,t,s,r,n,o){let{input:d}=this;for(let c=0;c<t.length;c++){if(r.has(c))continue;let l=s[c];l?l.success?d.onPatched?.(e,t[c]):o&&z(l)?o.push(t[c]):this.refused(e,t[c],l,n.get(c)):(this.pass2Failed+=y(t[c]),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t[c]),messages:[`No result returned for record (API truncated batch: ${s.length}/${t.length})`]}))}}refused(e,t,s,r){this.tellRefusedByFilter(e,t,s),this.pass2Failed+=y(t),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t),messages:r===void 0?s.errors:[...s.errors,C(r,$(this.splitting.allowance,U(e)),"run")]})}callThrew(e,t,s){for(let r of t)this.pass2Failed+=y(r);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e} batch failed`,messages:[P(s)]})}async sendAsJobs(e,t){let{input:s}=this,r=s.bulkUpdate;if(!r)return;let n=t.map((l,a)=>({record:l,at:a,value:Q(l)})).sort((l,a)=>l.value===a.value?l.at-a.at:l.value<a.value?-1:1).map(({record:l})=>l),o=U(e),{sizes:d,allowance:c}=this.splitting;for(let l=0;l<n.length;l+=F){let a=n.slice(l,l+F);if(this.cancelled||(this.cancelled=s.stopped?.()===!0),this.cancelled){this.leaveNotSent(e,a);continue}let p=d.of(o);if(p<200){let u=Math.ceil(a.length/p),f=c.take(o,u);d.countExtraCalls(o,f);let m=a.slice(0,f*p);try{await this.sendObject(e,m,void 0,{pricedAs:"job",paid:{calls:f}})}finally{f<u&&d.spend(o)}if(f===u)continue;if(a=a.slice(m.length),this.cancelled){this.leaveNotSent(e,a);continue}if(a.length<2e3){await this.sendObject(e,a);continue}}let h;try{h=await r(e,a)}catch(u){if(!(u instanceof T)){await this.sendObject(e,a);continue}for(let f of a)this.pass2Failed+=y(f);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e}: a Bulk API job of ${a.length} updates was lost`,messages:[P(u),"The target may hold any of these lookups: they are counted as left empty."]}),s.onAnswered?.();continue}if(h.aborted){this.cancelled=!0,this.leaveNotSent(e,a);continue}if(h.untouched){h.untouched.unsupported&&this.bulkUnsupported.add(e),await this.sendObject(e,a);continue}let k=[],S=[],v=[],b;a.forEach((u,f)=>{let m=h.rows[f]??"unprocessed",g=h.answers[f],O=m==="answered"?this.limitOf(g):void 0;O&&g?(b??=O,S.push(u),v.push(g)):m==="answered"&&g?.success?s.onPatched?.(e,u):m==="may-have-written"?(this.pass2Failed+=y(u),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(u),messages:["The Bulk API job may have written this update without saying so."]})):m!=="answered"||!g||q(g)?k.push(u):this.refused(e,u,g)}),s.onAnswered?.(),await this.sendAgainByRest(e,k),await this.sendObject(e,S,void 0,{refusedIn:{from:200,answers:v,...b?{cause:b}:{}}})}}async sendAgainByRest(e,t){let s=t;for(let r=0;s.length>0;r++){r>0&&await(this.input.wait??Z)(this.backoff.calculateDelay(r-1));let n=[];await this.sendObject(e,s,r<X-1?n:void 0),s=n}}tellRefusedByFilter(e,t,s){let r=this.input.onRefusedByFilter,n=t.Id;if(!r||typeof n!="string")return;let o=new Set((s.errorDetails??[]).filter(d=>d.statusCode===j).flatMap(d=>d.fields));for(let d of Object.keys(t))d!=="Id"&&o.has(d)&&r(e,d,n)}finish(){let{resolvedCount:e,unresolvedCount:t,insertOnlyLost:s,pass2Failed:r,notSent:n}=this;if(this.handed===0)return null;let o=e+t+s;if(this.input.deferUnresolved&&e===0&&r===0&&s===0)return null;let d=r+t+s+n;if(this.input.onProgress({objectName:"__pass2__",status:d>0?"error":"done",progress:100,message:`Pass 2 (cycle FK update): ${e-r-n}/${o} resolved`+(n>0?`; cancelled with ${n} not sent`:"")}),d>0){let c=n>0?[{recordSummary:`${[...this.notSentObjects].join(", ")}: ${n} lookup${n===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}]:[];return{objectApiName:"__pass2__",stage:"insert",failedCount:d,attemptedCount:o,samples:[...c,...this.pass2Samples,...this.unresolved].slice(0,3)}}return null}};export{w as a,fe as b,H as c,E as d};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as R,b as S,c as E,d as y}from"./chunk-BZ24IAP5.mjs";import{homedir as O}from"node:os";import{join as N,resolve as I}from"node:path";var P="SANDFORGE_JOURNAL_DIR";function k(e=process.env){let n=e[P];return n!==void 0&&n.trim()!==""?I(n):N(O(),".sandforge")}import{spawn as T}from"node:child_process";import{join as Y}from"node:path";import{StringDecoder as C}from"node:string_decoder";function G(){return process.execArgv.filter(e=>!/^--inspect/.test(e))}function j(e){return Y(__dirname,`${e}.mjs`)}var a="SANDFORGE_RELAYED_BY";function q(e={}){let n=(e.platform??process.platform)==="win32",A=e.scriptPath??j;return(v,w,o,i={})=>new Promise((B,L)=>{let p=i.relayedBy??e.relayedBy,b={...process.env,...p!==void 0?{[a]:p}:{},...n?{[y]:"ipc"}:{}},r=T(process.execPath,[...G(),A(v),...w],{stdio:n?["ignore","pipe","pipe","ipc"]:["ignore","pipe","pipe"],env:b,detached:!n,windowsHide:!0}),f=[],u=[],l=i.onStderr!==void 0?new C("utf8"):void 0;r.stdout?.on("data",t=>f.push(t)),r.stderr?.on("data",t=>{u.push(t),process.stderr.write(t);let d=l?.write(t);d&&i.onStderr?.(d)});let s=()=>{if(!n||!r.connected){r.kill("SIGINT");return}r.send(E,t=>{t&&r.kill("SIGINT")})};o.aborted?s():o.addEventListener("abort",s,{once:!0}),r.on("error",t=>{o.removeEventListener("abort",s),L(t)}),r.on("close",(t,d)=>{o.removeEventListener("abort",s);let m=l?.end();m&&i.onStderr?.(m);let g=R.find(h=>h===d);B({code:t??(g!==void 0?S(g):1),stdout:Buffer.concat(f).toString("utf8"),stderr:Buffer.concat(u).toString("utf8")})})})}function c(){let e=process.env[a]?.trim();return e===void 0||e===""?void 0:e}function _(){return c()?.startsWith("sandforge env")===!0}function ee(e,n){return _()?n:e}var F="sandforge mcp clone_org_plan",x="sandforge mcp clone_org",J=new Map([["sandforge env",["--sweep","--include-changed"]],["sandforge env, relayed by sandforge mcp",["--include-changed"]],["sandforge mcp",["--mute-automation","--leave-undeletable","--store","--include-changed","--preview"]],[F,["--max-total","--exclude-object","--exclude","--filter","--fit","--fit-within","--fit-seed","--fit-draw","--fit-parents","--fit-children","--fit-whole","--fit-floor","--anonymize","--accept-automation","--accept-emails","--mute-automation","--checkpoint-first"]],[x,[]]]);function ne(){return _()||c()===x}function H(e){let n=c();return n===void 0||J.get(n)?.includes(e)===!0}function te(e,n){return H(e)?e:n===void 0?`this script's own ${e}`:`this script's own ${n} with ${e}`}export{k as a,a as b,q as c,c as d,_ as e,ee as f,F as g,x as h,ne as i,H as j,te as k};
|
|
@@ -4,4 +4,4 @@ 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{a as y}from"./chunk-4TLYUZD5.mjs";import{d,f as i,g as u}from"./chunk-
|
|
7
|
+
import{a as y}from"./chunk-4TLYUZD5.mjs";import{d,f as i,g as u}from"./chunk-OHEOJISY.mjs";import{b as p,k as m,l as f}from"./chunk-WZQEK4WT.mjs";var M="SELECT Id, Name, DeveloperName, NamespacePrefix, SobjectType FROM RecordType WHERE IsActive = true",l=m(f({Id:p().min(1),Name:p(),DeveloperName:p().min(1),NamespacePrefix:p().nullable().optional(),SobjectType:p().min(1)}));function b(e){return l.parse(e).map(t=>({id:t.Id,name:t.Name,developerName:t.DeveloperName,namespacePrefix:t.NamespacePrefix?t.NamespacePrefix:null,sobjectType:t.SobjectType}))}var I=/^012000000000000(AAA)?$/;function T(e){return e===null||e===""||typeof e=="string"&&I.test(e)}function h(e){if(!T(e.RecordTypeId))return e;let t={...e};return delete t.RecordTypeId,t}function j(e,t,s="forge"){y.warn(`[${s}] ${e}: RecordTypeId ${t} has no active ${e} record type with the same API name on the target org. Records keep the source Id and the target org will likely refuse them \u2014 create or activate that record type on the target.`)}function k(e,t){let s=new Set(t.map(i)),a=[];for(let n of e){if(s.has(i(n)))continue;let o=t.filter(r=>r.developerName===n.developerName&&(r.sobjectType??"")===(n.sobjectType??""));o.length!==0&&a.push({objectApiName:n.sobjectType??"",source:d(n),target:o.map(d)})}return a}function v(e){let t=u(e.source).namespacePrefix,s=t?`of package ${t}`:"the source org's own";return`${e.objectApiName}: record type ${e.source}, ${s}, is not mapped to ${e.target.join(" or ")} in the target org: a record type is matched to one of the same namespace only. Its records keep the source Id unless the target gets ${e.source}, or a decision maps it.`}var R=class{buildMapping(t,s){let a=new Map;for(let o of s)a.set(i(o),o);let n=[];for(let o of t){let r=a.get(i(o));r&&n.push({sourceId:o.id,targetId:r.id,developerName:d(o)})}return n}apply(t,s,a){let n=new Map;for(let r of s)n.set(r.sourceId,r.targetId);let o=new Set;return t.map(r=>{let c=r.RecordTypeId;if(T(c))return h(r);if(typeof c!="string")return{...r};let g=n.get(c);return g?{...r,RecordTypeId:g}:(a&&!o.has(c)&&(o.add(c),a(c)),{...r})})}};export{M as a,b,T as c,h as d,j as e,k as f,v as g,R as h};
|