sandforge 1.81.0 → 1.83.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-J6G23RUI.mjs → chunk-262TP6UU.mjs} +1 -1
- package/lib/{chunk-NWVVCZUK.mjs → chunk-27BBEGUD.mjs} +1 -1
- package/lib/{chunk-Y5ZCPY36.mjs → chunk-2ADSD5WK.mjs} +1 -1
- package/lib/{chunk-55LQD3Y3.mjs → chunk-2GSMHGIV.mjs} +1 -1
- package/lib/chunk-2K5BYZQM.mjs +8 -0
- package/lib/{chunk-GK7VEYFM.mjs → chunk-2KTGDYUH.mjs} +1 -1
- package/lib/{chunk-T3PLRQ2T.mjs → chunk-2N73W63D.mjs} +1 -1
- package/lib/{chunk-7PK5QDQI.mjs → chunk-2R6GFNKF.mjs} +1 -1
- package/lib/{chunk-2OIRJEYE.mjs → chunk-2WMKJVD2.mjs} +1 -1
- package/lib/{chunk-D62KWDDT.mjs → chunk-36Y225OM.mjs} +1 -1
- package/lib/{chunk-HYOOJVR6.mjs → chunk-3CM7LAPE.mjs} +1 -1
- package/lib/{chunk-OIIL4NVI.mjs → chunk-3OVTKRS4.mjs} +1 -1
- package/lib/{chunk-UT27HXE7.mjs → chunk-3V4YH5KO.mjs} +1 -1
- package/lib/{chunk-OZNLOV4U.mjs → chunk-446GBKAC.mjs} +1 -1
- package/lib/{chunk-SQGP46QS.mjs → chunk-4GCYGQXD.mjs} +1 -1
- package/lib/{chunk-2NAIUKVL.mjs → chunk-4V3QO7HF.mjs} +1 -1
- package/lib/{chunk-GWRKS3AL.mjs → chunk-4X5D3MSV.mjs} +1 -1
- package/lib/{chunk-KGYXLSQ5.mjs → chunk-5OGNK3JP.mjs} +1 -1
- package/lib/{chunk-D7P7DTWL.mjs → chunk-6KOUYHEY.mjs} +1 -1
- package/lib/chunk-6QSHWIZI.mjs +48 -0
- package/lib/chunk-6VOQFISN.mjs +7 -0
- package/lib/{chunk-742SSN7I.mjs → chunk-6YC2ELCU.mjs} +1 -1
- package/lib/chunk-77IVKH7R.mjs +7 -0
- package/lib/{chunk-KNIRA333.mjs → chunk-77MZRBWX.mjs} +1 -1
- package/lib/{chunk-ZUA5BNAO.mjs → chunk-7BQMBXKX.mjs} +1 -1
- package/lib/{chunk-OQQHNYR7.mjs → chunk-7DPHZWA4.mjs} +2 -2
- package/lib/chunk-7V2UYZ6S.mjs +7 -0
- package/lib/chunk-7WSQ65WG.mjs +9 -0
- package/lib/{chunk-HVC5CYIB.mjs → chunk-7ZBDACVG.mjs} +1 -1
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-XC2QKQT5.mjs → chunk-AG24QMSY.mjs} +1 -1
- package/lib/{chunk-K77NR3UK.mjs → chunk-AHUGG3WU.mjs} +1 -1
- package/lib/{chunk-K55LH4ZQ.mjs → chunk-ALBY5SOH.mjs} +1 -1
- package/lib/chunk-AXFD2OH6.mjs +7 -0
- package/lib/{chunk-YCSFP6ER.mjs → chunk-BH76USTQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-YIGFYZQY.mjs → chunk-BPHTA6KP.mjs} +1 -1
- package/lib/{chunk-MNITSYI2.mjs → chunk-BT43WSOS.mjs} +1 -1
- package/lib/{chunk-ZWZXQTAK.mjs → chunk-BVZ5H3N4.mjs} +14 -14
- package/lib/{chunk-43K2C6H2.mjs → chunk-C6RKM4BB.mjs} +1 -1
- package/lib/{chunk-C4YGSK6W.mjs → chunk-CDWZGQAJ.mjs} +1 -1
- package/lib/chunk-CGZGL6VT.mjs +7 -0
- package/lib/{chunk-KE2PGD6C.mjs → chunk-CN5HGFG4.mjs} +1 -1
- package/lib/chunk-CQAFVEKP.mjs +13 -0
- package/lib/{chunk-XIZ5LMQM.mjs → chunk-CTPLYUXA.mjs} +1 -1
- package/lib/chunk-CXKZ6TYV.mjs +9 -0
- package/lib/{chunk-DHIW4IO5.mjs → chunk-D6JT4PAB.mjs} +1 -1
- package/lib/{chunk-AELFEK3G.mjs → chunk-D7XUNWWU.mjs} +1 -1
- package/lib/{chunk-GR3NGDVM.mjs → chunk-DB5RVDC5.mjs} +1 -1
- package/lib/{chunk-MO3N5XVV.mjs → chunk-DIGUC7S4.mjs} +2 -2
- package/lib/{chunk-2OZG6GRW.mjs → chunk-DKDKCGXV.mjs} +1 -1
- package/lib/chunk-DMT5SCO3.mjs +7 -0
- package/lib/chunk-DNQKVCUV.mjs +475 -0
- package/lib/{chunk-MAHZMPMZ.mjs → chunk-DSR2MSBH.mjs} +1 -1
- package/lib/{chunk-O6ADMP36.mjs → chunk-E3RQ575Y.mjs} +1 -1
- package/lib/{chunk-ETT5GP4P.mjs → chunk-EOQON3E5.mjs} +1 -1
- package/lib/{chunk-TKQQVB2D.mjs → chunk-ETNQHIDI.mjs} +1 -1
- package/lib/chunk-F5SBGJWW.mjs +7 -0
- package/lib/chunk-FBXH4VRQ.mjs +7 -0
- package/lib/chunk-FKCIGJOI.mjs +15 -0
- package/lib/{chunk-OVOLG3AL.mjs → chunk-FVLFO2S6.mjs} +1 -1
- package/lib/{chunk-YOGMP72T.mjs → chunk-FYWNSMOZ.mjs} +1 -1
- package/lib/{chunk-DHGPDSXS.mjs → chunk-GEEWPTV5.mjs} +1 -1
- package/lib/{chunk-FSDO4DJA.mjs → chunk-GLN4PI5P.mjs} +1 -1
- package/lib/{chunk-PYUEHBA6.mjs → chunk-GT5ZKU6V.mjs} +1 -1
- package/lib/chunk-GTRU5AV5.mjs +7 -0
- package/lib/chunk-H33DVU3D.mjs +7 -0
- package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-4L7FBOJS.mjs → chunk-HQZUQXDC.mjs} +1 -1
- package/lib/{chunk-VSU74RQ3.mjs → chunk-HVX2AFYW.mjs} +1 -1
- package/lib/chunk-I3ZO76LL.mjs +21 -0
- package/lib/{chunk-V4RKM4QZ.mjs → chunk-I5C4O3VA.mjs} +1 -1
- package/lib/{chunk-FSZTXLNW.mjs → chunk-IHGYJZZ2.mjs} +1 -1
- package/lib/chunk-ISA2NYJV.mjs +7 -0
- package/lib/{chunk-2IB7I3IQ.mjs → chunk-ISAUCWYK.mjs} +1 -1
- package/lib/{chunk-3B5H24ZG.mjs → chunk-ISOSTAJR.mjs} +1 -1
- package/lib/chunk-IXIY6Q4M.mjs +7 -0
- package/lib/{chunk-TPHXRHOA.mjs → chunk-J3TIHLWG.mjs} +1 -1
- package/lib/{chunk-TQM2XJ27.mjs → chunk-JAV6F6OA.mjs} +1 -1
- package/lib/chunk-JBWJ6UEZ.mjs +7 -0
- package/lib/{chunk-WM5JI4JI.mjs → chunk-JH4ZTVQN.mjs} +1 -1
- package/lib/{chunk-BZFIOZS3.mjs → chunk-JIPT5FUD.mjs} +1 -1
- package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/{chunk-67CC7RAE.mjs → chunk-JREKJO3D.mjs} +1 -1
- package/lib/{chunk-3AOKLIVE.mjs → chunk-JUOQUG7U.mjs} +1 -1
- package/lib/chunk-JYUMD357.mjs +7 -0
- package/lib/{chunk-56MPPWLA.mjs → chunk-K7G3W7XH.mjs} +1 -1
- package/lib/{chunk-OU5W7SCB.mjs → chunk-KKS2KFBT.mjs} +1 -1
- package/lib/{chunk-RKALOKAU.mjs → chunk-KWAVSZ2B.mjs} +1 -1
- package/lib/{chunk-WI4HYWV6.mjs → chunk-KXUOHACP.mjs} +1 -1
- package/lib/{chunk-GTIXJCGS.mjs → chunk-L3I6DAHX.mjs} +1 -1
- package/lib/{chunk-FLNLG43R.mjs → chunk-L47JCNP3.mjs} +1 -1
- package/lib/{chunk-5344TZBT.mjs → chunk-L4MSL4U7.mjs} +1 -1
- package/lib/chunk-L4RJX7DG.mjs +7 -0
- package/lib/chunk-L6CLN664.mjs +7 -0
- package/lib/chunk-LI2XNV7F.mjs +7 -0
- package/lib/chunk-LP2D3JJP.mjs +7 -0
- package/lib/{chunk-EH5YUA5W.mjs → chunk-LWES2KZE.mjs} +1 -1
- package/lib/{chunk-YJEXE6HZ.mjs → chunk-LYOGCIYD.mjs} +2 -2
- package/lib/{chunk-BNO5GIJ6.mjs → chunk-MJD6CPZZ.mjs} +1 -1
- package/lib/{chunk-33ZX3A56.mjs → chunk-MTM4KG3T.mjs} +1 -1
- package/lib/{chunk-E2YJVSX6.mjs → chunk-N2HYG3BL.mjs} +1 -1
- package/lib/chunk-N5UIE4IR.mjs +7 -0
- package/lib/{chunk-R6TF26V4.mjs → chunk-NDFFIJL5.mjs} +1 -1
- package/lib/{chunk-FDGFUEK3.mjs → chunk-NFEBX75O.mjs} +1 -1
- package/lib/{chunk-QXLZINZB.mjs → chunk-NNV7IGM7.mjs} +1 -1
- package/lib/{chunk-OXKZ4Y3B.mjs → chunk-NS6ONPWL.mjs} +1 -1
- package/lib/{chunk-OEHVAJAB.mjs → chunk-O7GCCRPW.mjs} +1 -1
- package/lib/chunk-OO24ZYYJ.mjs +7 -0
- package/lib/chunk-OOIDCHBQ.mjs +9 -0
- package/lib/{chunk-MWLFFVQV.mjs → chunk-OS5GE52G.mjs} +1 -1
- package/lib/chunk-OS6HFJ7L.mjs +7 -0
- package/lib/{chunk-HYBH5PFM.mjs → chunk-OTJH6AEA.mjs} +1 -1
- package/lib/chunk-OUU47Y7A.mjs +7 -0
- package/lib/{chunk-FTA5LOVX.mjs → chunk-P6WRYJN3.mjs} +1 -1
- package/lib/{chunk-DXOXLUZA.mjs → chunk-PDRXM5WN.mjs} +1 -1
- package/lib/chunk-PGRY365W.mjs +7 -0
- package/lib/chunk-Q4PPI3KG.mjs +7 -0
- package/lib/chunk-QFTF2PGS.mjs +21 -0
- package/lib/chunk-QKJXIY6L.mjs +7 -0
- package/lib/{chunk-DMBR24CK.mjs → chunk-QLRWU3MB.mjs} +1 -1
- package/lib/chunk-QO4MPHZD.mjs +7 -0
- package/lib/chunk-QP3JLFIO.mjs +7 -0
- package/lib/{chunk-UCHAZ4ZU.mjs → chunk-QQDZQCO2.mjs} +1 -1
- package/lib/chunk-QROPNEGY.mjs +14 -0
- package/lib/{chunk-6NADW3OI.mjs → chunk-QXB6U3ZP.mjs} +1 -1
- package/lib/chunk-R3OM3X4L.mjs +8 -0
- package/lib/chunk-R7GKMAT4.mjs +7 -0
- package/lib/{chunk-JU2XEKEO.mjs → chunk-RVCPQVKM.mjs} +1 -1
- package/lib/{chunk-WEZLXE34.mjs → chunk-RZKJQOOC.mjs} +1 -1
- package/lib/chunk-S4PRKKGC.mjs +8 -0
- package/lib/{chunk-NJ3EOEHS.mjs → chunk-SX6QWYCQ.mjs} +1 -1
- package/lib/{chunk-ONMBSACW.mjs → chunk-T36DZJPH.mjs} +1 -1
- package/lib/{chunk-AJPSGVMD.mjs → chunk-T7DDS4UQ.mjs} +1 -1
- package/lib/chunk-TCEXCHXR.mjs +7 -0
- package/lib/chunk-TMIESDE5.mjs +7 -0
- package/lib/chunk-TQJ5NPRC.mjs +7 -0
- package/lib/chunk-TUPZY2QJ.mjs +7 -0
- package/lib/{chunk-2Z54GB6X.mjs → chunk-U2CTKIPE.mjs} +1 -1
- package/lib/{chunk-DQR5NDMI.mjs → chunk-U4YFYSF3.mjs} +1 -1
- package/lib/{chunk-EOSEMFPU.mjs → chunk-UIR77ZJD.mjs} +1 -1
- package/lib/{chunk-UUSLTW5V.mjs → chunk-UOHZW2L4.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-CULAOP3U.mjs → chunk-VXZ5PTOM.mjs} +1 -1
- package/lib/{chunk-IBURU7T7.mjs → chunk-VZLJZEV2.mjs} +1 -1
- package/lib/chunk-W3BQGMTR.mjs +7 -0
- package/lib/{chunk-WWTXRWNZ.mjs → chunk-WABXKL4N.mjs} +1 -1
- package/lib/{chunk-E2OBAWSH.mjs → chunk-WAYQLQAD.mjs} +1 -1
- package/lib/{chunk-6CDIIFNX.mjs → chunk-WBELLGNE.mjs} +1 -1
- package/lib/{chunk-LO527YLT.mjs → chunk-WJAZ5LHL.mjs} +1 -1
- package/lib/{chunk-6IGEASOF.mjs → chunk-WXU6ZJIV.mjs} +1 -1
- package/lib/{chunk-YHIOS2PU.mjs → chunk-WZN36ACK.mjs} +1 -1
- package/lib/{chunk-AITNZWLB.mjs → chunk-X2XZQ434.mjs} +1 -1
- package/lib/chunk-X4HZD5U2.mjs +7 -0
- package/lib/chunk-X6XNTOGO.mjs +7 -0
- package/lib/{chunk-5VQNKDFU.mjs → chunk-XAMMIPZ4.mjs} +1 -1
- package/lib/{chunk-MHW6DV6T.mjs → chunk-XAUQXYPW.mjs} +1 -1
- package/lib/{chunk-5UT2ZBGF.mjs → chunk-XCJUNX63.mjs} +1 -1
- package/lib/chunk-XJICAOAQ.mjs +7 -0
- package/lib/{chunk-GYKNCYES.mjs → chunk-XKFHTBAB.mjs} +1 -1
- package/lib/{chunk-6SEDOIO3.mjs → chunk-XMQ5R6TC.mjs} +1 -1
- package/lib/chunk-XPXEQKLR.mjs +7 -0
- package/lib/{chunk-SW2NUKQL.mjs → chunk-Y7YUNRKK.mjs} +1 -1
- package/lib/{chunk-UIUPPEFB.mjs → chunk-YBZIDW6W.mjs} +1 -1
- package/lib/{chunk-X2ZVSQ54.mjs → chunk-YEVB7LVK.mjs} +1 -1
- package/lib/{chunk-EAFLDSQ2.mjs → chunk-Z3MGN42K.mjs} +1 -1
- package/lib/{chunk-MKNAZPOT.mjs → chunk-ZB5E7NHU.mjs} +1 -1
- package/lib/chunk-ZCOSME6P.mjs +7 -0
- package/lib/{chunk-KRNFVAGC.mjs → chunk-ZOSESZ22.mjs} +1 -1
- package/lib/chunk-ZTHC42X6.mjs +7 -0
- package/lib/{chunk-XEB6HZ34.mjs → chunk-ZXOUWHYE.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +1 -1
- package/lib/sandforge-backup.mjs +1 -1
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +4 -4
- package/lib/sandforge-env.mjs +184 -139
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +14 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +155 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +17 -3
- package/lib/chunk-2ZMGVBLW.mjs +0 -7
- package/lib/chunk-5C5XEVZN.mjs +0 -11
- package/lib/chunk-5CKWGZX4.mjs +0 -9
- package/lib/chunk-5ZKCLBTN.mjs +0 -474
- package/lib/chunk-7DALDJMO.mjs +0 -7
- package/lib/chunk-CAFUNR6D.mjs +0 -7
- package/lib/chunk-DPYTG6DM.mjs +0 -48
- package/lib/chunk-G4VXPS3A.mjs +0 -7
- package/lib/chunk-GF247DA7.mjs +0 -7
- package/lib/chunk-IKGHRYCN.mjs +0 -7
- package/lib/chunk-IM2XA6JI.mjs +0 -7
- package/lib/chunk-K5HV4YRO.mjs +0 -7
- package/lib/chunk-KOQV4WXC.mjs +0 -8
- package/lib/chunk-N6HHNR6J.mjs +0 -7
- package/lib/chunk-N7J6NJQ6.mjs +0 -7
- package/lib/chunk-NWPQF5XR.mjs +0 -7
- package/lib/chunk-O7DAFE6M.mjs +0 -14
- package/lib/chunk-OMZJ37JI.mjs +0 -15
- package/lib/chunk-R2BJWO5N.mjs +0 -20
- package/lib/chunk-T26C576X.mjs +0 -9
- package/lib/chunk-T5VAULLQ.mjs +0 -7
- package/lib/chunk-V2QO6KOE.mjs +0 -19
- package/lib/chunk-V473C7LY.mjs +0 -7
- package/lib/chunk-W2AAGIZF.mjs +0 -7
- package/lib/chunk-WD47PGUS.mjs +0 -10
- package/lib/chunk-XC54KKKC.mjs +0 -7
- package/lib/chunk-XGKSSCW7.mjs +0 -7
- package/lib/chunk-ZWCRWF7E.mjs +0 -7
|
@@ -4,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 A}from"./chunk-5LFSFYFJ.mjs";import{a as z,h as p}from"./chunk-TZE3Y7IQ.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";import{
|
|
7
|
+
import{a as A}from"./chunk-5LFSFYFJ.mjs";import{a as z,h as p}from"./chunk-TZE3Y7IQ.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";import{vc as C}from"./chunk-6QSHWIZI.mjs";import{b as g,f as b,k as w,l as m,o as j}from"./chunk-WZQEK4WT.mjs";function H(r,n){return{describe:e=>r.describe(e),describeGlobal:()=>r.describeGlobal(),query:async e=>{let t=await r.query(e);return A(r.limitInfo,n),{totalSize:t.totalSize,records:t.records}},update:(e,t)=>r.sobject(e).update(t,{headers:C()}),destroy:(e,t)=>r.sobject(e).destroy(t)}}var u=200,P=30,I=100,M=4,y=10,q=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function B(r){return typeof r=="string"&&q.test(r)}function k(r,n=u){let e=[];for(let t=0;t<r.length;t+=n)e.push(r.slice(t,t+n).map(s=>`'${z(s)}'`).join(", "));return e}var L=m({success:b(),id:g().nullish(),errors:w(j([m({message:g()}).loose(),g()])).optional()}).loose(),W=m({name:g(),label:g(),queryable:b().optional(),createable:b().optional(),layoutable:b().optional()}).loose(),_=m({sobjects:w(W)}).loose();async function F(r){let n=_.parse(await r.describeGlobal());return new Map(n.sobjects.filter(e=>e.queryable===!0&&e.createable===!0&&e.layoutable===!0).map(e=>[e.name,e.label]))}async function E(r,n){let e=new Array(r.length),t=0,s=async()=>{for(;t<r.length;){let i=t++;e[i]=await r[i]()}};return await Promise.all(Array.from({length:Math.min(n,r.length)},s)),e}async function Q(r,n,e,t){if(e.length===0)return{related:[],uncounted:[]};let s=(n.childRelationships??[]).filter(o=>o.cascadeDelete===!0&&t.has(o.childSObject)),i=s.slice(0,P),a=new Set(s.slice(P).map(o=>t.get(o.childSObject)??o.childSObject)),l=k(e),h=await E(i.map(o=>async()=>{try{let c=p(o.childSObject),d=p(o.field),O=0;for(let T of l)O+=(await r.query(`SELECT COUNT() FROM ${c} WHERE ${d} IN (${T})`)).totalSize;return{relationship:o,records:O}}catch{return{relationship:o,records:null}}}),M),f=new Map;for(let{relationship:o,records:c}of h){let d=t.get(o.childSObject)??o.childSObject;if(c===null){a.add(d);continue}f.set(o.childSObject,(f.get(o.childSObject)??0)+c)}return{related:[...f].filter(([,o])=>o>0).map(([o,c])=>({objectApiName:o,label:t.get(o)??o,records:c})).sort((o,c)=>c.records-o.records||o.label.localeCompare(c.label)),uncounted:[...a].sort()}}async function Z(r,n,e,t,s=1){let i=p(n),a=[...new Set(["Id",...e])].map(p),l=a.join(", "),h=a.length>I?u/4:u,f=await E(k(t,h).map(o=>()=>r.query(`SELECT ${l} FROM ${i} WHERE Id IN (${o})`)),s),R=[];for(let o of f)for(let c of o.records){if(typeof c!="object"||c===null)continue;let d={...c};delete d.attributes,R.push(d)}return R}function x(r,n,e){let t=Array.isArray(r)?r:[r];for(let s of t){let i=L.safeParse(s);if(i.success&&i.data.success){e.done++;continue}if(e.failed++,e.errors.length<y){let a=i.success?i.data.errors?.[0]:void 0,l=typeof a=="string"?a:a?.message??"The org gave no reason.";e.errors.push({objectApiName:n,message:l})}}}async function J(r,n,e,t){let s={done:0,failed:0,errors:[]};for(let i=0;i<e.length&&!t?.aborted;i+=u){let a=e.slice(i,i+u);try{x(await r.update(n,[...a]),n,s)}catch(l){s.failed+=a.length,s.errors.length<y&&s.errors.push({objectApiName:n,message:S(l)})}}return s}async function V(r,n,e,t){let s={done:0,failed:0,errors:[]};for(let i=0;i<e.length&&!t?.aborted;i+=u){let a=e.slice(i,i+u);try{x(await r.destroy(n,[...a]),n,s)}catch(l){s.failed+=a.length,s.errors.length<y&&s.errors.push({objectApiName:n,message:S(l)})}}return s}function D(r,n){return n===0?"success":r===0?"failure":"partial"}function Y(r){let n=r.reduce((t,s)=>t+s.counts.done,0),e=r.reduce((t,s)=>t+s.counts.failed,0);return{status:D(n,e),done:n,failed:e,objects:r.map(t=>({objectApiName:t.objectApiName,done:t.counts.done,failed:t.counts.failed})),errors:r.flatMap(t=>t.counts.errors).slice(0,y)}}export{H as a,u as b,B as c,k as d,F as e,E as f,Q as g,Z as h,J as i,V as j,Y 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,b}from"./chunk-
|
|
7
|
+
import{a,b}from"./chunk-JREKJO3D.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as seedObjectAccess,b as templateTheOrgTakes};
|
|
@@ -4,7 +4,7 @@ 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 B,b as J}from"./chunk-PC247GKX.mjs";import{a as S}from"./chunk-
|
|
7
|
+
import{a as B,b as J}from"./chunk-PC247GKX.mjs";import{a as S}from"./chunk-ISOSTAJR.mjs";import{$a as b,Ra as h,Sa as E,Ta as U,Ua as D}from"./chunk-6QSHWIZI.mjs";import{b as l,l as m,s as C,u as M,v as K}from"./chunk-WZQEK4WT.mjs";import{randomBytes as L}from"node:crypto";import{mkdirSync as ye,statSync as Z}from"node:fs";import{mkdir as w,open as Oe,readFile as R,readdir as _,rename as Fe,rm as f,rmdir as xe,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as Ie}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Ce,gzip as be}from"node:zlib";import{createHash as me}from"node:crypto";var G=16,Y=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:C(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return me("sha256").update(n).digest("hex")}function we(n){return JSON.stringify([n.name.toLowerCase(),n.type,n.createable===!0,n.updateable===!0,n.nillable===!0,[...n.referenceTo??[]].sort(),n.encrypted===!0])}function dn(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:we(t)})).sort((t,r)=>t.key<r.key?-1:t.key>r.key?1:0);return{digest:W(e.map(({line:t})=>t).join(`
|
|
8
8
|
`)),fields:Object.fromEntries(e.map(({name:t,line:r})=>[t,W(r).slice(0,G)]))}}function pn(n,e){let t={added:[],removed:[],changed:[]};if(n.digest===e.digest)return t;let r=new Map(Object.entries(n.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}])),i=new Map(Object.entries(e.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}]));for(let[o,{name:s,print:a}]of i){let p=r.get(o);p===void 0?t.added.push(s):p.print!==a&&t.changed.push(s)}for(let[o,{name:s}]of r)i.has(o)||t.removed.push(s);return t.added.sort(),t.removed.sort(),t.changed.sort(),t}var g=448,Pe=384,Ee=30,ee=3,De=15,ne=1440*6e4,I=1440*6e4,Se=Q(be),ve=Q(Ce),T="checkpoint.json",ze="fingerprints.json.gz",Ae="fingerprints.json",Le="snapshots.json",te="replay.json.gz",re=/^[A-Za-z][A-Za-z0-9_]*$/;function In(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?Ie(e):c(V(),".sandforge");return c(t,"checkpoints")}function Re(n=V()){return c(n,".sandforge","locks")}function k(n){let e=D.safeParse(n).success?S(n.slice(0,15)):void 0;if(e===void 0)throw new d("invalid","Not an Organization Id");return e}function Ne(n){return n.length===18&&D.safeParse(n).success&&S(n.slice(0,15))===n}function v(n,e,t){return ie(c(n,e,t),e,t)}function ie(n,e,t){return{organizationId:e,checkpointId:t,dir:n,checkpointFile:c(n,T),fingerprintsFile:c(n,ze),plainFingerprintsFile:c(n,Ae),snapshotsFile:c(n,Le),indexDir:c(n,"index"),binDir:c(n,"bin"),filesDir:c(n,"files"),previewsDir:c(n,"previews"),rewindsDir:c(n,"rewinds")}}function oe(n){if(!re.test(n)||n.length>80)throw new d("invalid","Not a Salesforce API name");return n}function Cn(n,e){return c(n.indexDir,`${oe(e)}.idx`)}function bn(n){return c(n.indexDir,"recreated.ndjson")}function Pn(n){return c(n.indexDir,"notInBin.ndjson")}function En(n,e){return c(n.binDir,`${oe(e)}.ids`)}function Dn(n){return c(n.filesDir,"documents.ndjson")}function Sn(n){return c(n.filesDir,"links.ndjson")}function vn(n){return c(n.dir,te)}var $e=[/^checkpoint\.json$/,/^fingerprints\.json(?:\.gz)?$/,/^snapshots\.json$/,/^backups\/[A-Za-z0-9_-]{1,200}__[A-Za-z][A-Za-z0-9_]{0,79}\.ndjson(?:\.gz)?$/,/^bin\/[A-Za-z][A-Za-z0-9_]{0,79}\.ids$/,/^files\/(?:links|documents)\.ndjson(?:\.gz)?$/,/^index\/(?:recreated|notInBin)\.ndjson$/,/^replay\.json\.gz$/],zn=te,je=["","backups","bin","files","index"],An=T;function se(n){return $e.some(e=>e.test(n))}async function Ln(n){let e=[];for(let t of je){let r;try{r=await _(c(n.dir,t),{withFileTypes:!0})}catch(i){if(F(i)==="ENOENT"||F(i)==="ENOTDIR")continue;throw i}for(let i of r){let o=t===""?i.name:`${t}/${i.name}`;if(!i.isFile()||!se(o))continue;let s=c(n.dir,t,i.name);e.push({path:o,file:s,bytes:(await x(s)).size})}}return e.sort((t,r)=>ge(t.path,r.path))}function Rn(n,e){if(!se(e))throw new d("invalid","Not a file a checkpoint holds");return c(n,...e.split("/"))}function Nn(n,e){return c(n.previewsDir,O(E,e))}function H(n,e){return c(n.rewindsDir,O(U,e))}function O(n,e){let t=n.safeParse(e);if(!t.success)throw new d("invalid","Not an id of this store");return t.data}async function X(n){await w(n,{recursive:!0,mode:g})}var q="abcdefghijklmnopqrstuvwxyz0123456789";function $n(n,e=new Date){let t=e.toISOString(),r=`${t.slice(0,4)}${t.slice(5,7)}${t.slice(8,10)}`,i=`${t.slice(11,13)}${t.slice(14,16)}${t.slice(17,19)}`,o=Array.from(L(4),s=>q[s%q.length]).join("");return`${n}-${r}-${i}-${o}`}function _e(n,e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Not a number of days: ${e}`);return e===0?null:new Date(n.getTime()+e*I).toISOString()}function ce(n,e){return n.expiresAt!==null&&Date.parse(n.expiresAt)<=e}function Te(n,e){if(n.expiresAt===null)return!1;let t=Date.parse(n.expiresAt);return t>e&&t-e<=ee*I}function He(n,e){let t=e-De*I;return Date.parse(n.readFrom)<t?new Date(t).toISOString():void 0}function Me(n,e){let t=ae(n);return t!==void 0&&t<=e}function ae(n){let e=n.scratchExpiresAt;if(e===void 0)return;let t=Date.parse(e);if(Number.isFinite(t))return/^\d{4}-\d{2}-\d{2}$/.test(e)?t+I:t}function Ke(n,e){let t=ae(n);return t!==void 0&&t>e&&t-e<=ee*I}var d=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointStoreError"}code};function jn(n,e,t){let r=n.detail!==void 0?` (${n.detail})`:"";if(n.path===e)switch(n.reason){case"otherOwner":return`another user of this machine owns it, and could read and replace the checkpoints in it. ${t} names a folder of your own.`;case"notAFolder":return`it is a file, not a folder. ${t} names a folder for them, or move the file away.`;case"cannotMake":return`it could not be made${r}. ${t} names a folder this user can write.`}let i="the folder of every org\u2019s lock, whatever the store";switch(n.reason){case"otherOwner":return`${i}, is owned by another user of this machine: run as its owner, or remove it.`;case"notAFolder":return`${i}, is a file, not a folder: move the file away.`;case"cannotMake":return`${i}, could not be made${r}: make it a folder this user can write.`}}var de=m({version:K(1),objects:C(l().regex(re).max(80),Y)});async function Ue(n,e){let t;try{t=JSON.parse(await Je(n))}catch{throw new d("damaged","The checkpoint\u2019s field prints cannot be read")}let r=de.safeParse(t);if(!r.success)throw new d("damaged","The checkpoint\u2019s field prints do not parse");let i=new Map(Object.entries(r.data.objects));for(let o of e)if(i.get(o.objectApiName)?.digest!==o.fingerprint)throw new d("damaged",`The field prints of ${o.objectApiName} are not the checkpoint\u2019s`);return i}async function Be(n){let e=de.safeParse({version:1,objects:n});if(!e.success)throw new d("invalid",`Not field prints: ${e.error.message}`);return Se(`${JSON.stringify(e.data)}
|
|
9
9
|
`)}async function Je(n){let e;try{e=await R(n.fingerprintsFile)}catch(t){if(t.code!=="ENOENT")throw t;return R(n.plainFingerprintsFile,"utf8")}return(await ve(e)).toString("utf8")}function _n(n){let e=n.uid??(()=>process.getuid?.()),t=n.locksDir??Re();for(let r of[n.root,t]){let i=We(r,e);if(i!==void 0)return{refusal:i}}return{store:new N({...n,locksDir:t})}}function We(n,e){try{let t=Z(n,{throwIfNoEntry:!1});if(t!==void 0&&!t.isDirectory())return{reason:"notAFolder",path:n};ye(n,{recursive:!0,mode:g});let r=e();return r!==void 0&&Z(n).uid!==r?{reason:"otherOwner",path:n}:void 0}catch(t){return{reason:"cannotMake",path:n,detail:cn(t)}}}var N=class{root;locksDir;renameFile;lockOptions;changes=new Map;constructor(e){this.root=e.root,this.locksDir=e.locksDir,this.renameFile=e.rename??((t,r)=>Fe(t,r)),this.lockOptions={...e.lockSelf?{self:e.lockSelf}:{},...e.lockChecks?{checks:e.lockChecks}:{}}}folderOf(e,t){return v(this.root,k(e),O(h,t))}async create(e,t){let r=this.folderOf(e,t);await X(c(this.root,r.organizationId));try{await w(r.dir,{mode:g})}catch(i){throw F(i)==="EEXIST"?new d("exists",`A checkpoint ${t} is kept already`):i}return await w(r.indexDir,{mode:g}),await w(r.binDir,{mode:g}),r}async write(e){let t=z(e),r=this.folderOf(t.org.organizationId,t.checkpointId);await this.writeWhole(r.checkpointFile,$(t))}async writeFingerprints(e,t){await this.writeWhole(e.fingerprintsFile,await Be(t))}async readFingerprints(e,t){return Ue(e,t.objects)}async checkpointsOf(e){return this.readsOf(k(e))}async read(e){let t=O(h,e);for(let r of await this.organizationKeys()){let i=v(this.root,r,t);if(await y(i.dir))return A(i)}}async update(e,t){let r=async()=>{let a=await this.read(e);if(a===void 0)throw new d("notFound",`No checkpoint ${e} is kept`);if(a.checkpoint===void 0)throw new d("damaged",`The checkpoint ${e} is damaged`);let p=t(structuredClone(a.checkpoint));if(p.checkpointId!==a.folder.checkpointId||j(p.org.organizationId)!==a.folder.organizationId)throw new d("invalid","A change never moves a checkpoint");return await this.write(p),b.parse(p)},o=(this.changes.get(e)??Promise.resolve()).then(r,r),s=o.catch(()=>{});return this.changes.set(e,s),s.then(()=>{this.changes.get(e)===s&&this.changes.delete(e)}),o}keep(e,t,r=new Date){return this.update(e,i=>({...i,expiresAt:t?null:_e(r,Ee)}))}async list(e={}){let t=(e.now??new Date).getTime(),r=e.organizationId!==void 0?k(e.organizationId):void 0,i=[];for(let o of await this.organizationKeys(r)){let s=await this.readsOf(o),a=qe(s);for(let p of s)i.push(await Qe(p,t,a,e.refreshedAt))}return i.sort((o,s)=>ge(s.checkpointId,o.checkpointId))}async delete(e){let t=await this.read(e);if(t===void 0)return{outcome:"notFound"};let r=this.lock(t.folder.organizationId,"delete",t.folder.checkpointId);if("busy"in r)return{outcome:"busy",holder:r.busy};try{await f(t.folder.dir,{recursive:!0,force:!0})}finally{r.lock.release()}return t.checkpoint?{outcome:"deleted",checkpoint:t.checkpoint}:{outcome:"deleted"}}async importInto(e,t,r){let i=this.folderOf(e,t),o=c(this.root,i.organizationId);await X(o);let s=ie(c(o,`${Ge}${L(6).toString("hex")}`),i.organizationId,i.checkpointId);await w(s.dir,{mode:g});try{let a=z(await r(s));if(a.checkpointId!==i.checkpointId||j(a.org.organizationId)!==i.organizationId)throw new d("invalid","An import keeps the checkpoint it was asked to");let p=z({...a,bytes:await Xe(s.dir,a)});if(await this.writeWhole(s.checkpointFile,$(p)),await y(i.dir))return{outcome:"exists"};try{await this.renameFile(s.dir,i.dir)}catch(u){if(await y(i.dir))return{outcome:"exists"};throw u}return{outcome:"imported",checkpoint:p}}finally{await f(s.dir,{recursive:!0,force:!0}),await xe(o).catch(()=>{})}}async sweep(e=new Date){let t=e.getTime(),r={checkpoints:[],journals:[],previews:0,skipped:[]};for(let i of await this.organizationKeys()){await Ze(c(this.root,i),t);let o=await en(await this.readsOf(i),t);if(o.length===0)continue;let s=this.lock(i,"sweep");if("busy"in s){r.skipped.push(i);continue}try{for(let a of o)await nn(await A(a),t,r)}finally{s.lock.release()}}return r}lock(e,t,r){return on(this.locksDir,e,{operation:t,...r!==void 0?{checkpointId:r}:{}},this.lockOptions)}heldBy(e){return sn(this.locksDir,e,this.lockOptions)}async organizationKeys(e){return(await P(this.root)).filter(r=>Ne(r)&&(e===void 0||r===e))}async readsOf(e){let t=(await P(c(this.root,e))).filter(i=>h.safeParse(i).success),r=[];for(let i of t)r.push(await A(v(this.root,e,i)));return r}async writeWhole(e,t){let r=`${e}.${process.pid}-${L(4).toString("hex")}.tmp`,i=await Oe(r,"wx",Pe);try{try{await i.writeFile(t,typeof t=="string"?"utf8":void 0),await i.sync()}finally{await i.close()}await this.renameFile(r,e)}catch(o){throw await f(r,{force:!0}),o}}},Ge=".importing-",Ye=/^\.importing-[0-9a-f]{12}$/;async function Ze(n,e){for(let t of await P(n)){if(!Ye.test(t))continue;let r=c(n,t),i=await x(r).catch(()=>{});i!==void 0&&i.mtimeMs+ne<=e&&await f(r,{recursive:!0,force:!0})}}function z(n){let e=b.safeParse(n);if(!e.success)throw new d("invalid",`Not a checkpoint: ${e.error.message}`);return e.data}function $(n){return`${JSON.stringify(n,null,2)}
|
|
10
10
|
`}async function pe(n,e){let t=0;for(let r of await _(n,{withFileTypes:!0})){let i=c(n,r.name);r.isDirectory()?t+=await pe(i,e):r.isFile()&&i!==e&&(t+=(await x(i)).size)}return t}async function Xe(n,e){let t=await pe(n,c(n,T)),r=o=>Buffer.byteLength($({...e,bytes:o}),"utf8"),i=t+r(t);return i=t+r(i),i}async function A(n){let e;try{e=JSON.parse(await R(n.checkpointFile,"utf8"))}catch{return{folder:n}}let t=b.safeParse(e);return t.success?t.data.checkpointId!==n.checkpointId||j(t.data.org.organizationId)!==n.organizationId?{folder:n}:{folder:n,checkpoint:t.data}:{folder:n}}function qe(n){let e;for(let{folder:t,checkpoint:r}of n){let i=r?.lastRewind?.rewindId;i!==void 0&&(e===void 0||i>e.rewindId)&&(e={checkpointId:t.checkpointId,rewindId:i})}return e}function Ve(n,e,t,r){if(n.status==="taking")return{why:"taking"};if(n.status==="failed")return{why:"failed"};let i=r?.(e);if(i!==void 0)return{why:"refreshed",refreshedAt:i};if(Me(n.org,t))return{why:"scratchExpired"}}async function Qe({folder:n,checkpoint:e},t,r,i){let o={checkpointId:n.checkpointId,organizationId:n.organizationId};if(e===void 0)return{...o,valid:!1,why:"damaged"};let s=Ve(e,n.organizationId,t,i);if(s!==void 0)return{...o,checkpoint:e,valid:!1,why:s.why,...s.refreshedAt!==void 0?{refreshedAt:s.refreshedAt}:{}};let a={...o,checkpoint:e,valid:!0};Te(e,t)&&(a.expiresSoon=!0),Ke(e.org,t)&&(a.scratchExpiresSoon=!0);let p=He(e,t);p!==void 0&&(a.binReachSince=p);let u=e.lastRewind;return u!==void 0&&r?.checkpointId===n.checkpointId&&u.undoUntil!==void 0&&u.undoneAt===void 0&&Date.parse(u.undoUntil)>t&&await y(H(n,u.rewindId))&&(a.undo={rewindId:u.rewindId,until:u.undoUntil}),a}async function en(n,e){let t=[];for(let{folder:r,checkpoint:i}of n)i!==void 0&&(ce(i,e)||await ue(r,i,e)||(await fe(r,e)).length>0)&&t.push(r);return t}async function ue(n,e,t){let r=e.lastRewind?.undoUntil;return e.lastRewind!==void 0&&r!==void 0&&Date.parse(r)<=t&&await y(H(n,e.lastRewind.rewindId))}async function fe(n,e){let t=[];for(let r of await P(n.previewsDir)){if(!E.safeParse(r).success)continue;let i=c(n.previewsDir,r),o=await x(i).catch(()=>{});o!==void 0&&o.mtimeMs+ne<=e&&t.push(i)}return t}async function nn(n,e,t){let{folder:r,checkpoint:i}=n;if(i===void 0)return;if(i.expiresAt!==null&&ce(i,e)){await f(r.dir,{recursive:!0,force:!0});let s=i.lastRewind?.undoUntil,a=s!==void 0&&i.lastRewind?.undoneAt===void 0&&Date.parse(s)>e;t.checkpoints.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,expiresAt:i.expiresAt,...a?{undoUntil:s}:{}});return}let o=i.lastRewind;o?.undoUntil!==void 0&&await ue(r,i,e)&&(await f(H(r,o.rewindId),{recursive:!0,force:!0}),t.journals.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,rewindId:o.rewindId,undoUntil:o.undoUntil}));for(let s of await fe(r,e))await f(s,{recursive:!0,force:!0}),t.previews+=1}var tn=m({...B,operation:M(["take","rewind","undo","delete","sweep","empty"]),checkpointId:h.optional()}),le=J(n=>{let e=tn.safeParse(n);return e.success?e.data:void 0});function rn(n,e){return c(n,`${k(e)}.lock`)}function on(n,e,t,r={}){let i=k(e),o=t.checkpointId!==void 0?O(h,t.checkpointId):void 0,s=le.acquire(c(n,`${i}.lock`),a=>({...a,operation:t.operation,...o!==void 0?{checkpointId:o}:{}}),r);return"busy"in s?{busy:he(s.busy)}:{lock:{organizationId:i,release:s.lock.release}}}function sn(n,e,t={}){let r=le.holder(rn(n,e),t);return r!==void 0?he(r):void 0}function he({version:n,token:e,...t}){return t}async function P(n){try{return(await _(n,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch(e){if(F(e)==="ENOENT"||F(e)==="ENOTDIR")return[];throw e}}async function y(n){return(await x(n).catch(()=>{}))?.isDirectory()===!0}function j(n){try{return k(n)}catch{return}}function ge(n,e){return n<e?-1:n>e?1:0}function F(n){return n?.code}function cn(n){return n instanceof Error?n.message:String(n)}export{dn as a,pn as b,g as c,Pe as d,Ee as e,ee as f,De as g,ne as h,In as i,Re as j,k,Cn as l,bn as m,Pn as n,En as o,Dn as p,Sn as q,vn as r,zn as s,An as t,se as u,Ln as v,Rn as w,Nn as x,H as y,X as z,$n as A,_e as B,ce as C,Te as D,He as E,Me as F,Ke as G,d as H,jn as I,Ue as J,Be as K,_n as L,N as M,qe as N,rn as O,on as P,sn as Q};
|
|
@@ -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 w,$b as wa,Ab as X,Ac as Xa,Bb as Y,Bc as Ya,Cb as Z,Cc as Za,Db as _,Dc as _a,Eb as $,Fa as a,Fb as aa,Ga as b,Gb as ba,Ha as c,Hb as ca,Ia as d,Ib as da,Ja as e,Jb as ea,Ka as f,Kb as fa,La as g,Lb as ga,Ma as h,Mb as ha,Na as i,Nb as ia,Oa as j,Ob as ja,Pa as k,Pb as ka,Qa as l,Qb as la,Ra as m,Rb as ma,Sa as n,Sb as na,Ta as o,Tb as oa,Ua as p,Ub as pa,Va as q,Vb as qa,Wa as r,Wb as ra,Xa as s,Xb as sa,Ya as t,Yb as ta,Za as u,Zb as ua,_a as v,_b as va,ab as x,ac as xa,bb as y,bc as ya,cb as z,cc as za,db as A,dc as Aa,eb as B,ec as Ba,fb as C,fc as Ca,gb as D,gc as Da,hb as E,hc as Ea,ib as F,ic as Fa,jb as G,jc as Ga,kb as H,kc as Ha,lb as I,lc as Ia,mb as J,mc as Ja,nb as K,nc as Ka,ob as L,oc as La,pb as M,pc as Ma,qb as N,qc as Na,rb as O,rc as Oa,sb as P,sc as Pa,tb as Q,tc as Qa,ub as R,uc as Ra,vb as S,vc as Sa,wb as T,wc as Ta,xb as U,xc as Ua,yb as V,yc as Va,zb as W,zc as Wa}from"./chunk-R3OM3X4L.mjs";import"./chunk-77IVKH7R.mjs";import"./chunk-2WMKJVD2.mjs";import"./chunk-VXZ5PTOM.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-ZOSESZ22.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-Z3MGN42K.mjs";import"./chunk-2GSMHGIV.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ISOSTAJR.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{v as API_BUDGET_EXCEEDED,r as API_BUDGET_NEAR_SHARE,o as API_REQUESTS_NOT_TOLD,I as BULK_BATCHES_NOT_TOLD,y as CHECKPOINT_REFUSED,B as CHECKPOINT_STOPPED_WORDS,a as DEFAULT_CONFIRM_ABOVE_RECORDS,b as DEFAULT_MAX_TOTAL,W as DELIVERABILITY_READ_MOST,fa as DEVELOPER_EDITION_SINGLE_EMAILS,ta as EMAILS_NOT_ACCEPTED,Oa as ForgeRunGateError,j as LastSimulations,Ma as OWNER_MAP_INACTIVE,Na as OWNER_MAP_UNKNOWN,c as READ_CEILING_PER_OBJECT,Z as SAMPLE_CANNOT_FIT,aa as SAMPLE_PLAN_GONE,$ as SAMPLE_PLAN_MISMATCH,Y as SAMPLE_STORAGE_UNREAD,_ as SAMPLE_TOO_LARGE,e as STORAGE_NEAR_SHARE,F as WHOLE_ORG_SOURCE_READS_PER_OBJECT,E as WHOLE_ORG_TARGET_READS_PER_OBJECT,ga as alertsCountAsSingle,u as apiBudgetCheckOf,w as apiBudgetRefusal,R as automationBytesOf,va as automationReadRequests,Wa as automationRefusal,La as automationUnreadOf,J as bulkBatchesRefusal,Va as bypassAssistantSentences,Ka as bypassesToAssign,z as checkpointPartOf,A as checkpointScopeStop,x as confirmationApiOf,l as confirmationSimulatedOf,Ca as confirmationStorageOf,ka as countedEmailChecksOf,g as countedStorageBytes,la as countedTargetEmails,Ba as deliverabilityAfterLeaseStop,ya as deliverabilityGate,xa as deliverabilityLineOf,wa as deliverabilityPartOf,sa as emailCheckLines,ja as emailChecksOf,ra as emailRefusal,ia as emailsCountedPerRecord,qa as emailsOfLimit,na as emailsUncountedOf,k as farPastTheSimulation,L as fileStorageRefusal,Qa as filesRefusalStop,Fa as firedOnInsertOf,Ga as firedOnUpdateOf,G as forgeRequestPartsOf,i as forgeVolumeCaseKey,P as forgeWriteBudgetOf,D as forgeWritesOf,Da as formatMB,Ea as formatMBPast,ma as insertsOf,Pa as isForgeRunGateError,Ta as leftOutLines,d as objectsAboveReadCeiling,Ha as objectsUpdatedAfterInsert,oa as overEmailOf,U as personalFieldsAsIsOf,m as pricesForLinesOf,q as readApiBudget,M as readBoundRefusal,N as readBoundStopOf,p as readDataStorage,ea as readEmailLimits,Ya as removalAutomationLines,Xa as removalAutomationRefusal,Ua as removalRiskLines,Za as removalStepsAutomationLines,_a as removalStepsAutomationRefusal,n as rolesMayBeOf,f as rowStorageBytes,Ja as runBypassesOf,s as runRequestsEstimate,t as runRequestsTotal,da as sampleGateErrorOf,ca as sampleGateStopOf,ba as sampleStorageUnreadStopOf,za as sendersOfNothingWritten,Aa as sendersOfNothingWrittenLine,ua as sendersUnreadOf,ha as singleCountAsWorkflow,K as sourceApiBudgetRefusal,Q as storageCheckOf,Ra as storageRefusal,S as storageTakesWords,C as takeCheckpointFirst,pa as unreadEmailOf,Ia as updateStepsOf,H as wholeOrgCostOf,X as wholeOrgDryRunOf,O as wholeOrgFilesOf,V as wholeOrgLeftOutOf,T as wholeOrgWritePlanOf,Sa as writePlanLines,h as writePlanOf};
|
|
@@ -4,7 +4,7 @@ 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{h as O}from"./chunk-
|
|
7
|
+
import{h as O}from"./chunk-X2XZQ434.mjs";import{A as R,B as _,e as X,k as S,r as P}from"./chunk-EOQON3E5.mjs";import{H as E,c as Y,p as A,q as z}from"./chunk-N2HYG3BL.mjs";import{g as w,h as y}from"./chunk-Z3MGN42K.mjs";import{Uc as u}from"./chunk-6QSHWIZI.mjs";import{b as D,e as W,f as Q,l as L}from"./chunk-WZQEK4WT.mjs";import{mkdir as se,rm as M}from"node:fs/promises";import{join as I}from"node:path";var ee=200,ne=X*10,B=2e3,te=["Id","ContentDocumentId","LinkedEntityId","ShareType","Visibility"],ae=["Id","LatestPublishedVersionId","ContentSize"],de="taking",h=D().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),T=D().regex(/^[A-Za-z]{1,40}$/,"Not a sharing value"),V=L({Id:h,ContentDocumentId:h,LinkedEntityId:h,ShareType:T,Visibility:T}),J=L({Id:h,LatestPublishedVersionId:h.nullable(),ContentSize:W().int().nonnegative().nullable(),anchored:Q()});function Re(e,n){return I(e,`${y}.${n}.ndjson`)}var Ce=V.extend({now:L({ShareType:T,Visibility:T})});function Fe(e,n){let t=new Set(n.map(r=>r.toLowerCase())),i=new Map;for(let r of e){let a=r.keyPrefix;t.has(r.name.toLowerCase())&&typeof a=="string"&&a.length===3&&i.set(a,r.name)}return i}function Te(e,n){let t=e.LinkedEntityId;return typeof t=="string"&&t.length>=15?n.get(t.slice(0,3)):void 0}function oe(e){return e.map(n=>{if(!h.safeParse(n).success)throw new Error(`Not a record id: ${n}`);return`'${n}'`}).join(", ")}function ce(e){let n=u(e);return{objectApiName:n,soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function be(e){let n=u(e);return{objectApiName:n,soql:`SELECT COUNT() FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function le(e,n){return{objectApiName:u(e),soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (${oe(n)})`,scanAll:!1}}function fe(e){return{objectApiName:w,soql:`SELECT ${ae.join(", ")} FROM ${w} WHERE Id IN (${oe(e)})`,scanAll:!1}}async function*v(e,n){let t=[];for await(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function*C(e,n){let t=[];for(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function G(e,n,t){let i=e.safeParse(n);if(!i.success)throw new Error(`The org answered a ${t} that does not read as one: ${i.error.message}`);return i.data}function F(e){return e.slice(0,15)}async function xe(e){let{reader:n,folder:t,signal:i}=e,r=e.files??S(O(t.dir)),a=I(t.filesDir,de);await se(a,{recursive:!0,mode:Y});let m=z(t),b=A(t);await r.writeFile(m,""),await r.writeFile(b,"");try{let x=new Map,q=0,H=async d=>{for await(let c of v(_(d),B)){let s=c.map(o=>G(V,o,"link"));for(let o of s)x.has(F(o.ContentDocumentId))||x.set(F(o.ContentDocumentId),o.ContentDocumentId);q+=s.length,await r.appendFile(m,s.map(o=>`${JSON.stringify(o)}
|
|
8
8
|
`).join(""))}await M(d,{force:!0})},K=e.linked.map(d=>({...ce(d),file:I(a,`${u(d)}.links.ndjson`)})),re=await R(n,K,i),$=[];for(let[d,c]of re.entries()){if(c.read){await H(K[d].file);continue}let s=e.linked[d];$.push(s);let o=await P.read(t,e.snapshotId,s),l=0;for(let g of C(C(pe(o),ee),ne)){let f=g.map(k=>({...le(s,k),file:I(a,`${u(s)}.links.${l++}.ndjson`)})),N=(await R(n,f,i)).find(k=>!k.read);if(N&&!N.read)throw new Error(`The links of the files of ${s} could not be read whole: ${c.reason}; read by the ids of its records, ${N.reason}`);for(let k of f)await H(k.file)}}let j=0,U=0,Z=new Set;for(let d of C(C(x.values(),ee),ne)){let c=d.map((l,g)=>({...fe(l),file:I(a,`documents.${g}.ndjson`)})),o=(await R(n,c,i)).find(l=>!l.read);if(o&&!o.read)throw new Error(`The files the links name could not be read by their ids: ${o.reason}`);for(let l of c){for await(let g of v(_(l.file),B)){let f=g.map(p=>({...G(J.omit({anchored:!0}),p,"file"),anchored:!0}));for(let p of f)Z.add(F(p.Id));j+=f.length,U+=f.length,await r.appendFile(b,f.map(p=>`${JSON.stringify(p)}
|
|
9
9
|
`).join(""))}await M(l.file,{force:!0})}}if(e.documentsInSnapshot){let d=await P.read(t,e.snapshotId,w);for await(let c of v(d.records(),B)){let s=c.filter(o=>typeof o.Id=="string"&&!Z.has(F(o.Id))).map(o=>({...G(J.omit({anchored:!0}),ue(o),"file"),anchored:!1}));j+=s.length,s.length>0&&await r.appendFile(b,s.map(o=>`${JSON.stringify(o)}
|
|
10
10
|
`).join(""))}}return{documents:j,links:q,anchored:U,...$.length>0?{readByIds:$}:{}}}finally{await M(a,{recursive:!0,force:!0})}}function*pe(e){for(let n=0;n<e.size;n++)yield e.idAt(n)}function ue(e){return{Id:e.Id,LatestPublishedVersionId:e.LatestPublishedVersionId??null,ContentSize:e.ContentSize??null}}async function*ie(e,n,t,i){if(!await e.exists(n))throw new E("damaged",`The checkpoint\u2019s ${i} are not there`);for await(let r of e.readLines(n)){if(r==="")continue;let a;try{a=JSON.parse(r)}catch{throw new E("damaged",`The checkpoint\u2019s ${i} hold a line that is not JSON`)}let m=t.safeParse(a);if(!m.success)throw new E("damaged",`The checkpoint\u2019s ${i} hold a line that does not parse`);yield m.data}}function $e(e,n=S(O(e.dir))){return ie(n,z(e),V,"file links")}function je(e,n=S(O(e.dir))){return ie(n,A(e),J,"files")}export{ee as a,te as b,V as c,Re as d,Ce as e,Fe as f,Te as g,ce as h,be as i,le as j,xe as k,$e as l,je as m};
|
|
@@ -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,b}from"./chunk-
|
|
7
|
+
import{a,b}from"./chunk-446GBKAC.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as FakerFallback,b as generateByMethod};
|
|
@@ -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{j as g}from"./chunk-
|
|
7
|
+
import{j as g}from"./chunk-6QSHWIZI.mjs";var f=class{link(n,r,i,t){return t.length===0?n:n.map(o=>({...o,[r]:t[Math.floor(Math.random()*t.length)]}))}resolveInsertOrder(n,r=[]){let i=new Map;for(let e of n)i.set(e.objectApiName,e);let t=new Set,o=new Set,d=[];function c(e){if(t.has(e))return;if(o.has(e))throw new Error(`Circular dependency detected involving: ${e}`);o.add(e);let s=i.get(e);if(s){let p=g(s,r);for(let j of p)c(j);d.push(s)}o.delete(e),t.add(e)}for(let e of n)c(e.objectApiName);return d}};export{f as a};
|
|
@@ -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{e as $}from"./chunk-
|
|
7
|
+
import{e as $}from"./chunk-DSR2MSBH.mjs";import{m as F,o as A}from"./chunk-VXZ5PTOM.mjs";import{c as M}from"./chunk-HF6LAK3G.mjs";var k=class{avgSecondsPerApiCall;batchStrategy;constructor(u){this.avgSecondsPerApiCall=u?.avgSecondsPerApiCall??.5,this.batchStrategy=new M}generate(u){let a=u.nodes.filter(o=>o.included);if(a.length===0)return{waves:[],totalRecords:0,totalApiCalls:0,estimatedDurationSeconds:0,cycleResolutions:[]};let{edges:c,components:t}=G(u),i=this.computeTopoLevels(c,t),l=new Map;for(let o of a){let e=i.get(o.objectApiName)??o.level,h=l.get(e);h?h.push(o.objectApiName):l.set(e,[o.objectApiName])}let n=[...l.keys()].sort((o,e)=>o-e),s=new Map(a.map(o=>[o.objectApiName,o])),g=n.map((o,e)=>{let h=l.get(o)??[],v=0,b=0,w=0;for(let N of h){let j=s.get(N);if(!j)continue;v+=j.recordCount;let x=this.batchStrategy.resolve(j.batchStrategy,j.recordCount),C=$(x,j.recordCount).batchCount;b+=C;let O=C*this.avgSecondsPerApiCall;O>w&&(w=O)}return{order:e,objectApiNames:h,totalRecords:v,estimatedDurationSeconds:w,estimatedApiCalls:b}}),r=this.detectCycles(u,c,t),p=g.reduce((o,e)=>o+e.totalRecords,0),f=g.reduce((o,e)=>o+e.estimatedApiCalls,0),m=g.reduce((o,e)=>o+e.estimatedDurationSeconds,0);return{waves:g,totalRecords:p,totalApiCalls:f,estimatedDurationSeconds:m,cycleResolutions:r}}computeTopoLevels(u,a){let c=new Map;a.forEach((n,s)=>{for(let g of n)c.set(g,s)});let t=new Map;for(let n of u){let s=c.get(n.sourceObject),g=c.get(n.targetObject);if(s===void 0||g===void 0||s===g)continue;let r=t.get(s);r?r.push(g):t.set(s,[g])}let i=a.map(()=>0);for(let n=a.length-1;n>=0;n--)for(let s of t.get(n)??[])i[s]=Math.max(i[s],i[n]+1);let l=new Map;for(let[n,s]of c)l.set(n,i[s]);return l}detectCycles(u,a,c){let t=c.filter(n=>n.length>1);if(t.length===0)return[];let i=new Map(A(u).map((n,s)=>[n.objectApiName,s])),l=n=>i.get(n)??0;return t.map(n=>{let s=new Set(n),g=[...n].sort((e,h)=>l(e)-l(h)),r=a.filter(e=>s.has(e.sourceObject)&&s.has(e.targetObject)&&l(e.targetObject)<l(e.sourceObject)),p=r.filter(e=>e.required===!0);if(p.length>0){let e=[...new Set(p.map(b=>b.targetObject))],h=[...new Set(p.map(b=>b.sourceObject))],v=e.length===1;return{objects:g,strategy:"unbreakable",description:`The run cannot break this cycle: ${y(p.map(S))} may not be left empty, and no order writes ${y(h)} first. ${y(e)} ${v?"is":"are"} refused, and what cannot be written without ${v?"it":"them"} is skipped.`}}let f=r.filter(e=>e.insertOnly!==!0),m=r.filter(e=>e.insertOnly===!0),o=[...f.length>0?[`${y(f.map(S))} left empty at insert and filled in by the second pass`]:[],...m.length>0?[`${y(m.map(S))} left empty for good: only an insert sets ${m.length===1?"it":"them"}, and no order writes ${y([...new Set(m.map(e=>e.sourceObject))])} first`]:[]];return{objects:g,strategy:"nullable_lookup",description:`Written in this order, with ${o.join(", and ")}.`}})}};function G(d){let u=d.nodes.filter(t=>t.included).map(t=>t.objectApiName),a=new Set(u),c=d.edges.filter(t=>t.sourceObject!==t.targetObject&&a.has(t.sourceObject)&&a.has(t.targetObject)&&F(t));return{edges:c,components:R(u,c)}}function R(d,u){let a=new Map;for(let r of d)a.set(r,[]);for(let r of u)a.get(r.sourceObject)?.push(r.targetObject);let c=0,t=new Map,i=new Map,l=new Set,n=[],s=[],g=r=>{let p=[];for(t.set(r,c),i.set(r,c),c++,n.push(r),l.add(r),p.push({v:r,neighbors:a.get(r)??[],i:0});p.length>0;){let f=p[p.length-1];if(f.i<f.neighbors.length){let e=f.neighbors[f.i++];t.has(e)?l.has(e)&&i.set(f.v,Math.min(i.get(f.v),t.get(e))):(t.set(e,c),i.set(e,c),c++,n.push(e),l.add(e),p.push({v:e,neighbors:a.get(e)??[],i:0}));continue}let m=f.v;p.pop();let o=p[p.length-1];if(o&&i.set(o.v,Math.min(i.get(o.v),i.get(m))),i.get(m)===t.get(m)){let e=[],h;do h=n.pop(),l.delete(h),e.push(h);while(h!==m);s.push(e)}}};for(let r of d)t.has(r)||g(r);return s}function S(d){return`${d.targetObject}'s lookup to ${d.sourceObject}`}function y(d){return d.length<=1?d.join(""):`${d.slice(0,-1).join(", ")} and ${d[d.length-1]}`}export{k as a,R as b};
|
|
@@ -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{j as Z,l as T}from"./chunk-GWRKS3AL.mjs";import{B as Q,s as Y,t as M,v as K,z as J}from"./chunk-T26C576X.mjs";import{d as G}from"./chunk-BNO5GIJ6.mjs";import{b as V,c as X,g as z}from"./chunk-6IGEASOF.mjs";import{$b as te,Ec as re,Pb as ee,tc as se,uc as N}from"./chunk-KOQV4WXC.mjs";import{b as U,c as B}from"./chunk-SU65Z2BA.mjs";import{B as H}from"./chunk-XEB6HZ34.mjs";import{b as $}from"./chunk-CA5NAXSU.mjs";import{Ad as q,nd as I,rd as C,wd as S,zd as F}from"./chunk-DPYTG6DM.mjs";var _e=5e3,x=2e3,le=1e3,me={masking:{during:"during the masking",records:"records it masked"},restore:{during:"during the restore",records:"records it put back"},erasure:{during:"during the erasure",records:"records it overwrote"}};function ne(e,t){let r=new Set(t.map(s=>s.toLowerCase()));return(e?.objects??[]).filter(s=>r.has(s.objectApiName.toLowerCase())).filter(s=>(s.duplicateRules??[]).length>0).map(s=>({objectApiName:s.objectApiName,rules:(s.duplicateRules??[]).map(n=>n.name)}))}function ae(e){return typeof e=="string"?e.slice(0,15):""}async function pe(e,t){let{rules:r}=t,s=0,n=a=>(s++,e.query(a));try{let a=H(new Date(Date.parse(t.since)-le).toISOString()),i=new Set([...t.masked].map(ae)),c=await n(`SELECT Id, DuplicateRecordSetId, RecordId FROM DuplicateRecordItem WHERE CreatedDate >= ${a} LIMIT ${x+1}`),u=c.done===!1||c.records.length>x,d=c.records.slice(0,x),p=new Set(d.filter(o=>i.has(ae(o.RecordId))).map(o=>String(o.DuplicateRecordSetId??"")).filter(o=>o!=="")),l=d.filter(o=>p.has(String(o.DuplicateRecordSetId??""))).length,m=0;for(let o of G([...p])){let f=await n(`SELECT Id FROM DuplicateRecordSet WHERE CreatedDate >= ${a} AND Id IN (${o})`);m+=f.records.length}return{rules:r,sets:m,items:l,...u?{atLeast:!0}:{},requests:s}}catch(a){return{rules:r,sets:0,items:0,unread:$(a),requests:s}}}function Ie(e,t,r){let s=r.now??Date.now,n=r.sleep??(l=>new Promise(m=>setTimeout(m,l))),a=new Set(t.map(l=>l.objectApiName.toLowerCase())),i=l=>a.has(l.toLowerCase()),c,u=0,d=new Set,p=0;return{covers:i,beforeWrite:l=>{i(l)&&c===void 0&&(u=s())},wrote:(l,m)=>{if(!i(l))return;let o=!1;for(let h of m)typeof h!="string"||h===""||(d.add(h),o=!0);if(!o)return;p=s();let f=u;c??=e.serverTime().then(h=>{let b=Date.parse(h);return Number.isNaN(b)?{unread:`it answered "${h}"`}:{at:new Date(b-Math.max(0,s()-f)).toISOString()}},h=>({unread:$(h)}))},held:()=>d.size,read:async()=>{if(d.size===0)return;let l=c?await c:void 0;if(!l||"unread"in l)return{rules:t,sets:0,items:0,unread:l?`the org's clock: ${l.unread}`:"the org's clock was not read",requests:l?1:0};let m=Math.max(0,p+r.settleMs-s());m>0&&await n(m);let o=await pe(e,{rules:t,since:l.at,masked:d});return{...o,requests:(o.requests??0)+1,waitedMs:m}}}}function Ce(e,t){if(!e)return t;if(!t)return e;let r=[e.unread,t.unread].filter(s=>s!==void 0);return{rules:t.rules.length>=e.rules.length?t.rules:e.rules,sets:e.sets+t.sets,items:e.items+t.items,...e.atLeast||t.atLeast?{atLeast:!0}:{},...r.length>0?{unread:r.join("; ")}:{},requests:(e.requests??0)+(t.requests??0),waitedMs:(e.waitedMs??0)+(t.waitedMs??0)}}function Fe(e){return e!==void 0&&(e.sets>0||e.items>0||e.unread!==void 0)}function ge(e){return e.map(t=>`"${t}"`).join(", ")}function fe(e){return e<=0?"without waiting":e<1e3?"after waiting less than 1 s":`after waiting ${Math.round(e/1e3)} s`}function qe(e,t,r="masking"){if(!e||e.rules.length===0)return"";let s=me[r],n=e.rules.map(c=>`${c.objectApiName} (${ge(c.rules)})`).join(", ");if(e.unread!==void 0)return`What the duplicate rules of ${t} on ${n} wrote ${s.during} could not be read (${e.unread}): a duplicate record set they wrote stays.`;let a=e.requests!==void 0?` Read in ${e.requests} request(s), ${fe(e.waitedMs??0)}.`:"";if(e.sets===0&&e.items===0)return`The duplicate rules of ${t} on ${n} wrote nothing for the ${s.records}.`+a;let i=e.atLeast===!0?"at least ":"";return`The duplicate rules of ${t} on ${n} wrote ${i}${e.sets} duplicate record set(s) and ${i}${e.items} item(s) ${s.during}, for ${s.records}: kept, as they name records that stay.${a}`}var he="AUTOMATION_NOT_ACCEPTED",we="EMAILS_EXCEEDED",Oe="ORG_TEMPORARILY_UNREACHABLE";function Ae(e,t){return e==="cleanup"||e==="empty"?{delete:[...t]}:e==="restore"?{bringBack:[...t],giveBack:[...t]}:e==="emptyUndo"?{bringBack:[...t]}:{giveBack:[...t]}}function be(e,t){let r=e==="cleanup"||e==="empty"?"delete":"update";return t.filter(s=>s.records>0).map(s=>({objectApiName:s.objectApiName,write:r,records:s.records}))}var E={masking:{heading:"masking automation: what {org} runs as the masking writes over the records",the:"the masking",this:"this masking",writes:"writes over",verb:"mask",nothing:"Nothing was written.",flag:"to mask all the same"},restore:{heading:"restore automation: what {org} runs as the restore puts the backup's values back",the:"the restore",this:"this restore",writes:"puts back",verb:"restore",nothing:"Nothing was written.",flag:"to restore all the same"},cleanup:{heading:"cleanup automation: what {org} runs as the cleanup deletes the records",the:"the cleanup",this:"this cleanup",writes:"deletes",verb:"delete",nothing:"Nothing was deleted.",flag:"to delete all the same"},empty:{heading:"emptying automation: what {org} runs as the emptying deletes the records",the:"the emptying",this:"this emptying",writes:"deletes",verb:"empty",nothing:"Nothing was deleted.",flag:"to empty all the same"},emptyUndo:{heading:"undo automation: what {org} runs as the undo brings the records back",the:"the undo",this:"this undo",writes:"brings back",verb:"undo",nothing:"Nothing was written.",flag:"to undo all the same"}},$e={masking:"masking",restore:"restore",cleanup:"cleanup",empty:"empty",emptyUndo:"undo"};function Je(e){return e.erasure===!0?"erasure":e.fromPage===!0?"page":void 0}var ye={"accept-automation":"acceptAutomation","accept-emails":"acceptEmails","mute-automation":"muteAutomation"},De={"accept-emails":"the confirmation's box that lets the org send these emails","mute-automation":"the confirmation's box that mutes the target's automation"},Re={mask:"masking",restore:"restore",delete:"cleanup",erase:"erasure",empty:"emptying",undo:"undo"};function oe(e){let t=r=>De[r]??`--${r}`;return e.replace(/\bAdd --accept-automation to (mask|restore|delete|erase|empty|undo) all the same\b/g,(r,s)=>`Confirm the ${Re[s]??s} from its confirmation, which lists what fires, to ${s} all the same`).replace(/\bWith --mute-automation,/g,`With ${t("mute-automation")} ticked,`).replace(/\bAdd --(accept-emails|mute-automation)\b/g,(r,s)=>`Tick ${t(s)}`).replace(/(^|[.:;] )--(accept-emails|mute-automation)\b/g,(r,s,n)=>`${s}${W(t(n))}`).replace(/--(accept-emails|mute-automation)\b/g,(r,s)=>t(s))}function L(e,t="flags"){return t==="step"?e.replace(/--(accept-automation|accept-emails|mute-automation)\b/g,(r,s)=>`${ye[s]??s} in the step`).replace(/\bAdd (acceptAutomation|acceptEmails|muteAutomation) in the step\b/g,"Turn on $1 in the step"):t==="erasure"?oe(e.replace(/\b(this|the|This|The) (masking|cleanup)\b/g,"$1 erasure").replace(/\bto (mask|delete) all the same\b/g,"to erase all the same").replace(/\b(mask|delete) fewer records\b/g,"erase fewer records")):t==="page"?oe(e):e}var ke={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Ee={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"},ue={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function de({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}function ce(e,t){return t.step==="delete"?Ee[t.when]:t.step==="bringBack"?"as it comes back from the recycle bin":`${e==="restore"?"as its values are put back":"as it is masked"}, ${ke[t.when]}`}function W(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}function ve(e,t,r,s){let n=E[r],a=[n.heading.replace("{org}",t)];if(typeof e.unread=="string")return a.push(` what ${t} runs could not be read: ${e.unread}`),a;let i=e;for(let d of S(i,s))a.push(` ${d.objectApiName}: ${ce(r,d)}: ${de(d)}`);let c=N(i);if(a.length===1&&c.length===0){let d=new Set(Object.values(s).flat()).size;a.push(` nothing fires on the ${d} object(s) it ${n.writes} records of`)}for(let d of ne(i,s.giveBack??[]))a.push(` ${d.objectApiName}: duplicate rules ${d.rules.map(p=>`"${p}"`).join(", ")}: ${n.the} saves a record a rule only alerts on, a rule that blocks still refuses it, and what a rule that reports writes (a duplicate record set and its items) stays`);let u=I(i);u.length>0&&a.push(` bypass held: the user ${n.the} writes as holds ${u.join(", ")}, and what names it stays quiet`);for(let{part:d,reason:p}of c)a.push(` ${ue[d]??d} could not be read: ${p}`);return a}function Se(e,t,r){let s=E[r.act],n=`${s.nothing} Add --accept-automation ${s.flag}, or turn that automation off in ${t} first.`;if(typeof e.unread=="string")return`What ${t} runs as ${s.this} ${s.writes} its records could not be read (${e.unread}), so what fires is not known. ${n}`;let a=e,i=S(a,r.steps),c=N(a);if(i.length===0&&c.length===0)return;let u=[];if(i.length>0){let l=i.map(m=>`${m.objectApiName}: ${de(m)} (${ce(r.act,m)})`);u.push(`${t} runs automation as ${s.this} ${s.writes} its records: ${l.join("; ")}.`)}for(let{part:l,reason:m}of c)u.push(`${W(ue[l]??l)} of ${t} could not be read (${m}), so what fires as ${s.the} ${s.writes} its records is not known.`);let d=r.assign??[];u.push(...re(d,t,s.the));let p=[...new Set(d.flatMap(l=>l.permissionSet??[]))];return r.mayMute===!0&&p.length>0&&u.push(`With --mute-automation, ${s.the} assigns ${p.join(", ")} to the user it writes as for ${s.the} alone, under a lease, and what ${p.length===1?"it keeps":"they keep"} quiet does not fire.`),u.push(n),u.join(" ")}function k(e){let t=e.objects.map(r=>`${r.perRecord} per ${r.objectApiName}`).join(", ");return`about ${te(e.emails,e.limit)} (${t}`+(e.alertsCounted?"; its email alerts among them, as a Developer Edition counts them":"")+")"}function Me(e,t,r){let s=e.map(n=>{if(n.verdict==="unread")return` emails: ${k(n)}; what ${t} has left today could not be read (${n.unread??"not said"})`;let a=`${n.remaining??0} of ${n.max??0} left today`;return n.verdict==="exceeds"?` emails: ${k(n)}, past the ${a}`:` emails: ${k(n)}, ${a}`});return r!==void 0&&s.push(` emails not counted: what sends them was not read (${r})`),s}function Te(e,t,r,s){let n=t.filter(u=>u.verdict==="exceeds");if(n.length===0)return;let a=E[e],i=n.map(u=>`${k(u)}, ${u.remaining??0} of ${u.max??0} left today`).join("; "),c=s?.kind==="enough"?`Turn off what sends them, give the user it writes as the bypass that keeps them quiet (--mute-automation assigns ${s.sets.join(", ")} for ${a.the} alone, and what still sends then fits what is left today), or ${a.verb} fewer records.`:`Turn off what sends them, or ${a.verb} fewer records.`+(s?.kind==="muting"?" What sends them still runs under the mute.":s?.kind==="notEnough"?" --mute-automation would not keep enough of them quiet.":"");return`${W(a.this)} would make ${r} send ${i}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. ${c} ${a.nothing}`}function Qe(e,t,r){return{readAutomation:t,readLimits:()=>ee(e),readDeliverability:()=>r?Promise.resolve(V):X(e),muteOrg:async()=>Y(e),...r?{production:r}:{}}}async function Ze(e,t,r,s){let n=e?.mute?.prepared;if(!e||!n)return{};let a;try{a=await n.acquire(t)}catch(c){if(!M(c))throw c;return{refused:{code:c.code,message:L(c.message,s)}}}let i=e.emails.afterLease(a.outcome,r);return i?(await a.release(),{refused:{code:i.code,message:L(i.message,s)}}):{held:a}}var Ne={objectsRead:[],objects:[],unread:[],conditionsNotRead:0,conditionsBound:0,requests:0};async function et(e){let{act:t,target:r,accord:s}=e,n=e.objects.filter(g=>g.records>0),a=n.map(g=>g.objectApiName),i=e.writes?.steps??Ae(t,a),c=F(i),u=a.length===0?Ne:await e.org.readAutomation(a).catch(g=>{let A=U(g);return{unread:A===void 0?$(g):`the org could not be reached (${A})`}}),d=typeof u.unread=="string"?void 0:u,p=B(u),l=E[t],m=[],o;if(s.muteAutomation===!0&&p===void 0)try{o=await J(e.org.muteOrg,u,{...e.muteLeases,writes:c})}catch(g){if(!M(g))throw g;m.push({code:g.code,message:g.message})}let f=o?.automation??d,h=e.mayMute&&s.muteAutomation!==!0&&e.org.production!==!0,b=[...ve(d??u,r,t,i),...o?Q(o.muted,r).map(g=>` ${g}`):[]],j=Se(f??u,r,{act:t,steps:i,...f?{assign:se(f,q(f,i),e.assignTo)}:{},mayMute:h});j!==void 0&&s.acceptAutomation!==!0&&m.push({code:he,message:j});let D=e.writes?e.writes.written.filter(g=>g.records>0):be(t,n),y=[],R,P;if(f&&p===void 0){if(D.some(A=>C(f,A.write).some(w=>w.objectApiName===A.objectApiName))){let A=await e.org.readLimits().catch(w=>({unread:$(w)}));if(y=T(D,f,A),y.some(w=>w.verdict==="exceeds")){let w=!o&&h&&d?K(d,c):void 0;P=o?{kind:"muting"}:w&&w.plan.assign.length>0?T(D,w.automation,A).some(v=>v.verdict==="exceeds")?{kind:"notEnough"}:{kind:"enough",sets:w.plan.assign.map(v=>v.permissionSet)}:void 0}}R=Z(D,f)}b.push(...Me(y,r,R));let _=Te(t,y,r,P);_!==void 0&&m.push({code:we,message:_});let O=await z({read:u,...o?.plan?{plan:o.plan}:{},writes:c,readDeliverability:p===void 0?e.org.readDeliverability:async()=>({reading:{unread:`${r} could not be reached`},requests:0}),accepted:s.acceptEmails===!0,target:r,run:$e[t],keepsAddresses:!0,mayMute:h});return O.gate.line!==void 0&&b.push(` ${O.gate.line}`),O.gate.stop&&m.push({...O.gate.stop}),p!==void 0&&m.splice(0,m.length,{code:Oe,message:`${r} could not be reached as what it runs was read (${p}), so ${l.the} was not started. ${l.nothing} Check the network, then try again.`}),{answer:{act:t,objects:n,steps:i,...d?{automation:d}:{automationUnread:String(u.unread)},lines:b,emails:y,...R!==void 0?{emailsUncounted:R}:{},...O.gate.deliverability?{deliverability:O.gate.deliverability}:{},emailsAsk:O.gate.verdict==="asks",refusals:m.map(g=>({...g,message:L(g.message,e.voice)})),...o?{mutedAutomation:o.muted}:{},...o?.plan?{mutePlan:o.plan}:{}},...o?{mute:o}:{},emails:O}}var xe=/\bnothing (?:was )?(?:written|deleted)\b/i,ie=/\s*\bNothing was (?:written|deleted)\./g;function tt(e){let[t,...r]=e.refusals;if(!t)return;let s=!1,n=e.refusals.map(a=>s?a.message.replace(ie,"").trim():(s=xe.test(a.message),a.message)).join(" ");return{code:t.code,message:n,alsoRefused:r.map(a=>({code:a.code,message:a.message.replace(ie,"").trim()}))}}function st(e){return e.alsoRefused.length>0?{extraPayload:{alsoRefused:[...e.alsoRefused]}}:{}}export{_e as a,ne as b,Ie as c,Ce as d,Fe as e,qe as f,Je as g,Qe as h,Ze as i,et as j,tt as k,st as l};
|
|
7
|
+
import{j as Z,l as T}from"./chunk-4X5D3MSV.mjs";import{a as Y,b as M,d as K,h as J,j as Q}from"./chunk-7WSQ65WG.mjs";import{d as G}from"./chunk-MJD6CPZZ.mjs";import{b as V,c as X,g as z}from"./chunk-WXU6ZJIV.mjs";import{Jb as ee,Vb as te,nc as se,oc as N,yc as re}from"./chunk-R3OM3X4L.mjs";import{b as U,c as B}from"./chunk-SU65Z2BA.mjs";import{B as H}from"./chunk-ZXOUWHYE.mjs";import{b as $}from"./chunk-CA5NAXSU.mjs";import{Md as I,Qd as C,Vd as S,Yd as F,Zd as q}from"./chunk-6QSHWIZI.mjs";var _e=5e3,x=2e3,le=1e3,me={masking:{during:"during the masking",records:"records it masked"},restore:{during:"during the restore",records:"records it put back"},erasure:{during:"during the erasure",records:"records it overwrote"}};function ne(e,t){let r=new Set(t.map(s=>s.toLowerCase()));return(e?.objects??[]).filter(s=>r.has(s.objectApiName.toLowerCase())).filter(s=>(s.duplicateRules??[]).length>0).map(s=>({objectApiName:s.objectApiName,rules:(s.duplicateRules??[]).map(n=>n.name)}))}function ae(e){return typeof e=="string"?e.slice(0,15):""}async function pe(e,t){let{rules:r}=t,s=0,n=a=>(s++,e.query(a));try{let a=H(new Date(Date.parse(t.since)-le).toISOString()),i=new Set([...t.masked].map(ae)),c=await n(`SELECT Id, DuplicateRecordSetId, RecordId FROM DuplicateRecordItem WHERE CreatedDate >= ${a} LIMIT ${x+1}`),u=c.done===!1||c.records.length>x,d=c.records.slice(0,x),p=new Set(d.filter(o=>i.has(ae(o.RecordId))).map(o=>String(o.DuplicateRecordSetId??"")).filter(o=>o!=="")),l=d.filter(o=>p.has(String(o.DuplicateRecordSetId??""))).length,m=0;for(let o of G([...p])){let f=await n(`SELECT Id FROM DuplicateRecordSet WHERE CreatedDate >= ${a} AND Id IN (${o})`);m+=f.records.length}return{rules:r,sets:m,items:l,...u?{atLeast:!0}:{},requests:s}}catch(a){return{rules:r,sets:0,items:0,unread:$(a),requests:s}}}function Ie(e,t,r){let s=r.now??Date.now,n=r.sleep??(l=>new Promise(m=>setTimeout(m,l))),a=new Set(t.map(l=>l.objectApiName.toLowerCase())),i=l=>a.has(l.toLowerCase()),c,u=0,d=new Set,p=0;return{covers:i,beforeWrite:l=>{i(l)&&c===void 0&&(u=s())},wrote:(l,m)=>{if(!i(l))return;let o=!1;for(let h of m)typeof h!="string"||h===""||(d.add(h),o=!0);if(!o)return;p=s();let f=u;c??=e.serverTime().then(h=>{let b=Date.parse(h);return Number.isNaN(b)?{unread:`it answered "${h}"`}:{at:new Date(b-Math.max(0,s()-f)).toISOString()}},h=>({unread:$(h)}))},held:()=>d.size,read:async()=>{if(d.size===0)return;let l=c?await c:void 0;if(!l||"unread"in l)return{rules:t,sets:0,items:0,unread:l?`the org's clock: ${l.unread}`:"the org's clock was not read",requests:l?1:0};let m=Math.max(0,p+r.settleMs-s());m>0&&await n(m);let o=await pe(e,{rules:t,since:l.at,masked:d});return{...o,requests:(o.requests??0)+1,waitedMs:m}}}}function Ce(e,t){if(!e)return t;if(!t)return e;let r=[e.unread,t.unread].filter(s=>s!==void 0);return{rules:t.rules.length>=e.rules.length?t.rules:e.rules,sets:e.sets+t.sets,items:e.items+t.items,...e.atLeast||t.atLeast?{atLeast:!0}:{},...r.length>0?{unread:r.join("; ")}:{},requests:(e.requests??0)+(t.requests??0),waitedMs:(e.waitedMs??0)+(t.waitedMs??0)}}function Fe(e){return e!==void 0&&(e.sets>0||e.items>0||e.unread!==void 0)}function ge(e){return e.map(t=>`"${t}"`).join(", ")}function fe(e){return e<=0?"without waiting":e<1e3?"after waiting less than 1 s":`after waiting ${Math.round(e/1e3)} s`}function qe(e,t,r="masking"){if(!e||e.rules.length===0)return"";let s=me[r],n=e.rules.map(c=>`${c.objectApiName} (${ge(c.rules)})`).join(", ");if(e.unread!==void 0)return`What the duplicate rules of ${t} on ${n} wrote ${s.during} could not be read (${e.unread}): a duplicate record set they wrote stays.`;let a=e.requests!==void 0?` Read in ${e.requests} request(s), ${fe(e.waitedMs??0)}.`:"";if(e.sets===0&&e.items===0)return`The duplicate rules of ${t} on ${n} wrote nothing for the ${s.records}.`+a;let i=e.atLeast===!0?"at least ":"";return`The duplicate rules of ${t} on ${n} wrote ${i}${e.sets} duplicate record set(s) and ${i}${e.items} item(s) ${s.during}, for ${s.records}: kept, as they name records that stay.${a}`}var he="AUTOMATION_NOT_ACCEPTED",we="EMAILS_EXCEEDED",Oe="ORG_TEMPORARILY_UNREACHABLE";function Ae(e,t){return e==="cleanup"||e==="empty"?{delete:[...t]}:e==="restore"?{bringBack:[...t],giveBack:[...t]}:e==="emptyUndo"?{bringBack:[...t]}:{giveBack:[...t]}}function be(e,t){let r=e==="cleanup"||e==="empty"?"delete":"update";return t.filter(s=>s.records>0).map(s=>({objectApiName:s.objectApiName,write:r,records:s.records}))}var E={masking:{heading:"masking automation: what {org} runs as the masking writes over the records",the:"the masking",this:"this masking",writes:"writes over",verb:"mask",nothing:"Nothing was written.",flag:"to mask all the same"},restore:{heading:"restore automation: what {org} runs as the restore puts the backup's values back",the:"the restore",this:"this restore",writes:"puts back",verb:"restore",nothing:"Nothing was written.",flag:"to restore all the same"},cleanup:{heading:"cleanup automation: what {org} runs as the cleanup deletes the records",the:"the cleanup",this:"this cleanup",writes:"deletes",verb:"delete",nothing:"Nothing was deleted.",flag:"to delete all the same"},empty:{heading:"emptying automation: what {org} runs as the emptying deletes the records",the:"the emptying",this:"this emptying",writes:"deletes",verb:"empty",nothing:"Nothing was deleted.",flag:"to empty all the same"},emptyUndo:{heading:"undo automation: what {org} runs as the undo brings the records back",the:"the undo",this:"this undo",writes:"brings back",verb:"undo",nothing:"Nothing was written.",flag:"to undo all the same"}},$e={masking:"masking",restore:"restore",cleanup:"cleanup",empty:"empty",emptyUndo:"undo"};function Je(e){return e.erasure===!0?"erasure":e.fromPage===!0?"page":void 0}var ye={"accept-automation":"acceptAutomation","accept-emails":"acceptEmails","mute-automation":"muteAutomation"},De={"accept-emails":"the confirmation's box that lets the org send these emails","mute-automation":"the confirmation's box that mutes the target's automation"},Re={mask:"masking",restore:"restore",delete:"cleanup",erase:"erasure",empty:"emptying",undo:"undo"};function oe(e){let t=r=>De[r]??`--${r}`;return e.replace(/\bAdd --accept-automation to (mask|restore|delete|erase|empty|undo) all the same\b/g,(r,s)=>`Confirm the ${Re[s]??s} from its confirmation, which lists what fires, to ${s} all the same`).replace(/\bWith --mute-automation,/g,`With ${t("mute-automation")} ticked,`).replace(/\bAdd --(accept-emails|mute-automation)\b/g,(r,s)=>`Tick ${t(s)}`).replace(/(^|[.:;] )--(accept-emails|mute-automation)\b/g,(r,s,n)=>`${s}${W(t(n))}`).replace(/--(accept-emails|mute-automation)\b/g,(r,s)=>t(s))}function L(e,t="flags"){return t==="step"?e.replace(/--(accept-automation|accept-emails|mute-automation)\b/g,(r,s)=>`${ye[s]??s} in the step`).replace(/\bAdd (acceptAutomation|acceptEmails|muteAutomation) in the step\b/g,"Turn on $1 in the step"):t==="erasure"?oe(e.replace(/\b(this|the|This|The) (masking|cleanup)\b/g,"$1 erasure").replace(/\bto (mask|delete) all the same\b/g,"to erase all the same").replace(/\b(mask|delete) fewer records\b/g,"erase fewer records")):t==="page"?oe(e):e}var ke={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Ee={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"},ue={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function de({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}function ce(e,t){return t.step==="delete"?Ee[t.when]:t.step==="bringBack"?"as it comes back from the recycle bin":`${e==="restore"?"as its values are put back":"as it is masked"}, ${ke[t.when]}`}function W(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}function ve(e,t,r,s){let n=E[r],a=[n.heading.replace("{org}",t)];if(typeof e.unread=="string")return a.push(` what ${t} runs could not be read: ${e.unread}`),a;let i=e;for(let d of S(i,s))a.push(` ${d.objectApiName}: ${ce(r,d)}: ${de(d)}`);let c=N(i);if(a.length===1&&c.length===0){let d=new Set(Object.values(s).flat()).size;a.push(` nothing fires on the ${d} object(s) it ${n.writes} records of`)}for(let d of ne(i,s.giveBack??[]))a.push(` ${d.objectApiName}: duplicate rules ${d.rules.map(p=>`"${p}"`).join(", ")}: ${n.the} saves a record a rule only alerts on, a rule that blocks still refuses it, and what a rule that reports writes (a duplicate record set and its items) stays`);let u=I(i);u.length>0&&a.push(` bypass held: the user ${n.the} writes as holds ${u.join(", ")}, and what names it stays quiet`);for(let{part:d,reason:p}of c)a.push(` ${ue[d]??d} could not be read: ${p}`);return a}function Se(e,t,r){let s=E[r.act],n=`${s.nothing} Add --accept-automation ${s.flag}, or turn that automation off in ${t} first.`;if(typeof e.unread=="string")return`What ${t} runs as ${s.this} ${s.writes} its records could not be read (${e.unread}), so what fires is not known. ${n}`;let a=e,i=S(a,r.steps),c=N(a);if(i.length===0&&c.length===0)return;let u=[];if(i.length>0){let l=i.map(m=>`${m.objectApiName}: ${de(m)} (${ce(r.act,m)})`);u.push(`${t} runs automation as ${s.this} ${s.writes} its records: ${l.join("; ")}.`)}for(let{part:l,reason:m}of c)u.push(`${W(ue[l]??l)} of ${t} could not be read (${m}), so what fires as ${s.the} ${s.writes} its records is not known.`);let d=r.assign??[];u.push(...re(d,t,s.the));let p=[...new Set(d.flatMap(l=>l.permissionSet??[]))];return r.mayMute===!0&&p.length>0&&u.push(`With --mute-automation, ${s.the} assigns ${p.join(", ")} to the user it writes as for ${s.the} alone, under a lease, and what ${p.length===1?"it keeps":"they keep"} quiet does not fire.`),u.push(n),u.join(" ")}function k(e){let t=e.objects.map(r=>`${r.perRecord} per ${r.objectApiName}`).join(", ");return`about ${te(e.emails,e.limit)} (${t}`+(e.alertsCounted?"; its email alerts among them, as a Developer Edition counts them":"")+")"}function Me(e,t,r){let s=e.map(n=>{if(n.verdict==="unread")return` emails: ${k(n)}; what ${t} has left today could not be read (${n.unread??"not said"})`;let a=`${n.remaining??0} of ${n.max??0} left today`;return n.verdict==="exceeds"?` emails: ${k(n)}, past the ${a}`:` emails: ${k(n)}, ${a}`});return r!==void 0&&s.push(` emails not counted: what sends them was not read (${r})`),s}function Te(e,t,r,s){let n=t.filter(u=>u.verdict==="exceeds");if(n.length===0)return;let a=E[e],i=n.map(u=>`${k(u)}, ${u.remaining??0} of ${u.max??0} left today`).join("; "),c=s?.kind==="enough"?`Turn off what sends them, give the user it writes as the bypass that keeps them quiet (--mute-automation assigns ${s.sets.join(", ")} for ${a.the} alone, and what still sends then fits what is left today), or ${a.verb} fewer records.`:`Turn off what sends them, or ${a.verb} fewer records.`+(s?.kind==="muting"?" What sends them still runs under the mute.":s?.kind==="notEnough"?" --mute-automation would not keep enough of them quiet.":"");return`${W(a.this)} would make ${r} send ${i}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. ${c} ${a.nothing}`}function Qe(e,t,r){return{readAutomation:t,readLimits:()=>ee(e),readDeliverability:()=>r?Promise.resolve(V):X(e),muteOrg:async()=>Y(e),...r?{production:r}:{}}}async function Ze(e,t,r,s){let n=e?.mute?.prepared;if(!e||!n)return{};let a;try{a=await n.acquire(t)}catch(c){if(!M(c))throw c;return{refused:{code:c.code,message:L(c.message,s)}}}let i=e.emails.afterLease(a.outcome,r);return i?(await a.release(),{refused:{code:i.code,message:L(i.message,s)}}):{held:a}}var Ne={objectsRead:[],objects:[],unread:[],conditionsNotRead:0,conditionsBound:0,requests:0};async function et(e){let{act:t,target:r,accord:s}=e,n=e.objects.filter(g=>g.records>0),a=n.map(g=>g.objectApiName),i=e.writes?.steps??Ae(t,a),c=F(i),u=a.length===0?Ne:await e.org.readAutomation(a).catch(g=>{let A=U(g);return{unread:A===void 0?$(g):`the org could not be reached (${A})`}}),d=typeof u.unread=="string"?void 0:u,p=B(u),l=E[t],m=[],o;if(s.muteAutomation===!0&&p===void 0)try{o=await J(e.org.muteOrg,u,{...e.muteLeases,writes:c})}catch(g){if(!M(g))throw g;m.push({code:g.code,message:g.message})}let f=o?.automation??d,h=e.mayMute&&s.muteAutomation!==!0&&e.org.production!==!0,b=[...ve(d??u,r,t,i),...o?Q(o.muted,r).map(g=>` ${g}`):[]],j=Se(f??u,r,{act:t,steps:i,...f?{assign:se(f,q(f,i),e.assignTo)}:{},mayMute:h});j!==void 0&&s.acceptAutomation!==!0&&m.push({code:he,message:j});let D=e.writes?e.writes.written.filter(g=>g.records>0):be(t,n),y=[],R,P;if(f&&p===void 0){if(D.some(A=>C(f,A.write).some(w=>w.objectApiName===A.objectApiName))){let A=await e.org.readLimits().catch(w=>({unread:$(w)}));if(y=T(D,f,A),y.some(w=>w.verdict==="exceeds")){let w=!o&&h&&d?K(d,c):void 0;P=o?{kind:"muting"}:w&&w.plan.assign.length>0?T(D,w.automation,A).some(v=>v.verdict==="exceeds")?{kind:"notEnough"}:{kind:"enough",sets:w.plan.assign.map(v=>v.permissionSet)}:void 0}}R=Z(D,f)}b.push(...Me(y,r,R));let _=Te(t,y,r,P);_!==void 0&&m.push({code:we,message:_});let O=await z({read:u,...o?.plan?{plan:o.plan}:{},writes:c,readDeliverability:p===void 0?e.org.readDeliverability:async()=>({reading:{unread:`${r} could not be reached`},requests:0}),accepted:s.acceptEmails===!0,target:r,run:$e[t],keepsAddresses:!0,mayMute:h});return O.gate.line!==void 0&&b.push(` ${O.gate.line}`),O.gate.stop&&m.push({...O.gate.stop}),p!==void 0&&m.splice(0,m.length,{code:Oe,message:`${r} could not be reached as what it runs was read (${p}), so ${l.the} was not started. ${l.nothing} Check the network, then try again.`}),{answer:{act:t,objects:n,steps:i,...d?{automation:d}:{automationUnread:String(u.unread)},lines:b,emails:y,...R!==void 0?{emailsUncounted:R}:{},...O.gate.deliverability?{deliverability:O.gate.deliverability}:{},emailsAsk:O.gate.verdict==="asks",refusals:m.map(g=>({...g,message:L(g.message,e.voice)})),...o?{mutedAutomation:o.muted}:{},...o?.plan?{mutePlan:o.plan}:{}},...o?{mute:o}:{},emails:O}}var xe=/\bnothing (?:was )?(?:written|deleted)\b/i,ie=/\s*\bNothing was (?:written|deleted)\./g;function tt(e){let[t,...r]=e.refusals;if(!t)return;let s=!1,n=e.refusals.map(a=>s?a.message.replace(ie,"").trim():(s=xe.test(a.message),a.message)).join(" ");return{code:t.code,message:n,alsoRefused:r.map(a=>({code:a.code,message:a.message.replace(ie,"").trim()}))}}function st(e){return e.alsoRefused.length>0?{extraPayload:{alsoRefused:[...e.alsoRefused]}}:{}}export{_e as a,ne as b,Ie as c,Ce as d,Fe as e,qe as f,Je as g,Qe as h,Ze as i,et as j,tt as k,st as l};
|
|
@@ -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-ALBY5SOH.mjs";import{b as ut,c as pt,d as Qt,e as en,f as Ws,g as tn}from"./chunk-6YC2ELCU.mjs";import{b as Gs,d as Us}from"./chunk-XCJUNX63.mjs";import{a as zs,c as qs}from"./chunk-WZN36ACK.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-GEEWPTV5.mjs";import{Dc as Cr}from"./chunk-AXFD2OH6.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-5OGNK3JP.mjs";import{k as us}from"./chunk-QLRWU3MB.mjs";import{i as Ir,o as vr}from"./chunk-XMQ5R6TC.mjs";import{F as Or,M as Ar,l as qt,q as kr}from"./chunk-IXIY6Q4M.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-YBZIDW6W.mjs";import{a as Kt}from"./chunk-QSRAEUGZ.mjs";import{h as Fr,j as jr}from"./chunk-EOQON3E5.mjs";import{b as Tr,f as Mr}from"./chunk-7WSQ65WG.mjs";import{b as Ut,c as Ge,d as ee}from"./chunk-MJD6CPZZ.mjs";import{f as Pr,g as Er}from"./chunk-WXU6ZJIV.mjs";import{$a as dt,$b as ss,La as qr,Ma as Kr,Qb as Qr,Tb as es,Ua as Hr,Ub as ts,Va as Yr,Wb as ns,Xa as we,Za as at,_a as Jr,_b as rs,ab as Vr,bb as Xr,cb as ct,db as lt,ec as is,fb as Zr,fc as os,gc as xe,tb as Ne,uc as as}from"./chunk-R3OM3X4L.mjs";import{q as zr}from"./chunk-2WMKJVD2.mjs";import{a as mr,d as yr,e as wr,f as Sr,g as Rr}from"./chunk-ZOSESZ22.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-ZXOUWHYE.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-2GSMHGIV.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-ISOSTAJR.mjs";import{a as Jn,w as Vn}from"./chunk-ICIYL45C.mjs";import{c as ir,d as or}from"./chunk-7BQMBXKX.mjs";import{Ec as Me,Fc as ge,Jc as nt,Rd as Gn,Uc as rt,Vb as vn,Wb as et,Zc as xn,ee as Lt,fd as st,g as Fn,gc as Nn,i as Dt,j as jn,k as fe,kd as Dn,ld as Ln,md as $n,nd as Bn,od as _n,pd as Wn,vc as tt}from"./chunk-6QSHWIZI.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};
|