sandforge 1.81.0 → 1.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-C4YGSK6W.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/{chunk-TKQQVB2D.mjs → chunk-2JZGCCPG.mjs} +1 -1
- package/lib/{chunk-TPHXRHOA.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-ZWZXQTAK.mjs → chunk-32EUNQT6.mjs} +14 -14
- package/lib/{chunk-HYOOJVR6.mjs → chunk-3C2ZZIFN.mjs} +1 -1
- package/lib/{chunk-AELFEK3G.mjs → chunk-3CX7GPCR.mjs} +1 -1
- package/lib/{chunk-YJEXE6HZ.mjs → chunk-3HEMJTAP.mjs} +2 -2
- package/lib/{chunk-DQR5NDMI.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-D7P7DTWL.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-MNITSYI2.mjs → chunk-3SKLBRPL.mjs} +1 -1
- package/lib/{chunk-MAHZMPMZ.mjs → chunk-3XG25GTF.mjs} +1 -1
- package/lib/{chunk-N7J6NJQ6.mjs → chunk-42BFLWHR.mjs} +1 -1
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/{chunk-DHGPDSXS.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-5344TZBT.mjs → chunk-5K2I2DMP.mjs} +1 -1
- package/lib/{chunk-2OZG6GRW.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/{chunk-SW2NUKQL.mjs → chunk-6KP6WETK.mjs} +1 -1
- package/lib/{chunk-FSZTXLNW.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-6NADW3OI.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-67CC7RAE.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-IBURU7T7.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/{chunk-CULAOP3U.mjs → chunk-7PY3VQP3.mjs} +1 -1
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/{chunk-V4RKM4QZ.mjs → chunk-7WSLT5VX.mjs} +1 -1
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-K77NR3UK.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/{chunk-MWLFFVQV.mjs → chunk-AUS6NFLZ.mjs} +1 -1
- package/lib/{chunk-NWPQF5XR.mjs → chunk-BMTNTBBM.mjs} +1 -1
- package/lib/{chunk-FTA5LOVX.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-WM5JI4JI.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-5UT2ZBGF.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-GYKNCYES.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/{chunk-W2AAGIZF.mjs → chunk-CCEH7L53.mjs} +1 -1
- package/lib/{chunk-WWTXRWNZ.mjs → chunk-CELEBWEZ.mjs} +1 -1
- package/lib/{chunk-D62KWDDT.mjs → chunk-CV47FDQW.mjs} +1 -1
- package/lib/{chunk-AJPSGVMD.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/{chunk-YIGFYZQY.mjs → chunk-DBBPDSFN.mjs} +1 -1
- package/lib/{chunk-T5VAULLQ.mjs → chunk-DIL62SUN.mjs} +1 -1
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-GK7VEYFM.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-MHW6DV6T.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-PYUEHBA6.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-E2OBAWSH.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-MKNAZPOT.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-UUSLTW5V.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-DHIW4IO5.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/{chunk-BZFIOZS3.mjs → chunk-FOIWWK7G.mjs} +1 -1
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/{chunk-XIZ5LMQM.mjs → chunk-G2JR3F63.mjs} +1 -1
- package/lib/{chunk-2Z54GB6X.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-2NAIUKVL.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-TQM2XJ27.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-2IB7I3IQ.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-YHIOS2PU.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-WI4HYWV6.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-KRNFVAGC.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/{chunk-OIIL4NVI.mjs → chunk-HIHCYMSL.mjs} +1 -1
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/{chunk-V2QO6KOE.mjs → chunk-IRZJU2PG.mjs} +14 -11
- package/lib/{chunk-CAFUNR6D.mjs → chunk-ISSP2FZ5.mjs} +1 -1
- package/lib/{chunk-OEHVAJAB.mjs → chunk-IVZJSDJD.mjs} +1 -1
- package/lib/{chunk-E2YJVSX6.mjs → chunk-J24TIGSI.mjs} +1 -1
- package/lib/{chunk-YCSFP6ER.mjs → chunk-JESRFE2Z.mjs} +1 -1
- package/lib/{chunk-KOQV4WXC.mjs → chunk-JFNLKHY6.mjs} +2 -2
- package/lib/{chunk-NJ3EOEHS.mjs → chunk-JH27IKCO.mjs} +1 -1
- package/lib/{chunk-DXOXLUZA.mjs → chunk-JJITOWZK.mjs} +1 -1
- package/lib/{chunk-KNIRA333.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-J6G23RUI.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/{chunk-6IGEASOF.mjs → chunk-JQZTMFO7.mjs} +1 -1
- package/lib/{chunk-55LQD3Y3.mjs → chunk-KIMQQ6JQ.mjs} +1 -1
- package/lib/{chunk-EH5YUA5W.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/{chunk-56MPPWLA.mjs → chunk-KP5G6FUC.mjs} +1 -1
- package/lib/{chunk-EAFLDSQ2.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-MO3N5XVV.mjs → chunk-LAUOSXMN.mjs} +2 -2
- package/lib/{chunk-HVC5CYIB.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-7PK5QDQI.mjs → chunk-LXDSRP2W.mjs} +1 -1
- package/lib/{chunk-YOGMP72T.mjs → chunk-MKTXJCXN.mjs} +1 -1
- package/lib/{chunk-VSU74RQ3.mjs → chunk-MUEQRIK7.mjs} +1 -1
- package/lib/{chunk-UCHAZ4ZU.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-OVOLG3AL.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/{chunk-6SEDOIO3.mjs → chunk-O2PUGRNW.mjs} +1 -1
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/{chunk-KGYXLSQ5.mjs → chunk-P55MKIZX.mjs} +1 -1
- package/lib/{chunk-KE2PGD6C.mjs → chunk-P63WJMXQ.mjs} +1 -1
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-OMZJ37JI.mjs → chunk-PE435FVH.mjs} +2 -2
- package/lib/{chunk-GR3NGDVM.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-ZUA5BNAO.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/{chunk-43K2C6H2.mjs → chunk-PWVDNN2C.mjs} +1 -1
- package/lib/{chunk-DMBR24CK.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-OXKZ4Y3B.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-EOSEMFPU.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/chunk-QROPNEGY.mjs +14 -0
- package/lib/{chunk-6CDIIFNX.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-X2ZVSQ54.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/{chunk-ETT5GP4P.mjs → chunk-SAMWHL22.mjs} +1 -1
- package/lib/{chunk-LO527YLT.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-33ZX3A56.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-GTIXJCGS.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/{chunk-OQQHNYR7.mjs → chunk-SZGGFST2.mjs} +2 -2
- package/lib/{chunk-OU5W7SCB.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-FLNLG43R.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-RKALOKAU.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/{chunk-WEZLXE34.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-ONMBSACW.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-HYBH5PFM.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-BNO5GIJ6.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-3AOKLIVE.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/{chunk-742SSN7I.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-GWRKS3AL.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-2OIRJEYE.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-FDGFUEK3.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-UIUPPEFB.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-XC2QKQT5.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-UT27HXE7.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/{chunk-5VQNKDFU.mjs → chunk-XK5W7BVE.mjs} +1 -1
- package/lib/{chunk-OZNLOV4U.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-FSDO4DJA.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/{chunk-AITNZWLB.mjs → chunk-XU25YA46.mjs} +1 -1
- package/lib/{chunk-XEB6HZ34.mjs → chunk-XZISAZA6.mjs} +1 -1
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/{chunk-4L7FBOJS.mjs → chunk-YAIIRFKJ.mjs} +1 -1
- package/lib/{chunk-T3PLRQ2T.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-Y5ZCPY36.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/{chunk-R6TF26V4.mjs → chunk-YMDFF657.mjs} +1 -1
- package/lib/{chunk-JU2XEKEO.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-NWVVCZUK.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-O6ADMP36.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/{chunk-QXLZINZB.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/{chunk-SQGP46QS.mjs → chunk-ZUOPC4W2.mjs} +1 -1
- package/lib/{chunk-3B5H24ZG.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-K55LH4ZQ.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +1 -1
- package/lib/sandforge-backup.mjs +1 -1
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +1 -1
- package/lib/sandforge-env.mjs +185 -139
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +14 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +157 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +17 -3
- package/lib/chunk-2ZMGVBLW.mjs +0 -7
- package/lib/chunk-5C5XEVZN.mjs +0 -11
- package/lib/chunk-5CKWGZX4.mjs +0 -9
- package/lib/chunk-5ZKCLBTN.mjs +0 -474
- package/lib/chunk-7DALDJMO.mjs +0 -7
- package/lib/chunk-DPYTG6DM.mjs +0 -48
- package/lib/chunk-G4VXPS3A.mjs +0 -7
- package/lib/chunk-GF247DA7.mjs +0 -7
- package/lib/chunk-IKGHRYCN.mjs +0 -7
- package/lib/chunk-IM2XA6JI.mjs +0 -7
- package/lib/chunk-K5HV4YRO.mjs +0 -7
- package/lib/chunk-N6HHNR6J.mjs +0 -7
- package/lib/chunk-O7DAFE6M.mjs +0 -14
- package/lib/chunk-R2BJWO5N.mjs +0 -20
- package/lib/chunk-T26C576X.mjs +0 -9
- package/lib/chunk-V473C7LY.mjs +0 -7
- package/lib/chunk-WD47PGUS.mjs +0 -10
- package/lib/chunk-XC54KKKC.mjs +0 -7
- package/lib/chunk-XGKSSCW7.mjs +0 -7
- package/lib/chunk-ZWCRWF7E.mjs +0 -7
|
@@ -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 Tt,d as _t,e as Bt,g as xt,h as Ft,i as Ut,j as $t,k as et}from"./chunk-54HYHHVL.mjs";import{a as Ce,b as q,d as H,e as vt,f as Xe,h as j}from"./chunk-VPDEJGPS.mjs";import{e as Ht,h as Jt,i as zt}from"./chunk-HFUDCNU5.mjs";import{da as me,e as te,ea as Ze,ga as pe,ja as Pe}from"./chunk-KIMQQ6JQ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{Bc as Ye,Cc as Lt,dd as jt,lc as Nt,qc as Mt,rc as ee,vc as Ee,yc as ge,zc as Ge}from"./chunk-ZQO5PDX5.mjs";import{b as x,e as Ke,f as L,i as Pt,k as ae,l as X,o as Ie,s as Ct}from"./chunk-WZQEK4WT.mjs";var Ne=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function $n(r,e){let t=et(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Me(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>$n(Ht(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>et(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var qt=100,tt=2e3,Wt=20,Qt=20,Jn=X({name:x(),label:x(),type:x(),createable:L().optional(),updateable:L().optional(),nillable:L().optional(),defaultedOnCreate:L().optional(),aggregatable:L().optional(),groupable:L().optional(),filterable:L().optional(),nameField:L().optional(),autoNumber:L().optional(),calculated:L().optional(),referenceTo:ae(x()).optional()}).loose(),G=X({name:x(),label:x(),queryable:L().optional(),updateable:L().optional(),deletable:L().optional(),fields:ae(Jn),childRelationships:ae(X({childSObject:x(),field:x(),cascadeDelete:L().optional(),restrictedDelete:L().optional()}).loose()).optional()}).loose(),zn=Ct(x(),Pt()),qn=X({k:Ie([x(),Ke(),L()]).nullable(),n:Ke().int().nonnegative()}).loose();function Vt(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function Wn(r){return r.groupable===!0&&(Vt(r)||r.nameField===!0)}function Qn(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Nt(r,e.name)}function Le(r,e,t){let n=P(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Vn(r,e,t,n){let o=new Map,s=[],a=[],i=(f,u)=>{s.push({fieldApiName:f.name,label:f.label,reason:u})},d=t.filter(f=>f.aggregatable===!0),l=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&i(f,"not-countable");if(n===0)for(let f of[...d,...l])o.set(f.name,0);else{for(let f=0;f<d.length;f+=qt){let u=d.slice(f,f+qt);try{let g=u.map(R=>`COUNT(${N(R.name)})`).join(", "),m=await r.query(`SELECT ${g} FROM ${e}`),h=zn.parse(m.records[0]??{});u.forEach((R,b)=>{let w=h[`expr${b}`];if(typeof w!="number")throw new Error(`The org answered no count for ${e}.${R.name}.`);o.set(R.name,w)})}catch(g){Le(a,"fill",g);for(let m of u)o.delete(m.name),i(m,"refused")}}for(let[f,u]of l.entries()){if(f>=Qt){i(u,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${N(u.name)} != null`);o.set(u.name,g.totalSize)}catch(g){Le(a,"fill",g),i(u,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Qn(e,f)})).sort((f,u)=>f.filled-u.filled||f.fieldApiName.localeCompare(u.fieldApiName)),unmeasured:s,errors:a}}async function Kn(r,e,t,n,o){let s=[],a=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!a)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let i={keyField:a.name,keyLabel:a.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:i,errors:s};try{let d=await Gn(r,e,a.name),l=d.rows.map(c=>({value:String(c.value),count:c.count}));return{duplicates:{...i,groups:l.slice(0,Wt),groupCount:l.length,recordCount:l.reduce((c,f)=>c+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Le(s,"duplicates",d),{duplicates:null,errors:s}}}async function Gn(r,e,t){let n=N(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${tt}`),s=[];for(let a of o.records){let i=qn.safeParse(a);!i.success||i.data.k===null||s.push({value:i.data.k,count:i.data.n})}return{rows:s,truncated:o.records.length>=tt}}async function Yn(r,e,t,n,o){let s=[];if(!t.some(a=>a.name==="LastModifiedDate"&&a.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let a=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:a.totalSize},errors:s}}catch(a){return Le(s,"stale",a),{stale:null,errors:s}}}async function Zn(r,e,t){let n,o,s;try{if(n=G.parse(await r.describe(N(e.objectApiName))),o=N(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(c){return{status:"failed",objectApiName:e.objectApiName,message:P(c)}}let a=n.fields.filter(Wn).sort((c,f)=>c.label.localeCompare(f.label)),[i,d,l]=await Promise.all([Vn(r,o,n.fields.filter(Vt),s),Kn(r,o,a,e.duplicateKey,s),Yn(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:i.fields,unmeasured:i.unmeasured,duplicates:d.duplicates,stale:l.stale,keyFields:a.map(c=>({fieldApiName:c.name,label:c.label})),errors:[...i.errors,...d.errors,...l.errors]}}async function oo(r,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Zn(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:tt,duplicateSample:Wt,singleFieldQueries:Qt},objects:o}}var nt=1e4,ve=5e4,Kt="DELETE_FAILED",rt="UNABLE_TO_LOCK_ROW",Gt=3,Xn=2e3,Yt="FEATURENOTENABLED",ot="ContentVersion",Zt="ContentDocument",st=new Set([ot,Zt]);async function he(r,e,t,n,o="delete"){let s=!1,a={},i=0,d=0,l=(g,m)=>(d+=g,m()),c={bulk2:{createJob:g=>{let m=r.bulk2.createJob(g);return{get id(){return m.id},open:()=>l(1,()=>m.open()),uploadData:h=>l(1,()=>m.uploadData(h)),close:async()=>{await l(1,()=>m.close()),s=!0},abort:()=>l(1,()=>m.abort()),check:async()=>{let h=await l(1,()=>m.check());return a={state:h.state,message:h.errorMessage},h},getAllResults:async()=>{let h=await l(zt,()=>m.getAllResults());return i=Array.isArray(h)?h.length:(h.successfulResults?.length??0)+(h.failedResults?.length??0),h}}}}},f;try{f=await new Jt().executeBulk({connection:c,bulkManager:new Ne(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let m=g?.errorCode;return{kind:"untouched",reason:P(g),...typeof m=="string"&&m!==""?{code:m}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(a.state!=="JobComplete"&&i===0)return{kind:"untouched",reason:a.message||`job ${a.state??"not complete"}`,requests:d};let u=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,m)=>{let h=u.get(m);return h?.success?{success:!0}:{success:!1,error:h?.error??"The job gave no result for it."}})}}function yo(r,e){let t=Me(r);return{...Ce(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>he(t,n,o,s),bulkHardDestroy:(n,o,s)=>he(t,n,o,s,"hardDelete")}}var it=X({success:L(),errors:ae(Ie([X({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ne(r){return r.slice(0,15)}function je(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function at(r){if(typeof r=="string")return r;let e=je(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function de(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function er(r){return new Promise(e=>setTimeout(e,r))}function tr(r){let e=Xn*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Xt(r,e,t,n){let o=[...t];for(let s=0;s<Gt;s++){let a=o.flatMap((d,l)=>d.kind==="refused"&&d.locked===!0?[l]:[]);if(a.length===0||n.stopped?.()===!0||(await(n.wait??er)(tr(s)),n.stopped?.()===!0))break;let i=await e(a.map(d=>r[d]));if(i===void 0)break;a.forEach((d,l)=>{let c=i[l];c&&(o[d]={...c,lockResends:s+1})})}return o}async function dt(r,e,t,n={}){if(e===ot)return dr(r,t,n);let o=s=>nr(r,e,s);return Xt(t,o,await o(t),n)}async function nr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let a=P(s);return t.map(()=>({kind:"refused",reason:a,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,a)=>{let i=it.safeParse(o[a]);if(i.success&&i.data.success)return{kind:"deleted"};let d=i.success?i.data.errors??[]:[];if(d.some(c=>je(c)==="ENTITY_IS_DELETED"))return{kind:"gone"};let l=d.length>0&&d.every(c=>je(c)===rt);return{kind:"refused",reason:d.length>0?at(d[0]):"The org gave no reason.",dependency:d.some(c=>je(c)===Kt),...l?{locked:!0}:{}}})}async function rr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:or}:"untouched";let a=async d=>{let l;try{l=await s(e,d,o.signal)}catch(f){let u=P(f);return d.map(()=>({kind:"refused",reason:u,dependency:!1}))}if(l.kind==="aborted")return"aborted";if(l.kind==="untouched"){if(n!=="hard")return"untouched";if(l.code===Yt)return{hardRefused:sr(l.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${l.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:c}=l;return d.map((f,u)=>{let g=c[u];if(g?.success===!0)return{kind:"deleted"};let{code:m,message:h}=ar(g?.error??"");return m==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:m&&h?`${m}: ${h}`:g?.error||m||h||"The org gave no reason.",dependency:m===Kt,...m===rt?{locked:!0}:{}}})},i=await a(t);return Array.isArray(i)?Xt(t,async d=>{let l=await a(d);return Array.isArray(l)?l:void 0},i,o):i}var or="Records cannot be deleted for good through this connection: nothing was sent.";function sr(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${Yt}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var ir="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function ar(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function dr(r,e,t){let n;try{n=await j(r,ot,["ContentDocumentId"],e)}catch(d){let l=P(d);return e.map(()=>({kind:"refused",reason:l,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ne(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],a=s.length>0?await dt(r,Zt,s,t):[],i=new Map(s.map((d,l)=>[d,a[l]]));return e.map(d=>{let l=o.get(ne(d));return l===void 0?{kind:"gone"}:i.get(l)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function en(r){let e=[];for(let t=0;t<r.length;t+=q)e.push({ids:r.slice(t,t+q),byJob:!1});return e}function tn(r,e,t,n="recycle"){return st.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=nt}async function cr(r,e,t,n="recycle"){let o=[],s=!st.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),a=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<nt){o.push(...en(d));return}let l=Math.ceil(d.length/Math.ceil(d.length/ve));for(let c=0;c<d.length;c+=l)o.push({ids:d.slice(c,c+l),byJob:!0})};if(!Ee(e)||t.length===0)return a(t),o;let i=new Set;try{i=new Set([...await pe(de(r),t)].map(ne))}catch{}return a(t.filter(d=>!i.has(ne(d)))),a(t.filter(d=>i.has(ne(d)))),o}function nn(r){return{objectApiName:r,op:"delete"}}async function rn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:a}=await $t(t,{key:nn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async i=>({answers:await dt(r,e,i,s)}),limited:i=>i?.kind==="refused"?jt([i.reason]):void 0,settle:(i,d,l,c)=>{let f=[],u=[];i.forEach((g,m)=>{if(l.has(m))return;let h=d[m]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},R=c.get(m);f.push(g),u.push(R!==void 0&&h.kind==="refused"?{...h,dependency:!1,limit:R}:h)}),f.length>0&&o.settle(f,u)}});return a!==void 0}function ct(r,e){let t=nn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(xt(n)),n.notSplit>0&&o.push(Ft(n.notSplit,Ut(e.allowance,t),"removal")),n.keptWhole>0?o.push(Bt):n.alone>0&&o.push(_t),o}function on(r){let e=0,t=0,n=0,o=0;for(let a of r)e++,a==="deleted"?t++:a==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${rt}), each sent again up to ${Gt} times, a wait before each: ${s.join(", ")}.`]}async function sn(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&st.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:ir,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},a=await cr(r,e,t,o);for(let i=a.shift();i!==void 0;i=a.shift()){let{ids:d,byJob:l}=i;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!l){if(await rn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let c=await rr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(c==="aborted")return{stopped:!0};if(c==="untouched"){a.unshift(...en(d));continue}if(!Array.isArray(c))return{stopped:!0,hardRefused:c.hardRefused};n.settle(d,c)}return{stopped:!1}}async function an(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let a=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>a&&(n=!0)}}return!1}async function Te(r,e){let t=new Set(e.map(a=>a.objectApiName)),n=new Map;for(let{objectApiName:a}of e){let i;try{i=(G.parse(await r.describe(a)).childRelationships??[]).map(l=>l.childSObject)}catch{continue}for(let d of i){if(d===a||!t.has(d))continue;let l=n.get(d)??new Set;l.add(a),n.set(d,l)}}let o=[...e],s=[];for(;o.length>0;){let a=o.findIndex(i=>!o.some(d=>d!==i&&n.get(d.objectApiName)?.has(i.objectApiName)));s.push(...o.splice(a>=0?a:0,1))}return s}async function lt(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(a){return{gone:[],unchecked:[...r],failure:P(a)}}let o=new Set(n.map(a=>ne(String(a.Id)))),s=r.filter(a=>!o.has(ne(a)));return{gone:s.filter(t),unchecked:s.filter(a=>!t(a))}}function lr(r){return r.filter(e=>me[e]!==void 0&&!Ze.has(e))}async function ut(r,e,t,n,o,s){let a=de(r),i=[];for(let{objectApiName:d}of e){let l=me[d];if(!l||Ze.has(d))continue;let c;for await(let f of t.pages(d)){let u=f.filter(w=>n(d,w));if(u.length===0)continue;if(o())return{drafted:i,cancelled:!0};c??=await Pe(a,l);let g=c,m=g?.draft;if(!g||!m)break;let h=await s(d,u),R;try{R=await j(r,d,["Status"],u)}catch{continue}let b=R.filter(w=>typeof w.Id=="string"&&!h.has(w.Id.slice(0,15))).filter(w=>{let k=g.categoryOf.get(String(w.Status));return k!==void 0&&k!=="Draft"}).map(w=>({objectApiName:d,id:String(w.Id),draft:m,status:String(w.Status)}));for(let w=0;w<b.length;w+=q){if(o())return{drafted:i,cancelled:!0};let k=b.slice(w,w+q);i.push(...k);try{await r.update(d,k.map(({id:I})=>({Id:I,Status:m})))}catch{}}}}return{drafted:i,cancelled:!1}}function Oo(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function dn(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(c=>c.objectApiName===o),a=new Map(s.map(c=>[c.id.slice(0,15),c])),i=s.map(c=>c.id),d;try{d=await j(r,o,["Status"],i)}catch(c){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${P(c)}`,!0);continue}let l=d.flatMap(c=>{let f=typeof c.Id=="string"?a.get(c.Id.slice(0,15)):void 0;return f&&c.Status===f.draft?[f]:[]});for(let c=0;c<l.length;c+=q){let f=l.slice(c,c+q),u;try{u=await r.update(o,f.map(({id:m,status:h})=>({Id:m,Status:h})))}catch(m){u=f.map(()=>({success:!1,errors:[P(m)]}))}let g=Array.isArray(u)?u:[u];f.forEach(({draft:m,status:h},R)=>{let b=it.safeParse(g[R]);if(b.success&&b.data.success){t.note(o,`Status set to ${m} for the delete, then back to ${h}.`,!1,f[R]);return}let w=b.success?b.data.errors??[]:[],k=w.length>0?at(w[0]):"The org gave no reason.";t.note(o,`Status set to ${m} for the delete, and left there: the org refused ${h} back \u2014 ${k}`,!0,f[R])})}}}var le="DuplicateRecordSet",ur="DuplicateRecordItem",_e=2e3,fr=999,gr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function T(r){return r.slice(0,15)}function cn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function ft(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function ln(r,e){return(await mr(r,e)).map(t=>({id:t.id,modified:pr(t,e)}))}async function mr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!gr.test(e.user))return[];let t;try{let l=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${le} WHERE CreatedDate >= ${cn(e.start-2e3)} AND CreatedDate <= ${cn(e.end+6e4)} LIMIT ${_e}`);if(l.records.length>=_e)return[];t=l.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);if(n.length===0)return[];let o=new Map,s=new Map,a=new Map;try{for(let l of H(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${ur} WHERE DuplicateRecordSetId IN (${l}) LIMIT ${_e}`);if(c.records.length>=_e)return[];for(let f of c.records){let u=f??{},g=u.DuplicateRecordSetId,m=u.RecordId;if(typeof g!="string")continue;let h=ft(u.CreatedDate);if(Number.isFinite(h)&&!(h<=(a.get(T(g))??Number.NaN))&&a.set(T(g),h),typeof m!="string"||!e.has(T(m))){let R=o.get(T(g))??new Set;R.add(typeof m=="string"?T(m):`item ${String(u.Id)}`),o.set(T(g),R)}else s.set(T(g),[...s.get(T(g))??[],T(m)])}}}catch{return[]}let i=T(e.user),d=(l,c)=>{let f=o.get(l)?.size??0;return s.has(l)?f<=1:f===0&&typeof c=="string"&&T(c)===i};return t.flatMap(l=>typeof l.Id=="string"&&d(T(l.Id),l.LastModifiedById)?[{id:l.Id,created:ft(l.CreatedDate),modified:ft(l.LastModifiedDate),...typeof l.LastModifiedById=="string"?{modifiedBy:l.LastModifiedById}:{},names:s.get(T(l.Id))??[],...a.has(T(l.Id))?{itemsMade:a.get(T(l.Id))}:{}}]:[])}function pr(r,e){if((r.modifiedBy!==void 0?T(r.modifiedBy):"")===T(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+fr)?Math.min(r.modified,e.end):r.modified}async function un(r,e,t,n="recycle"){let o=N(e),s=new Set;try{for(let a of H(t)){let i=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${a}) AND IsDeleted = true`);for(let d of i.records){let l=d?.Id;typeof l=="string"&&s.add(l.slice(0,15))}}}catch(a){return{error:P(a)}}return{deleted:s,inBin:n!=="hard"}}var hr=/__kav$/i;function ye(r){return hr.test(r)}function gn(r){return r.replace(/v$/i,"")}var gt="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",yr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},fn=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",br="An article version is deleted through its article, over REST.",Rr={success:!1,errors:[{message:"The org gave no reason."}]};function J(r){return r.slice(0,15)}function mn(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>ye(n)?wr(r,n):r.describe(n),destroy:(n,o)=>ye(n)?Sr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>ye(n)?Promise.resolve({kind:"untouched",reason:br,requests:0}):t(n,o,s)}:{}}}async function wr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(gn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function pn(r,e,t){let n=N(e),o=new Map,s=new Map,a=(d,l)=>{for(let c of d){let f=c;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;l?.set(J(f.Id),f.KnowledgeArticleId);let u=J(f.KnowledgeArticleId),g=s.get(u)??new Set;g.add(J(f.Id)),s.set(u,g)}};for(let d of["",fn])for(let l of H(t)){let c=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${l})${d}`);a(c.records,o)}let i=[...new Set(o.values())];for(let d of["",fn])for(let l of H(i)){let c=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${l})${d}`);a(c.records)}return{articleOf:o,versions:s}}function hn({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(J)),s=a=>[...e.get(a)??[]].some(i=>!o.has(i));return new Set([...r.values()].map(J).filter(s))}async function yn(r,e,t,n){let o=await pn(r,e,t),s=hn(o,t,n);return new Set(t.map(J).filter(a=>{let i=o.articleOf.get(a);return i!==void 0&&s.has(J(i))}))}async function Sr(r,e,t,n){let o=await pn(r,e,t),{articleOf:s}=o,a=[...new Set(s.values())],i=hn(o,t,n),d=a.filter(c=>!i.has(J(c))),l=new Map;if(d.length>0){let c;try{c=await r.destroy(gn(e),d)}catch(u){let g=P(u);c=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(c)?c:[c];d.forEach((u,g)=>l.set(J(u),f[g]))}return t.map(c=>{let f=s.get(J(c));return f===void 0?{success:!1,errors:[yr]}:i.has(J(f))?{success:!1,errors:[{message:gt}]}:l.get(J(f))??Rr})}var xe="Quote",Re="QuoteLineItem",be="Opportunity",we="OpportunityLineItem",bn=2e3;function kr(r){return r.slice(0,15)}function Rn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function F(r,e){let t=r[e];return typeof t=="string"&&t!==""?kr(t):void 0}function pt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function Or(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let m=F(g,"Id"),h=F(g,"SyncedQuoteId");!m||!h||!pt(e,m)||!e.has(h)||(t.add(h),n.add(m))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let m=F(g,"QuoteId");return m!==void 0&&t.has(m)&&F(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let m=F(g,"OpportunityId");return m!==void 0&&n.has(m)&&F(g,"Id")!==void 0}),a=g=>F(g,"CreatedById"),i=(g,m)=>{let h=F(g,"Id");if(!h||pt(e,h)||!m)return!1;let R=e.user??a(m),b=Rn(g.CreatedDate);return R!==void 0&&a(g)===R&&b>=e.start&&b<=e.end},d=g=>({id:String(g.Id),modified:Rn(g.LastModifiedDate)}),l=new Map(s.flatMap(g=>{let m=F(g,"Id");return m&&e.has(m)?[[m,g]]:[]})),c=new Map;for(let g of o){let m=F(g,"Id"),h=F(g,"OpportunityLineItemId");m&&h&&e.has(m)&&!c.has(h)&&c.set(h,g)}let f=o.filter(g=>{let m=F(g,"OpportunityLineItemId");return i(g,m?l.get(m):void 0)}).map(d),u=s.filter(g=>{let m=F(g,"Id");return i(g,m?c.get(m):void 0)}).map(d);return[...f.length>0?[{objectApiName:Re,copies:f}]:[],...u.length>0?[{objectApiName:we,copies:u}]:[]]}function wn(r,e=[]){let t=new Set(r),n=t.has(be)||new Set(e).has(be);if(!t.has(xe)||!n)return[];let o=t.has(Re),s=t.has(we);return o===s?[]:[o?we:Re]}async function mt(r,e,t,n,o){let s=t.map(N).join(", "),a=[];for(let i of H(o)){let d=await r.query(`SELECT ${s} FROM ${N(e)} WHERE ${N(n)} IN (${i}) LIMIT ${bn}`);if(d.records.length>=bn)throw new Error(`More ${e} records than one read takes.`);for(let l of d.records)typeof l=="object"&&l!==null&&a.push(l)}return a}async function Sn(r,e,t,n){let o=n.has(Re)||n.has(we),s=n.has(be)||e.otherParts?.objects.has(be)===!0;if(t.length===0||!s||!o)return[];try{let i=(await mt(r,be,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(c=>{let f=F(c,"Id");return f!==void 0&&pt(e,f)});if(i.length===0)return[];let d=await mt(r,Re,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(i.map(c=>String(c.SyncedQuoteId)))]),l=await mt(r,we,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",i.map(c=>String(c.Id)));return Or({syncing:i,quoteLines:d,opportunityLines:l},e)}catch{return[]}}var Ar=5,Se=4,Fe=2e3,Dr=4,He=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],yt=1e4,Ir="005",kn="ContentDocumentLink",Er="ContentDocument",Pr="ContentVersion",Cr=5;function Je(r){let e=new Set(r.flatMap(n=>n.ids.map(y))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function re(r){return!Array.isArray(r)}function es(r){return re(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function ts(r){return(re(r)?r.objects:r).map(e=>e.objectApiName)}var ze=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},bt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function ue(r,e){return typeof r=="string"&&e.has(y(r))}var On=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],ht={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return ue(r.ContentDocumentId,e)&&(ue(t,e)||typeof t=="string"&&t.startsWith(Ir))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>ue(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>ue(r.ContentDocumentId,e)},[te.objectApiName]:{ends:[te.parent,te.field],cameWithRun:(r,e)=>r[te.field]===te.value&&ue(r[te.parent],e)}};function ns(r,e){return{...Ce(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>he(Me(r),t,n,o)}}function Rt(r,e,t){let n=new Map;for(let o of r??[]){let s=kt(o.span,[],t);if(Number.isFinite(s.end))for(let a of o[e]??[]){let i=y(a);s.end<=(n.get(i)?.end??Number.NEGATIVE_INFINITY)||n.set(i,s)}}return n}function Nr(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>re(n)?n:Je(n)),Je(e)];return{has:n=>t.some(o=>o.has(n))}}function Mr(r=[],e=[]){return new Set([...r.map(({plan:t})=>re(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function Pn(r,e){return new Map([...Rt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function Cn(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function wt(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function An(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new ke(o,s,t(o)).result,notReached:s}));return r}var rs={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function y(r){return r.slice(0,15)}function Lr(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(P(r))}function jr(r,e){let t=/no such column '(\w+)'/i.exec(P(r))?.[1],n=He.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?He.length:n}function M(r){return typeof r=="string"?Date.parse(r):Number.NaN}function Nn(){return{modified:new bt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var ke=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ze;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(y(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let a of this.secondTry){let i=y(a);this.deletedLater.has(i)?e++:this.goneLater.has(i)?t++:this.refused.has(a)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let a=this.automationHeld.get(y(s));return a?[a]:[]}),t=this.held.filter(s=>{let a=y(s);return this.automationHeld.has(a)&&this.automationHeldAfter.has(a)}).length,n=this.held.filter(s=>{let a=y(s);return this.automationHeld.has(a)&&this.automationHeldAlong.has(a)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...on(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,Ar),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,Cr)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function os(r,e,t){let n=re(e)?e:Je(e),o=n,s=o.objects.reduce((p,S)=>p+S.count,0),a=new Map,i=p=>a.get(p)??0,d=()=>t.signal?.aborted===!0,l=t.splitting??Tt(),c=()=>({objects:An([],o.objects,i),cancelled:!0,gone:[],stamps:{},left:()=>En(n)}),f=new Map,u=new Map;for(let{objectApiName:p}of o.objects){let S=Nn();f.set(p,S);let O=0;for await(let A of o.pages(p)){if(d())return c();let v=A[0];v!==void 0&&!u.has(v.slice(0,3))&&u.set(v.slice(0,3),p);let E=O;if(O+=A.length,S.error!==void 0)continue;let D=await Ur(r,p,A,E,S);if(S.error!==void 0||D.length===0)continue;if(d())return c();let B=await un(r,p,D);if("error"in B)S.binError=B.error;else for(let z of B.deleted)S.binned.add(z)}}let g=new Map,m=!1,h=r.bulkDestroy?.bind(r),R={query:p=>r.query(p),destroy:(p,S)=>(m=!0,r.destroy(p,S)),...h?{bulkDestroy:(p,S)=>(m=!0,h(p,S,t.signal))}:{},update:(p,S)=>(m=!0,r.update(p,S)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:p=>r.queryDeleted(p),describeGlobal:()=>r.describeGlobal(),describe:p=>{let S=g.get(p);return S||(S=r.describe(p),g.set(p,S)),S}},b=mn(R,{includeChanged:t.includeChanged}),w=await Te(b,o.objects),k=await xr(b,w,(p,S)=>S-(f.get(p)?.missing.size??0)),I=new Set(k.map(p=>p.objectApiName));if(k.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return c();if(!await t.onUndeletable(k))return{...c(),objects:[],undeletable:k,stoppedForUndeletable:!0}}let[C,_]=await Promise.all([Jr(b),t.previewOnly===!0?void 0:zr(b)]),{start:Y,end:V}=kt(t,f.values(),C.aheadMs);if(d())return c();let oe=Nr(t.otherParts,t.otherPartRecords),qe=Mr(t.otherParts,t.otherPartRecords),Ae=await $r(b,o,{start:Y,end:V,...t.runUserId?{user:y(t.runUserId)}:{},...oe?{otherParts:{has:p=>oe.has(p),objects:qe}}:{},undeletable:I,snapshots:f}),We=[];if(t.runUserId&&t.alongAccepted!==!0){let p=await ln(b,{has:S=>o.has(S),start:Y,end:V,user:t.runUserId});if(p.length>0&&!o.objects.some(S=>S.objectApiName===le)&&await Mn(b,le)){Ae.push({objectApiName:le,copies:p});for(let S of p)We.push(S.id)}}if(Ae.length>0){o=await Hr(o,Ae,f,u);for(let{objectApiName:p,copies:S}of Ae)a.set(p,S.length);s=o.objects.reduce((p,S)=>p+S.count,0),w=await Te(b,o.objects)}let Tn=new Map(Object.entries(t.removalStamps??{}).map(([p,S])=>[y(p),M(S)])),_n=Pn(t.laterParts,C.aheadMs),se=new Set;for(let{objectApiName:p}of o.objects){let S=f.get(p);if(!S||S.error!==void 0)continue;let O=0;for await(let A of o.pages(p))for(let v of A){let E=S.modified.at(O++),D=y(v);if(S.missing.has(D))continue;E<=V||E<=(Tn.get(D)??Number.NaN)||E<=(_n.get(D)??Number.NaN)||se.add(D)}}if(t.previewOnly===!0){if(d())return c();let p=new Set,S=await Tr(b,o,w,{snapshots:f,changed:se,undeletable:I,includeChanged:t.includeChanged,stopped:d,copiesOf:i,...t.previewHeld===!0?{held:{notSent:p,check:new Oe(b,{runRecords:o,reached:{has:()=>!1},stays:O=>p.has(O),runStart:Y,runEnd:V,removalStart:C.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(O=>({start:M(O.first),end:M(O.last),user:y(O.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:y(t.runUserId)}:{},...t.laterParts?{linkedLater:Rt(t.laterParts,"linked",C.aheadMs)}:{},...oe?{otherPartRecords:oe,otherPartObjects:qe}:{}})}}:{}});return S?{...k.length>0?{undeletable:k}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>En(n),preview:S}:c()}let Ot=await Fr(b,t.otherParts??[],C.aheadMs,d);if(!Ot)return c();let At=new Set,Bn={has:p=>o.has(p)&&At.has(u.get(p.slice(0,3))??"")},Qe=new Oe(b,{runRecords:o,reached:Bn,stays:p=>se.has(p)&&!t.includeChanged,runStart:Y,runEnd:V,removalStart:C.start,removalUser:_,earlierRemovals:(t.removalSpans??[]).map(p=>({start:M(p.first),end:M(p.last),user:y(p.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:y(t.runUserId)}:{},...t.automationMade?{automationMade:vn(t.automationMade)}:{},...t.laterParts?{linkedLater:Rt(t.laterParts,"linked",C.aheadMs)}:{},...oe?{otherPartRecords:oe,otherPartObjects:qe}:{}});if(d())return c();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(l)&&(m=!0);let Z=[],Dt=p=>Z.find(S=>S.result.objectApiName===p);async function*Ve(p,S,O){for(let{objectApiName:A}of S){let v=Dt(A),E=0;for await(let D of p.pages(A)){let B=D.filter(z=>O(A,z,v?.isGone(z,E++)===!0));B.length>0&&(yield{objectApiName:A,ids:B})}}}let xn=()=>Ve(o,w,(p,S,O)=>{let A=f.get(p),v=y(S);return A?.modifiedColumn==="LastModifiedDate"&&!A.missing.has(v)&&!se.has(v)&&!O}),De=[],$=async p=>{await dn(b,De,{note:(D,B,z)=>{let U=Dt(D);if(!U){if(!z)return;let W=o.objects.find(Q=>Q.objectApiName===D);U=new ke(D,W?.count??0,i(D)),Z.push(U)}U.note(B)}});let S=m?await Dn(b,xn(),{start:C.start,user:_}):{},O=[];if(m)for(let D of Ot)O.push(await Dn(b,D.unchanged(),{start:C.start,user:_}));let A=m?qr(C,_):void 0,v=[];if(!re(e))for await(let{ids:D}of Ve(n,w,(B,z,U)=>U))for(let B of D)v.push(B);for(let D of Z)D.limitNotes=ct(D.result.objectApiName,l);let E=Z.map(D=>D.settle());return{...k.length>0?{undeletable:k}:{},objects:p?An(E,w,i):E,cancelled:p,gone:v,left:()=>Ve(n,n.objects,(D,B,z)=>!z),stamps:S,...A?{span:A}:{},...O.length>0?{otherPartStamps:O}:{},...We.length>0?{duplicateSets:We}:{}}};if(d())return m?$(!0):c();let It=async(p,S)=>(await Qe.heldAmong(p,S)).held,Et=await ut(b,w,o,(p,S)=>{let O=y(S),A=f.get(p);return A!==void 0&&A.error===void 0&&!I.has(p)&&!A.missing.has(O)&&!(se.has(O)&&!t.includeChanged)},d,It);if(De=Et.drafted,Et.cancelled)return $(!0);if(t.alongToDraft){let p=await ut(b,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,It);if(De=[...De,...p.drafted],p.cancelled)return $(!0)}let K=0;for(let{objectApiName:p,count:S}of w){if(d())return $(!0);let O=new ke(p,S,i(p));Z.push(O),At.add(p);let A=f.get(p);if(!A||A.error!==void 0){O.unread={reason:A?.error??"The org gave no reason.",count:S},K+=S,t.onProgress?.(K,s,p);continue}if(I.has(p)){let U=0,W=0;for await(let Q of o.pages(p))for(let ie of Q){let fe=y(ie),Un=U++;A.missing.has(fe)?A.binned.has(fe)?(O.result.alreadyGone++,O.goneAt.add(Un)):O.notVisible++:W++}O.notVisible>0&&(O.notVisibleNote=wt(O.notVisible,A.binError)),W>0&&(O.unread={reason:Cn(p,W),count:W}),K+=S,t.onProgress?.(K,s,p);continue}let v=tn(b,p,S),E=[],D=new Map,B=async()=>{let U=E,W=D;return E=[],D=new Map,In(b,Qe,O,U,{stopped:d,splitting:l,placeOf:W,onDeleted:Q=>{K+=Q,t.onProgress?.(K,s,p)},onHeld:Q=>{K+=Q,t.onProgress?.(K,s,p)}})},z=0;for await(let U of o.pages(p)){if(d())return $(!0);let W=E.length;for(let Q of U){let ie=y(Q),fe=z++;A.missing.has(ie)?A.binned.has(ie)?(O.result.alreadyGone++,O.goneAt.add(fe)):O.notVisible++:se.has(ie)&&!t.includeChanged?O.result.keptChanged++:(E.push(Q),D.set(ie,fe))}if(O.notVisible>0&&(O.notVisibleNote=wt(O.notVisible,A.binError)),K+=U.length-(E.length-W),!(v&&E.length<ve)&&await B())return $(!0)}if(v&&E.length>0&&(d()||await B()))return $(!0)}let Fn=Z.some(p=>p.result.deleted>0);if(await an(Z,{stopped:d,idsOf:(p,S)=>{if(S>0)return p.waiting();let O=p.refusedToSendAgain();return O.length>0||Fn?[...O,...p.held]:[]},send:async(p,S,O)=>{let A=new Set(O===0?p.refusedToSendAgain():[]),v=await In(b,Qe,p,S,{stopped:d,splitting:l,onSent:E=>{for(let D of E)A.has(D)&&p.secondTry.add(D)}});for(let E of p.held)A.has(E)&&p.secondTry.add(E);return v},deleted:p=>p.result.deleted}))return $(!0);if(t.afterRemoval){if(d())return $(!0);await t.afterRemoval(l)&&(m=!0)}for(let p of Z){if(d())return $(!0);await Br(b,p,f.get(p.result.objectApiName))}return $(!1)}async function vr(r,e,t,n,o){let{changed:s,includeChanged:a}=o,i=[];for await(let d of e.pages(t))for(let l of d){let c=y(l);!n.has(c)&&(a||!s.has(c))&&i.push(l)}try{return{kept:await yn(r,t,i,{includeChanged:a})}}catch(d){return{kept:new Set,unread:P(d)}}}async function Tr(r,e,t,n){let o=[],s=new Set,a=new Set;for(let{objectApiName:i,count:d}of t){let l=n.copiesOf(i),c={objectApiName:i,planned:d,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...l>0?{platformCopies:l}:{},reasons:[]};o.push(c);let f=n.snapshots.get(i);if(!f||f.error!==void 0){if(c.unread=d,c.reasons.push(f?.error??"The org gave no reason."),n.held)for await(let R of e.pages(i))for(let b of R)n.held.notSent.add(y(b));continue}let u=ye(i)&&!n.undeletable.has(i)?await vr(r,e,i,f.missing,n):void 0,g=[],m=[],h=R=>{n.held?.notSent.add(R)};for await(let R of e.pages(i))for(let b of R){let w=y(b);f.missing.has(w)?f.binned.has(w)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,h(w)):u?.unread!==void 0?(c.unread++,h(w)):n.changed.has(w)?(c.changedSince++,g.push(b),n.includeChanged?(c.toDelete++,m.push(b)):(c.keptChanged++,h(w))):u?.kept.has(w)?(c.changedSince++,c.keptChanged++,h(w)):(c.toDelete++,m.push(b))}if(n.held&&m.length>0){if(n.stopped())return;let R=await n.held.check.heldAmong(i,m),b=m.filter(k=>R.held.has(y(k)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...R.holders];for(let I of b)n.held.notSent.add(y(I));let k=b.filter(I=>R.byAutomation.has(y(I)));k.length>0&&(c.heldByAutomation=k.length)}let w=new Map;for(let k of m)if(!R.held.has(y(k)))for(let[I,C]of R.cameAlong.get(y(k))??[])a.has(I)||(a.add(I),w.set(I,C));w.size>0&&(c.cameAlong={count:w.size,objects:[...new Set(w.values())]}),R.reason!==void 0&&c.reasons.push(R.reason),R.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...R.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(u?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${u.unread}`):u!==void 0&&u.kept.size>0&&c.reasons.push(gt),c.notVisible>0&&c.reasons.push(wt(c.notVisible,f.binError)),c.undeletable>0&&c.reasons.push(Cn(i,c.undeletable)),!(g.length===0||f.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let R=await j(r,i,["LastModifiedById"],g,Se);for(let b of R){let w=b.LastModifiedById;typeof w!="string"||w===""||(c.changedBy[w]=(c.changedBy[w]??0)+1,s.add(w))}}catch(R){c.reasons.push(`Who changed them since the run could not be read: ${P(R)}`)}}}if(!n.stopped())return{objects:o,userNames:await _r(r,[...s])}}async function _r(r,e){let t={};if(e.length===0)return t;try{for(let n of await j(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function Br(r,e,t){let{gone:n,unchecked:o,failure:s}=await lt(e.refusedSent(),a=>j(r,e.result.objectApiName,[],a),a=>t!==void 0&&t.error===void 0&&!t.missing.has(y(a)));for(let a of n)e.refused.delete(a),e.goneLater.add(y(a)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(s?` \u2014 ${s}`:"."))}function ss(r,e=[],t={}){return[...new Set([...r,...wn(r,e),...t.userKept===!0&&r.length>0?[le]:[]])]}async function xr(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===Pr||s===0)continue;let a=t(o,s);if(a!==0)try{let i=G.safeParse(await r.describe(o));i.success&&i.data.deletable===!1&&n.push({objectApiName:o,records:a})}catch{}}return n}async function Dn(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:a,ids:i}of e){let d;try{d=await j(r,a,["LastModifiedDate","LastModifiedById"],i)}catch{continue}for(let l of d)typeof l.Id=="string"&&typeof l.LastModifiedDate=="string"&&typeof l.LastModifiedById=="string"&&y(l.LastModifiedById)===s&&M(l.LastModifiedDate)>=o&&(n[l.Id]=l.LastModifiedDate)}return n}async function Fr(r,e,t,n){let o=[];for(let s of e){let a=re(s.plan)?s.plan:Je(s.plan),{end:i}=kt(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,u])=>[y(f),M(u)])),l=Pn(s.laterParts,t),c=new Map;if(Number.isFinite(i))for(let{objectApiName:f}of a.objects){let u=new ze,g=0,m=!1;for await(let h of a.pages(f)){if(n())return;let R=g;if(g+=h.length,m)continue;let b;try{b=await j(r,f,["LastModifiedDate"],h,Se)}catch{m=!0;continue}let w=new Map;for(let k of b)typeof k.Id=="string"&&w.set(y(k.Id),M(k.LastModifiedDate));h.forEach((k,I)=>{let C=y(k),_=w.get(C);_!==void 0&&(_<=i||_<=(d.get(C)??Number.NaN)||_<=(l.get(C)??Number.NaN))&&u.add(R+I)})}m||c.set(f,u)}o.push({unchanged:async function*(){for(let{objectApiName:f}of a.objects){let u=c.get(f);if(!u)continue;let g=0;for await(let m of a.pages(f)){let h=m.filter(()=>u.has(g++));h.length>0&&(yield{objectApiName:f,ids:h})}}}})}return o}async function In(r,e,t,n,o){let{objectApiName:s}=t.result,a=await e.heldAmong(s,n);a.reason!==void 0&&t.note(a.reason);for(let u of a.unchecked)t.result.unchecked.includes(u)||t.result.unchecked.push(u);let i=n.filter(u=>a.held.has(y(u)));if(o.placeOf){for(let u of i)t.held.push(u);t.result.heldBy=[...new Set([...t.result.heldBy,...a.holders])]}else t.held=i,t.result.heldBy=[...a.holders];for(let u of i)t.refused.delete(u);for(let u of n){let g=y(u),m=a.byAutomation.get(g);m?t.automationHeld.set(g,m):t.automationHeld.delete(g),m&&a.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),m&&a.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(i.length);let d=n.filter(u=>!a.held.has(y(u))),l=new Map,c=(u,g)=>{u.forEach((m,h)=>{let R=g[h],b=y(m);if((R.lockResends!==void 0||t.lockResent.has(b))&&t.lockResent.set(b,R.kind),R.kind==="refused"){t.refused.set(m,{reason:R.reason,dependency:R.dependency,sent:!0,...R.limit?{limit:!0}:{}});return}t.refused.delete(m);let w=o.placeOf?.get(b);if(w!==void 0?t.goneAt.add(w):t.goneLater.add(b),R.kind==="deleted"){t.result.deleted++,w===void 0&&t.deletedLater.add(b);for(let k of l.get(b)??[])t.filesLeft.set(k.key,k.name);for(let[k,I]of a.along.get(b)??[])t.tookAlong.set(k,I);for(let[k,I]of a.cameAlong.get(b)??[])t.cameAlong.set(k,I)}else t.result.alreadyGone++}),o.onSent?.(u),o.onDeleted?.(u.length)},{stopped:f}=await sn(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async u=>{l=await e.filesOn(u)},settle:c});return f}async function Ur(r,e,t,n,o){let s,a=o.modifiedColumn?On.filter(({modified:i})=>i===o.modifiedColumn):On;for(let{created:i,modified:d}of a)try{let c=await j(r,e,i?[i,d]:[d],t,Se),f=new Map;for(let g of c)typeof g.Id=="string"&&f.set(y(g.Id),M(g[d])),i&&(o.firstCreated=Ln(o.firstCreated,M(g[i])),o.lastCreated=St(o.lastCreated,M(g[i])));o.modifiedColumn=d;let u=[];return t.forEach((g,m)=>{let h=y(g),R=f.get(h);R===void 0&&(o.missing.add(h),u.push(g)),o.modified.set(n+m,R??Number.NaN)}),u}catch(l){s??=P(l)}return o.error=s,o.modifiedColumn=void 0,[]}async function*En(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function $r(r,e,t){let n=new Set(e.objects.filter(i=>i.count>0).map(i=>i.objectApiName));if(!n.has(xe))return[];let o=[];for await(let i of e.pages(xe))o.push(...i);let s=await Sn(r,{has:i=>e.has(i),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),a=[];for(let i of s){let{objectApiName:d}=i;if(t.undeletable.has(d))continue;let l=t.snapshots.get(d);if(l){if(l.error!==void 0||l.modifiedColumn!=="LastModifiedDate")continue}else if(!await Mn(r,d))continue;a.push(i)}return a}async function Mn(r,e){try{let t=G.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function Hr(r,e,t,n){let o=new Map(e.map(({objectApiName:i,copies:d})=>[i,d])),s=new Set(e.flatMap(({copies:i})=>i.map(d=>y(d.id)))),a=r.objects.map(i=>{let d=o.get(i.objectApiName);return d?{objectApiName:i.objectApiName,count:i.count+d.length}:i});for(let[i,d]of o){r.objects.some(u=>u.objectApiName===i)||a.push({objectApiName:i,count:d.length});let l=t.get(i);l||(l={...Nn(),modifiedColumn:"LastModifiedDate"},t.set(i,l));let c=0;for await(let u of r.pages(i))c+=u.length;for(let u of d)l.modified.set(c++,u.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,i)}return{objects:a,pages:async function*(i){yield*r.pages(i);let d=o.get(i);d&&d.length>0&&(yield d.map(l=>l.id))},has:i=>r.has(i)||s.has(i)}}async function Jr(r){let e=Date.now(),t=Number.NaN;try{t=M(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function zr(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?y(e):void 0}catch{return}}function qr(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+yt).toISOString(),userId:e}}function Ln(r,e){return Number.isNaN(r)||e<r?e:r}function St(r,e){return Number.isNaN(r)||e>r?e:r}var jn=999;function Wr(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=St(n,o.lastCreated)),n=St(n,o.modified.latestWithin(e,t));return n}function kt(r,e,t){let n=Qr(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+jn;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Qr(r,e,t){let n=[...e],o=Number.NaN;for(let l of n)o=Ln(o,l.firstCreated);let s=r.runDurationMs??0,a=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(a)){let l=a-s-yt,c=a+yt,f=r.endedByItsWrites===!0?Wr(n,l,c):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>l?o:l),end:Number.isFinite(f)?Math.min(f+jn,c):c}}let i=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??i+s;return{start:i,end:d}}function vn(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(y)),t=r.size),e.has(n))}}function is(r,e){let t=new Oe(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:M(n.first),end:M(n.last),user:y(n.userId)})),includeChanged:e.includeChanged,automationMade:vn(e.taken),...e.runUserId?{runUser:y(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var Ue="IsPersonAccount";function Vr(r,e){return{holding:new Set([...r.holding,...e.holding]),automation:[...r.automation,...e.automation],along:[...r.along,...e.along],goes:[...r.goes,...e.goes],unchecked:r.unchecked||e.unchecked}}var Kr=50;function $e(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Oe=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let u=G.parse(await this.org.describe(e)),g=await this.workedObjects(),m=e==="Account"&&u.fields.some(h=>h.name===Ue);s=(u.childRelationships??[]).filter(h=>(h.cascadeDelete===!0||h.restrictedDelete===!0)&&g.has(h.childSObject)).map(h=>({childSObject:h.childSObject,field:h.field,restricted:h.cascadeDelete!==!0,...m&&h.childSObject==="Contact"&&h.field==="AccountId"?{personContacts:!0}:{}}))}catch(u){return o.reason=P(u),t.forEach(g=>this.hold(o,y(g))),o}let a=[];for(let u=0;u<t.length;u+=q)a.push(t.slice(u,u+q));let i=a.length>1?await Xe(s.map(u=>()=>this.anyPointing(u)),Se):s.map(()=>!0),d=s.filter((u,g)=>i[g]).flatMap(u=>a.map(g=>async()=>({relationship:u,...await this.holdingIn(u,g)}))),l=o.mayBeAutomation,c=new Map;for(let{relationship:u,holding:g,unchecked:m,automation:h,along:R,goes:b}of await Xe(d,Se)){m&&o.unchecked.add(u.childSObject),(g.size>0||h.length>0)&&o.holders.add(u.childSObject),g.forEach(w=>this.hold(o,w));for(let w of h)o.held.add(y(w.parent));l.push(...h);for(let{parent:w,key:k}of R){let I=o.along.get(w)??new Map;I.set(k,u.childSObject),o.along.set(w,I)}b.length>0&&c.set(u.childSObject,[...c.get(u.childSObject)??[],...b])}if(await this.heldBelow(c,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),Ee(e)&&await this.standardPricesHeld(t,o),e===Ye&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(l,o);let f=await this.byAutomationOnly(e,l,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,a,i,d)=>{let l=s.get(a)??new Map;l.set(i,d),s.set(a,l)};for(let[s,a]of e){let i=[...new Set(a.map(l=>l.id))],d=n+1<Dr?await this.heldAmong(s,i,n+1):void 0;for(let{parent:l,id:c,came:f}of a){let u=y(c);if(!d||d.held.has(u)){this.hold(t,l),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,l,u,s);for(let[g,m]of d.along.get(u)??[])o(t.along,l,g,m);for(let[g,m]of d.cameAlong.get(u)??[])o(t.cameAlong,l,g,m)}d?.unchecked.forEach(l=>t.unchecked.add(l))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(y(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let a=await this.heldAmong(o,[...new Set(s.map(i=>i.id))],1);for(let i of s){let d=y(i.id),l=a.mayBeAutomation.some(c=>y(c.parent)===d&&c.creator!==i.creator);!a.otherwise.has(d)&&!l||(this.hold(t,y(i.parent)),a.holders.forEach(c=>t.holders.add(c)))}a.unchecked.forEach(i=>t.unchecked.add(i))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,a=t.filter(f=>!n.has(y(f.parent)));if(a.length===0)return{objects:o,after:s,along:new Set};let i;try{let f=await j(this.org,e,["CreatedDate","CreatedById"],[...new Set(a.map(u=>u.parent))]);i=new Map(f.flatMap(u=>typeof u.Id=="string"?[[y(u.Id),u]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,l=new Set;for(let f of a){let u=y(f.parent),g=i.get(u),m=M(g?.CreatedDate),h=g?.CreatedById,R=this.context.runUser??(typeof h=="string"?y(h):void 0),b=f.created-m;if(!(R!==void 0&&f.creator===R&&b>=-2e3&&b<=6e4)){d.add(u);continue}let k=o.get(u)??new Set;k.add(f.object),o.set(u,k),f.created>this.context.runEnd&&s.add(u),f.along||l.add(u)}for(let f of d)o.delete(f),s.delete(f);let c=new Set([...o.keys()].filter(f=>!l.has(f)));return{objects:o,after:s,along:c}}async holdingIn(e,t){let n=N(e.childSObject),o=N(e.field),[s]=H(t,t.length),a=new Set(["Id",o,...ht[n]?.ends??[],...e.personContacts?[Ue]:[]]),i=this.datesKept.get(n)??0;for(;i<He.length;){let d=He[i],l;try{l=await this.org.query(`SELECT ${[...a,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Fe}`)}catch(R){Lr(R)?(i=jr(R,i),this.datesKept.set(n,i)):i++;continue}if(l.records.length>=Fe){if(t.length>1){let R=Math.ceil(t.length/2);return Vr(await this.holdingIn(e,t.slice(0,R)),await this.holdingIn(e,t.slice(R)))}return{holding:new Set(t.map(y)),automation:[],along:[],goes:[],unchecked:!1}}let c=new Set,f=[],u=[],g=[],m=new Map;for(let R of l.records){if(typeof R!="object"||R===null)continue;let b=R,w=b[e.field];if(typeof w!="string"||typeof b.Id!="string"||(n===kn&&o==="LinkedEntityId"&&this.noteFile(b),this.lockedUnder.get(y(b.Id))===y(w)))continue;let k={onlyIncluded:!1};if(!this.stays(b,n,e.restricted,e.personContacts,k)){if(k.onlyIncluded&&u.push({parent:y(w),key:y(b.Id)}),n!==kn&&this.goesAlongUnread(b)){let _=!(ht[n]?.cameWithRun(b,this.context.runRecords)===!0||e.personContacts===!0&&b[Ue]===!0)&&!k.onlyIncluded&&k.byRemoval!==!0&&this.context.goesWithParent?.(b,this.context.runEnd)!==!0;g.push({parent:y(w),id:b.Id,came:_})}continue}let I=this.mayBeAutomation(b);if(I){let C={parent:w,id:b.Id,object:n,along:!e.restricted,...I};f.push(C),e.restricted&&m.set(b.Id,C)}else c.add(y(w))}let h=await this.ofOtherParts(n,[...m.keys()]);for(let[R,b]of m)h.has(y(R))&&(f.splice(f.indexOf(b),1),c.add(y(b.parent)));return{holding:c,automation:f,along:u,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=y(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:a,runEnd:i}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||a?.(e,i)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:a}=this.context;if(t.length===0||!o||!s)return n;let i=this.cascadeEnds.get(e);i||(i=(async()=>{let c=new Set;for(let f of s)try{let u=G.parse(await this.org.describe(f));for(let g of u.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&c.add(g.field)}catch{}return[...c]})(),this.cascadeEnds.set(e,i));let d=await i;if(d.length===0)return n;let l;try{l=await j(this.org,e,d,t)}catch{return n}for(let c of l){if(typeof c.Id!="string")continue;let f=d.flatMap(u=>{let g=c[u];return typeof g=="string"?[y(g)]:[]});f.some(u=>a.has(u))||f.some(u=>o.has(u))&&n.add(y(c.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:a}=this.context;if(typeof e.Id!="string"||t.has(y(e.Id))||a?.has(y(e.Id))===!0||typeof e.CreatedById!="string")return;let i=y(e.CreatedById);if(s!==void 0&&i!==s)return;let d=M(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let l=M(e.LastModifiedDate),c=typeof e.LastModifiedById=="string"?y(e.LastModifiedById):void 0;if(!(l>o&&c!==void 0&&c!==i))return{created:d,creator:i}}async anyPointing(e){try{let t=N(e.childSObject),n=N(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||ue(n,this.context.runRecords))return;let o=this.files.get(y(t))??new Set;o.add(n),this.files.set(y(t),o)}async filesOn(e){let t=new Map;for(let s of e){let a=this.files.get(y(s));a&&a.size>0&&t.set(y(s),[...a])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await j(this.org,Er,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(y(s.Id),s.Title)}catch{}return new Map([...t].map(([s,a])=>[s,a.map(i=>({key:y(i),name:o.get(y(i))??i}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(Mt)){let a=s.find(u=>u.object===e)?.lookup,i=me[o];if(!a||!i)continue;let d=await this.statusCategoriesOf(i);if(!d)continue;let l,c;try{l=await j(this.org,e,[a],t);let u=[...new Set(l.map(g=>g[a]).filter(g=>typeof g=="string"))];c=u.length>0?await j(this.org,o,["Status"],u):[]}catch{continue}let f=new Set(c.filter(u=>{let g=d.categoryOf.get(String(u.Status));return g!==void 0&&g!=="Draft"}).map(u=>y(String(u.Id))));for(let u of l){let g=u[a];typeof u.Id!="string"||typeof g!="string"||f.has(y(g))&&(this.hold(n,y(u.Id)),n.holders.add(o),this.lockedUnder.set(y(u.Id),y(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=Pe(de(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=de(this.org),o=[...await pe(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),a=await j(this.org,ee,s,o),i=await this.pricesOfProducts(a,s),d=i.flatMap(u=>typeof u.Id=="string"?[u.Id]:[]),l=new Set([...await pe(n,d)].map(y)),c=new Set(e.map(y)),f=new Set;for(let u of i){if(typeof u.Id!="string")continue;let g=y(u.Id);if(l.has(g))continue;(c.has(g)?t.held.has(g):this.stays(u,ee,!0))&&f.add($e(u,s))}for(let u of a)typeof u.Id!="string"||!f.has($e(u,s))||(this.hold(t,y(u.Id)),t.holders.add(ee))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ge,Ge];try{let o=await j(this.org,Ye,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),a=new Set(s.filter(i=>typeof i.Id=="string"&&i.IsActive===!0&&this.stays(i,ee,!0)).map(i=>$e(i,n)));for(let i of o)typeof i.Id!="string"||!a.has($e(i,n))||(this.hold(t,y(i.Id)),t.holders.add(ee))}catch{}}async priceKeyFields(){let e=G.parse(await this.org.describe(ee)),t=new Set(e.fields.map(n=>n.name));return[ge,...[Ge,Lt].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(a=>a[ge]).filter(a=>typeof a=="string"))],o=[...new Set(["Id",...t])].map(N).join(", "),s=[];for(let a of H(n,Kr)){let i=await this.org.query(`SELECT ${o} FROM ${ee} WHERE ${ge} IN (${a}) LIMIT ${Fe}`);if(i.records.length>=Fe)throw new Error("More prices than one read takes.");for(let d of i.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let a=y(e.Id),{runRecords:i,reached:d,runStart:l,runEnd:c,removalStart:f,removalUser:u,earlierRemovals:g,includeChanged:m}=this.context;if(i.has(a))return d.has(a)||this.context.stays(a);if(n)return!0;if(this.context.automationMade?.has(a)===!0||this.context.goesWithParent?.(e,c)===!0||this.context.alongToDraft?.has(a)===!0||ht[t]?.cameWithRun(e,i))return!1;if(o&&e[Ue]===!0)return!(M(e.LastModifiedDate??e.SystemModstamp)<=c)&&!m;let h="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!h)return!0;let R=M(e[h]),b=M(h==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(R>=l))return!0;let w=this.context.linkedLater?.get(a);if(w&&(R<=c||R>=w.start)&&b<=w.end)return!1;let k=typeof e.CreatedById=="string"?y(e.CreatedById):void 0,I=(_,Y)=>_!==void 0&&(_===u&&Y>=f||g.some(V=>_===V.user&&Y>=V.start&&Y<=V.end));if(I(k,R))return s&&(s.byRemoval=!0),!1;if(b<=c)return!1;let C=typeof e.LastModifiedById=="string"?y(e.LastModifiedById):void 0;return R<=c&&I(C,b)?!1:(m&&s&&(s.onlyIncluded=!0),!m)}workedObjects(){return this.worked??=vt(this.org),this.worked}};export{Ne as a,tt as b,Wt as c,Qt as d,G as e,Vt as f,Wn as g,Vn as h,Kn as i,Gn as j,Yn as k,oo as l,Me as m,nt as n,ve as o,he as p,yo as q,dt as r,or as s,ir as t,tn as u,rn as v,ct as w,on as x,sn as y,an as z,Te as A,lt as B,lr as C,ut as D,Oo as E,dn as F,Sn as G,le as H,mr as I,yt as J,re as K,es as L,ts as M,ns as N,rs as O,os as P,ss as Q,is as R};
|
|
@@ -4,5 +4,5 @@ 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 C,f as I}from"./chunk-
|
|
7
|
+
import{e as C,f as I}from"./chunk-YT22LMF7.mjs";import{e as T,r as S,z as O}from"./chunk-SAMWHL22.mjs";import{H as A,d as P,r as b}from"./chunk-J24TIGSI.mjs";import{b as w}from"./chunk-CA5NAXSU.mjs";import{a as u}from"./chunk-ZUTUYBNW.mjs";import{_a as h}from"./chunk-ZQO5PDX5.mjs";import{b as i,f as R,l as m}from"./chunk-WZQEK4WT.mjs";import{randomBytes as q}from"node:crypto";import{open as U,readFile as F,rename as $,rm as M}from"node:fs/promises";import{promisify as N}from"node:util";import{gunzip as L,gzip as _}from"node:zlib";var D=N(_),Q=N(L),G=200,E="005",j="User",z="Group",H=new Set(["Pricebook2","PricebookEntry"]);function Re(e,n){let t=new Set(n);return e.fields.filter(o=>t.has(o.name)&&!C.includes(o.name)&&o.type==="reference"&&o.createable===!0&&(o.referenceTo??[]).some(r=>r===j||r===z)).map(o=>o.name)}async function Ae(e,n,t){let o=new Set;for(let{objectApiName:r,userLookups:s}of t){if(s.length===0)continue;let c=await S.read(e,n,r);for await(let l of c.records())for(let y of s){let a=l[y];if(typeof a!="string")continue;let p=u(a,E);p!==void 0&&o.add(p)}}return[...o].sort()}function ke(e){for(let n of e)if((n.name==="Account"||n.name==="Contact")&&n.fields.some(t=>t.name===I))return!0;return!1}function be(e){for(let n of e)if(H.has(n))return!0;return!1}function J(e){return e.map(n=>{if(u(n,E)!==n)throw new Error(`Not a user id: ${n}`);return`'${n}'`}).join(", ")}function W(e,n){let t=[];for(let o=0;o<e.length;o+=n)t.push(e.slice(o,o+n));return t}function B(e,n){return[...v(e),...W(n,G).map(t=>({part:"users",objectApiName:j,soql:`SELECT Id, Username, Name, IsActive, UserType FROM User WHERE Id IN (${J(t)})`,scanAll:!1}))]}function v(e){let n=[{part:"recordTypes",objectApiName:"RecordType",soql:`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${e.personAccounts?", IsPersonType":""} FROM RecordType`,scanAll:!1},{part:"queues",of:"groups",objectApiName:z,soql:"SELECT Id, DeveloperName, Name FROM Group WHERE Type = 'Queue'",scanAll:!1},{part:"queues",of:"objects",objectApiName:"QueueSobject",soql:"SELECT QueueId, SobjectType FROM QueueSobject",scanAll:!1}];return e.catalog&&n.push({part:"standardPricebook",objectApiName:"Pricebook2",soql:"SELECT Id FROM Pricebook2 WHERE IsStandard = true LIMIT 1",scanAll:!1}),n}function xe(e){return Math.ceil((v(e).length+1)/T)}var K=m({Id:i(),SobjectType:i(),DeveloperName:i(),NamespacePrefix:i().nullish(),Name:i(),IsActive:R(),IsPersonType:R().nullish()}).loose(),X=m({Id:i(),DeveloperName:i(),Name:i().nullish()}).loose(),V=m({QueueId:i(),SobjectType:i()}).loose(),Y=m({Id:i(),Username:i(),Name:i().nullish(),IsActive:R(),UserType:i()}).loose(),f="the org answered with rows this SandForge does not read";function Z(e,n){let t=[];for(let o of e){let r=K.safeParse(o);if(!r.success)return{unread:f};let s=r.data;t.push({id:u(s.Id)??s.Id,sobjectType:s.SobjectType,developerName:s.DeveloperName,...s.NamespacePrefix?{namespacePrefix:s.NamespacePrefix}:{},name:s.Name,isActive:s.IsActive,...n&&typeof s.IsPersonType=="boolean"?{isPersonType:s.IsPersonType}:{}})}return{rows:t.sort((o,r)=>x(`${o.sobjectType}.${o.developerName}`,`${r.sobjectType}.${r.developerName}`))}}function ee(e,n){let t=new Map;for(let r of n){let s=V.safeParse(r);if(!s.success)return{unread:f};let c=s.data.QueueId.slice(0,15);t.set(c,[...t.get(c)??[],s.data.SobjectType])}let o=[];for(let r of e){let s=X.safeParse(r);if(!s.success)return{unread:f};let c=s.data;o.push({id:u(c.Id)??c.Id,developerName:c.DeveloperName,name:c.Name??"",sobjectTypes:[...t.get(c.Id.slice(0,15))??[]].sort()})}return{rows:o.sort((r,s)=>x(r.developerName,s.developerName))}}function ne(e){let n=[];for(let t of e){let o=Y.safeParse(t);if(!o.success)return{unread:f};let r=o.data;n.push({id:u(r.Id)??r.Id,username:r.Username,name:r.Name??"",isActive:r.IsActive,userType:r.UserType})}return{rows:n.sort((t,o)=>x(t.id,o.id))}}async function we(e){let n=B(e,e.users),t=n.map(()=>[]),o=await O(e.reader,n,(a,p)=>{t[a].push(...p)},e.signal),r=new Map;o.forEach((a,p)=>{let{part:d}=n[p];!a.read&&!r.has(d)&&r.set(d,a.reason)});let s=(a,p)=>n.flatMap((d,g)=>d.part===a&&(p===void 0||d.of===p)?t[g]:[]),c={version:1,organizationId:u(e.organizationId)??e.organizationId,recordTypes:[],users:[],queues:[],unread:[]},l=(a,p,d)=>{let g=r.get(a);if(g!==void 0){c.unread.push({part:a,reason:oe(g)});return}let k=p();"unread"in k?c.unread.push({part:a,reason:k.unread}):d(k.rows)};l("recordTypes",()=>Z(s("recordTypes"),e.personAccounts),a=>{c.recordTypes=a}),l("queues",()=>ee(s("queues","groups"),s("queues","objects")),a=>{c.queues=a}),e.catalog&&l("standardPricebook",()=>{let[a]=s("standardPricebook"),p=typeof a?.Id=="string"?u(a.Id,"01s"):void 0;return a!==void 0&&p===void 0?{unread:f}:{rows:p}},a=>{a!==void 0&&(c.standardPricebookId=a)}),l("users",()=>ne(s("users")),a=>{c.users=a});let y=h.safeParse(c);return y.success?y.data:re(c,y.error.issues)}function re(e,n){let t=new Set;for(let r of n){let[s]=r.path;(s==="recordTypes"||s==="users"||s==="queues")&&t.add(s),s==="standardPricebookId"&&t.add("standardPricebook")}let o={...e,unread:[...e.unread]};for(let r of t)r==="recordTypes"&&(o.recordTypes=[]),r==="users"&&(o.users=[]),r==="queues"&&(o.queues=[]),r==="standardPricebook"&&delete o.standardPricebookId,o.unread.push({part:r,reason:f});return h.parse(o)}function x(e,n){return e<n?-1:e>n?1:0}function oe(e){let n=e.trim()===""?"the org gave no reason":e.trim();return n.length<=500?n:`${n.slice(0,499)}\u2026`}function te(e){let n=[...new Set(e.unread.map(t=>t.part))];return{recordTypes:e.recordTypes.length,users:e.users.length,queues:e.queues.length,standardPricebook:e.standardPricebookId!==void 0,...n.length>0?{unread:n}:{}}}async function Te(e,n){let t=h.safeParse(n);if(!t.success)throw new A("invalid",`Not a replay annex: ${t.error.message}`);let o=b(e),r=`${o}.${process.pid}-${q(4).toString("hex")}.tmp`,s=await U(r,"wx",P);try{try{await s.writeFile(await D(`${JSON.stringify(t.data)}
|
|
8
8
|
`)),await s.sync()}finally{await s.close()}await $(r,o)}catch(c){throw await M(r,{force:!0}),c}return te(t.data)}async function Pe(e){let n;try{n=await F(b(e))}catch(r){if(r.code==="ENOENT")return;throw r}let t;try{t=JSON.parse((await Q(n)).toString("utf8"))}catch(r){throw new A("damaged",`The checkpoint\u2019s replay annex cannot be read: ${w(r)}`)}let o=h.safeParse(t);if(!o.success)throw new A("damaged","The checkpoint\u2019s replay annex does not parse");return o.data}export{Re as a,Ae as b,ke as c,be as d,xe as e,we as f,te as g,Te as h,Pe as i};
|
|
@@ -0,0 +1,28 @@
|
|
|
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 s}from"./chunk-SCKUIE3R.mjs";import{readFileSync as d}from"node:fs";import{extname as p,join as i}from"node:path";import{pathToFileURL as c}from"node:url";var r={autopilot:"run an Autopilot copy between two orgs",backup:"take and restore DataOps snapshots",checkpoint:"take a checkpoint of an org's data, and rewind the org to it",cleanup:"Bulk delete records you created on a sandbox in a time window",clone:"clone a record, or whole tables, from one org to a sandbox, or remove a run",compare:"compare two orgs the way the Compare page does",dataops:"mask an org's records, and put them back",empty:"empty objects of a sandbox, or the whole of it",env:"apply a sandforge.yaml to an org, and take it back",frozen:"build and replay a Frozen Dataset",mcp:"the MCP server: these scripts as tools for an AI agent, on stdio",monitor:"read an org the way the Monitor page does",pipeline:"plan and run an Automation pipeline exported from VS Code",seed:"fill an org from a seed template",sync:"run a Sync between two orgs",users:"set up the users of a sandbox after its refresh, and take them back"},a=o=>Object.prototype.hasOwnProperty.call(r,o);function m(o){let[e,...n]=o;if(e===void 0)return{kind:"refused",reason:"Name the command to run."};if(e==="--help"||e==="-h"||e==="help")return{kind:"help"};if(e==="--version"||e==="-v")return{kind:"version"};if(a(e))return{kind:"run",tool:e,args:n};let t=e.replace(/^sandforge-/,"");return t!==e&&a(t)?{kind:"refused",reason:`"${e}" is named ${t} here: ${s(t)} \u2026.`}:{kind:"refused",reason:e.startsWith("-")?`"${e}" is not a flag sandforge reads: name a command first.`:`"${e}" is not a command of sandforge.`}}function l(){let o=Math.max(...Object.keys(r).map(n=>n.length));return`sandforge \u2014 SandForge's command lines, without the editor: Seed, Forge's clone, Sync,
|
|
8
|
+
Checkpoints, DataOps, Frozen Dataset, the emptying of a sandbox, the users of a sandbox,
|
|
9
|
+
sandforge.yaml environments, Automation pipelines, and the MCP server.
|
|
10
|
+
|
|
11
|
+
Usage:
|
|
12
|
+
sandforge <command> [options]
|
|
13
|
+
sandforge <command> --help what the command does, its options and its exit codes
|
|
14
|
+
|
|
15
|
+
Commands:
|
|
16
|
+
${Object.entries(r).map(([n,t])=>` ${n.padEnd(o)} ${t}`).join(`
|
|
17
|
+
`)}
|
|
18
|
+
|
|
19
|
+
Each org is named by its sf CLI alias: the Salesforce CLI (sf) must be installed and logged in
|
|
20
|
+
to it. In Claude Code:
|
|
21
|
+
claude mcp add sandforge -- npx -y sandforge mcp
|
|
22
|
+
|
|
23
|
+
--version the version of SandForge these scripts belong to
|
|
24
|
+
--help this text
|
|
25
|
+
`}function f(o,e=__dirname,n=__filename){return i(e,`sandforge-${o}${p(n)}`)}function u(o=__dirname){let e=JSON.parse(d(i(o,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}var g=o=>import(c(o).href);async function h(o=process.argv,e=g){let n=m(o.slice(2));switch(n.kind){case"help":process.stdout.write(l());return;case"version":process.stdout.write(`${u()}
|
|
26
|
+
`);return;case"refused":process.stderr.write(`${n.reason} Nothing was run. The commands: ${Object.keys(r).join(", ")}. Run with --help.
|
|
27
|
+
`),process.exitCode=2;return;case"run":{let t=f(n.tool);process.argv=[o[0]??process.execPath,t,...n.args],await e(t);return}}}/(?:^|[\\/])sandforge\.[cm]?[jt]s$/.test(process.argv[1]??"")&&h().catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
|
|
28
|
+
`),process.exit(1)});export{r as a,m as b,l as c,f as d,u as e,h as f};
|
|
@@ -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{b as S,d as z}from"./chunk-
|
|
7
|
+
import{b as S,d as z}from"./chunk-VPDEJGPS.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{ic as R}from"./chunk-ZQO5PDX5.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-WZQEK4WT.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{c as Jt,d as Ts,e as Ms,f as Vt}from"./chunk-ZXFL2MSN.mjs";import{b as ut,c as pt,d as Qt,e as en,f as Ws,g as tn}from"./chunk-VYOYXTCU.mjs";import{b as Gs,d as Us}from"./chunk-C3LNYAVJ.mjs";import{a as zs,c as qs}from"./chunk-GJ6SZVHT.mjs";import{a as ze,b as Fs,c as js,d as vs,f as Ns,g as xs,h as Ds,i as Ls,j as $s,l as Q,n as Xt,o as Zt,p as Bs,q as _s,s as qe}from"./chunk-52EXDVPN.mjs";import{Dc as Cr}from"./chunk-ISSP2FZ5.mjs";import{a as ve,c as Ht}from"./chunk-BOGNK4LV.mjs";import{$a as Ps,F as ps,G as fs,Ga as ys,Ha as ws,L as gs,M as hs,O as ms,Oa as Ss,Pa as Rs,Qa as bs,Ra as ks,Sa as Os,Ua as As,Va as Cs,Xa as Is,ab as Es,g as ds,i as Yt}from"./chunk-P55MKIZX.mjs";import{k as us}from"./chunk-PYRZFUVU.mjs";import{i as Ir,o as vr}from"./chunk-O2PUGRNW.mjs";import{G as Or,N as Ar,m as qt,r as kr}from"./chunk-7SDZR6SR.mjs";import{l as cs,m as ls}from"./chunk-TEIBWMJM.mjs";import{l as br}from"./chunk-54HYHHVL.mjs";import{f as Nr,h as xr,i as Ue,k as Dr,l as Lr,m as $r,o as Br,p as _r,q as Wr,r as Gr,s as Ur}from"./chunk-WSUKC2U3.mjs";import{a as Kt}from"./chunk-QSRAEUGZ.mjs";import{h as Fr,j as jr}from"./chunk-SAMWHL22.mjs";import{b as Tr,f as Mr}from"./chunk-HKUWHVI7.mjs";import{b as Ut,c as Ge,d as ee}from"./chunk-VPDEJGPS.mjs";import{f as Pr,g as Er}from"./chunk-JQZTMFO7.mjs";import{$a as Yr,Ac as as,Ra as qr,Sa as Kr,Wb as Qr,Zb as es,_a as Hr,_b as ts,ac as ns,bb as we,db as at,eb as Jr,ec as rs,fb as dt,fc as ss,gb as Vr,hb as Xr,ib as ct,jb as lt,kc as is,lb as Zr,lc as os,mc as xe,zb as Ne}from"./chunk-JFNLKHY6.mjs";import{q as zr}from"./chunk-VZVICK7Q.mjs";import{a as mr,d as yr,e as wr,f as Sr,g as Rr}from"./chunk-HFUDCNU5.mjs";import{A as Ie,B as dr,C as _t,D as ot,E as Wt,G as Gt,H as cr,I as lr,J as je,n as Xn,o as Fe,q as Zn,r as Qn,s as er,t as tr,u as nr,v as rr,w as sr,y as ar,z as We}from"./chunk-XZISAZA6.mjs";import{a as Yn}from"./chunk-EADHKH3A.mjs";import{F as X,G as oe,I as Bt,N as Kn,P as Hn,f as it,g as zn,m as qn,r as $t}from"./chunk-KIMQQ6JQ.mjs";import{f as Un,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{c as ur,d as pr,f as fr,h as gr,j as hr,k as zt}from"./chunk-ZUTUYBNW.mjs";import{a as Jn,w as Vn}from"./chunk-ICIYL45C.mjs";import{c as ir,d as or}from"./chunk-PR74GYVI.mjs";import{$c as $n,Ed as Gn,Hc as rt,Ib as vn,Jb as et,Mc as xn,Td as Lt,Uc as st,Vb as Nn,Zc as Dn,_c as Ln,ad as Bn,bd as _n,cd as Wn,g as Fn,i as Dt,ic as tt,j as jn,k as fe,rc as Me,sc as ge,wc as nt}from"./chunk-ZQO5PDX5.mjs";import{b as _e,k as vt,l as Nt,u as Tn,v as Mn,z as xt}from"./chunk-WZQEK4WT.mjs";var ft=class{classify(e){let t=et(e.statusCode),s=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:s}}classifyBatch(e){let t=e.map(a=>this.classify(a)),s={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},r={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";s[d]=(s[d]??0)+1,r[a.originalError.statusCode]=(r[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:s,byErrorCode:r,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return et(e).retryable}hasBlockingError(e){return e.some(t=>et(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys(vn).length}getSuggestedAction(e,t){return t.suggestUpsert?"Consider using upsert with external ID":t.suggestTruncate?"Truncate field values to fit within limits":t.blockAll?"Operation blocked: resolve storage/limit issue first":t.strategy==="reauth_then_retry"?"Re-authenticate and retry":t.strategy==="reduce_batch"?"Reduce batch size and retry":t.retryable?`Retry after ${t.delay??0}ms`:`Fix ${e} error and retry manually`}};function Vi(n,e){return new Promise(t=>{if(e?.aborted){t();return}let s=()=>{clearTimeout(r),e?.removeEventListener("abort",s),t()},r=setTimeout(s,n);e?.addEventListener("abort",s,{once:!0})})}var gt=class{constructor(e={}){this.options=e;this.strategy=new Lr({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new ft}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),s,r=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:r}}catch(o){s=o instanceof Error?o:new Error(String(o));let a=Xi(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:s,attempts:i+1,totalDelay:r};if(i<t.maxRetries){let c={success:!1,error:s,attempts:i+1,totalDelay:r,cancelled:!0};if(this.options.signal?.aborted)return c;let l=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,l),r+=l,await Vi(l,this.options.signal),this.options.signal?.aborted)return{...c,totalDelay:r}}}return{success:!1,error:s,attempts:t.maxRetries+1,totalDelay:r}}async executeBatch(e,t){let s=[...e],r=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;s.length>0&&o<=a;){let d=await t(s);r.push(...d.successes);let c=[];for(let l of d.failures)this.classifier.classify(l.error).classification.retryable&&o<a?c.push(l.record):i.push(l);if(s=c,s.length>0){let l=this.options.retryConfig?.initialDelay??1e3,u=this.options.retryConfig?.maxDelay??3e4,f=l*Math.pow(2,o);await new Promise(p=>setTimeout(p,Math.min(f,u))),o++}}return{successes:r,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function Xi(n){if(typeof n!="object"||n===null)return{statusCode:"UNKNOWN_ERROR",message:String(n)};let e=n,t=[e.errorCode,e.statusCode,e.name].find(r=>typeof r=="string"&&r.length>0&&r!=="Error"),s=e.fields??e.data?.fields;return{statusCode:t??"UNKNOWN_ERROR",errorCode:typeof e.errorCode=="string"?e.errorCode:void 0,message:typeof e.message=="string"?e.message:String(n),fields:Array.isArray(s)?s.filter(r=>typeof r=="string"):void 0}}var Zi=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Qi(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function eo(n,e,t,s=()=>Date.now()){let r=await br(n,e,{now:s,successfulOnly:!0});return r.state==="running"?{state:"running"}:r.state!=="ended"?r:{state:"ended",created:(r.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!Zi.test(a)?[]:t&&Qi(o.sf__Created)!==!0?[]:[a]}),...typeof r.info.systemModstamp=="string"?{at:r.info.systemModstamp}:{}}}async function cd(n,e,t,s,r=()=>new Date){let i,o=()=>(i??=(async()=>{if(!s)return 0;try{let d=r().getTime(),c=Date.parse(await s());return Number.isFinite(c)?c-(d+r().getTime())/2:0}catch{return 0}})(),i),a=[];for(let d of e.jobs??[]){if(d.job===void 0)continue;let c={job:d.job,objectApiName:d.objectApiName},l=await eo(t,d.job,d.upsert===!0,()=>r().getTime());if(l.state==="running"||l.state==="unread"){a.push({...c,read:l,answered:!1});continue}let u=r().toISOString();l.state==="ended"&&l.at!==void 0&&Number.isFinite(Date.parse(l.at))?u=new Date(Date.parse(l.at)-await o()).toISOString():e.lastWrittenAt!==void 0&&(u=e.lastWrittenAt);let f=l.state==="ended"?l.created:[],p=await n.answerInFlight(e.runId,d.objectApiName,f,u,d.job);a.push({...c,read:l,answered:p})}return a}function ld(n,e){return e.map(({job:t,read:s})=>{let r=`${n}, job ${t}`;switch(s.state){case"ended":return`[INFO] ${r}: the job no line of the run answered ended in the org; ${s.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${r}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${r}: the job is still running in the org; read again later`;default:return`[WARN] ${r}: the job could not be read back: ${s.reason}`}})}var Le=5e3,rn=200,ht=_e().refine(n=>Ge(n),"not a record id"),to=Nt({sourceOrgId:_e().min(1).max(200),targetOrgId:_e().min(1).max(200),objectApiName:_e().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:Tn(["document","attachment"]),sourceId:ht,targetId:ht,sourceVersionId:ht.optional(),sourceModifiedAt:xt.datetime().optional(),linked:vt(ht).max(rn),copiedAt:xt.datetime()}),no=Nt({version:Mn(1),entries:vt(to).max(Le)});function Hs(n){if(n==null)return{kind:"none"};let e=no.safeParse(n);if(e.success)return{kind:"stored",map:e.data};let t=e.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"map"}: ${t.message}`}}function kd(n,e,t){return n?n.check({orgId:e,orgTier:xn(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var le=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Ke=class extends Error{};function ro(){return{copied:0,versions:0,bytes:0,links:0,unchanged:0,tooLarge:0,pastRunCap:0,external:0,recordNotWritten:0,failed:0}}function te(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function mt(n,e){let t=n;for(let s of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[s]}return Wt(t)}function De(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function so(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function He(n,e,t){return`${n}|${e}|${t}`}function io(n,e){let t=e.load(n.id);if(t===null)throw new le("Files are copied by a saved configuration only: it keeps which file it copied where, so that running it again copies none of them twice. Save the configuration, then run it. Nothing was read or written.");if(t.kind==="unreadable")throw new le(`The record of the files this configuration copied could not be read (${t.issue}), so a run could copy them a second time. Turn the files off, or save the configuration again under a new name. Nothing was read or written.`);let s=new Map;if(t.kind==="stored")for(let r of t.map.entries)s.set(He(r.sourceOrgId,r.targetOrgId,r.sourceId),r);return s}var nn="ContentDocument.LatestPublishedVersion.SystemModstamp";async function oo(n,e,t,s){let r=rt(t.objectApiName),i=t.where?.trim()?` WHERE (${Un(t.where)})`:"",o=`SELECT Id FROM ${r}${i}`,a=_t(s),d=new Set,c,l=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${nn} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${nn} > ${a})`);for(let f of l){let p=te(f,"LinkedEntityId");p&&Ge(p)&&d.add(p),c=De(De(c,mt(f,"SystemModstamp")),mt(f,nn))}let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT ParentId, LastModifiedDate FROM Attachment WHERE ParentId IN (${o}) AND LastModifiedDate > ${a}`);for(let f of u){let p=te(f,"ParentId");p&&Ge(p)&&d.add(p),c=De(c,mt(f,"LastModifiedDate"))}return{ids:[...d],...c!==void 0?{newest:c}:{}}}async function ao(n,e,t){let s=new Map;for(let r of ee(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${r})`);for(let o of i){let a=te(o,"Id"),d=Wt(o.LastModifiedDate);a&&d&&s.set(a,d)}}return s}function co(n,e,t){return e===void 0||n.targetId===n.sourceId?!1:n.sourceModifiedAt!==void 0?n.sourceModifiedAt!==e:t!==void 0&&Date.parse(e)>Date.parse(t)}async function lo(n,e,t,s,r,i){let o=[...r.values()].filter(l=>l.kind==="document"&&l.objectApiName===t&&l.sourceOrgId===e.sourceOrgId&&l.targetOrgId===e.targetOrgId&&!i.has(l.sourceId)).map(l=>l.sourceId),a=_t(s),d=[],c;for(let l of ee(o)){let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SystemModstamp FROM ContentVersion WHERE ContentDocumentId IN (${l}) AND IsLatest = true AND SystemModstamp > ${a}`);for(let f of u){c=De(c,mt(f,"SystemModstamp"));let p=te(f,"ContentDocumentId"),h=te(f,"Id");if(!p||!h||(te(f,"ContentLocation")??"S")!=="S")continue;let y=te(f,"Title")??p;d.push({objectApiName:"ContentDocument",sourceId:p,body:{objectApiName:"ContentVersion",id:h},name:y,bytes:so(f,"ContentSize"),hosts:[],fields:{Title:y,PathOnClient:te(f,"PathOnClient")??y}})}}return{files:d,...c!==void 0?{newest:c}:{}}}async function uo(n,e,t,s){let r=new Map,i=new Date().toISOString(),o=(l,u,f)=>({sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:t,kind:l,sourceId:u,targetId:u,linked:[],copiedAt:i,...f}),a=s.filter(l=>l.objectApiName==="ContentDocument").map(l=>l.sourceId);for(let l of ee(a)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");if(!p)continue;let h=te(f,"LatestPublishedVersionId");r.set(p,o("document",p,h?{sourceVersionId:h}:{}))}}let d=[...r.keys()];for(let l of ee(d)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${l})`);for(let f of u){let p=te(f,"ContentDocumentId"),h=te(f,"LinkedEntityId"),y=p?r.get(p):void 0;y&&h&&Ge(h)&&y.linked.length<rn&&y.linked.push(h)}}let c=s.filter(l=>l.objectApiName==="Attachment").map(l=>l.sourceId);for(let l of ee(c)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id FROM Attachment WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");p&&r.set(p,o("attachment",p,{}))}}return r}async function Ys(n){let{config:e,option:t,objects:s,deps:r}=n,i=io(e,r.store),o;try{o=await gs(r.copy,e.targetOrgId)}catch(p){throw new le(`The file storage the target has left could not be read (${K(p)}), so the files could not be measured against it. Nothing was written.`)}let a=t.maxFileSizeMB*1048576,d=t.maxRunMB*1048576,c=0,l=0,u=new Set,f={objects:new Map,storage:{remainingBytes:o,plannedBytes:0}};for(let{objectConfig:p,changedSince:h,filesSeen:y}of s){if(p.operation==="delete")continue;let m=p.objectApiName,R=await r.sourceIds(p,h),S=[],b=h===void 0?void 0:y!==void 0&&Date.parse(y)>Date.parse(h)?dr(y):h,k=h===void 0?void 0:y,g=new Map;if(b!==void 0)try{let j=new Set(R),D=await oo(r,e,p,b);k=De(k,D.newest);let _=D.ids.filter(z=>!j.has(z));if(_.length>0){let z=n.tie?await n.tie(p,_):{held:new Map};g=z.held;let H=_.filter(G=>!g.has(G)).length;H>0&&S.push(`${H} record(s) whose files changed since the last run, and nothing else of them, could not be tied to their copy in the target`+(z.refused?` (${z.refused})`:"")+": their new files are copied when the record changes, or on a full read.")}}catch(j){throw new le(`${m}: the files its records gained since the last run could not be looked up (${K(j)}). Run it again, or turn the files off. Nothing was written.`)}let w=[...R,...g.keys()],M=await ps({scope:new Map([[m,w]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:r.copy.queryRecords});if(fs(M)){let j=new Set(M.errors.flatMap(D=>D.samples.flatMap(_=>_.messages)));throw new le(`${m}: the files of its records could not all be looked up in the source (${[...j].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let A=ro();for(let j of M.leftOut)j.reason==="too-large"?A.tooLarge++:j.reason==="external"&&A.external++;A.tooLarge>0&&S.push(`${A.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let O=M.files,E=[],F=new Map;try{if(b!==void 0){let _=new Set(O.map(H=>H.sourceId)),z=await lo(r,e,m,b,i,_);k=De(k,z.newest);for(let H of z.files)H.bytes>a?A.tooLarge++:O=[...O,H]}let j=O.filter(_=>!i.has(He(e.sourceOrgId,e.targetOrgId,_.sourceId)));if(j.length>0)for(let[_,z]of await uo(r,e,m,j))i.set(He(e.sourceOrgId,e.targetOrgId,_),z),E.push(z);let D=O.filter(_=>_.objectApiName==="Attachment");D.length>0&&(F=await ao(r,e,D.map(_=>_.sourceId)))}catch(j){throw new le(`${m}: the files an earlier run copied could not be looked up (${K(j)}), so a run could copy them twice. Nothing was written.`)}let N=[],$=new Map,T=0,v=0;for(let j of O){if(u.has(j.sourceId)){A.unchanged++,N.push(j);continue}let D=i.get(He(e.sourceOrgId,e.targetOrgId,j.sourceId)),_=D?.kind==="attachment"&&co(D,F.get(j.sourceId),h);if(_&&!r.deleteFromTarget){v++;continue}if(D&&!_&&(D.kind==="attachment"||D.sourceVersionId===j.body.id)){A.unchanged++,D.kind==="document"&&N.push({...j,into:{documentId:D.targetId,linked:D.linked,unchanged:!0}});continue}if(!D&&l>=Le-i.size){T++,A.pastRunCap++;continue}if(c+j.bytes>d){A.pastRunCap++;continue}c+=j.bytes,A.bytes+=j.bytes,u.add(j.sourceId),D&&_?(A.replaced=(A.replaced??0)+1,$.set(j.sourceId,D.targetId),N.push(j)):D?(A.versions++,N.push({...j,into:{documentId:D.targetId,linked:D.linked}})):(l++,A.copied++,N.push(j))}A.pastRunCap>T&&S.push(`${A.pastRunCap-T} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),v>0&&S.push(`${v} legacy attachment(s) the source changed since they were copied were left as copied: replacing one deletes its earlier copy, and this run may not delete in the target.`),T>0&&S.push(`${T} file(s) were not copied: this configuration keeps the record of ${Le} copied files at most, which it holds already. Removing an earlier run of it frees the entries of the files that run copied: Remove what this run created on its History entry, or --remove on the command line.`),f.objects.set(m,{scope:new Set(w),files:N,outcome:A,notes:S,shared:E,held:g,replacing:$,attachmentsChangedAt:F,...k!==void 0?{filesSeen:k}:{}})}return f.storage={remainingBytes:o,plannedBytes:c,...c>o?{shortfall:`The files to copy take ${st(c)} and the target has ${st(Math.max(0,o))} of file storage left. Lower the largest file or the most a run copies, or leave the files out.`}:{}},f}function po(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function Js(n){let{config:e,option:t,objectApiName:s,planned:r,written:i,deps:o,signal:a}=n,d={...r.outcome,copied:0,versions:0,bytes:0,...r.outcome.replaced!==void 0?{replaced:0}:{}},c=[...r.notes],l=[...i.keys()].filter(g=>!r.scope.has(g)).length;l>0&&c.push(`${l} record(s) written were not in the source when the files were looked up: their files are copied by the next run.`);try{for(let g of r.shared)o.store.record(e.id,g)}catch(g){c.push(`The files the target already held could not be recorded (${K(g)}): the next run looks them up again.`)}if(r.files.length===0)return{outcome:d,notes:c,unplanned:l,cancelled:!1};let u=o.store.load(e.id),f=new Map((u?.kind==="stored"?u.map.entries:[]).filter(g=>g.sourceOrgId===e.sourceOrgId&&g.targetOrgId===e.targetOrgId).map(g=>[g.sourceId,g])),p=r.files.map(g=>{let w=g.into?void 0:f.get(g.sourceId);return w&&w.kind==="document"?{...g,into:{documentId:w.targetId,linked:w.linked,unchanged:!0}}:g}),h=hs({files:p.filter(g=>!g.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),y=[],m,R=!1,S=[],b={ids:[],note:void 0},k=(g,w)=>{let M=He(e.sourceOrgId,e.targetOrgId,g.sourceId),A=[...new Set([...g.into?.linked??[],...w.linked])].slice(0,rn),O=g.objectApiName==="ContentDocument",E=r.replacing.get(g.sourceId),F=r.attachmentsChangedAt.get(g.sourceId);w.asVersion?(d.versions++,d.bytes+=g.bytes):E!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=g.bytes):g.into?.unchanged||(d.copied++,d.bytes+=g.bytes),!w.asVersion&&!g.into&&n.onCreated?.(O?"ContentDocument":"Attachment",w.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:s,kind:O?"document":"attachment",sourceId:g.sourceId,targetId:w.targetId,...O?{sourceVersionId:g.body.id}:{},...!O&&F!==void 0?{sourceModifiedAt:F}:{},linked:A,copiedAt:new Date().toISOString()}),E!==void 0&&E!==w.targetId&&S.push(E)}catch(N){m=`${K(N)} (${M})`}};try{await ms({files:p,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:g=>i.has(g)||r.held.has(g),get:g=>i.get(g)??r.held.get(g),add:()=>{}},deps:o.copy,report:h,errors:y,waitIfPaused:async()=>{if(m!==void 0)throw new Ke;if(await n.waitIfPaused?.(),a?.aborted)throw new Ke},onProgress:g=>{g.status==="running"&&o.onProgress?.(g.progress,`${s}: ${g.message}`)},onCopied:k})}catch(g){if(!(g instanceof Ke))throw g;R=m===void 0}finally{S.length>0&&(b=await fo(o,S))}return d.links=h.links,d.failed=h.objects.reduce((g,w)=>g+w.failed,0)+b.ids.length,d.recordNotWritten=h.leftOut.filter(g=>g.reason==="record-not-created").length,c.push(...po(y)),b.note!==void 0&&c.push(b.note),d.recordNotWritten>0&&c.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),m!==void 0&&(d.failed++,c.push(`A copied file could not be recorded, so no more files were copied: ${m}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:c,unplanned:l,cancelled:R}}var Ks=200;async function fo(n,e){let t=[],s=new Set;for(let r=0;r<e.length;r+=Ks){let i=e.slice(r,r+Ks);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let c=o[d];c?.success||(t.push(a),s.add(c?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),s.add(K(o))}}return t.length===0?{ids:[],note:void 0}:{ids:t,note:`${t.length} earlier copy(ies) of an attachment replaced could not be deleted from the target (${[...s].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function Od(n){let e=t=>{let s=n[t];if(!s)throw new Error(`No connection for the org ${t}.`);return s};return{queryRecords:async(t,s)=>(await Yn(e(t).pages,s)).records,readFileBody:(t,s,r)=>Ss(e(t).transport,s,r),insertFile:(t,s,r)=>Rs(e(t).transport,s,r),insertRecords:async(t,s,r)=>hr(await e(t).create(s,r),s).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>bs(e(t).transport)}}function Ad(n){let e=0,t=0,s=0;for(let r of n)e+=r.copied+r.versions+(r.replaced??0),t+=r.bytes,s+=r.tooLarge+r.pastRunCap;return`${e} file(s), ${st(t)} copied, ${s} skipped past the caps`}var sn="sync:config:",Vs="syncConfigs",Je="sync:delta:",on="syncDelta",yt="sync:files:",Xs="syncFiles",Zs=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${sn}${e.id}`,e,Vs)}load(e){return this.configStore.get(`${sn}${e}`)}isSaved(e){return this.load(e)!==void 0}deltaStore(){return{load:e=>this.isSaved(e)?this.loadDelta(e):null,record:(e,t)=>this.recordWatermark(e,t)}}fileStore(){return{load:e=>this.isSaved(e)?this.loadFiles(e):null,record:(e,t)=>this.recordFile(e,t)}}list(){let e=this.configStore.getByCategory(Vs);return Object.values(e).sort((s,r)=>r.updatedAt.localeCompare(s.updatedAt))}delete(e){return this.configStore.delete(`${Je}${e}`),this.configStore.delete(`${yt}${e}`),this.configStore.delete(`${sn}${e}`)}loadDelta(e){return ar(this.configStore.get(`${Je}${e}`))}recordWatermark(e,t){let s=this.loadDelta(e),o={version:1,entries:[...(s.kind==="stored"?s.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...s.kind==="stored"&&s.state.resetAt?{resetAt:s.state.resetAt}:{}};this.configStore.set(`${Je}${e}`,o,on)}loadFiles(e){return Hs(this.configStore.get(`${yt}${e}`))}recordFile(e,t){let s=this.loadFiles(e);if(s.kind==="unreadable")throw new Error(`the record of copied files does not read: ${s.issue}`);let i=(s.kind==="stored"?s.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=Le)throw new Error(`the record of copied files holds ${Le} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${yt}${e}`,o,Xs)}forgetFiles(e,t,s){let r=this.loadFiles(e);if(r.kind!=="stored"||s.length===0)return[];let i=new Set(s.map(d=>d.slice(0,15))),o=[],a=r.map.entries.filter(d=>{let c=d.sourceOrgId===t.sourceOrgId&&d.targetOrgId===t.targetOrgId&&i.has(d.targetId.slice(0,15));return c&&o.push(d),!c});if(o.length>0){let d={version:1,entries:a};this.configStore.set(`${yt}${e}`,d,Xs)}return o}markRemoved(e,t,s,r){let i=this.loadDelta(e);if(i.kind!=="stored"||s.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!s.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:r}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${Je}${e}`,d,on)}return o}clearDelta(e){let t=this.loadDelta(e),s=t.kind==="stored"?t.state.entries.length:0,r={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${Je}${e}`,r,on),s}};async function go(n,e,t){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=ye(i);for(let d of ee(o)){if(t?.aborted)return;let c=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${a} WHERE Id IN (${d})`);for(let l of c.records){let u=Date.parse(String(l.CreatedDate??""));Number.isFinite(u)&&(s=Math.min(s,u),r=Math.max(r,u))}}}if(!(!Number.isFinite(s)||!Number.isFinite(r)))return{first:new Date(s).toISOString(),last:new Date(r).toISOString()}}async function Nd(n,e){let t=r=>({note:`What the duplicate rules of the target reported of the run could not be read (${K(r)}): the empty DuplicateRecordSet records it left, if any, stay.`}),s=new Set;try{for(let{ids:r}of e)for(let i of ee(r)){let{records:o}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE RecordId IN (${i})`);for(let a of o){let d=a.DuplicateRecordSetId;typeof d=="string"&&s.add(d)}}}catch(r){return{take:async()=>t(r)}}return{take:async(r=[])=>{let i=new Set(r.map(l=>l.slice(0,15))),o=[...s].filter(l=>!i.has(l.slice(0,15)));if(o.length===0)return{};let a=new Set;try{for(let l of ee(o)){let{records:u}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${l})`);for(let f of u)a.add(String(f.DuplicateRecordSetId))}}catch(l){return t(l)}let d=o.filter(l=>!a.has(l));if(d.length===0)return{};let c={objectApiName:"DuplicateRecordSet",planned:d.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let l=0;l<d.length;l+=Ut){let u=d.slice(l,l+Ut);for(let f of await kr(n,c.objectApiName,u))f.kind==="deleted"?c.deleted+=1:f.kind==="gone"?c.alreadyGone+=1:(c.refused+=1,c.reasons.includes(f.reason)||c.reasons.push(f.reason))}return{object:c}}}}async function ho(n,e){if(!n||!e)return n;let t=Date.parse(e.at),s=Date.parse(e.lastAt??""),r=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(s))return n;let o=await Qs(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(r,t+o):r,d=Number.isFinite(s)?Math.max(i,s+o):i;return a===r&&d===i?n:{first:a===r?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function Qs(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),s=Date.parse(await n.serverTime());return Number.isFinite(s)?s-(t+e().getTime())/2:void 0}catch{return}}async function mo(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),s=await Qs(n);if(s===void 0)return;let r=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+s).toISOString(),last:new Date(r+s).toISOString()}}var yo=50,wo=3,ei=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function So(n,e,t,s){let r=Date.parse(t.first)-ks,i=Date.parse(t.last)+Os;if(!Number.isFinite(r)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:c}of e){if(a>=wo||o.size>1||s?.aborted)break;let l=c.slice(0,yo);if(l.length===0)continue;let u;try{let[p]=ee(l,l.length);u=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${ye(d)} WHERE Id IN (${p})`)).records}catch{continue}let f=!1;for(let p of u){let{LastModifiedById:h,LastModifiedDate:y}=p??{},m=typeof y=="string"?Date.parse(y):Number.NaN;typeof h!="string"||!ei.test(h)||!(m>=r&&m<=i)||(o.has(h.slice(0,15))||o.set(h.slice(0,15),h),f=!0)}f&&a++}return o.size===1?[...o.values()][0]:void 0}async function xd(n,e,t,s,r,i,o){let a=e.some(({ids:p})=>p.length>0),d=a?await ho(await go(n,e,s),r):await mo(r),c=o.runUserId!==void 0&&ei.test(o.runUserId)?o.runUserId:void 0,l=n.query?.bind(n),u=!c&&!a&&d&&l?await So({query:l},i,d,s):void 0,f=i.filter(({ids:p})=>p.length>0);return{writtenBetween:d,created:e,remap:new Set([...e,...i].flatMap(({ids:p})=>p.map(h=>h.slice(0,15)))),automation:As(t),...c?{runUserId:c}:{},...u?{user:u}:{},ties:{...o.ties,...f.length>0?{writtenOver:f}:{}},...s?{signal:s}:{}}}var wt={status:"cancelled",objects:[],unread:[],handWork:[]};function zd(n,e,t){return{...Ar(n,e),counts:Cs(jr(Fr(n),t))}}async function qd(n,e){let t=Date.parse(n.writtenBetween?.first??""),s=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(s))return n;let{created:r}=n,i=new Set(r.flatMap(({ids:c})=>c.map(l=>l.slice(0,15)))),o=await Or(e,{has:c=>i.has(c),start:t,end:s,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},r.filter(c=>c.objectApiName==="Quote").flatMap(({ids:c})=>c),new Set(r.map(c=>c.objectApiName))),a=new Set(o.flatMap(c=>c.copies.map(l=>l.id.slice(0,15))));if(a.size===0)return n;let{remap:d}=n;return{...n,remap:{has:c=>d.has(c)||a.has(c)}}}async function Kd(n){let e,t,s;try{let o=await n.input();"refused"in o?s={...wt,status:"refused",refusal:o.refused}:t=Is(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:c}=await Cr(n.guard,{...n.guardOf,objectName:Es(a).join(", "),recordCount:Ps(a)});if(e=c,c==="refused")return`Operation blocked by Production Guard: ${d.blockedReason??d.impactSummary}`;if(c==="declined")return"Operation cancelled by user (confirmation declined)."}})}catch(o){s={...wt,status:"failure",refusal:K(o)}}let r=async o=>{if(!t||s)return!1;try{return await o(t)}catch(a){return s={...t.result(),status:"failure",refusal:K(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await r(async o=>(await o.ask(),!1))},get takes(){return s?[]:t?.takes??[]},first:o=>r(a=>a.first(o)),afterRemoval:o=>r(a=>a.afterRemoval(o)),result:()=>s??t?.result()??wt,settle:()=>(i??=(async()=>{let o=s??t?.result()??wt;return n.onGuardDecision(o,e),t&&(t.made.size>0||t.late.size>0||t.gone.size>0)&&await n.keepMade?.(t.made,t.late,t.gone).catch(()=>{}),o})(),i)}}function Hd(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var ti=6e4;function ko(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&Oo(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function Oo(n,e){let t=Date.parse(n?.first??""),s=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(s)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=s+9e5+ti&&Math.max(e.from,e.to)>=t-2e3-ti}var Ao=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function Yd(n,e){return n.filter(t=>Ao.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let s=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:s,to:s}})}function Co(n){let e=Date.parse(n.firstWrittenAt??n.startedAt),t=Date.parse(n.lastWriteAt??n.lastWrittenAt??n.end?.at??n.startedAt);return{ids:[...n.created,...n.overwritten??[]].flatMap(({ids:s})=>s),from:e,to:Number.isFinite(t)?t:e}}function Io(n,e,t){return n.filter(s=>s.targetOrgId===e&&s.runId!==t).map(Co)}async function Jd(n,e,t,s){let r=await s(n.targetOrgId,e).catch(()=>[]),i=Po(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:ko(e,[...Io(t,n.targetOrgId,n.runId),...r]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function Vd(n,e,t,s=[]){let r=[...s],i=Kt(n.madeEarlier,e,r),o=Kt(n.lateEarlier,t,r),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function Po(n){let e;for(let t of n??[]){let s=Date.parse(t.first);Number.isFinite(s)&&(!e||s<e.at)&&(e={at:s,first:t.first})}return e?.first}var ae=class extends Error{constructor(t,s,r){super(t);this.result=s;this.cause=r;this.name="SyncRunFailure"}result;cause},$e=class extends ae{constructor(t,s,r){super(t,s);this.code=r;this.name="SyncRunRefused"}code};function Qd(n){return typeof n!="number"||!Number.isFinite(n)?5e4:Math.min(5e4,Math.max(1,Math.floor(n)))}var Eo=/\b(QUERY_TIMEOUT|OPERATION_TOO_LARGE)\b/;function an(n){return Eo.test(n)?" Salesforce gave up on the count: filter the object on an indexed field (CreatedDate, SystemModstamp, Id, Name or an External ID) or on a narrower range of CreatedDate, then run it again. A user with View All Data reads the source without its sharing, which is what slows such a count most.":""}var To={raise:"the sandforge.sync.maxRecordsPerObject setting",sample:"Forge, with Depth ALL and Records per object set to A sample that fits the target"};function Mo(n,e,t){let s=e<5e4?`raise ${t.raise} (50000 at most), or `:"";return n==="target"?`To compare every record, ${s}narrow the object's filter.`:`To copy the rest, ${s}read it in slices: a filter on CreatedDate, one range per run. To copy a sample of the source that fits the target instead, use ${t.sample}.`}function ec(n){let e=n.cutAtReadCap??[];if(!(n.readCap===void 0||e.length===0))return`the read of the source stopped at ${n.readCap} records of ${e.join(", ")} (sandforge.sync.maxRecordsPerObject): the run copied part of ${e.length===1?"it":"each"}. `+Mo("source",n.readCap,To)}var Fo=2e3,jo=5e3,St=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??Fo,this.pollIntervalMs=e.pollIntervalMs??jo,this.signal=e.signal}async executeChunked(e,t,s,r,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:s,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,c={id:d,operation:s,object:t,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString(),totalRecords:i};e.bulkManager.registerJob(c);try{await a.open();let l=wr(a);l!==void 0&&e.onOpened?.(l);let u=[];for await(let w of r){if(this.signal?.aborted)break;for(let M of w)u.push(M);e.onProgress?.(u.length,i)}let f,p=0;if(this.signal?.aborted||(f=mr(s,u,o),await a.uploadData(f.text),p=u.length),this.signal?.aborted||f===void 0)return await Rr(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(p);await a.close();let h=await a.check();for(;h.state==="InProgress"||h.state==="UploadComplete";)e.bulkManager.updateJobState(d,h.state),e.onProgress?.(h.numberRecordsProcessed??0,i),await new Promise(w=>setTimeout(w,this.pollIntervalMs)),h=await a.check();let y=await a.getAllResults(),m=yr(y,f,Sr(h)),R=m.outcomes,S=[],b=[],k=m.unattributedSuccessIds.length;for(let w of R)w.success?(k++,w.id!==void 0&&S.push(w.id)):b.push(w.error??"Unknown error");S.push(...m.unattributedSuccessIds),b.push(...m.unattributedFailures);let g=h.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,g),e.bulkManager.updateJobCounts(d,h.numberRecordsProcessed??i,b.length),{totalRecords:p,successCount:k,failureCount:b.length,successIds:S,errors:b,aborted:!1,outcomes:R,...m.unattributedSuccessIds.length>0?{unmatchedIds:m.unattributedSuccessIds}:{}}}catch(l){throw e.bulkManager.updateJobState(d,"Failed"),l}}async*createChunkGenerator(e,t){let s=t??this.chunkSize;for(let r=0;r<e.length;r+=s)yield e.slice(r,r+s)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var vo=1e4,ni=fe.REST_API_BATCH_SIZE;function No(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function xo(n){return!n.success&&Br(n.errors,n.errorDetails)}function Do(n,e){let[t,...s]=n.errors;return t===void 0?n:{...n,errors:[Wr(t,e),...s]}}function dn(n){return typeof n.created=="boolean"?{created:n.created}:{}}function ii(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function ri(n){let e=n===void 0?void 0:pr(n);return e?ii([e]):{}}function cn(n,e){return n!=="insert"&&n!=="upsert"?[]:e.flatMap(t=>t.success&&typeof t.id=="string"&&t.id!==""&&(n==="insert"||t.created===!0)?[t.id]:[])}function Lo(n,e){return!n||!e?n??e:{before:async(t,s,r,i)=>await n.before?.(t,s,r,i)??await e.before?.(t,s,r,i),sending:(t,s,r)=>{n.sending(t,s,r),e.sending(t,s,r)},opened:(t,s,r,i)=>{n.opened?.(t,s,r,i),e.opened?.(t,s,r,i)},answered:(t,s,r,i)=>{n.answered(t,s,r,i),e.answered(t,s,r,i)}}}function pc(n,e){let t=s=>s==="insert"||s==="upsert";return{...e?{before:(s,r,i,o)=>e.before(s,r,i,o)}:{},sending:(s,r,i)=>{t(r)?n.sending?.(s,i,r==="upsert"?{upsert:!0}:void 0):n.writing?.(s,i)},opened:(s,r,i,o)=>{t(r)&&n.sending?.(s,i,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(s,r,i)=>{t(r)?n.answered?.(s,cn(r,i)):i.length>0&&n.writing?.(s,i.length),e?.answered(s,r,i)}}}var si=class{constructor(e){this.deps=e;this.wait=e.wait??(t=>_r(t,e.signal)),this.retryOp=new gt({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,s,r)=>{e.log(`[RETRY] sync attempt=${t} code=${s.originalError.statusCode} delay=${r}ms`)}})}deps;retryOp;wait;async insert(e,t,s,r){let i=Lo(this.deps.calls,r),o=l=>this.deps.connection.sobject(e).create(l,{headers:tt()}),a="Insert failed after retries",d=await this.tryStreaming("insert",e,t,void 0,i)??await this.tryBulk("insert",e,t,void 0,i),c=d?await this.duplicatesAgain("insert",e,t,d,o,a,i):await this.executeRestBatches("insert",e,t,s,o,a,i);return this.locksAgain("insert",e,t,c,o,a,i)}async upsert(e,t,s,r){let i=c=>this.deps.connection.sobject(e).upsert(c,t,{headers:tt()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,s,t)??await this.tryBulk("upsert",e,s,t),d=a?await this.duplicatesAgain("upsert",e,s,a,i,o,this.deps.calls,t):await this.executeRestBatches("upsert",e,s,r,i,o,this.deps.calls,t);return this.locksAgain("upsert",e,s,d,i,o,this.deps.calls,t)}async update(e,t,s){let r=d=>this.deps.connection.sobject(e).update(d,{headers:tt()}),i="Update failed after retries",o=await this.tryStreaming("update",e,t)??await this.tryBulk("update",e,t),a=o?await this.duplicatesAgain("update",e,t,o,r,i):await this.executeRestBatches("update",e,t,s,r,i);return this.locksAgain("update",e,t,a,r,i)}async delete(e,t,s){let r=d=>this.deps.connection.sobject(e).destroy(d),i="Delete failed after retries",o=t.map(d=>({Id:d})),a=await this.tryBulk("delete",e,o)??await this.executeRestBatches("delete",e,t,s,r,i);return this.locksAgain("delete",e,t,a,r,i)}async tryStreaming(e,t,s,r,i=this.deps.calls){if(s.length<=vo)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o=await this.refusedBefore(i,t,e,s,r);if(o)return o;let a=new St({signal:this.deps.signal});i?.sending(t,e,s.length);let d={connection:qt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(u,f)=>{this.deps.onProgress(u,f,`Streaming ${e} ${t}`)},onOpened:u=>i?.opened?.(t,e,s.length,u)},c=await a.executeChunked(d,t,e,a.createChunkGenerator(s),s.length,r);if(c.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Streaming ${e} ${t}`,c.unmatchedIds);let l=(c.outcomes??[]).map(u=>this.withExistingRecord(t,{id:u.id,success:u.success,errors:u.success?[]:[u.error??"Streaming error"],...dn(u),...u.success?{}:ri(u.error)}));return i?.answered(t,e,l),l}async tryBulk(e,t,s,r,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(s.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o={connection:qt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(l,u)=>{this.deps.onProgress(l,u,`Bulk ${e} ${t}`)},signal:this.deps.signal,onOpened:l=>i?.opened?.(t,e,s.length,l)},a=await this.refusedBefore(i,t,e,s,r);if(a)return a;i?.sending(t,e,s.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,s,r);if(d.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Bulk ${e} ${t}`,d.unmatchedIds);let c=d.outcomes.map(l=>this.withExistingRecord(t,{id:l.id,success:l.success,errors:l.success?[]:[l.error??"Bulk error"],...dn(l),...l.success?{}:ri(l.error)}));return i?.answered(t,e,c),c}async refusedBefore(e,t,s,r,i){if(s==="delete"||!e?.before)return;let o=await e.before(t,s,r,i);if(o!==void 0)return this.deps.log(`[WARN] ${s} ${t}: ${r.length} row(s) not sent: ${o}`),r.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,s,r,i,o,a=this.deps.calls,d){let c=r.flatMap((p,h)=>h<s.length&&No(p)?[h]:[]);if(c.length===0||this.deps.signal?.aborted)return r;let l;try{l=await this.executeRestBatches(e,t,c.map(p=>s[p]),ni,i,o,a,d,c)}catch(p){if(!(p instanceof Q))throw p;l=p.written}let u=[...r];l.forEach((p,h)=>{u[c[h]]=p});let f=l.filter(p=>p.success).length;return this.deps.log(`[INFO] ${e} ${t}: ${c.length} row(s) a duplicate rule refused in the Bulk API job, which cannot carry the header that lets a rule's matches be saved, went again through REST with it: ${f} saved`+(l.length<c.length?`, ${c.length-l.length} not sent (cancelled)`:"")),u}async locksAgain(e,t,s,r,i,o,a=this.deps.calls,d){let c=new Map,l=await Gr({outcomes:r.slice(0,s.length),locked:xo,written:p=>p.success,send:async p=>{let h;try{h=await this.executeRestBatches(e,t,p.map(y=>s[y]),ni,i,o,a,d,p)}catch(y){if(!(y instanceof Q))throw y;h=y.written}for(let y of p.slice(0,h.length))c.set(y,(c.get(y)??0)+1);return h},note:Do,wait:p=>this.wait(p),stopped:()=>this.deps.signal?.aborted===!0}),u=Ur("row(s)",l);return u===void 0?r:(this.deps.log(`[INFO] ${e} ${t}: ${u}`),[...l.outcomes.map((p,h)=>{let y=c.get(h);return y===void 0?p:{...p,lockResends:y}}),...r.slice(s.length)])}logUnmatched(e,t){t&&t.length>0&&this.deps.log(`[WARN] ${e}: the job wrote ${t.length} record(s) no row was matched to: ${t.join(", ")}`)}withExistingRecord(e,t){if(t.success)return t;let s=zt(t,this.deps.keyPrefixOf?.(e));return s.kind==="linked"?{...t,existingId:s.id}:t}async executeRestBatches(e,t,s,r,i,o,a=this.deps.calls,d,c){let l=[];for(let u=0;u<s.length;u+=r){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t,l);let f=s.slice(u,u+r);if(e!=="delete"){let y=await this.refusedBefore(a,t,e,f,d);if(y){l.push(...y);continue}if(this.deps.signal?.aborted)throw new Q(t,l)}a?.sending(t,e,f.length);let p=await this.retryOp.execute(()=>i(f));if(p.cancelled)throw a?.answered(t,e,[],c&&[]),new Q(t,l);let h=[];if(p.success&&p.result)for(let y of Array.isArray(p.result)?p.result:[p.result])h.push(this.restOutcome(t,y));else h.push(...f.map(()=>({success:!1,errors:[p.error?.message??o]})));l.push(...h),a?.answered(t,e,h,c?.slice(u,u+f.length))}return l}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...dn(t)};let s=t.errors??[],r=s.map(fr),i={id:t.id,success:!1,errors:[r[0]??"Unknown error"],...ii(s.map(ur))},o=zt({success:!1,errors:r,duplicateMatchIds:s.flatMap(a=>gr(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};function oi(n,e){if(n.operation==="delete")return[];let t=or(n.fieldMappings,n.excludedFields??[]),s=new Set([...ir(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),r=i=>!t.has(i.toLowerCase())||s.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&r(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function ai(n,e){let t=[...n].sort((b,k)=>b.insertOrder-k.insertOrder),s=new Map(t.map((b,k)=>[b.objectApiName,k])),r=new Set(t.filter(b=>b.operation!=="delete").map(b=>b.objectApiName)),i=new Map([...r].map(b=>[b.toLowerCase(),b])),o=[],a=new Set;for(let b of t){let k=b.objectApiName;if(r.has(k))for(let{field:g,referenceTo:w}of e.get(k)??[])for(let M of w){let A=i.get(M.toLowerCase());if(A===void 0||A===k)continue;let O=`${A}>${k}`;a.has(O)||(a.add(O),o.push({parent:A,child:k,field:g}))}}let d=$o(t.map(b=>b.objectApiName),o),c=new Map;d.forEach((b,k)=>{for(let g of b)c.set(g,k)});let l=d.map(b=>[...b].sort((k,g)=>(s.get(k)??0)-(s.get(g)??0))),u=l.map(b=>s.get(b[0])??0),f=l.map(()=>new Set);for(let{parent:b,child:k}of o){let g=c.get(b)??0,w=c.get(k)??0;g!==w&&f[w].add(g)}let p=new Set,h=[];for(;p.size<l.length;){let b;if(l.forEach((k,g)=>{p.has(g)||[...f[g]].some(w=>!p.has(w))||(b===void 0||u[g]<u[b])&&(b=g)}),b===void 0)break;p.add(b),h.push(...l[b])}let y=new Map(t.map(b=>[b.objectApiName,b])),m=h.flatMap(b=>{let k=y.get(b);return k?[k]:[]}),R=new Map(h.map((b,k)=>[b,k])),S=[];for(let b of m){let k=b.objectApiName,g=o.filter(w=>w.child===k&&(s.get(w.parent)??0)>(s.get(k)??0)&&(R.get(w.parent)??0)<(R.get(k)??0)).sort((w,M)=>(R.get(M.parent)??0)-(R.get(w.parent)??0));g.length>0&&S.push({objectApiName:k,after:g[0].parent,field:g[0].field})}return{ordered:m,order:{objects:h,moved:S,cycles:l.filter(b=>b.length>1)}}}function $o(n,e){let t=new Map(n.map(l=>[l,[]]));for(let{parent:l,child:u}of e)t.get(l)?.push(u);let s=0,r=new Map,i=new Map,o=[],a=new Set,d=[],c=l=>{r.set(l,s),i.set(l,s),s++,o.push(l),a.add(l);for(let p of t.get(l)??[])r.has(p)?a.has(p)&&i.set(l,Math.min(i.get(l)??0,r.get(p)??0)):(c(p),i.set(l,Math.min(i.get(l)??0,i.get(p)??0)));if(i.get(l)!==r.get(l))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;a.delete(f),u.push(f)}while(f!==l);d.push(u)};for(let l of n)r.has(l)||c(l);return d}var Bo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,de=n=>n.toLowerCase();function Rt(n){return n==="insert"||n==="upsert"}function _o(n,e){let t=de(e);if(n.addOnFields.some(r=>de(r.fieldApiName)===t)||n.transformRules.some(r=>r.field&&de(r.field)===t))return;let s=n.fieldMappings.find(r=>r.type!=="exclude"&&de(r.targetField)===t);return s?(s.type==="direct"||s.type==="rename")&&(s.transformRules??[]).length===0?s.sourceField:void 0:e}function Wo(n){return n!==void 0&&[...n.source.active].some(e=>!n.target.active.has(e))}async function di(n){let e=new Map,t=new ze(n.earlier),s=new Set,r=new Set([...n.leftOut].map(de)),i,o=async l=>{let u=await n.read(l);return u.length>0&&ut(l.objectApiName,u)&&(i=await n.standardPricebooks?.(),i&&t.noteMatched(i.source,i.target)),u},a=n.matched,d=(l,u)=>{a&&u>0&&a.set(l,(a.get(l)??0)+u)},c=(l,u)=>{let f=i?.source;return l===ge&&f!==void 0?u.filter(p=>p.Id===f).length:0};for(let l of n.ordered){let u=l.objectApiName;if(r.has(de(u))){if(!Rt(l.operation))continue;let A=await o(l);for(let O of A){let E=O.Id;typeof E=="string"&&E!==""&&t.noteRefused(E,u)}d(u,c(u,A)),s.add(de(u));continue}if(l.operation==="delete")continue;let f=(n.lookups.get(u)??[]).flatMap(({field:A,referenceTo:O})=>{let F=O.filter(N=>de(N)!==de(u)&&s.has(de(N))).length>0?_o(l,A):void 0;return F!==void 0?[{field:A,source:F}]:[]}),p=a!==void 0&&Rt(l.operation),h=p&&u===ge&&await n.standardPricebooks?.()!==void 0,y=p&&u===Me&&await n.standardPricebooks?.()?await n.currencies?.():void 0,m=Wo(y);if(f.length===0&&!h&&!m)continue;let R=new Map,S=A=>{let O=`${A.parent}|${A.field}`,E=R.get(O);E?E.rows++:R.set(O,{...A,rows:1})},b=n.copied?.get(u),k=(await o(l)).filter(A=>{let O=A.Id;return!(b&&typeof O=="string"&&b.has(O.slice(0,15)))}),g=new Map;for(let A of f.length>0?k:[]){let O=A.Id,E=f.find(({source:N})=>{let $=A[N];return typeof $=="string"&&Bo.test($)&&t.refusedObjectOf($)!==void 0});if(!E)continue;let F={parent:t.refusedObjectOf(A[E.source])??"",field:E.field};S(F),typeof O=="string"&&O!==""&&g.set(O,F),Rt(l.operation)&&typeof O=="string"&&O!==""&&t.noteRefused(O,u)}if(h&&d(u,c(u,k)),m){let A=pt(Me,{records:k,sources:k,sourceIds:k.map(E=>typeof E.Id=="string"?E.Id:void 0)},i,y,E=>t.refusedObjectOf(E)!==void 0),O=0;for(let[E,F]of A.standsFor){if(g.has(E))continue;let N=t.refusedObjectOf(F)!==void 0?g.get(F):void 0;if(N){S(N),g.set(E,N),t.noteRefused(E,u);continue}O++}d(u,O)}let w=[...R.values()],M=w.reduce((A,O)=>A+O.rows,0);M>0&&(e.set(u,{objectApiName:u,rows:M,parent:w[0].parent,field:w[0].field,parents:w}),Rt(l.operation)&&s.add(de(u)))}return e}var ci=Symbol("not written");function Go(n,e){if(n==="delete")return{rules:[],onChange:[]};let t=[],s=[];for(let{onChangeOnly:r,...i}of e)r&&n==="insert"?s.push(i.name):t.push(i);return{rules:t,onChange:s}}function Uo(n){return`${n.length} active validation rule(s) of the target left out of what may refuse these inserts: their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is \u2014 ${n.join(", ")}`}var zo=/^012000000000000(AAA)?$/;function qo(n){let e=n.RecordTypeId;return typeof e=="string"&&e.length>=15&&!zo.test(e)}function un(n){let e=n?.[Jn];return typeof e=="string"&&e!==""}async function li(n,e,t,s){let r=e.some(qo)?await n.recordTypes():void 0,i=t.some(un)||e.some(un)?await n.currencies():void 0,o=n.later?.get(s),a=n.recordTypesUnderTheLease?.get(s);return{links:n.links,sources:t,...r?{recordTypes:r}:{},...i?{currencies:i,currencyChangesById:n.currencyChangesById}:{},...n.contactPoints?{contactPoints:n.contactPoints}:{},...o&&o.size>0?{later:o}:{},...a?{recordTypesUnderTheLease:a}:{},...n.createdWithoutRecordType?{createdWithoutRecordType:n.createdWithoutRecordType}:{}}}function ui(n){let e=new Map;for(let t of n?.cycles??[])t.forEach((s,r)=>{r<t.length-1&&e.set(s,new Set(t.slice(r+1)))});return e}function Ko(n,e,t){return{...n,...e.set?{lookupsSetAfter:{...e.set,after:[...t]}}:{},...e.leftOut.length>0?{lookupsLeftOut:[...n.lookupsLeftOut??[],...e.leftOut]}:{}}}function pi(n,e){return e.flatMap((t,s)=>{let r=n[s];return t.success&&r!==void 0?[r]:[]})}function fi(n,e){let t=e.encryptedLeftOut??[];return t.length>0?{...n,encryptedLeftOut:[...t]}:n}function re(n){return n.slice(0,15)}function Ho(n,e){if(!e)return n;if(e.unread!==void 0)return{...n,errors:[...n.errors,`The contact roles the platform wrote with the run's opportunities were not looked up, so written as read: an opportunity may hold the role of its contact twice. ${e.unread}`]};let{records:t,given:s,refusal:r,alike:i}=e,o=i!==void 0?{...n,errors:[...n.errors,Kn(i)]}:n;return t===0?o:{...o,skipped:o.skipped+t,writtenByThePlatform:{records:t,given:s,...r!==void 0?{refusal:r}:{}}}}function Yo(n,e,t){if(n.objectApiName!==X||!ue(n.operation)||!t.sentWithAContact||e.records.length===0)return{prepared:e,linked:0};let s=a=>typeof a=="string"&&a!==""?t.targetOf(a):void 0,r=e.records.map((a,d)=>({OpportunityId:s(a.OpportunityId),[oe]:s(a[oe]),IsPrimary:e.sources[d]?.IsPrimary??a.IsPrimary})),i=new Set(Bt(r,a=>t.contactSentWith(a)));if(i.size===0)return{prepared:e,linked:0};for(let a of i){t.roleLinkedFor(String(r[a].OpportunityId));let d=e.sourceIds[a];d!==void 0&&t.noteWritten(d,d)}let o=(a,d)=>!i.has(d);return{prepared:{...e,records:e.records.filter(o),sourceIds:e.sourceIds.filter(o),sources:e.sources.filter(o),unsettled:e.unsettled.length===e.records.length?e.unsettled.filter(o):e.unsettled},linked:i.size}}var Jo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ln=200;function Vo(n,e,t){let s=c=>{let l=t?.fields?.find(u=>u.name===c);return l?.nillable===!1&&l.defaultedOnCreate!==!0},r=[],i=new Set,o=new Set,a=0;for(let[c,l]of n){let u=e[c]==="insert"?l.filter(s):[];if(u.length>0){r.push(c);for(let f of u)i.add(f);continue}a++;for(let f of l)o.add(f)}let d=[];return a>0&&d.push(`${a} record(s) would be written without ${[...o].sort().join(", ")}: a lookup held an id from the source org that the target does not have, which the run learns from its first refusal and sends the record again without the lookups it did not settle.`),r.length>0&&d.push(`${r.length} record(s) would be refused: a lookup held an id from the source org that the target does not have, and sent again without the lookups the run did not settle, the record lacks ${[...i].sort().join(", ")}, which the target requires (REQUIRED_FIELD_MISSING).`),{refused:r,notes:d}}function Xo(n){return`${n} record(s) would be linked to the contact role the platform writes with their opportunity, for its contact, not written.`}function pn(n){let e=n.alreadyLinked,t=n.alreadyCopied-e;return{...t>0?{alreadyCopied:t}:{},...e>0?{alreadyLinked:e}:{}}}function Zo(n,e){return e.alreadyCopied===0?n:{...n,skipped:n.skipped+e.alreadyCopied,...pn(e)}}function gi(n,e){return`What earlier runs of this configuration copied could not be read (${n}), and ${e.map(t=>t.objectApiName).join(", ")} ${e.length===1?"is":"are"} inserted: the records they copied would be copied a second time. Nothing was written.`}var Qo="SYNC_EARLIER_UNREAD",ea=new Set(["account","contact"]);function ue(n){return n==="insert"||n==="upsert"}function hi(n,e,t,s=new Map,r=new Set,i=new Map,o=new Map,a=new Set,d,c={}){let l=0,u=0,f=n.map(g=>{let w=g.objectApiName,M=e.get(w)??{rows:0},A=t.get(w)??new Set,O=A.size,E=Math.min(O,M.rows),F=Math.min([...A].filter(v=>a.has(v)).length,E);u+=F,l+=E-F;let $=(s.has(w)?0:i.get(w)?.rows??0)+(o.get(w)??0),T=c.keys?.get(w);return{objectApiName:w,operation:g.operation,rows:Math.max(0,M.rows-O-$),...M.personAccounts!==void 0?{personAccounts:M.personAccounts}:{},batchSize:g.batchSize,...T?{overwriteKey:T}:{}}}),p=f.flatMap(g=>{let w=s.get(g.objectApiName);return w?[{...g,why:w.why,...w.key?{key:w.key}:{}}]:[]}),h=f.find(g=>g.objectApiName===X),y=h&&d!==void 0?Math.min(d,h.rows):0;h&&y>0&&(h.rows-=y);let m=f.filter(g=>!s.has(g.objectApiName)),R=m.filter(g=>g.rows>0&&ue(g.operation)&&r.has(g.objectApiName)).length,S=[...i.values()].filter(({objectApiName:g})=>!s.has(g)),b=d===void 0?ta(n,m):0,k=m.filter(g=>c.typed?.has(g.objectApiName)).length;return{objects:m,alreadyCopied:l,...u>0?{alreadyLinked:u}:{},...p.length>0?{unwritable:p}:{},...S.length>0?{heldBack:S}:{},...R>0?{readBack:R}:{},...b>0?{rolesByThePlatform:b}:{},...y>0?{rolesLinked:y}:{},...k>0?{describedAgain:k}:{}}}var Ee="Opportunity";function ta(n,e){let t=o=>e.find(a=>a.objectApiName===o&&ue(a.operation)),s=t(Ee),r=t(X);return!s||!r||n.find(o=>o.objectApiName===Ee)?.excludedFields.includes(oe)?0:Math.min(s.rows,r.rows)}function na(n,e,t){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:t,conflictCount:0,errors:[`${e.message} Left out of the run, as confirmed before it wrote.`]}}function mi(n,e,t){if(ue(e.operation))for(let s of t){let r=s?.Id;typeof r=="string"&&r!==""&&n.noteRefused(r,e.objectApiName)}}function bt(n,e,t){let s=[];for(let[r,i]of t){let o=n.targetOf(i);o!==void 0?n.noteMatched(r,o):ue(e.operation)&&n.refusedObjectOf(i)!==void 0&&(n.noteRefused(r,e.objectApiName),s.push(r))}return s}function yi(n,e,t){let s=Qt(e,t),r=tn(n,{...e,prices:s});return t.length===0?r:{...r,processed:r.processed+t.length,failed:r.failed+t.length,errors:[...r.errors,en(n.objectApiName,t.length)]}}function wi(n){let e=Ln(n.objects);return e.length>0?`${$n(e)} Nothing was read or written.`:void 0}function Si(n){let e=_n(n.objects);return e.length>0?`${Wn(e)} Nothing was read or written.`:void 0}var Ri=class{deps;constructor(e){this.deps=e}async execute(e){let t=Date.now(),s=`sync-${Date.now()}`,r=[],i=wi(e);if(i!==void 0)throw new $e(i,{...se(e.id,s,[],t,"failure"),error:i},Dn);let o=Si(e);if(o!==void 0)throw new $e(o,{...se(e.id,s,[],t,"failure"),error:o},Bn);let{ordered:a,order:d,refused:c,typed:l,lookups:u,keys:f}=await this.writeOrderOf(e.objects),p=ui(d),h=this.deps.queryTargetRows?l:new Set,y=this.deltaLoadOf(e),m=(C,I)=>new $e(C,{...se(e.id,s,[],t,"failure"),error:C},I),R;try{R=await this.planFiles(e,a,y)}catch(C){let I=C instanceof Error?C.message:String(C);throw new ae(I,se(e.id,s,[],t,"failure"),C)}if(R?.storage.shortfall)throw new ae(`${R.storage.shortfall} Nothing was written.`,{...se(e.id,s,[],t,"failure"),files:R.storage});let S=await this.earlierLinks(e),b=a.filter(C=>C.operation==="insert");if(S.unread!==void 0&&b.length>0)throw m(gi(S.unread,b),Qo);let k;try{k=await this.alreadyCopiedOf(e,a,S.links)}catch(C){let I=`What earlier runs of this configuration copied could not be looked up in the target (${C instanceof Error?C.message:String(C)}), so nothing was written.`;throw new ae(I,{...se(e.id,s,[],t,"failure"),error:I},C)}let g=await this.countRun(e,a,y,this.deps.writeGate!==void 0);if(this.deps.writeGate&&"unread"in g){let C=`The records to write could not be counted (${g.unread}), so nothing was written.`+an(g.unread);throw new ae(C,{...se(e.id,s,[],t,"failure"),error:C})}let w=new Map,M=this.standardPricebooksOnce(),A=this.currenciesOnce(),O=y===void 0?new Map:void 0;if(this.deps.writeGate&&"counted"in g){let C;try{C=await this.heldBackOfRun(e,a,c,u,y,S.links,k,M,A,O)}catch(B){let q=B instanceof Error?B.message:String(B);throw new ae(q,{...se(e.id,s,[],t,"failure"),error:q},B)}let I=hi(a,g.counted,k,c,h,C.heldBack,C.matched,S.linked,await this.rolesLinkedAtTheGate(e,a,c,C.heldBack,k,S.links,O),{keys:f,...this.deps.describeTargetFieldsAgain?{typed:l}:{}}),{answer:x}=await this.deps.writeGate.hold(I);if(!x.go)throw m(x.message,x.code);for(let B of I.unwritable??[])w.set(B.objectApiName,B.rows)}let E=this.deps.leaseOfTheGate?.(),F=E&&E.assigned>0?await this.recordTypesReadAgain(a.map(C=>C.objectApiName).filter(C=>l.has(C)&&!w.has(C))):void 0,N=new Map,$=async()=>{let C=E;E=void 0,await C?.giveBack().catch(()=>{});for(let[I,x]of await this.readBackRecordTypes(N))for(let B=r.length-1;B>=0;B--)if(r[B].objectApiName===I){r[B]={...r[B],recordTypeGiven:x};break}},T=new ze(S.links),v=this.recordTypesOnce(),j=new Map,D=Ls(e),_=this.deps.idMap,z={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},H=Promise.resolve(),G,ne=(C,I,x)=>{if(!_)return;let B=ra(C.operation,I,x);for(let[q,Y]of[[B.written,!1],[B.linked,!0]])q.length!==0&&(H=H.then(()=>_.record(e.id,z,C.objectApiName,q,Y).catch(pe=>{G??=pe instanceof Error?pe.message:String(pe)})))},Te=0,Se=(C,I)=>{if(I.length===0)return;this.deps.creations?.deleted?.(C,I),Te+=I.length,T.noteDeleted(I);let x=_?.forget?.bind(_);x&&(H=H.then(()=>x(e.id,z,I).then(()=>{},B=>{G??=B instanceof Error?B.message:String(B)})))},V=this.deps.creations,Re=new Map,ie=0,P=(C,I)=>{if(!V)return;let x=cn(C.operation,I);if(x.length===0)return;let B=C.objectApiName;V.noteUnanswered?V.noteUnanswered(B,x):V.note(B,x),Re.set(B,(Re.get(B)??0)+x.length)},W=(C,I)=>{V&&(V.note(C,[I]),ie++)},Z=!1,he=!1,Be=!1,zi=async C=>{let I=await V?.flush();await H;let x=[];return S.unread!==void 0&&!Be&&(Be=!0,x.push(`What earlier runs of this configuration wrote could not be read (${S.unread}): a lookup at a record one of them wrote went as the source holds it.`)),I!==void 0&&!Z&&(Z=!0,x.push(`What this run created could not all be kept (${I}): removing the run may leave some of it in the target.`)),G!==void 0&&!he&&(he=!0,x.push(`Which record of the target each record this run wrote became could not all be kept (${G}): a later run may send a lookup at one of them as the source holds it.`)),x.length===0?C:{...C,errors:[...C.errors,...x]}},ce=async C=>{r.push(await zi(C))},be=new Map,qi=new Set((d?.cycles??[]).map(C=>C[C.length-1])),bn=(C,I)=>{for(let x=r.length-1;x>=0;x--)if(r[x].objectApiName===C){r[x]=Ko(r[x],I,[...p.get(C)??[]]);return}},Xe=new Map,Ki=(C,I)=>{for(let x=r.length-1;x>=0;x--)if(r[x].objectApiName===C){r[x]={...r[x],errors:[...r[x].errors,I]};return}},It=(C,I,x)=>{for(let B=r.length-1;B>=0;B--){let q=r[B];if(q.objectApiName!==C)continue;if(!q.delta)return;let Y=(q.delta.lookupsOwed??0)+I;r[B]={...q,delta:{...q.delta,...x!==void 0?{recorded:x}:{},...Y>0?{lookupsOwed:Y}:{}}};return}},Hi=async()=>{for(let[C,I]of[...be]){be.delete(C),await this.deps.pauseGate?.whilePaused(this.deps.signal);let x=this.deps.signal?.aborted?{leftOut:Zt(I.pending),unset:Xt(I.pending)}:await this.deps.dataSync.setLookups(I.objectConfig,I.pending,T,!0);"set"in x&&x.set&&V?.touched?.(C,x.set.records),bn(C,x);let B=Xe.get(C);if(Xe.delete(C),x.unset===0){let q=B?.();q!==void 0&&It(C,0,q)}else It(C,x.unset)}},Pt=()=>{for(let[C,I]of[...be])be.delete(C),Xe.delete(C),bn(C,{leftOut:Zt(I.pending)}),It(C,Xt(I.pending))},Ze=C=>{let I=$s(D,C.objectResults.some(Y=>Y.success>0)),x={...C,...R?{files:R.storage}:{},...I?{contactPoints:I}:{}},B=V?.overwrittenCount?.()??0,q=V?.deleted?Te:0;return!V||Re.size===0&&ie===0&&B===0&&q===0?x:{...x,created:{runId:V.runId,objects:[...Re].map(([Y,pe])=>({objectApiName:Y,count:pe})),files:ie,...B>0?{overwritten:B}:{},...q>0?{deleted:q}:{}}}},kn="counted"in g?[...g.counted.values()].reduce((C,{rows:I})=>C+I,0):void 0,Et=this.isGrappeActive(kn);Et&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:s,totalPartitions:a.length,totalRecords:kn}});let On=()=>{if(!Et)return;let C=0,I=0;for(let x of r)C+=x.processed,I+=x.failed;this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:s,totalProcessed:C,totalFailed:I}})},ke=async(C,I)=>(Pt(),await $(),On(),await V?.flush(),await H,Ze(ia(e.id,s,r,t,C,I))),Tt=0;for(let[C,I]of a.entries()){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return ke(a.slice(C));let x=c.get(I.objectApiName),B=w.get(I.objectApiName);if(x&&B!==void 0){let L=na(I,x,B);try{await this.noteLeftOutRefused(e,I,y,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...O?{gateReads:O}:{}},k.get(I.objectApiName))}catch(U){let me=U instanceof Error?U.message:String(U);throw await ce({...L,errors:[...L.errors,me]}),Pt(),new ae(me,Ze(se(e.id,s,r,t,"failure")),U)}await ce(L);continue}let q=new it,{plan:Y,mark:pe}=await this.readPlan(e,I,y),Oe={changedSince:Y?.read==="delta"?Ie(Y.since):void 0,rows:0,cut:!1},Ae=(L,U)=>Y?{...L,delta:je(Y,Oe.rows,U)}:L,Qe=R?.objects.get(I.objectApiName),Mt=Qe?new Map:void 0,Ft;try{Ft=await this.syncObject(e,I,q,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...D?{contactPoints:D}:{},later:p,...F?{recordTypesUnderTheLease:F}:{},createdWithoutRecordType:N,...O?{gateReads:O}:{}},Y?Oe:void 0,Mt,V||_?(L,U)=>{P(I,L),ne(I,L,U)}:void 0,k.get(I.objectApiName),(p.get(I.objectApiName)?.size??0)>0?L=>{let U=be.get(I.objectApiName);U?U.pending.push(...L):be.set(I.objectApiName,{objectConfig:I,pending:L})}:void 0)}catch(L){if(L instanceof Q){let U=Pe(qe(I.objectApiName,I.operation,L.written,L.notes,L.lookupsLeftOut,L.writtenWithoutFields),q);return(U.processed>0||U.skipped>0)&&await ce(Ae(U)),ke(a.slice(C))}throw await ce(Ae(Pe({...kt(I),failed:1,errors:[L instanceof Error?L.message:String(L)]},q))),Pt(),new ae(L instanceof Error?L.message:String(L),Ze(se(e.id,s,r,t,"failure")),L)}if(Ft===ci){let L=Pe(kt(I),q);return L.skipped>0&&await ce(Ae(L)),ke(a.slice(C))}let J=Ft,An=!0;if(Qe&&Mt&&e.files){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await ce(Ae(J)),ke(a.slice(C+1),bi(I));let L=await Js({config:e,option:e.files,objectApiName:I.objectApiName,planned:Qe,written:Mt,deps:this.deps.files,signal:this.deps.signal,waitIfPaused:()=>this.deps.pauseGate?.whilePaused(this.deps.signal)??Promise.resolve(),onCreated:W});if(J={...J,files:L.outcome,errors:[...J.errors,...L.notes]},An=L.outcome.failed===0&&L.outcome.pastRunCap===0&&L.unplanned===0,L.cancelled)return await ce(Ae(J)),ke(a.slice(C+1),bi(I))}let Ce;if(Y?.read==="delta"&&e.propagateDeletes===!0&&Oe.changedSince){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await ce(Ae(J)),ke(a.slice(C));try{Ce=await this.carryDeletions(I,Oe.changedSince,L=>Se(I.objectApiName,L))}catch(L){if(!(L instanceof Q))throw L;let U=qe(I.objectApiName,"delete",L.written);return await ce(Ae({...J,errors:[...J.errors,...U.errors,...L.notes]},{deleted:U.success,deleteFailed:U.failed,notes:[],complete:!1})),ke(a.slice(C))}J={...J,errors:[...J.errors,...Ce.notes]}}let Cn=Oe.lookupsUnset??0,Ji=J.failed===0&&An&&!Oe.cut&&Cn===0&&(Ce===void 0||Ce.deleteFailed===0&&Ce.error===void 0&&Ce.complete),In=(L,U,me)=>{let En=Qe?.filesSeen;try{return this.deps.deltaStore?.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:I.objectApiName,watermark:L,fingerprint:U,recordedAt:new Date().toISOString(),...En!==void 0?{filesSeen:En}:{}}),L}catch(jt){me(`The watermark could not be saved, so the next run reads from the previous one: ${jt instanceof Error?jt.message:String(jt)}`);return}},Pn;if(Y&&pe!==null&&Ji){let{fingerprint:L}=Y,U=I.objectApiName;be.has(U)?Xe.set(U,()=>In(pe,L,me=>Ki(U,me))):Pn=In(pe,L,me=>{J={...J,errors:[...J.errors,me]}})}Y&&(J={...J,delta:je(Y,Oe.rows,Ce,Pn,Cn)}),await ce(J),qi.has(I.objectApiName)&&await Hi(),Et&&(Tt++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`sync-partition-${Tt}`,percentage:Math.round(Tt/a.length*100),processedRecords:J.processed}}))}await $();let Yi=ki(r);return On(),await V?.flush(),await H,Ze(se(e.id,s,r,t,Yi))}async recordTypesReadAgain(e){let t=this.deps.describeTargetFieldsAgain,s=new Map;return t&&await Promise.all(e.map(async r=>{try{s.set(r,(await t(r)).recordTypes??[])}catch{}})),s}async readBackRecordTypes(e){let t=this.deps.queryTargetRows,s=new Map;return await Promise.all([...e].map(async([r,{given:i,types:o,ids:a}])=>{if(!t||a.length===0){s.set(r,i);return}try{let d=await t(cs(r,a));s.set(r,{...i,readBack:ls(d,o)})}catch(d){let c=d instanceof Error?d.message:String(d);s.set(r,{...i,readBack:{read:0,types:[],unread:c}})}})),s}async earlierLinks(e){let t=this.deps.idMap;if(!t)return{};try{let s={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},r=await t.load(e.id,s);if(!r)return{};let i=await t.linked?.(e.id,s);return{links:r,...i!==void 0&&i.size>0?{linked:i}:{}}}catch(s){return{unread:s instanceof Error?s.message:String(s)}}}recordTypesOnce(){let e;return()=>{let t=this.deps.recordTypes;return t?(e??=t().catch(s=>{throw new Error(`The record types of the two orgs could not be read, so none of these records was sent: ${s instanceof Error?s.message:String(s)}`)}),e):Promise.resolve(void 0)}}currenciesOnce(){let e;return()=>{let t=this.deps.currencies;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}standardPricebooksOnce(){let e;return()=>{let t=this.deps.standardPricebooks;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}async pricesSettled(e,t,s){let r=e.objectApiName,i=e.operation!=="delete"&&ut(r,t.sources)?await s.standardPricebooks?.():void 0;i&&s.links.noteMatched(i.source,i.target);let o=i&&r===Me&&t.sources.some(un)?await s.currencies():void 0;return pt(r,t,i,o,a=>s.links.refusedObjectOf(a)!==void 0)}deltaLoadOf(e){if(e.mode==="delta")return!this.deps.deltaStore||!this.deps.deltaReads?null:this.deps.deltaStore.load(e.id)}async readPlan(e,t,s){if(s===void 0)return{plan:null,mark:null};let r=We(e,t,s),i=this.deps.deltaReads;if(!i||r.read==="full"&&r.reason==="not_saved")return{plan:r,mark:null};try{return{plan:r,mark:await i.latestModstamp(t.objectApiName)}}catch{return{plan:{read:"full",reason:"no_modstamp",fingerprint:r.fingerprint},mark:null}}}async carryDeletions(e,t,s){let r=await this.tallyObjectDeletions(e,t);if("error"in r)return{deleted:0,deleteFailed:0,error:r.error,notes:[r.error],complete:!1};let{tally:i,notes:o}=r;if(i.ids.length===0)return{deleted:0,deleteFailed:0,notes:o,complete:!i.truncated};let a={...e,operation:"delete",fieldMappings:[],transformRules:[],addOnFields:[]},d;try{d=await this.deps.dataSync.write(a,i.ids.map(l=>({Id:l})))}catch(l){throw l instanceof Q&&s(pi(i.ids,l.written)),l}s(pi(i.ids,d.outcomes));let c=qe(e.objectApiName,"delete",d.outcomes,d.notes);return{deleted:c.success,deleteFailed:c.failed,notes:[...c.errors,...o],complete:!i.truncated}}async tallyObjectDeletions(e,t){let s=this.deps.deltaReads;if(!s)return{error:"Deletions need the source's recycle bin, and none was given."};let r=Gt(e);if("refused"in r)return{error:r.refused};let i=ot(e.where,t)??"";try{let o=await cr(s,e,r,i,a=>{if(r.sourceField==="Id")return a.Id;let d=this.deps.fieldMapping.apply(a,e.fieldMappings,e.excludedFields);return this.deps.transformPipeline.transformRecord(d,e)[r.keyField]});return{tally:o,notes:lr(o,r.keyField)}}catch(o){if(this.deps.signal?.aborted)throw new Q(e.objectApiName,[]);return{error:`The source's deletions could not be read, so none was carried; the next run looks for them again: ${o instanceof Error?o.message:String(o)}`}}}async countRun(e,t,s,r){let i=this.deps.countSource;if(!r&&!this.deps.grappeConfig?.enabled||!i)return{none:!0};let o=new Map;try{for(let a of t){let d=s===void 0?null:We(e,a,s),c=d?.read==="delta"?{changedSince:Ie(d.since)}:void 0,l=c?await i(e.sourceOrgId,a,c):await i(e.sourceOrgId,a);if(!Number.isFinite(l)||l<0)throw new Error(`the source answered no count of ${a.objectApiName}`);let u=r&&l>0&&this.deps.countPersonAccounts&&ea.has(a.objectApiName.toLowerCase())?await this.deps.countPersonAccounts(a,c):void 0;o.set(a.objectApiName,{rows:l,...u!==void 0&&u>0?{personAccounts:u}:{}})}}catch(a){return{unread:a instanceof Error?a.message:String(a)}}return{counted:o}}async alreadyCopiedOf(e,t,s){let r=new Map,i=this.deps.readSourceIds,o=this.deps.findInTarget;if(!s||s.size===0||!i||!o)return r;for(let a of t){if(a.operation!=="insert")continue;if(this.deps.signal?.aborted)break;let d=new Map;for(let f of await i(a)){let p=s.get(re(f));p!==void 0&&d.set(re(f),p)}if(d.size===0)continue;let c=await o(e.targetOrgId,a,"Id",[...new Set(d.values())]),l=new Set([...c.keys()].map(f=>f.slice(0,15))),u=new Set;for(let[f,p]of d)l.has(p.slice(0,15).toLowerCase())&&u.add(f);u.size>0&&r.set(a.objectApiName,u)}return r}async writeOrderOf(e){let t=this.deps.describeTargetFields,s=new Map,r=new Set,i=new Map;if(!t)return{ordered:[...e].sort((d,c)=>d.insertOrder-c.insertOrder),refused:s,typed:r,lookups:new Map,keys:i};let o=new Map,a=[];for(let d of e){if(d.operation==="delete"){a.push(d);continue}let c=await Ds(t,d.objectApiName,d.operation,d.externalIdField);"refused"in c&&s.set(d.objectApiName,c.refused);let l="target"in c&&c.target?xs(Ns(d,c.target),c.target):d;a.push(l),!("refused"in c)&&(l.operation==="update"||l.operation==="upsert"||l.objectApiName===X)&&i.set(d.objectApiName,Ms(l.operation==="upsert"?l.externalIdField??"Id":"Id","target"in c?c.target:void 0)),"target"in c&&c.target&&(o.set(d.objectApiName,oi(l,c.target)),ue(d.operation)&&(c.target.recordTypes??[]).some(u=>!u.master)&&r.add(d.objectApiName))}return{...ai(a,o),refused:s,typed:r,lookups:o,keys:i}}async heldBackOfRun(e,t,s,r,i,o,a,d,c,l){let u=new Map,f=t.some(h=>ue(h.operation)&&(h.objectApiName===ge||h.objectApiName===Me));return s.size===0&&!f?{heldBack:new Map,matched:u}:{heldBack:await di({ordered:t,lookups:r,leftOut:new Set(s.keys()),...o?{earlier:o}:{},copied:a,standardPricebooks:d,currencies:c,matched:u,read:async h=>{let y=i===void 0?null:We(e,h,i);if(y?.read==="delta")return this.deps.querySource(e.sourceOrgId,h,{changedSince:Ie(y.since)});let m=await this.deps.querySource(e.sourceOrgId,h);return l?.set(h.objectApiName,m),m}}),matched:u}}async rolesLinkedAtTheGate(e,t,s,r,i,o,a){let d=m=>t.find(R=>R.objectApiName===m),c=d(Ee),l=d(X);if(!c||!l||!ue(l.operation))return;if(!this.deps.queryTargetRows||c.excludedFields.includes(oe))return 0;if(!a||c.operation!=="insert")return;let u=m=>m.fieldMappings.length===0&&m.addOnFields.length===0&&m.transformRules.length===0;if(!u(c)||!u(l)||[Ee,X,$t].some(m=>s.has(m)||r.has(m)))return;let p=await this.deps.describeTargetFields?.(Ee).catch(()=>{});if(!p)return;if(!p.creatable.has(oe))return 0;let h=async m=>{let R=a.get(m.objectApiName);if(R)return R;let S=await this.deps.querySource(e.sourceOrgId,m);return a.set(m.objectApiName,S),S},y=m=>typeof m.Id=="string"&&m.Id!==""?m.Id:void 0;try{let m=new Set([...o?.keys()??[]].map(re)),R=d($t);if(R&&ue(R.operation)&&t.indexOf(R)<t.indexOf(c))for(let g of await h(R)){let w=y(g);w&&m.add(re(w))}let S=g=>i.get(g)??new Set,b=new Map;for(let g of await h(c)){let w=y(g),M=g[oe];!w||typeof M!="string"||M===""||S(Ee).has(re(w))||!m.has(re(M))||b.set(re(w),M)}if(b.size===0)return 0;let k=(await h(l)).filter(g=>{let w=y(g);return w!==void 0&&!S(X).has(re(w))});return Bt(k,g=>b.get(re(g))).length}catch{return}}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&e!==void 0&&e>=t.autoActivateThreshold)}async simulate(e){let t=wi(e);if(t!==void 0)throw new Error(t);let s=Si(e);if(s!==void 0)throw new Error(s);let r=Date.now(),i=[],{ordered:o,order:a,refused:d,typed:c,lookups:l,keys:u}=await this.writeOrderOf(e.objects),f,p,h,y=await this.validationRulesOf(o),m=(F={})=>({configId:e.id,operationId:`sync-simulation-${r}`,direction:e.direction,conflictStrategy:e.conflictStrategy,objects:i,duration:Date.now()-r,timestamp:new Date().toISOString(),...f?{files:f.storage}:{},...y.unread!==void 0?{validationRulesUnread:y.unread}:{},...a?{writeOrder:a}:{},...p?{writeCheck:p}:{},...h!==void 0?{writeCheckUnread:h}:{},...F}),R=this.deltaLoadOf(e);try{f=await this.planFiles(e,o,R)}catch(F){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:F instanceof Error?F.message:String(F)})}let S=await this.earlierLinks(e),b=o.filter(F=>F.operation==="insert");if(S.unread!==void 0&&b.length>0)return m({error:gi(S.unread,b)});let k;try{k=await this.alreadyCopiedOf(e,o,S.links)}catch(F){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:F instanceof Error?F.message:String(F)})}let g=this.deps.writeGate,w=this.standardPricebooksOnce(),M=this.currenciesOnce(),A=R===void 0?new Map:void 0,O=g?await this.countRun(e,o,R,!0):void 0;if(g&&O&&"unread"in O&&(h=`${O.unread}${an(O.unread)}`),g&&O&&"counted"in O)try{let F=await this.heldBackOfRun(e,o,d,l,R,S.links,k,w,M,A);p=await g.measure(hi(o,O.counted,k,d,this.deps.queryTargetRows?c:new Set,F.heldBack,F.matched,S.linked,await this.rolesLinkedAtTheGate(e,o,d,F.heldBack,k,S.links,A),{keys:u,typed:c}))}catch(F){h=F instanceof Error?F.message:String(F)}let E={links:new ze(S.links),...S.linked?{earlierLinked:S.linked}:{},recordTypes:this.recordTypesOnce(),currencies:M,currencyChangesById:new Map,standardPricebooks:w,later:ui(a),...A?{gateReads:A}:{}};for(let[F,N]of o.entries()){if(this.deps.signal?.aborted)return m({cancelled:!0});this.deps.onSimulationProgress?.(F,o.length,N.objectApiName);try{let $=await this.simulateObject(e,N,R,E,k.get(N.objectApiName),d.get(N.objectApiName)),T=f?.objects.get(N.objectApiName),{rules:v,onChange:j}=Go(N.operation,y.byObject.get(N.objectApiName)??[]),D=[...$.notes,...T?.notes??[],...j.length>0?[Uo(j)]:[]];i.push({...$,...T?{files:T.outcome}:{},notes:D,...v.length>0?{validationRules:v}:{}})}catch($){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:$ instanceof Error?$.message:String($),failedObject:N.objectApiName})}}if(p){let F=new Set([...p.objects.map(G=>G.objectApiName),...(p.rolesLinked??0)>0?[X]:[]]),N=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.operation==="delete"?ne.delete:ne.insert+ne.update),0),$={...p};delete $.rolesByThePlatform,delete $.rolesLinked;let T=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.writtenByThePlatform??0),0),v=(p.rolesLinked??0)-T,j=p.total+v,D=j-N,_={objectApiName:X,rows:0},z=$.objects.some(G=>G.objectApiName===X)?$.objects:[...$.objects,_],H=j>0&&N===0;p={...$,objects:z.map(G=>G.objectApiName===X?{...G,rows:Math.max(0,G.rows+v)}:G).filter(G=>G.rows>0),total:j,...T>0?{rolesLinked:T}:{},...D>0?{notWritten:D}:{},...H?{total:0}:{},...H&&$.verdict==="writes"?{verdict:"nothing"}:{}}}return m()}async validationRulesOf(e){let t=this.deps.readValidationRules,s=e.filter(i=>i.operation!=="delete").map(i=>i.objectApiName),r=new Map;if(!t||s.length===0)return{byObject:r};try{for(let{objectApiName:i,...o}of await t(s))r.set(i,[...r.get(i)??[],o]);return{byObject:r}}catch(i){return{byObject:r,unread:i instanceof Error?i.message:String(i)}}}async simulateObject(e,t,s,r,i,o){let a=this.deps.findInTarget;if(!a)throw new Error("A simulation needs to look records up in the target org.");let d=new it,{plan:c}=await this.readPlan(e,t,s),l={changedSince:c?.read==="delta"?Ie(c.since):void 0,rows:0,cut:!1},u=await this.prepare(e,t,d,c?l:void 0,i,r.gateReads,r.earlierLinked),f=u.records.length>0?await this.pricesSettled(t,u,r):void 0,p=f?{...u,...f}:u;if(o&&p.records.length>0){mi(r.links,t,p.sources);let P=f?bt(r.links,t,f.standsFor):[];return fi({objectApiName:t.objectApiName,operation:t.operation,read:p.read,insert:0,update:0,delete:0,skipped:p.alreadyCopied,...pn(p),refused:p.records.length+P.length,conflicts:0,conflictFields:[],notes:[o.message]},p)}let h=Yo(t,p,r.links),y=h.prepared,m=null;if(y.records.length>0&&this.deps.describeTargetFields)try{let P=await this.deps.describeTargetFields(t.objectApiName);m=P.creatable.size>0?P:null}catch{m=null}let R=await li(r,y.records,y.sources,t.objectApiName),S=vs({config:{...t,fieldMappings:[],addOnFields:[]},records:y.records,target:m,run:R}),b=S.sentAt.map(P=>y.records[P]),k=Xn(t),g=new Map;if(k!==null){let P=new Map;for(let W of b){let Z=W[k],he=Fe(Z);he!==null&&P.set(he,Z)}P.size>0&&(g=await a(e.targetOrgId,t,k,[...P.values()]))}let w=b.map(P=>Qn(t,P,g)),M=t.operation==="upsert"&&k!==null&&k.toLowerCase()!=="id"?tr(k,b.map(P=>Fe(P[k])),w,er(b.length,t.batchSize,this.deps.bulkThreshold??fe.REST_API_BATCH_SIZE)):void 0;for(let P of M?.updated??[])w[P]="update";let A=w.flatMap((P,W)=>(P==="insert"||P==="update")&&M?.refused.has(W)!==!0?[W]:[]),O=m?.fields!==void 0&&A.length>0?rr(t.objectApiName,A.map(P=>({payload:S.payloads[P],source:y.sources[S.sentAt[P]]??{},creates:w[P]==="insert"})),m.fields):{refused:new Set,notes:[],refusedFor:[]},E=new Set([...[...O.refused].map(P=>A[P]),...M?.refused??[]]),F=await this.lookupsTheTargetLacks(A.filter(P=>!E.has(P)),S.payloads,S.settled,m),N=Vo(F,w,m);for(let P of N.refused)E.add(P);let $=A.filter(P=>w[P]==="insert"&&!E.has(P)),T=t.operation==="insert"?(m?.fields??[]).filter(P=>P.unique===!0&&P.createable):[],v=new Map;for(let P of T){let W=new Map;for(let Z of $){let he=S.payloads[Z][P.name],Be=Fe(he);Be!==null&&W.set(Be,he)}W.size!==0&&v.set(P.name,await a(e.targetOrgId,t,P.name,[...W.values()]))}let j=sr($.map(P=>S.payloads[P]),v);for(let P of j.refused)E.add($[P]);let D=new Set([...j.linked].map(P=>$[P])),_=b.flatMap((P,W)=>E.has(W)||D.has(W)?[]:[W]),z=new Set(_.map(P=>S.sentAt[P])),H=y.unsettled.filter((P,W)=>z.has(W)),G=nr({objectConfig:t,read:y.read,records:_.map(P=>b[P]),leftOut:d.counts(t.objectApiName),inTarget:g,simulated:_.map(P=>w[P]),conflicts:y.conflicts,unsettled:H,matchField:y.matchField,writable:m?.creatable??null}),ne=t.operation==="insert"||t.operation==="upsert",Te=P=>{let W=y.sources[P]?.Id;return typeof W=="string"&&W!==""?W:void 0},Se=[];if(t.operation!=="delete"){for(let{index:P}of S.held){let W=Te(P);W&&ne&&r.links.noteRefused(W,t.objectApiName)}if(S.sentAt.forEach((P,W)=>{let Z=Te(P);Z&&(E.has(W)||Zn.has(w[W])?ne&&r.links.noteRefused(Z,t.objectApiName):r.links.noteWritten(Z,Z))}),t.objectApiName===Ee&&ne)for(let P of _){let W=Te(S.sentAt[P]),Z=S.payloads[P]?.[oe];w[P]!=="insert"||!W||typeof Z!="string"||Z===""||r.links.noteSentWithContact(W,Z)}f&&(Se=bt(r.links,t,f.standsFor))}let V=Fs(t.objectApiName,_.flatMap(P=>{let W=w[P]==="insert"?S.withoutRecordType.get(S.sentAt[P]):void 0;return W?[W]:[]}),js(m?.recordTypes??[],R.recordTypes)),Re=[...M?.refusedFor??[],...O.refusedFor,...j.refusedFor],ie={...G,skipped:G.skipped+D.size+y.alreadyCopied+h.linked,...pn(y),...h.linked>0?{writtenByThePlatform:h.linked}:{},...y.encryptedLeftOut?{encryptedLeftOut:[...y.encryptedLeftOut]}:{},...V?{recordTypeGiven:V}:{},refused:G.refused+S.held.length+E.size+Se.length,...Re.length>0?{refusedFor:Re}:{},notes:[...f?.standardMatched?[Ws]:[],...us(f?Qt(f,Se):[]).map(P=>`${P}.`),...h.linked>0?[Xo(h.linked)]:[],...G.notes,...M?.notes??[],...S.notes,...Se.length>0?[en(t.objectApiName,Se.length)]:[],...S.currencies.map(P=>`${Vn(P)}.`),...O.notes,...N.notes,...j.notes]};if(!c)return ie;if(c.read==="delta"&&e.propagateDeletes===!0&&l.changedSince){let P=await this.tallyObjectDeletions(t,l.changedSince);if("error"in P)return{...ie,notes:[...ie.notes,P.error],delta:je(c,l.rows,{deleted:0,deleteFailed:0,error:P.error})};let W=P.tally.ids.length;return{...ie,delete:ie.delete+W,notes:[...ie.notes,...P.notes],delta:je(c,l.rows,{deleted:W,deleteFailed:0})}}return{...ie,delta:je(c,l.rows)}}async lookupsTheTargetLacks(e,t,s,r){let i=this.deps.queryTargetRows,o=new Map;if(!i||!r?.fields||r.references.size===0)return o;let a=new Map,d=new Map;for(let u of e){let f=t[u]??{},p=[];for(let[h,y]of Object.entries(f)){if(h==="RecordTypeId"||!r.references.has(h)||s[u]?.has(h)||typeof y!="string"||!Jo.test(y))continue;p.push({field:h,id:y});let m=r.fields.find(R=>R.name===h)?.referenceTo??[];for(let R of m)d.set(R,(d.get(R)??new Set).add(y))}p.length>0&&a.set(u,p)}if(a.size===0)return o;let c=new Set,l=new Set;for(let[u,f]of d){let p=[...f];for(let[h,y]of ee(p,ln).entries())try{let m=await i(`SELECT Id FROM ${ye(u)} WHERE Id IN (${y})`);for(let R of m){let S=R.Id;typeof S=="string"&&c.add(S.slice(0,15))}}catch{let m=h*ln;for(let R of p.slice(m,m+ln))l.add(R.slice(0,15))}}for(let[u,f]of a)f.some(({id:h})=>!c.has(h.slice(0,15))&&!l.has(h.slice(0,15)))&&o.set(u,f.map(({field:h})=>h).sort());return o}async noteLeftOutRefused(e,t,s,r,i){if(!ue(t.operation))return;let{plan:o}=await this.readPlan(e,t,s),a={changedSince:o?.read==="delta"?Ie(o.since):void 0,rows:0,cut:!1},d=await this.prepare(e,t,new it,o?a:void 0,i,r.gateReads,r.earlierLinked);if(d.records.length===0)return;let c=await this.pricesSettled(t,d,r);mi(r.links,t,c.sources),bt(r.links,t,c.standsFor)}async syncObject(e,t,s,r,i,o,a,d,c){let l=await this.prepare(e,t,s,i,d,r.gateReads,r.earlierLinked),u=await this.rolesWrittenWithTheirOpportunity(t,l,r,a),f=u.prepared,p=w=>Ho(fi(Zo(w,f),f),u.said);if(f.records.length===0)return p(Pe(kt(t),s));let h=await this.pricesSettled(t,f,r),{records:y,sourceIds:m,sources:R}=h;if(y.length===0)return p(Pe(tn(kt(t),h),s));let S={...await li(r,y,R,t.objectApiName),...h.standardFirst>0?{standardFirst:h.standardFirst}:{}},b=()=>bt(r.links,t,h.standsFor);if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return ci;if(o||a||c||i){let w=M=>{M.forEach((A,O)=>{let E=m[O];o&&A.success&&A.id&&E&&o.set(E,A.id)}),a?.(M,m)};try{let{outcomes:M,notes:A,currencies:O,lookupsLeftOut:E,writtenWithoutFields:F,lookupsToSet:N,lookupsUnset:$}=await this.deps.dataSync.write({...t,fieldMappings:[],addOnFields:[]},y,S);i&&$!==void 0&&(i.lookupsUnset=$),w(M);let T=b();return N&&c?.(N),p(Pe(yi(_s(qe(t.objectApiName,t.operation,M,A,E,F),O),h,T),s))}catch(M){throw M instanceof Q&&w(M.written),M}}let k=await this.deps.dataSync.sync({...t,fieldMappings:[],addOnFields:[]},y,S),g=b();return p(Pe(yi(k,h,g),s))}async rolesWrittenWithTheirOpportunity(e,t,s,r){let i=this.deps.queryTargetRows;if(e.objectApiName!==X||e.operation!=="insert"&&e.operation!=="upsert"||!i||!s.links.sentWithAContact||t.records.length===0)return{prepared:t};let o=g=>typeof g=="string"&&g!==""?s.links.targetOf(g):void 0,a=t.records.map((g,w)=>({OpportunityId:o(g.OpportunityId),[oe]:o(g[oe]),IsPrimary:t.sources[w]?.IsPrimary??g.IsPrimary})),d=await this.deps.describeTargetFields?.(X).catch(()=>{}),c=g=>g!=="Id"&&g!=="OpportunityId"&&g!==oe&&(d?.creatable.has(g)??!0),l=[...new Set(t.records.flatMap(g=>Object.keys(g)))].filter(c),u;try{u=await Hn(async g=>await i(g),a,g=>s.links.contactSentWith(g),l)}catch(g){return{prepared:t,said:{records:0,given:0,unread:g instanceof Error?g.message:String(g)}}}let{found:f,alike:p}=u;for(let g of p)s.links.roleLinkedFor(String(a[g].OpportunityId));let h=p.length>0?{alike:p.length}:{};if(f.size===0)return p.length>0?{prepared:t,said:{records:0,given:0,...h}}:{prepared:t};let y=[];for(let[g,w]of f){let M=Object.entries(t.records[g]??{}).filter(([A,O])=>c(A)&&O!==null&&O!==void 0&&String(w[A]??"")!==String(O));M.length>0&&y.push({Id:String(w.Id),...Object.fromEntries(M)})}let m=0,R;if(y.length>0)try{let g=await this.deps.dataSync.updateRecords(X,y,e.batchSize);y.forEach((w,M)=>{let A=g[M];A?.success?m++:R??=`${String(w.Id)}: ${A?.errors[0]??"not updated"}`})}catch(g){R=g instanceof Error?g.message:String(g)}let S=[],b=[];for(let[g,w]of f){let M=t.sourceIds[g],A=String(w.Id);s.links.roleLinkedFor(String(a[g].OpportunityId)),M!==void 0&&(s.links.noteWritten(M,A),S.push(M),b.push({success:!1,errors:[],existingId:A}))}r?.(b,S);let k=(g,w)=>!f.has(w);return{prepared:{...t,records:t.records.filter(k),sourceIds:t.sourceIds.filter(k),sources:t.sources.filter(k)},said:{records:f.size,given:m,...R!==void 0?{refusal:R}:{},...h}}}async prepare(e,t,s,r,i,o,a){let d=r?void 0:o?.get(t.objectApiName);d&&o?.delete(t.objectApiName);let c=r?await this.deps.querySource(e.sourceOrgId,t,{changedSince:r.changedSince,onBoundReached:()=>{r.cut=!0}}):d??await this.deps.querySource(e.sourceOrgId,t);r&&(r.rows=c.length);let l=t.externalIdField??"Id",u=this.deps.maskedSourceFields,p=(c.length>0&&u?await u(t.objectApiName).catch(()=>[]):[]).filter(O=>c.some(E=>Object.prototype.hasOwnProperty.call(E,O)));for(let O of c)for(let E of p)delete O[E];let h=p.length>0?{encryptedLeftOut:p}:{},y=t.operation==="insert"||t.operation==="upsert",m=y?s.keep(t.objectApiName,c):c,R=i&&i.size>0&&t.operation==="insert"?m.filter(O=>!(typeof O.Id=="string"&&i.has(re(O.Id)))):m,S=m.length-R.length,b=S>0&&a&&a.size>0?m.filter(O=>typeof O.Id=="string"&&i?.has(re(O.Id))===!0&&a.has(re(O.Id))).length:0;if(R.length===0)return{read:c.length,records:[],sourceIds:[],sources:[],conflicts:[],unsettled:[],matchField:l,alreadyCopied:S,alreadyLinked:b,...h};let g=R.map(O=>{let E=this.deps.fieldMapping.apply(O,t.fieldMappings,t.excludedFields);return this.deps.transformPipeline.transformRecord(E,t)}).map(O=>{let E=this.deps.fieldMapping.applyAddOns(O,t.addOnFields);return y?sa(t.objectApiName,E):E}),w=g,M=[],A=t.operation==="upsert"||t.operation==="update";if(e.direction==="bidirectional"&&A){let O=await this.deps.queryTarget(e.targetOrgId,t);for(let E of O)for(let F of p)delete E[F];if(M=this.deps.conflictResolver.detectConflicts(g,O,l),M.length>0){let E=this.deps.conflictResolver.resolve(M,e.conflictStrategy),F=new Map(E.map(N=>[N.recordId,N.resolvedValues]));w=g.map(N=>{let $=String(N[l]??""),T=F.get($);return T?{...N,...T}:N})}}return{read:c.length,records:w,sourceIds:R.map(O=>typeof O.Id=="string"?O.Id:void 0),sources:R,conflicts:M,unsettled:g,matchField:l,alreadyCopied:S,alreadyLinked:b,...h}}async planFiles(e,t,s){let r=e.files;if(!r)return;let i=this.deps.files;if(!i)throw new le("This session cannot copy files: it reads no file content or file storage. Nothing was read or written.");return Ys({config:e,option:r,deps:i,tie:(o,a)=>this.tieToTarget(e,o,a),objects:t.map(o=>{let a=s===void 0?null:We(e,o,s);return{objectConfig:o,...a?.read==="delta"?{changedSince:Ie(a.since),...a.filesSeen!==void 0?{filesSeen:a.filesSeen}:{}}:{}}})})}async tieToTarget(e,t,s){let r=this.deps.deltaReads,i=this.deps.files;if(!r||!i)return{held:new Map,refused:"the target cannot be asked"};let o=Gt(t);if("refused"in o)return{held:new Map,refused:o.refused};let a=t.objectApiName,d=new Map;if(o.sourceField==="Id")for(let u of s)d.set(u,u);else{let u=rt(a),f=ye(o.sourceField);for(let p of ee(s)){let h=await i.copy.queryRecords(e.sourceOrgId,`SELECT Id, ${f} FROM ${u} WHERE Id IN (${p})`);for(let y of h){let m=this.deps.fieldMapping.apply(y,t.fieldMappings,t.excludedFields),R=this.deps.transformPipeline.transformRecord(m,t)[o.keyField];typeof y.Id=="string"&&Fe(R)!==null&&d.set(y.Id,R)}}}if(d.size===0)return{held:new Map};let c=await r.targetIdsByKey(a,o.keyField,[...new Set(d.values())]),l=new Map;for(let[u,f]of d){let p=c.get(Fe(f))??[];p.length===1&&l.set(u,p[0])}return{held:l}}};function ra(n,e,t){let s=[],r=[];return n!=="insert"&&n!=="upsert"?{written:s,linked:r}:(e.forEach((i,o)=>{let a=t[o];if(a===void 0)return;if(i.success&&typeof i.id=="string"&&i.id!==""){s.push([a,i.id]);return}let d=Bs(n,i);d!==void 0&&r.push([a,d])}),{written:s,linked:r})}function sa(n,e){let t=qn(n,e);if(t.length===0)return e;let s={...e};for(let r of t)delete s[r];return s}function Pe(n,e){let t=e.counts();return t.length===0?n:{...n,skipped:n.skipped+t.reduce((s,{count:r})=>s+r,0),errors:[...n.errors,...t.map(({why:s,count:r})=>zn(r,s))]}}function kt(n){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:0,conflictCount:0,errors:[]}}function ia(n,e,t,s,r,i){let o=ki(t)==="failure"?"failure":"partial",a=r.map(c=>c.objectApiName),d=a.length>0?`Cancelled before ${a.join(", ")} ${a.length===1?"was":"were"} synced.`:"Cancelled.";return{...se(n,e,t,s,o),cancelled:!0,error:i?`${i} ${a.length>0?d:""}`.trim():d}}function bi(n){return`Cancelled while the files of ${n.objectApiName} were copied: those copied stay in the target, the others are copied by the next run.`}function ki(n){return n.length===0?"success":n.every(s=>s.failed>0&&s.success===0)?"failure":n.some(s=>s.failed>0||oa(s.delta)||(s.files?.failed??0)>0)?"partial":"success"}function oa(n){return n!==void 0&&(n.deleteFailed>0||n.deletionError!==void 0)}function se(n,e,t,s,r){let i=0,o=0,a=0,d=0;for(let c of t)i+=c.processed,o+=c.success,a+=c.failed,d+=c.skipped;return{configId:n,operationId:e,status:r,objectResults:t,totalProcessed:i,totalSuccess:o,totalFailed:a,totalSkipped:d,duration:Date.now()-s,timestamp:new Date().toISOString()}}var aa=2;async function Oi(n,e,t,s,r=()=>!1){let i=t.rows;if(!i||i.length!==e.length||t.stopped)return{result:t,unsent:[]};let o=[...i],a=[...e],d=e.map(()=>[]),c=[],l=!1;for(let f=0;f<aa&&!r();f++){let p=[],h=[],y=[];if(o.forEach((S,b)=>{if(S.id)return;let k=Nr(S.errorDetails,a[b],void 0);!k||k.some(({field:g})=>s.has(g))||(p.push(b),h.push(xr(a[b],k)),y.push(k))}),p.length===0)break;let m;try{m=await n(h)}catch(S){let b=[...new Set(y.flat().map(({field:k})=>k))].sort();c.push(`${p.length} record(s) refused on ${b.join(", ")} could not be written again without ${b.length===1?"it":"them"}: ${K(S)}`);break}if(da(m,h.length).forEach((S,b)=>{let k=p[b];o[k]=S,a[k]=h[b],d[k].push(...y[b])}),m.stopped){l=!0;break}}let u;return o.forEach((f,p)=>{!f.id||d[p].length===0||(u=Ue(u,{rows:1,fields:d[p].map(h=>({...h,rows:1}))}))}),{result:{successIds:o.flatMap(f=>f.id?[f.id]:[]),errors:o.flatMap(f=>f.id?[]:[f.error??"Unknown insert error"]),rows:o,...l?{stopped:!0}:{}},...u?{written:u}:{},unsent:c}}function da(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(r=>({id:r})),...n.errors.map(r=>({error:r}))];return(e===1?t:t.map(r=>({...r,unmatched:!0}))).slice(0,e)}var ca=1e4,la=5e5,hn=200;function At(n){let e=Math.floor(la/Math.max(1,n.fieldRules.length));return Math.max(hn,Math.min(ca,e))}var Ai=class{deps;constructor(e){this.deps=e}async execute(e,t,s){let r=s??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return Ti(e.id,r,o.errors.map(l=>l.message),this.deps.now());let a=await Us(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return Ti(e.id,r,a,this.deps.now());let d=e.objects.reduce((l,u)=>l+u.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,r,i):this.executeSequential(e,t,r,i)}preview(e){return this.deps.planBuilder.build(e)}shouldActivateGrappe(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}reportProgress(e,t,s,r=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,r);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:s,percentage:Math.round(i/Math.max(s,1)*100)})}async executeSequential(e,t,s,r){let i=Ci(e,this.platformRolesOf(t),this.deps.onRowIds),o=this.deps.referenceLinker.resolveInsertOrder(e.objects,i.relations),a=e.objects.reduce((d,c)=>d+c.recordCount,0);for(let d of o){if(this.deps.signal?.aborted)return this.stoppedResult(e,s,i,r);let c=await this.readyToWrite(d,i,a);if(!c)continue;let l={},u={successIds:[],errors:[]},f={result:u,unsent:[]},p=Ii(c),h=0,y=0,m=!1,R=At(c.config);for await(let S of this.slicesOf(c,i,R,l)){if(this.deps.signal?.aborted){m=!0;break}h>0&&this.reportProgress(d.objectApiName,i.objectResults,a,u.successIds.length+u.errors.length);let b=await this.insert(t,d,S,c,i);if(h++,Pi(p,c.config.rows,y,S.length,b.result),y+=S.length,ka(f,b),b.result.stopped){m=!0;break}}if(h>0&&Ot(i,d,gn(u,c),[...c.notes,...fn(f)],l,p),m)return this.stoppedResult(e,s,i,r)}return this.ended(e,s,i,r)}async ended(e,t,s,r){let i,o=!1;try{i=await this.deps.knowledge?.({ids:ga(s),results:s.objectResults})}catch(l){o=!0,i={skipped:`The articles were neither published nor linked: ${K(l)}`}}let a=Ei(e.id,t,s.objectResults,r,this.deps.now());if(!i)return a;let d=o||[i.publish,i.links].some(l=>(l?.notDone.length??0)>0),c=this.deps.signal?.aborted===!0;return{...a,knowledge:i,...(d||c)&&a.status==="success"?{status:"partial"}:{},...c?{cancelled:!0}:{}}}async readyToWrite(e,t,s){let r=Dt(e.objectApiName,t.relations),i=jn(e,t.relations).filter(m=>t.wroteNothing.has(m));if(i.length>0)return Ve(t,e.objectApiName,`Skipped: ${i.join(", ")} wrote no records, so there is nothing for ${e.objectApiName} to point at.`);let o=await this.closedObject(e.objectApiName);if(o)return Ve(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,s);let a=vi(e,r),{config:d,dropped:c}=await Mi(a,this.deps.describeCreateableFields),l=await this.whyDropped(e.objectApiName,c),u=m=>m.fieldRules.length===0&&mn(m.rows).length===0;if(u(d)&&!u(a))return Ve(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${l.join("; ")}).`);let{config:f,filled:p}=await Fi(await this.withTheOrgsPicklistValues(d),r,this.deps.describeRequiredFields),h=await this.matchStandardPricebook(f,t);if(h)return Ve(t,e.objectApiName,h);let y;if(r){let m=await this.placeChildren(f,r,t);if("skipped"in m)return Ve(t,e.objectApiName,m.skipped);if(m.parentIds.length===0&&m.unwritten){let{lines:R,keys:S}=m.unwritten;return Ot(t,e,{successIds:[],errors:R},[],{},S),null}y=m}return{relation:r,config:y?{...f,recordCount:y.parentIds.length,...y.rows?{rows:y.rows}:{}}:f,placed:y,...f.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...l.map(m=>`Written without ${m}.`),...p.length>0?[`Written with ${p.join(", ")}, which this org requires and the template names no rule for.`]:[],...y?.notes??[]]}}async placeChildren(e,t,s){let{childObject:r,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(r,i))return{skipped:`Skipped: this org does not let a seed write ${r}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return fa(e.rows??[],t,s.keys.get(o));let a=s.existingIds,d;if(t.parents.kind==="generated")d=a.get(o)??[];else if(t.parents.kind==="records")d=[...t.parents.ids];else{let f=this.deps.readExistingParentIds;if(!f)return{skipped:`Skipped: this run cannot read the ${o} records already in the org, so ${r} has nothing to point at.`};try{d=await f(o,t.parents.where,t.parents.limit)}catch(p){return{skipped:`Skipped: reading the ${o} records already in the org failed (${K(p)}), so ${r} has nothing to point at.`}}}if(d.length===0){let f=t.parents.kind==="existing"?t.parents.where?.trim():"";return{skipped:`Skipped: ${t.parents.kind==="generated"?`${o} wrote no records`:`no ${o} record in the org matches ${f?`"${f}"`:"the relation"}`}, so there is nothing for ${r} to point at.`}}let c=Fn(t.distribution,d.length,this.deps.random),l=c.reduce((f,p)=>f+p,0),u=[];for(let[f,p]of c.entries())for(let h=0;h<p&&u.length<e.recordCount;h++)u.push(d[f]);return u.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${r}.`}:{parentIds:u,notes:l>u.length?[`Stopped at ${u.length} ${r} records, the most the template asks for: the relation spreads ${l} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,s,r){let i=e.config.recordCount,o=Math.max(1,Math.floor(s)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),c=wa(e.config,e.relation)?Sa(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,l=>{r.aiFallback=ba(r.aiFallback,l)},a,e.lengths);Ra(c,e.relation,e.placed,a),yield c,a+=d}while(a<i)}async insert(e,t,s,r,i){let o=f=>this.deps.insert(e,t.objectApiName,f,t.batchSize),a=t.objectApiName===X?await i.platformRoles.link(s):new Map,d=a.size>0?s.filter((f,p)=>!a.has(p)):s,c=d.length===0&&s.length>0?{successIds:[],errors:[],rows:[]}:await o(d),l=await Oi(o,d,c,ua(r),()=>this.deps.signal?.aborted===!0);t.objectApiName===zs&&i.platformRoles.opportunitiesWritten(d,l.result);let u=a.size>0?ha(l,s.length,a):l;return c.notes&&c.notes.length>0?{...u,notes:c.notes}:u}platformRolesOf(e){return new qs({orgId:e,readTarget:this.deps.readTarget,update:this.deps.update,stopped:()=>this.deps.signal?.aborted===!0})}async closedObject(e){if(!this.deps.objectAccess)return;let t;try{t=await this.deps.objectAccess(e)}catch{return}if(t.access==="createable")return;let s=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${s}.`:`Skipped: the user this seed runs as may not create ${e} records${s}`+(t.reason?".":`: give that user Create on ${e} in a permission set.`)}async withTheOrgsPicklistValues(e){if(!this.deps.describePicklistValues||!e.fieldRules.some(i=>i.ruleType==="picklist_random"))return e;let t;try{t=await this.deps.describePicklistValues(e.objectApiName)}catch{return e}let s=!1,r=e.fieldRules.map(i=>{let o=t.get(i.fieldApiName),a=i.config.picklistValues;if(i.ruleType!=="picklist_random"||!o?.length||!a)return i;let d=a.filter(c=>o.includes(c));return d.length===a.length?i:(s=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return s?{...e,fieldRules:r}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>nt(o,t.written))||t.existingIds.has(ge))return;let s=this.deps.readExistingParentIds,r=`${e.objectApiName} points at the org's standard price book`;if(!s)return`Skipped: ${r}, and this run cannot read it.`;let i;try{i=await s(ge,"IsStandard = true",1)}catch(o){return`Skipped: ${r}, and reading it failed (${K(o)}).`}if(i.length===0)return`Skipped: ${r}, and the org shows this user no standard price book (Pricebook2): give that user Read on Price Books in a permission set.`;t.existingIds.set(ge,i)}async orgTakesField(e,t){if(!this.deps.describeCreateableFields)return!0;try{return(await this.deps.describeCreateableFields(e)).has(t)}catch{return!0}}async whyDropped(e,t){if(t.length===0)return[];let s=new Set;try{this.deps.describeVisibleFields&&(s=await this.deps.describeVisibleFields(e))}catch{}let r;try{this.deps.describeComputedFields&&(r=await this.deps.describeComputedFields(e))}catch{}let i=t.filter(c=>s.has(c)&&r?.has(c)===!0),o=t.filter(c=>s.has(c)&&r?.has(c)!==!0),a=t.filter(c=>!s.has(c)),d=(c,l,u)=>c.length===1?l:u;return[...a.length>0?[`${a.join(", ")}: this org does not have ${d(a,"that field","those fields")}, or field-level security hides ${d(a,"it","them")} from the user SandForge connects as`]:[],...i.length>0?[`${i.join(", ")}: ${d(i,"a formula or auto-number field","formula or auto-number fields")}, which the org fills itself and no user sets: take ${d(i,"its rule","their rules")} out of the template`]:[],...o.length>0?[`${o.join(", ")}: ${d(o,"it exists","they exist")}, but the user SandForge connects as may not set ${d(o,"it","them")}`+(r!==void 0?`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set)`:`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set), unless it is a formula or auto-number field, whose rule comes out of the template`)]:[]]}async fieldLengths(e){if(!this.deps.describeFieldLengths)return new Map;try{return await this.deps.describeFieldLengths(e)}catch{return new Map}}async executeWithGrappe(e,t,s,r){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((y,m)=>y+m.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:s,totalPartitions:o.length,totalRecords:a}});let d=Ci(e,this.platformRolesOf(t),this.deps.onRowIds),c=this.deps.referenceLinker.resolveInsertOrder(e.objects,d.relations),l=[],u=0,f=this.deps.grappeConfig?.grappeSize??2e3,p=()=>{let y=d.objectResults.reduce((R,S)=>R+S.recordsCreated,0),m=d.objectResults.reduce((R,S)=>R+S.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:s,totalProcessed:y,totalFailed:m}})},h=()=>(p(),this.stoppedResult(e,s,d,r));for(let y of c){if(this.deps.signal?.aborted)return h();let m=Math.ceil(y.recordCount/f),R=await this.readyToWrite(y,d,a);if(!R){u=this.settleUnusedPartitions(o,u,m,0);continue}let S={},b=Math.max(1,Math.ceil(R.config.recordCount/f)),k=0,g=0,w=[],M=[],A={result:{successIds:[],errors:[]},unsent:[]},O,E=Ii(R),F=0,N=-1;for await(let $ of this.slicesOf(R,d,f,S)){if(N++,this.deps.signal?.aborted){O=N;break}N>0&&this.reportProgress(y.objectApiName,d.objectResults,a,k+g);let T=Date.now(),v=o[u]?.id??this.deps.generateId(),j=await this.insert(t,y,$,R,d),D=j.result;Pi(E,R.config.rows,F,$.length,D),F+=$.length,j.written&&(A.written=Ue(A.written,j.written)),A.unsent.push(...j.unsent);for(let z of j.notes??[])(A.notes??[]).includes(z)||(A.notes=[...A.notes??[],z]);k+=D.successIds.length,g+=D.errors.length,w.push(...D.errors),M.push(...D.successIds),l.push({grappeId:v,status:D.errors.length===0?"success":D.successIds.length>0?"partial":"failure",processedRecords:$.length,successCount:D.successIds.length,failureCount:D.errors.length,errors:D.errors,duration:Date.now()-T}),u++;let _=Math.round(u/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:v,percentage:_,processedRecords:k+g}}),D.stopped){O=N+1;break}}if(O!==void 0)return O>0&&Ot(d,y,gn({successIds:M,errors:w},R),[...R.notes,...fn(A)],S,E),h();u=this.settleUnusedPartitions(o,u,m-b,k+g),Ot(d,y,gn({successIds:M,errors:w},R),[...R.notes,...fn(A)],S,E)}return p(),this.ended(e,s,d,r)}stoppedResult(e,t,s,r){let i=Ei(e.id,t,s.objectResults,r,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,s,r){let i=t;for(let o=s;o>0;o--){let a=e[i]?.id??this.deps.generateId();i++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:a,percentage:Math.round(i/Math.max(e.length,1)*100),processedRecords:r}})}return i}};function Ci(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(s=>s.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function ua(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function fn(n){return[...n.notes??[],...n.written?[Dr(n.written)]:[],...n.unsent]}function Ve(n,e,t,s=!1){let r=Oa(e,t);return n.objectResults.push(s?{...r,optional:!0}:r),n.wroteNothing.add(e),null}function Ot(n,e,t,s,r,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,pa(i)));let o=n.platformRoles.resultOf(e.objectApiName),a=[...t.successIds,...o.linkedIds];n.existingIds.set(e.objectApiName,a),e.recordCount>0&&a.length===0&&n.wroteNothing.add(e.objectApiName),n.objectResults.push({objectApiName:e.objectApiName,recordsCreated:t.successIds.length,recordsFailed:t.errors.length,createdIds:t.successIds,errors:[...t.errors,...s,...o.notes],...r,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function pa(n){let e={};for(let[t,s]of n)"id"in s&&(e[t]=s.id);return e}function fa(n,e,t){let{childObject:s,parentObject:r}=e;if(!t)return{skipped:`Skipped: ${s} is placed by key, and ${r} wrote no rows to place it under.`};let i=[],o=[],a=[],d=new Map;for(let c of n){let l=c.parentKey,u=l===void 0?void 0:t.get(l);if(u&&"id"in u){i.push(u.id),o.push(c);continue}let f=l===void 0?`it names no ${r} row`:`its ${r} ${l} ${u?u.why:`is no ${r} row this run wrote`}`;a.push(`${s} ${c.key} not written: ${f}.`),d.set(c.key,{why:`was not written, as ${f}`})}return{parentIds:i,notes:[],rows:o,unwritten:{lines:a,keys:d}}}function ga(n){let e=new Map;for(let[t,s]of n.keys){let r=new Map;for(let[i,o]of s)"id"in o&&r.set(i,o.id);e.set(t,r)}return e}function Ii(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function Pi(n,e,t,s,r){if(!n||!e)return;let i=r.rows&&(r.rows.length===s||r.stopped)?r.rows:void 0;for(let o=0;o<s;o++){let a=e[t+o];if(!a)continue;let d=i?.[o];i?d?d.id&&d.unmatched?n.set(a.key,{why:"has no id this run can tell: the org did not say which of the ids it answered is its"}):d.id?n.set(a.key,{id:d.id}):n.set(a.key,{why:`was refused (${d.error??"Unknown insert error"})`}):n.set(a.key,{why:"was not sent: the run was stopped before it"}):n.set(a.key,{why:"has no id this run can tell: the insert did not answer record by record"})}}function gn(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function ha(n,e,t){let s=n.result.rows;if(!s)return n;let r=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){r.push({id:String(a.Id)});continue}let d=s[i++];if(!d)break;r.push(d)}return{...n,result:{...n.result,rows:r}}}function mn(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function ma(n){return!n||n.length===0?[]:mn(n).filter(e=>n.every(t=>e in t.values))}function ya(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([s])=>!e.has(s)))}))}async function Mi(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let s=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),r=mn(n.rows).filter(a=>!t.has(a));if(s.length===n.fieldRules.length&&r.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!s.includes(a)).map(a=>a.fieldApiName),...r])],o=n.rows&&ya(n.rows,new Set(r));return{config:{...n,fieldRules:s,...o?{rows:o}:{}},dropped:i}}async function Fi(n,e,t){if(!t)return{config:n,filled:[]};let s;try{s=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let r=new Set([...n.fieldRules.map(o=>o.fieldApiName),...ma(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of s){if(r.has(o.fieldApiName))continue;let a=Nn(o);a.ruleType==="static"&&a.config.staticValue===void 0||i.push({fieldApiName:o.fieldApiName,fieldType:o.type,...a})}return i.length===0?{config:n,filled:[]}:{config:{...n,fieldRules:[...n.fieldRules,...i]},filled:i.map(o=>o.fieldApiName)}}async function ji(n,e,t){let s=Dt(n.objectApiName,e),{config:r}=await Mi(vi(n,s),t.describeCreateableFields),{config:i}=await Fi(r,s,t.describeRequiredFields);return At(i)}function vi(n,e){if(!e)return n;let t=n.fieldRules.filter(s=>s.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function wa(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function Sa(n){return Array.from({length:n},()=>({}))}function Ra(n,e,t,s=0){if(!(!e||!t))for(let[r,i]of n.entries())i[e.lookupField]=t.parentIds[s+r]}function ba(n,e){return n?{fields:[...new Set([...n.fields,...e.fields])],reason:n.reason==="no-answer"&&e.reason==="no-answer"?"no-answer":"short-answer"}:e}function ka(n,e){for(let t of e.result.successIds)n.result.successIds.push(t);for(let t of e.result.errors)n.result.errors.push(t);e.written&&(n.written=Ue(n.written,e.written)),n.unsent.push(...e.unsent);for(let t of e.notes??[])(n.notes??[]).includes(t)||(n.notes=[...n.notes??[],t])}function Oa(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function Ei(n,e,t,s,r){let i=t.reduce((d,c)=>d+c.recordsCreated,0),o=t.reduce((d,c)=>d+c.recordsFailed,0),a=t.some(d=>!d.optional&&d.recordsCreated===0&&d.recordsFailed===0&&d.errors.length>0);return{templateId:n,operationId:e,status:Aa(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-s,timestamp:r}}function Aa(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function Ti(n,e,t,s){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:s}}var Ca=200,Ia=1,Pa=1,yn=2,Ea=2,Di=3,Ta=1,Ma=200,Fa="Campaign";function Li(n,e){if(!n)return;let t=e.toLowerCase();for(let[s,r]of n)if(s.toLowerCase()===t)return r}function ja(n,e){let t=Math.max(1,Math.floor(e)),s=[],r=0;do{let i=Math.max(0,Math.min(t,n-r));s.push(i),r+=i}while(r<n);return s}function va(n,e={}){let t=e.bulkThreshold??Ca,s=!1;return n.objects.flatMap(i=>{let o=Li(e.duplicateRules,i.objectApiName),a=o===!1&&!ys.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??At(i);return ja(i.recordCount,d).map(c=>{let l=we([{rows:c,perCall:i.batchSize}]);if(c<=t||(s=!0,o===!0))return l;let u=we([{rows:c,bulk:!0}]);return a?u:Math.max(u,l)})}).reduce((i,o)=>i+o,0)+(s?Ia:0)+we(Da(n))}function Na(n,e={}){return va(n,e)+xa(n,e)}function xa(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),s=n.objects.some(i=>i.fieldRules.some(o=>nt(o,t))),r=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+we([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/Gs):i,0);return Pa+n.objects.length+yn+(t.has(Fa)?yn+1:0)+r+(s?Ta:0)+(e.typedFirst?Ea:0)+Di+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function ol(n,e,t){let s=new Map;if(t!==void 0)return s;for(let r of n.objects)r.recordCount<=hn||s.set(r.objectApiName,await ji(r,n.relations,e));return s}function al(n,e){return n?.enabled&&e.objects.reduce((s,r)=>s+r.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function Ct(n,e){return n.reduce((t,{objectApiName:s,rows:r,perCall:i,deletes:o})=>{if(r<=e.threshold)return t+we([{rows:r,perCall:i??e.perCall}]);let a=o===!0||Li(e.duplicateRules,s)===!1?0:r;return t+we([{rows:r,bulk:!0},{rows:a}])},0)}function wn(n=0,e=0){return Di+yn+Math.max(0,n)+Math.max(0,e)}function dl(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,s=Math.min(t("Opportunity"),t("OpportunityContactRole")),r=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return Ct(n,e)+(s>0?Math.ceil(s/Ma)+Ct([{objectApiName:"OpportunityContactRole",rows:s}],e):0)+we(r)+wn(n.length,e.automationRead)}function Da(n){let e=s=>n.objects.find(r=>r.objectApiName===s)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function La(n,e){return n.objects.reduce((t,s)=>t+qr(s.objectApiName,{rows:s.recordCount,personAccounts:e.includes(s.objectApiName)?s.recordCount:0}),0)}function ll(n,e){let t=n.automationStarts??[],s=t.filter(a=>a.why!=="leftEmpty"),r=n.automationAtMostMB!==void 0&&n.automationAtMostMB>0&&s.length>0?` (${xe(n.automationAtMostMB)} MB of it at most: ${s.map(a=>`${Ni(a)} ${xi(a)}`).join("; ")})`:"",i=`data storage: about ${xe(n.estimateMB)} MB to write`+(n.automationMB!==void 0&&n.automationMB>0?`, about ${xe(n.automationMB)} MB of it for what the target's automation creates under them${r}`:""),o=t.filter(a=>a.why==="leftEmpty").map(a=>`; nothing counted for ${Ni(a)}: it ${xi(a)}`).join("");return n.verdict==="unread"?`${i}; what ${e} has left could not be read (${n.unread})${o}`:`${i}, ${e} has ${n.remainingMB} MB left of ${n.maxMB} MB`+(n.verdict==="near"?": close to what it has left":"")+o}function Ni(n){return`${n.name} on ${n.objectApiName}`}function xi(n){let e=n.why==="leftEmpty"?"which the seed leaves empty":n.why==="automationMayFill"?"which the seed leaves empty and the target's automation may fill first":"which the seed may leave empty";return`starts only on a record whose ${n.fields.join(" and ")} ${n.fields.length===1?"is":"are"} filled, ${e}`}var ul="SEED_STORAGE_EXCEEDED";async function pl(n,e,t,s,r,i={},o={},a={perRecord:[]}){let d={storageBytes:La(e,t)},c;try{c=await Hr(n)}catch(w){c={unread:K(w)}}let l=new Map(e.objects.map(w=>[w.objectApiName,w.recordCount])),u=w=>l.get(w)??0,f=Yt(a,u),p=a.atMost?Yt({perRecord:a.atMost},u):0,h=Ne(d,c,f),m={...h.verdict==="exceeds"&&p>0&&Ne(d,c,f-p).verdict!=="exceeds"?{...h,verdict:"near"}:h,...p>0?{automationAtMostMB:p/1048576}:{},...a.starts&&a.starts.length>0?{automationStarts:a.starts}:{}},R="unread"in c?await Yr(n).catch(w=>({unread:K(w)})):c.dailyApiRequests,S=at({run:Na(e,o),...ct(r),...i},R),b=lt(r);if(b)return{check:m,api:S,refusal:b.message,refusedFor:"checkpoint",checkpointRefusal:b.refusal};let k=as(m,s);if(k)return{check:m,api:S,refusal:`${k} Nothing was written.`,refusedFor:"storage"};let g=dt(S,s);return g?{check:m,api:S,refusal:g,refusedFor:"apiRequests"}:{check:m,api:S}}function fl(n,e){let{check:t,api:s}=n,r=s.parts??{},i={checkpoint:r.checkpoint??0,mute:r.mute??0,readBack:r.readBack??0,deliverability:r.deliverability??0,fit:r.fit??0};return ds({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB},...e!==void 0?{withinMB:e}:{},api:s.verdict==="unread"?{unread:s.unread}:{max:s.max,remaining:s.remaining},otherRequests:i})}function $a(n){return n==="insert"||n==="upsert"}function _i(n){return n==="update"||n==="upsert"}function Ba(n){return Kr(n.objects.filter(e=>$a(e.operation)).map(({objectApiName:e,rows:t,personAccounts:s})=>({objectApiName:e,rows:[],counted:{rows:t,...s!==void 0?{personAccounts:s}:{}}})))}var Wi=fe.REST_API_BATCH_SIZE;function _a(n,e){return Ct(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:s,rows:r,batchSize:i})=>({objectApiName:t,rows:r,...i!==void 0?{perCall:i}:{},...s==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??Wi,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var Wa="Opportunity",Ga="OpportunityContactRole",Ua=200,za={update:{characters:Jt,wide:!0},upsert:{characters:Ts(),wide:!0}},qa=2,$i=Array.from({length:qa},()=>1),Ka=1;function Ha(n){let e=Math.min(Math.max(0,n),5e4);return Ka+Math.max(1,Math.ceil(e/vr))}function Rn(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(s,r)=>Math.min(t,n-r*t))}function Ya(n,e){if(n.rows<=(e.bulkThreshold??Wi))return Rn(n.rows,n.batchSize??fe.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([s])=>s.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:Rn(n.rows,fe.REST_API_BATCH_SIZE)]}function Ja(n,e){let t=0,s=!1;for(let d of e.targetHeld?.values()??[])t+=Ha(d);for(let d of n.objects)d.rows<=0||d.operation==="delete"||(t+=$i.length,!(d.operation!=="update"&&d.operation!=="upsert")&&(s=!0,t+=Vt([...Ya(d,e),...$i],d.overwriteKey??za[d.operation])));let r=d=>n.objects.find(c=>c.objectApiName===d&&(c.operation==="insert"||c.operation==="upsert")),i=r(Wa),o=r(Ga),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=Rn(a,o.batchSize??fe.REST_API_BATCH_SIZE);s=!0,t+=Math.ceil(a/Ua)+d.length+Vt(d,{characters:Jt,wide:o.overwriteKey?.wide??!0})}return s&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function Gi(n){let e=new Map;for(let{objectApiName:t,operation:s}of n.objects){let r=e.get(t)??new Set;(s==="insert"||s==="upsert")&&r.add("insert"),(s==="update"||s==="upsert")&&r.add("update"),s==="delete"&&r.add("delete"),e.set(t,r)}return(t,s)=>e.get(t)?.has(s)===!0}function Ui(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(s=>t.has(s)),objects:n.objects.filter(s=>t.has(s.objectApiName))}}function Va(n){let e;return t=>{if(e&&t.every(r=>e?.objects.includes(r)))return e.answer.then(r=>Ui(r,t));let s=n(t);return e??={objects:[...t],answer:s},s}}function Ml(n,e){if(n.direction==="bidirectional")return async t=>{let s=n.objects.find(i=>i.objectApiName===t),r=ot(s?.where,void 0);return e(`SELECT COUNT() FROM ${ye(t)}${r?` WHERE ${r}`:""}`)}}async function Xa(n,e){let t=new Set((n.heldBack??[]).filter(({rows:r})=>r>0).map(({objectApiName:r})=>r)),s=new Map;for(let{objectApiName:r,operation:i,rows:o}of n.objects){if(!_i(i)||s.has(r)||o<=0&&!t.has(r))continue;let a=await e(r).catch(()=>5e4);s.set(r,Number.isFinite(a)&&a>=0?a:5e4)}return s}async function Bi(n,e){let t=Ba(n),s=n.objects.filter(T=>T.rows>0).map(({objectApiName:T,rows:v})=>({objectApiName:T,rows:v})).sort((T,v)=>v.rows-T.rows||T.objectApiName.localeCompare(v.objectApiName)),r=s.reduce((T,v)=>T+v.rows,0),i=n.objects.filter(T=>_i(T.operation)).reduce((T,v)=>T+v.rows,0),o=Ne(t,{maxMB:0,remainingMB:0}),a=[],d,c=r>0?Va(e.readAutomation):e.readAutomation,l,u,f,p=Gi(n),h;if(r>0){let T=n.objects.filter(v=>v.rows>0).map(v=>v.objectApiName);if(h=await c(T).catch(v=>({unread:v instanceof Error?v.message:String(v)})),e.checkpointFirst){let v="objects"in h?Lt(h,void 0,p):{firing:[]};try{l=await e.checkpointFirst.scope(T,v)}catch(j){u=zr(j)}}}let y={unread:"not read"};if(r>0){let T=await e.readStorage().catch(v=>({unread:v instanceof Error?v.message:String(v)}));y="unread"in T?await e.readApiBudget().catch(v=>({unread:v instanceof Error?v.message:String(v)})):T.dailyApiRequests,t.totalRows>0&&(o=Ne(t,T))}if(t.totalRows>0){let T=await Qr({plan:t,objects:t.objects.map(v=>v.objectApiName),readAutomation:c,readLimits:e.readLimits});a=T.checks,d=T.unread}h!==void 0&&(f=await Er({...e.emails,read:h,writes:p,readDeliverability:e.readDeliverability,run:"sync"}));let m=r>0&&e.countTarget?await Xa(n,e.countTarget):void 0,R=ss(f?.ofRun),S=e.sentBefore?.(),b=r===0?0:S!==void 0?Math.max(0,S-(R.deliverability??0)):wn(0,h!==void 0?rs(h):0)+(m?.size??0),k=h!==void 0?ws(h):void 0,g=r===0?0:Ja(n,{bulkThreshold:e.bulkThreshold,duplicateRules:k,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...m?{targetHeld:m}:{}}),w=at({run:_a(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:k})+b+g,...ct(l),...Mr(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...R},y),M=e.confirmAboveRecords,A=M>0&&r>M?M:void 0,O=(n.unwritable??[]).map(({objectApiName:T,rows:v,why:j,key:D})=>({...D!==void 0?{key:D}:{},objectApiName:T,rows:v,why:j})),E=(n.heldBack??[]).map(({objectApiName:T,rows:v,parent:j,field:D,parents:_})=>({objectApiName:T,rows:v,parent:j,field:D,..._!==void 0?{parents:_.map(z=>({...z}))}:{}})),F=f?.gate,N=r===0?O.length>0?"refused":"writes":o.verdict==="exceeds"||w.verdict==="exceeds"||u!==void 0||l?.refusal!==void 0?"refused":A!==void 0||O.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(T=>T.verdict!=="fits")||d!==void 0||l!==void 0||F?.verdict==="asks"?"asks":"writes";return{check:{objects:s,total:r,alreadyCopied:n.alreadyCopied,...(n.alreadyLinked??0)>0?{alreadyLinked:n.alreadyLinked}:{},...i>0?{overwrites:i}:{},...(n.rolesByThePlatform??0)>0?{rolesByThePlatform:n.rolesByThePlatform}:{},...(n.rolesLinked??0)>0?{rolesLinked:n.rolesLinked}:{},...A!==void 0?{aboveRecords:A}:{},storage:o.verdict==="unread"?{verdict:"unread",estimateMB:o.estimateMB,unread:o.unread}:t.totalRows===0?{verdict:"fits",estimateMB:0}:{verdict:o.verdict,estimateMB:o.estimateMB,maxMB:o.maxMB,remainingMB:o.remainingMB},emails:a.map(T=>({limit:T.limit,emails:T.emails,verdict:T.verdict,...T.remaining!==void 0?{remaining:T.remaining}:{},...T.max!==void 0?{max:T.max}:{},...T.alertsCounted?{alertsCounted:!0}:{},objects:T.objects.map(({objectApiName:v,perRecord:j})=>({objectApiName:v,perRecord:j})),...T.unread!==void 0?{unread:T.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...F?.deliverability?{deliverability:F.deliverability}:{},...O.length>0?{unwritable:O}:{},...E.length>0?{heldBack:E}:{},...r>0?{apiRequests:w.verdict==="unread"?{verdict:"unread",estimate:w.estimate,unread:w.unread}:{verdict:w.verdict,estimate:w.estimate,remaining:w.remaining,max:w.max}}:{},verdict:N,...u!==void 0?{checkpointUnread:u}:{}},plan:t,storage:o,emails:a,api:w,...l!==void 0?{checkpoint:l}:{},...u!==void 0?{checkpointFailed:u}:{},...f!==void 0?{runEmails:f}:{},emailsAccepted:e.emails.accepted}}function Za(n,e){let{check:t,storage:s,emails:r,plan:i,api:o}=n,a=[],d=t.unwritable??[];if(d.length>0&&(e.policy!=="ask"||t.total===0)&&a.push({code:"SYNC_TARGET_UNWRITABLE",message:td(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:Xr,message:n.checkpointFailed});else{let l=lt(n.checkpoint);l&&a.push(l)}i.totalRows>0&&s.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${xe(s.estimateMB)} MB of data storage, and ${e.org} has ${s.remainingMB} MB left of ${s.maxMB} MB: leave objects out, narrow their filters, or free data storage in ${e.org}. To copy a sample of the source that fits ${e.org} instead, use Forge with Depth ALL and a sample that fits the target (sandforge clone --depth all --fit share). Nothing was written.`});let c=dt(o,e.org,$r);if(c&&a.push({code:Jr,message:c}),e.policy!=="ask"){let l=ns(r,e.org);l&&a.push({code:"SYNC_EMAILS_EXCEEDED",message:`${l} Nothing was written.`});let u=n.runEmails?.gate,f=u?.stop;f&&a.push({code:f.code,message:Ht(f.message,"sync",e.emailsLiftedBy),...ve(u,!1)})}return a}async function Qa(n,e){let{check:t,storage:s,emails:r,api:i}=n,[o]=Za(n,e);if(o)return{go:!1,...o};if(t.total===0)return{go:!0,asked:!1};let a=n.runEmails?.gate;if(e.policy!=="ask")return{go:!0,asked:!1,...ve(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...ve(a,!1)};let c=Ir(e.orgTier),l=r.filter(h=>h.verdict==="exceeds").map(es),u=r.filter(h=>h.verdict==="unread").map(ts),f=e.confirm?await e.confirm({stage:"write",module:"sync",org:e.org,orgTier:e.orgTier,objects:t.objects,total:t.total,...t.aboveRecords!==void 0?{aboveRecords:t.aboveRecords}:{},...c!==void 0&&t.total>c?{largeVolume:c}:{},storage:os(s),counted:!0,...t.overwrites!==void 0?{overwrites:t.overwrites}:{},...l.length>0?{emails:l}:{},...u.length>0?{emailsUnread:u}:{},...t.emailsUnread!==void 0?{emailsUncounted:t.emailsUnread}:{},...t.alreadyCopied>0?{alreadyCopied:t.alreadyCopied}:{},...(t.alreadyLinked??0)>0?{alreadyLinked:t.alreadyLinked}:{},...(t.rolesLinked??0)>0?{rolesLinked:t.rolesLinked}:{},...d.length>0?{unwritable:d}:{},...t.heldBack!==void 0&&t.heldBack.length>0?{heldBack:t.heldBack}:{},...Vr(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(f==="confirmed")return{go:!0,asked:!0,...ve(a,a?.verdict==="asks")};let p=ve(a,!1);return f==="declined"?{go:!1,code:"SYNC_WRITE_DECLINED",message:"The sync was cancelled before it wrote anything. Nothing was written.",...p}:{go:!1,code:"SYNC_CONFIRMATION_UNAVAILABLE",message:"The sync needed a confirmation before it wrote, and there was no one to ask. Nothing was written.",...p}}var ed={notInTarget:n=>`${n} has no such object, or the user the run writes as cannot see it`,notCreateable:n=>`the user the run writes as may not create its records in ${n}`,notUpdateable:n=>`the user the run writes as may not edit its records in ${n}`,unread:n=>`${n} did not describe it, so what it takes could not be told`,notAKey:(n,e)=>`its upsert matches on ${e??"a field"}, neither an External ID nor an idLookup field in ${n}`};function td(n,e,t=[]){let s=n.map(({objectApiName:R,rows:S,why:b,key:k})=>`${R} (${S} record${S===1?"":"s"}): ${ed[b](e,k)}`).join("; "),r=n.length===1?"it":"them",i=n.filter(({why:R})=>R==="notAKey"),o=n.filter(({why:R})=>R!=="notAKey"),a=i.length>0&&o.length>0,d=R=>R.map(({objectApiName:S})=>S).join(" and "),c=`give the user SandForge writes as access to ${a?d(o):r} in ${e}`,l=`match ${a?`${d(i)} `:""}on an External ID field of ${e}`,u=a?`${c}, or ${l}`:i.length>0?`or ${l}`:`or ${c}`,f=new Set(n.map(({objectApiName:R})=>R)),p=({parent:R,field:S})=>`whose ${S} names ${/^[aeiou]/i.test(R)?"an":"a"} ${R} record `+(f.has(R)?"left out":"held back"),h=t.flatMap(({objectApiName:R,rows:S,parent:b,field:k,parents:g})=>(g??[{parent:b,field:k,rows:S}]).map(w=>`${w.rows} ${R} record${w.rows===1?"":"s"}, ${p(w)}`)).join("; "),y=n.filter(({why:R})=>R==="notInTarget"),m=y.length>0?` Where ${e} has not ${d(y)}, Compare deploys ${y.length===1?"it":"them"} from the source: tick Data Model, compare, then Deploy from Diff.`:"";return`${e} would take no record of ${n.length===1?"one object":`${n.length} objects`} the sync writes \u2014 ${s}.`+(h!==""?` Left out, ${r==="it"?"it holds":"they hold"} back ${h}.`:"")+` Leave ${r} out of the run, ${u}.${m} Nothing was written.`}function Fl(n,e){return{measure:async t=>(await Bi(t,n)).check,hold:async t=>{let s=await Bi(t,n),r=await Qa(s,e);return{check:s.check,answer:await nd(s,r,n.checkpointFirst)}}}}async function nd(n,e,t){let s=n.checkpoint;if(!e.go||s===void 0||t===void 0)return e;let r=await Zr(()=>t.take(s));return"stop"in r?{go:!1,...r.stop}:{...e,checkpoint:r.checkpoint}}function jl(n,e){return e==="insert"||e==="update"||e==="delete"}function vl(n,e,t,s,r){let i,o,a,d,c=n(async u=>{let f=i?.automation;return f&&u.every(p=>f.objectsRead.includes(p))?Ui(f,u):e(u)},()=>i?.plan),l=u=>{if(!Tr(u))throw u;return{go:!1,code:u.code,message:u.message}};return{gate:{measure:u=>c.measure(u),hold:async u=>{let f=u.objects.filter(h=>h.rows>0).map(h=>h.objectApiName);if(!i&&f.length>0){d=await e(f).catch(h=>({unread:h instanceof Error?h.message:String(h)}));try{i=await t(d),a=i.muted}catch(h){return{check:await c.measure(u),answer:l(h)}}}let p=await c.hold(u);if(p.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(s),a=o.outcome}catch(b){let{checkpoint:k}=p.answer;return{check:p.check,answer:{...l(b),...k?{checkpoint:k}:{}}}}let{checkpoint:h,emails:y}=p.answer,{deliverability:m}=p.check,R=Gi(u),S=i.plan&&d&&"objects"in d?is({planned:m?.senders??[],held:Gn(Lt(d,Pr(i.plan,o.outcome),R),{writes:R}),...m?{reading:m.reading}:{},accepted:y?.accepted===!0,target:r.target,run:"sync"}):void 0;if(S)return{check:p.check,answer:{go:!1,code:S.code,message:Ht(S.message,"sync",r.liftedBy),...h?{checkpoint:h}:{},...y?{emails:y}:{}}}}return p}},release:async()=>(o&&(a=await o.release()),a),lease:()=>{let u=o;if(u)return{assigned:u.outcome.assigned.length,giveBack:async()=>(a=await u.release(),a)}}}}export{gt as a,St as b,cd as c,ld as d,kd as e,Od as f,Ad as g,Zs as h,go as i,Nd as j,xd as k,zd as l,qd as m,Kd as n,Hd as o,ko as p,Oo as q,Yd as r,Io as s,Jd as t,Vd as u,Po as v,ae as w,$e as x,oi as y,ai as z,Qd as A,To as B,Mo as C,ec as D,cn as E,pc as F,si as G,Ri as H,Ai as I,Li as J,Na as K,ol as L,al as M,Ct as N,wn as O,dl as P,La as Q,ll as R,ul as S,pl as T,fl as U,Ml as V,Bi as W,Za as X,Qa as Y,td as Z,Fl as _,nd as $,jl as aa,vl as ba};
|