sandforge 1.82.0 → 1.84.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 +1 -1
- package/lib/chunk-23SEDORH.mjs +11 -0
- package/lib/{chunk-7WSLT5VX.mjs → chunk-24RFOFYT.mjs} +1 -1
- package/lib/chunk-26POJDIT.mjs +7 -0
- package/lib/{chunk-SFGZFB4F.mjs → chunk-2AZQHBEF.mjs} +1 -1
- package/lib/{chunk-6VSZNZHH.mjs → chunk-2HVOZUM4.mjs} +1 -1
- package/lib/{chunk-XFU3HRUV.mjs → chunk-2JDAOWUW.mjs} +1 -1
- package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
- package/lib/chunk-2WFIVO4F.mjs +13 -0
- package/lib/chunk-2YHZBUZE.mjs +7 -0
- package/lib/{chunk-SZGGFST2.mjs → chunk-326AJTIU.mjs} +14 -14
- package/lib/{chunk-Q6SXNKV2.mjs → chunk-36JOHEJL.mjs} +1 -1
- package/lib/chunk-3PVRGTVK.mjs +7 -0
- package/lib/{chunk-VZVICK7Q.mjs → chunk-3Q353S2R.mjs} +1 -1
- package/lib/chunk-3TZSBHEY.mjs +7 -0
- package/lib/{chunk-UHFLKP26.mjs → chunk-43TOMFV4.mjs} +1 -1
- package/lib/{chunk-XK5W7BVE.mjs → chunk-4CVUUVGJ.mjs} +1 -1
- package/lib/{chunk-VYOYXTCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
- package/lib/{chunk-EOFO3PHS.mjs → chunk-4JE4BYXK.mjs} +1 -1
- package/lib/{chunk-7EYQYZJP.mjs → chunk-54WZUS7J.mjs} +1 -1
- package/lib/chunk-5CRLRHOJ.mjs +7 -0
- package/lib/{chunk-FA4ZKDCU.mjs → chunk-5IZTFMJM.mjs} +1 -1
- package/lib/chunk-5M5FQ7RP.mjs +7 -0
- package/lib/{chunk-3HROD5RE.mjs → chunk-5SMWFNE7.mjs} +1 -1
- package/lib/{chunk-YAIIRFKJ.mjs → chunk-5XTUSN72.mjs} +1 -1
- package/lib/chunk-6I6TWNV5.mjs +7 -0
- package/lib/{chunk-PYRZFUVU.mjs → chunk-6JWWSDM6.mjs} +1 -1
- package/lib/chunk-6O222PW6.mjs +7 -0
- package/lib/{chunk-2UU42PTD.mjs → chunk-6PD6K7LP.mjs} +1 -1
- package/lib/{chunk-GGUOIDWP.mjs → chunk-6QE6R6RL.mjs} +1 -1
- package/lib/{chunk-DJCGURW7.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
- package/lib/{chunk-DT3T7FRD.mjs → chunk-6YL7BNYD.mjs} +1 -1
- package/lib/chunk-6ZLKIT3H.mjs +7 -0
- package/lib/{chunk-CBL42DUU.mjs → chunk-7QYHEHMA.mjs} +1 -1
- package/lib/chunk-7SQSWVAU.mjs +9 -0
- package/lib/{chunk-ZUBBEP75.mjs → chunk-7UVKIWKV.mjs} +1 -1
- package/lib/{chunk-TWV4A5RK.mjs → chunk-7WATA4SB.mjs} +1 -1
- package/lib/chunk-7YNM6KFZ.mjs +7 -0
- package/lib/chunk-A3MYSOOC.mjs +7 -0
- package/lib/chunk-AL4C3GFT.mjs +7 -0
- package/lib/chunk-B3FBHVNN.mjs +21 -0
- package/lib/{chunk-27Z76O2O.mjs → chunk-B63POIPQ.mjs} +1 -1
- package/lib/{chunk-RTWYLOCA.mjs → chunk-BAWCOKRW.mjs} +1 -1
- package/lib/{chunk-NWOI25WY.mjs → chunk-BBRWFKS5.mjs} +1 -1
- package/lib/chunk-BEA27DLS.mjs +7 -0
- package/lib/chunk-BRY3PLIZ.mjs +7 -0
- package/lib/chunk-CBH3TOWK.mjs +341 -0
- package/lib/chunk-CPQIZGG5.mjs +7 -0
- package/lib/chunk-CVHNXJH3.mjs +7 -0
- package/lib/{chunk-HFUDCNU5.mjs → chunk-D4GF4FAB.mjs} +1 -1
- package/lib/chunk-DGDRQRCW.mjs +7 -0
- package/lib/{chunk-YAJQS3OL.mjs → chunk-DPMRIMUC.mjs} +1 -1
- package/lib/chunk-DUN2EPRC.mjs +7 -0
- package/lib/chunk-E3A3LOCY.mjs +7 -0
- package/lib/{chunk-TMA34QMA.mjs → chunk-EAC5QCE3.mjs} +1 -1
- package/lib/{chunk-VQJMP3DC.mjs → chunk-EC72TIEG.mjs} +1 -1
- package/lib/chunk-EPFCERGL.mjs +7 -0
- package/lib/{chunk-3MGMNK3Q.mjs → chunk-ETDCBLGU.mjs} +1 -1
- package/lib/{chunk-LXDSRP2W.mjs → chunk-F3AQW6IU.mjs} +1 -1
- package/lib/{chunk-A65ADTCR.mjs → chunk-FITPY3L4.mjs} +1 -1
- package/lib/chunk-FNJ4SGWO.mjs +7 -0
- package/lib/{chunk-SAMWHL22.mjs → chunk-FP7CYB2F.mjs} +1 -1
- package/lib/{chunk-JLZRZL5E.mjs → chunk-GKY2JMHY.mjs} +1 -1
- package/lib/chunk-GMIGWR6U.mjs +7 -0
- package/lib/{chunk-AUS6NFLZ.mjs → chunk-GNRSF65U.mjs} +1 -1
- package/lib/chunk-GOOVPVWX.mjs +7 -0
- package/lib/{chunk-PPHVWUFY.mjs → chunk-GWZRR3MM.mjs} +1 -1
- package/lib/{chunk-JH27IKCO.mjs → chunk-H2BHESDA.mjs} +2 -2
- package/lib/chunk-H33DVU3D.mjs +7 -0
- package/lib/chunk-H4CGM6YO.mjs +7 -0
- package/lib/{chunk-WOOUISSO.mjs → chunk-HCGXK7G7.mjs} +1 -1
- package/lib/{chunk-VZT4E2OJ.mjs → chunk-HIDW7FNV.mjs} +1 -1
- package/lib/chunk-HSBXRQTI.mjs +7 -0
- package/lib/chunk-HUZPBE47.mjs +7 -0
- package/lib/chunk-HV7VPEXP.mjs +7 -0
- package/lib/chunk-I6E6T6YY.mjs +7 -0
- package/lib/chunk-IUM4NFKI.mjs +10 -0
- package/lib/chunk-IVFVNNGB.mjs +37 -0
- package/lib/{chunk-5K2I2DMP.mjs → chunk-IZGCEOYO.mjs} +1 -1
- package/lib/{chunk-ZHIZY3ZC.mjs → chunk-J3DND3BC.mjs} +1 -1
- package/lib/{chunk-VPDEJGPS.mjs → chunk-JAEDM4SI.mjs} +1 -1
- package/lib/chunk-JCFBFF4Y.mjs +7 -0
- package/lib/{chunk-GBGHJTPC.mjs → chunk-JE6SCT6R.mjs} +1 -1
- package/lib/chunk-JGZPD4IM.mjs +7 -0
- package/lib/{chunk-C3LNYAVJ.mjs → chunk-JKJ74BX5.mjs} +1 -1
- package/lib/{chunk-EEFUE2ES.mjs → chunk-JLSIWO4Z.mjs} +1 -1
- package/lib/{chunk-3CX7GPCR.mjs → chunk-JSAJS3MY.mjs} +1 -1
- package/lib/chunk-JTJK2D36.mjs +7 -0
- package/lib/{chunk-V3R45ZWT.mjs → chunk-KAZS5Z6W.mjs} +1 -1
- package/lib/chunk-KB4ZHM4Q.mjs +10 -0
- package/lib/{chunk-J24TIGSI.mjs → chunk-KGU4SVIT.mjs} +1 -1
- package/lib/chunk-KJWFYBMU.mjs +15 -0
- package/lib/{chunk-H4JUYUSL.mjs → chunk-KZTZDC7H.mjs} +1 -1
- package/lib/chunk-L2E5WBGD.mjs +8 -0
- package/lib/{chunk-XU25YA46.mjs → chunk-L53JWJ3S.mjs} +1 -1
- package/lib/{chunk-Y4TDVDP2.mjs → chunk-LA4KIATH.mjs} +6 -6
- package/lib/chunk-LC3NDW4N.mjs +7 -0
- package/lib/{chunk-GCGHHN4K.mjs → chunk-LKTNQEBS.mjs} +1 -1
- package/lib/chunk-M2ABR4JM.mjs +7 -0
- package/lib/{chunk-3C2ZZIFN.mjs → chunk-M4BLK6HJ.mjs} +1 -1
- package/lib/{chunk-L4INJ5TZ.mjs → chunk-M6K34KGF.mjs} +1 -1
- package/lib/chunk-MDMPJEV3.mjs +7 -0
- package/lib/{chunk-32EUNQT6.mjs → chunk-MJZU3U5O.mjs} +68 -63
- package/lib/{chunk-PBE44M2Y.mjs → chunk-MSIEU5MR.mjs} +1 -1
- package/lib/{chunk-NLB3RGIY.mjs → chunk-N4WPCWJO.mjs} +1 -1
- package/lib/{chunk-SNEOKYV7.mjs → chunk-NCZKWSC7.mjs} +1 -1
- package/lib/{chunk-6KP6WETK.mjs → chunk-NED4MBIM.mjs} +1 -1
- package/lib/chunk-NOBQTEQD.mjs +7 -0
- package/lib/{chunk-RCYEBY42.mjs → chunk-NSQWI7ZY.mjs} +1 -1
- package/lib/{chunk-DBBPDSFN.mjs → chunk-O677VOGO.mjs} +1 -1
- package/lib/chunk-OFTT7J2M.mjs +7 -0
- package/lib/{chunk-C2N2TNEU.mjs → chunk-OLCVHL7I.mjs} +1 -1
- package/lib/chunk-OM5NORJG.mjs +7 -0
- package/lib/chunk-OMNMLKDT.mjs +7 -0
- package/lib/{chunk-CELEBWEZ.mjs → chunk-OPMO6I45.mjs} +1 -1
- package/lib/{chunk-LHU6CPGE.mjs → chunk-OUZQPYT3.mjs} +1 -1
- package/lib/chunk-OVNMB6Q2.mjs +7 -0
- package/lib/{chunk-6GQUZ4IP.mjs → chunk-PAXNWTYK.mjs} +1 -1
- package/lib/{chunk-XSKPYGMT.mjs → chunk-PBY2O6OF.mjs} +1 -1
- package/lib/chunk-PEDQPM2P.mjs +926 -0
- package/lib/chunk-PH7SP4YK.mjs +21 -0
- package/lib/{chunk-3SKLBRPL.mjs → chunk-PMN4PAC3.mjs} +1 -1
- package/lib/chunk-PMWAFDUB.mjs +48 -0
- package/lib/chunk-PPLVFX6N.mjs +7 -0
- package/lib/{chunk-STRMWSIQ.mjs → chunk-PR3XCSPO.mjs} +1 -1
- package/lib/{chunk-GJ6SZVHT.mjs → chunk-PR42EZSR.mjs} +1 -1
- package/lib/{chunk-YMDFF657.mjs → chunk-PWRJRL5U.mjs} +1 -1
- package/lib/{chunk-Q3DY7TO2.mjs → chunk-Q7GIJBCD.mjs} +1 -1
- package/lib/chunk-Q7TLC3I2.mjs +7 -0
- package/lib/{chunk-ZXFL2MSN.mjs → chunk-QAFPQ3YB.mjs} +1 -1
- package/lib/{chunk-T7WREYA5.mjs → chunk-QKEKG2LD.mjs} +1 -1
- package/lib/chunk-QO53K5W2.mjs +9 -0
- package/lib/{chunk-MUEQRIK7.mjs → chunk-QTG6LUZT.mjs} +1 -1
- package/lib/{chunk-KP5G6FUC.mjs → chunk-RE7RYF3B.mjs} +1 -1
- package/lib/{chunk-FOIWWK7G.mjs → chunk-RGBGUCJA.mjs} +1 -1
- package/lib/{chunk-DWMRIWV5.mjs → chunk-RGUQOSBU.mjs} +1 -1
- package/lib/{chunk-7PY3VQP3.mjs → chunk-RHNTHGNU.mjs} +1 -1
- package/lib/chunk-RKTFFCNS.mjs +7 -0
- package/lib/chunk-RMFU4BAL.mjs +28 -0
- package/lib/{chunk-KKOA62S4.mjs → chunk-ROV3QXEF.mjs} +14 -13
- package/lib/chunk-RT47RKLY.mjs +7 -0
- package/lib/{chunk-ZUTUYBNW.mjs → chunk-S42RBRH2.mjs} +1 -1
- package/lib/{chunk-Z42PHCVZ.mjs → chunk-SI267LYR.mjs} +1 -1
- package/lib/chunk-T3G6VZNS.mjs +7 -0
- package/lib/chunk-TNT27RBG.mjs +7 -0
- package/lib/chunk-UBIKR5VO.mjs +7 -0
- package/lib/chunk-UI3JQVRU.mjs +8 -0
- package/lib/{chunk-YT22LMF7.mjs → chunk-UIOMAX56.mjs} +1 -1
- package/lib/chunk-UX3BVH2Y.mjs +7 -0
- package/lib/chunk-VCUXCK36.mjs +7 -0
- package/lib/chunk-VINGECAJ.mjs +10 -0
- package/lib/chunk-VOXJHJIE.mjs +7 -0
- package/lib/chunk-W6PN6TJG.mjs +7 -0
- package/lib/{chunk-FKK5YBGZ.mjs → chunk-WAPSSYMT.mjs} +1 -1
- package/lib/{chunk-PR74GYVI.mjs → chunk-WUUKFE2U.mjs} +1 -1
- package/lib/chunk-WWTCWWZI.mjs +7 -0
- package/lib/chunk-WXDLQT2O.mjs +10 -0
- package/lib/chunk-WY5V5PR3.mjs +7 -0
- package/lib/chunk-X4BXESMQ.mjs +7 -0
- package/lib/chunk-XBQGZGWR.mjs +7 -0
- package/lib/chunk-XGGOUNPP.mjs +7 -0
- package/lib/chunk-XKWW3GKF.mjs +7 -0
- package/lib/{chunk-JJITOWZK.mjs → chunk-Y2DRK37K.mjs} +1 -1
- package/lib/{chunk-XZISAZA6.mjs → chunk-YA6ATMTB.mjs} +1 -1
- package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
- package/lib/chunk-YHR4WQPR.mjs +7 -0
- package/lib/{chunk-KJYEQHYP.mjs → chunk-YTLUYSMF.mjs} +1 -1
- package/lib/chunk-YWEQQL3C.mjs +8 -0
- package/lib/{chunk-PWVDNN2C.mjs → chunk-Z4LKKOFY.mjs} +1 -1
- package/lib/chunk-ZBAWJUG2.mjs +7 -0
- package/lib/{chunk-XO5FBOQF.mjs → chunk-ZJW6YOMV.mjs} +1 -1
- package/lib/chunk-ZQQXSCVI.mjs +7 -0
- package/lib/{chunk-47UHTN3Q.mjs → chunk-ZQWIVYVM.mjs} +1 -1
- package/lib/chunk-ZV7ZFQQC.mjs +9 -0
- package/lib/sandforge-autopilot.mjs +25 -25
- 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 +52 -21
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +4 -4
- package/lib/sandforge-env.mjs +106 -107
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +12 -12
- 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 +21 -23
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/compare.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-2JZGCCPG.mjs +0 -9
- package/lib/chunk-3HEMJTAP.mjs +0 -925
- package/lib/chunk-3XG25GTF.mjs +0 -7
- package/lib/chunk-42BFLWHR.mjs +0 -7
- package/lib/chunk-466F37VD.mjs +0 -7
- package/lib/chunk-4JKR4PTZ.mjs +0 -8
- package/lib/chunk-52EXDVPN.mjs +0 -7
- package/lib/chunk-7CVDVBEE.mjs +0 -7
- package/lib/chunk-7LKI7OAS.mjs +0 -7
- package/lib/chunk-7SDZR6SR.mjs +0 -7
- package/lib/chunk-A32ISQ6M.mjs +0 -28
- package/lib/chunk-A7JJWOLT.mjs +0 -7
- package/lib/chunk-BMTNTBBM.mjs +0 -7
- package/lib/chunk-BN33LVPQ.mjs +0 -7
- package/lib/chunk-BZ24IAP5.mjs +0 -7
- package/lib/chunk-CCEH7L53.mjs +0 -7
- package/lib/chunk-CV47FDQW.mjs +0 -7
- package/lib/chunk-CZLJZQCS.mjs +0 -7
- package/lib/chunk-DIL62SUN.mjs +0 -7
- package/lib/chunk-DIS254AN.mjs +0 -7
- package/lib/chunk-FZF23M6R.mjs +0 -7
- package/lib/chunk-G2JR3F63.mjs +0 -7
- package/lib/chunk-GGNUACTY.mjs +0 -7
- package/lib/chunk-GHPR5UVV.mjs +0 -7
- package/lib/chunk-HIHCYMSL.mjs +0 -7
- package/lib/chunk-HKUWHVI7.mjs +0 -9
- package/lib/chunk-HQQVANWQ.mjs +0 -20
- package/lib/chunk-IRZJU2PG.mjs +0 -22
- package/lib/chunk-ISSP2FZ5.mjs +0 -7
- package/lib/chunk-IVZJSDJD.mjs +0 -7
- package/lib/chunk-JESRFE2Z.mjs +0 -11
- package/lib/chunk-JFNLKHY6.mjs +0 -8
- package/lib/chunk-JKT5YAQ2.mjs +0 -7
- package/lib/chunk-JQZTMFO7.mjs +0 -7
- package/lib/chunk-KIMQQ6JQ.mjs +0 -7
- package/lib/chunk-LAUOSXMN.mjs +0 -341
- package/lib/chunk-MKTXJCXN.mjs +0 -10
- package/lib/chunk-O2PUGRNW.mjs +0 -10
- package/lib/chunk-O4BROUGM.mjs +0 -7
- package/lib/chunk-P55MKIZX.mjs +0 -37
- package/lib/chunk-P63WJMXQ.mjs +0 -7
- package/lib/chunk-PE435FVH.mjs +0 -15
- package/lib/chunk-PPGDAUEQ.mjs +0 -7
- package/lib/chunk-QAPVKPEC.mjs +0 -7
- package/lib/chunk-RLWB7F26.mjs +0 -7
- package/lib/chunk-RYRMUPMY.mjs +0 -7
- package/lib/chunk-SCKUIE3R.mjs +0 -7
- package/lib/chunk-SU65Z2BA.mjs +0 -7
- package/lib/chunk-TCBAE65A.mjs +0 -7
- package/lib/chunk-WEMLDUQA.mjs +0 -7
- package/lib/chunk-WSUKC2U3.mjs +0 -7
- package/lib/chunk-WT3SCUHS.mjs +0 -7
- package/lib/chunk-YGJF55VJ.mjs +0 -7
- package/lib/chunk-YH4DYI6D.mjs +0 -7
- package/lib/chunk-ZQO5PDX5.mjs +0 -48
- package/lib/chunk-ZUOPC4W2.mjs +0 -7
|
@@ -0,0 +1,37 @@
|
|
|
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{E as rs,s as Ko}from"./chunk-VINGECAJ.mjs";import{A as yn,G as ce,H as To,I as St,Q as Fo,e as yt,l as Ao,u as Io,v as jo,w as No,z as wn}from"./chunk-H4CGM6YO.mjs";import{e as bs,h as Rs}from"./chunk-TEIBWMJM.mjs";import{a as vo,b as Co}from"./chunk-T63U4OZJ.mjs";import{a as et,d as ts,i as ns,o as Te}from"./chunk-5XTUSN72.mjs";import{a as xo}from"./chunk-YYZL7UGV.mjs";import{a as yo,l as Oo}from"./chunk-YDXMTWAT.mjs";import{d as Po}from"./chunk-QIRO4HTE.mjs";import{b as Eo}from"./chunk-QSRAEUGZ.mjs";import{d as Ss}from"./chunk-H2BHESDA.mjs";import{t as Ae}from"./chunk-FP7CYB2F.mjs";import{a as _o,c as Do,d as At,e as Ee,f as Bo,g as $o,h as kt,i as Wo,j as qo,k as Uo,l as zo,m as Vo,n as Go,o as se,p as ie,q as It,r as we,s as Jo}from"./chunk-UI3JQVRU.mjs";import{d as bn,z as Ho}from"./chunk-KGU4SVIT.mjs";import{a as ho,b as Le,c as wo,d as X,h as fe}from"./chunk-JAEDM4SI.mjs";import{a as go}from"./chunk-5LFSFYFJ.mjs";import{Ec as hs,Fc as ws,Gc as ys,Hb as cs,Hc as pe,Nb as us,O as Xo,Ob as ls,P as On,Pb as fs,Q as es,Ua as Fe,Va as tt,Wa as Tt,Xa as os,Ya as ye,ib as ke,lb as ss,mb as is,wc as ps,xb as as,yb as ds,yc as ms,zc as gs}from"./chunk-KB4ZHM4Q.mjs";import{b as no,j as ro}from"./chunk-23SEDORH.mjs";import{b as Ot}from"./chunk-VV3B6IC3.mjs";import{f as Et}from"./chunk-RHNTHGNU.mjs";import{a as oo,b as so,c as pn,e as io,f as ao,g as co,i as mn,j as uo}from"./chunk-INIT2UKJ.mjs";import{a as So,c as hn,j as ko}from"./chunk-D4GF4FAB.mjs";import{f as po,g as mo}from"./chunk-YA6ATMTB.mjs";import{a as U,b as ue,c as jt,d as Rn,e as Yo,f as Nt,g as Zo,h as Sn,i as Qo}from"./chunk-TQ2TQHTT.mjs";import{g as fo}from"./chunk-OHEOJISY.mjs";import{c as lo}from"./chunk-EADHKH3A.mjs";import{b as eo,r as to}from"./chunk-M6K34KGF.mjs";import{A as qr,B as ln,C as Ur,F as zr,G as fn,J as Vr,K as Gr,O as Jr,R as Hr,S as Kr,T as Yr,U as Zr,V as Qr,W as Xr,e as un,q as de,r as oe,s as Me,x as $r,y as Wr}from"./chunk-TNT27RBG.mjs";import{a as xe,h as J}from"./chunk-TZE3Y7IQ.mjs";import{a as wt,b as H}from"./chunk-CA5NAXSU.mjs";import{a as Mo,b as Lo}from"./chunk-PC247GKX.mjs";import{a as bt,c as gn,f as bo,i as Rt,k as Ro}from"./chunk-S42RBRH2.mjs";import{Aa as Fr,Ac as Qe,Ba as Pr,Bc as pt,Ca as vr,Ec as Xe,Fc as cn,Gc as mt,Gd as Dr,Hd as Br,Lc as Ce,Mc as gt,O as Ze,Pc as ht,T as an,Ya as Cr,_ as dn,fd as Oe,sc as xr,ua as Se,ud as _r,va as Tr,yc as Mr,zc as Lr}from"./chunk-PMWAFDUB.mjs";import{b as W,e as te,f as Ke,i as Ne,k as Z,l as V,m as on,r as Er,s as sn,u as ve,v as Ye}from"./chunk-WZQEK4WT.mjs";function Ul(n){return`Salesforce can take several minutes to count a load in what ${n} says it has left: what runs from this machine wrote to it in the last ${no} minutes and it has not counted yet is taken off, a load from anywhere else is not`}function zl(n){return n.uncountedMB!==void 0&&n.uncountedMB>0?`, ${ps(n.uncountedMB)} MB for what runs from this machine wrote to it that Salesforce has not counted yet`:""}function As(n){if("unread"in n.storage)return n.withinMB===void 0?{unread:n.storage.unread}:Os(n,Math.floor(Math.max(0,n.withinMB)*1048576),{share:Fe,roundingMB:tt,withinMB:n.withinMB,limitedBy:"within"});let{remainingMB:e,maxMB:t,uncountedWrites:r}=n.storage,o=Fe*Tt(n.storage)*1048576,s=n.withinMB!==void 0?Math.max(0,n.withinMB)*1048576:1/0,i=s<o?"within":"storage",a={remainingMB:e,maxMB:t,share:Fe,roundingMB:tt,...r?{uncountedMB:r.mb}:{},...n.withinMB!==void 0?{withinMB:n.withinMB}:{},limitedBy:i},d=Math.floor(Math.min(o,s));return Os(n,d,a)}function ks(n,e){return e.bytesLimit==="within"&&e.storageBytes!==void 0&&n>e.storageBytes?"storage":e.bytesLimit}function Os(n,e,t){if(!n.api)return{bytes:e,terms:t};if("unread"in n.api)return{bytes:e,terms:t,requestsUnread:n.api.unread};let r=Object.values(n.otherRequests??{}).reduce((s,i)=>s+Math.max(0,i??0),0),o=Math.max(0,Math.floor(n.api.remaining-ke*n.api.max-r));return{bytes:e,terms:t,runRequests:o}}var ka=/__e$/i,Ia=/Share$/;function Vl(n,e){let t=new Map,r=new Map,o=(i,a)=>{let d=`${i}
|
|
8
|
+
${a}`,c=t.get(d);return c||(c={objectApiName:i,act:a,bytes:0,creates:[]},t.set(d,c)),c},s=i=>{r.set(`${i.objectApiName}
|
|
9
|
+
${i.kind}
|
|
10
|
+
${i.name}`,i)};for(let i of n.firing){let a=i.write;if(!(a!=="insert"&&a!=="update")&&e(i.objectApiName,a)){if(i.kind==="trigger"||!i.flow){s({objectApiName:i.objectApiName,kind:"trigger",name:i.name});continue}if(i.flow.condition!=="read"){s({objectApiName:i.objectApiName,kind:"notRead",name:i.name});continue}for(let d of i.flow.creates??[]){if(ka.test(d))continue;if(Ia.test(d)){s({objectApiName:i.objectApiName,kind:"share",name:d});continue}let c=o(i.objectApiName,a);c.bytes+=ye(d,{rows:1}),c.creates.push({objectApiName:d,by:i.name})}}}return{perRecord:[...t.values()].filter(i=>i.bytes>0),notCounted:[...r.values()]}}function Gl(n,e){return n.perRecord.reduce((t,r)=>t+r.bytes*Math.max(0,e(r.objectApiName,r.act)),0)}function Jl(n,e,t){return{budgetMB:Math.max(0,n.bytes-e)/1048576,...n.terms,automationMB:e/1048576,...t.notCounted.length>0?{notCounted:t.notCounted.map(r=>({...r}))}:{}}}function Is(n,e){if(!e(1))return 0;if(e(n))return n;let t=1,r=n;for(;r-t>1;){let o=Math.floor((t+r)/2);e(o)?t=o:r=o}return t}function Hl(n,e){let t=Math.max(0,Math.floor(n)),r=Math.min(t,Math.max(0,Math.floor(e))),o=[];if(r===0)return o;for(let s=0;s<t;s++)Math.floor((s+1)*r/t)>Math.floor(s*r/t)&&o.push(s);return o}import{existsSync as ja,readFileSync as Na,writeFileSync as Ea}from"node:fs";function Ql(n){let e={getData:()=>ja(n)?JSON.parse(Na(n,"utf8")):{},setData:r=>Ea(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384})},t=new rs(e);return t.initialize(),t}var An="User",Ta="005",Ns=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Fa(n,e,t=eo){let r=n.referenceTo??[];return n.name==="RecordTypeId"||r.length===0?!1:r.every(o=>t(o))?!0:r.length===1&&e?.(r[0])===!0}var js=1e5;async function rf(n){let{known:e,ownerMappings:t={},mapped:r,refused:o,inactive:s}=n,i=n.lookups.filter(m=>Fa(m,n.outsideTheRun,n.neverCopied)),a=new Map,d=new Set;for(let m of i)for(let g of n.rows){let h=g[m.name];if(typeof h!="string"||!Ns.test(h)||m.name==="OwnerId"&&t[h]!==void 0||r?.(h)===!0||(d.add(h),e.has(h)))continue;let y=m.referenceTo??[];if(!y.some(R=>o?.has(R)===!0))for(let R of y)a.set(R,(a.get(R)??new Set).add(h))}let c=new Set,f=new Set,l=new Set;for(let[m,g]of a){let h=s!==void 0&&m===An,y=h?"Id, IsActive":"Id";for(let R of X([...g]))try{let S=await n.query(`SELECT ${y} FROM ${J(m)} WHERE Id IN (${R})`);for(let w of S){let b=w.Id;typeof b=="string"&&(c.add(b),c.add(b.slice(0,15)),h&&w.IsActive===!1&&(l.add(b),l.add(b.slice(0,15))))}}catch{for(let S of g)f.add(S);o?.add(m);break}}let p=new Map;for(let m of a.values())for(let g of m)c.has(g)||c.has(g.slice(0,15))?p.set(g,!0):!f.has(g)&&!p.has(g)&&p.set(g,!1);for(let[m,g]of p){if(e.size>=js)break;e.set(m,g)}if(s&&l.size>0){let m=[...a.get(An)??[]].filter(g=>l.has(g)||l.has(g.slice(0,15)));for(let g of[...l,...m]){if(s.size>=js)break;s.add(g)}}let u=new Set;for(let m of d)(p.get(m)??e.get(m))===!1&&u.add(m);return u}function of(n,e,t={}){let r=new Set;if(e.size===0)return r;for(let o of n){let s=o.OwnerId;typeof s!="string"||!s||t[s]===void 0&&e.has(s)&&r.add(s)}return r}var Pa="SELECT PermissionsUpdateWithInactiveOwner FROM UserPermissionAccess";async function va(n){try{let[e]=await n(Pa);return e?.PermissionsUpdateWithInactiveOwner===!0}catch{return!1}}function sf(n){let e;return()=>(e??=va(n),e)}async function Es(n,e){let t=new Map;for(let[i,a]of Object.entries(n)){if(!Ns.test(a))continue;let d=a.slice(0,15),c=t.get(d)??{user:a,sources:[]};c.sources.push(i),t.set(d,c)}let r=[],o=[],s=[...t.values()];for(let i=0;i<s.length;i+=Le){let a=s.slice(i,i+Le),[d]=X(a.map(({user:l})=>l)),c;try{c=await e(`SELECT Id, Name, IsActive FROM ${An} WHERE Id IN (${d})`)}catch{continue}let f=new Set;for(let l of c){let p=l.Id;if(typeof p!="string"||(f.add(p.slice(0,15)),l.IsActive!==!1))continue;let u=t.get(p.slice(0,15));if(!u)continue;let m=l.Name;r.push({user:u.user,...typeof m=="string"&&m!==""?{name:m}:{},sources:u.sources})}for(let{user:l,sources:p}of a)l.startsWith(Ta)&&!f.has(l.slice(0,15))&&o.push({user:l,sources:p})}return{inactive:r,unknown:o}}var Ft=10,kn="Nothing was read or written.",uf="Nothing was written.";function Ts(n,e=kn){let t=n.slice(0,Ft).map(({user:o,name:s,sources:i})=>`${s!==void 0?`${s} (${o})`:o}, given the records of `+i.join(", ")).join("; "),r=n.length-Ft;return`Owners given to users the target holds inactive: ${t}${r>0?`; and ${r} more`:""}. The target refuses a record owned by an inactive user, and the run will not give it to the user it writes as instead of the one chosen. Give those records to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line), or reactivate the user in the target. `+e}function Ca(n,e=kn){let t=n.slice(0,Ft).map(({user:o,sources:s})=>`${o}, given the records of ${s.join(", ")}`).join("; "),r=n.length-Ft;return`Owners given to users the target does not hold: ${t}${r>0?`; and ${r} more`:""}. The target refuses a record owned by a user it does not hold (INVALID_CROSS_REFERENCE_KEY), and the run will not give it to the user it writes as instead of the one chosen. Give those records to a user of the target under Owners (Review \u2192 Controls, or --owner-map on the command line). `+e}async function lf(n,e,t=kn){let{inactive:r,unknown:o}=await Es(n,e);if(o.length>0){let s=Ca(o,t);return new pe(ys,r.length>0?`${s.slice(0,-t.length)}${Ts(r,t)}`:s)}return r.length>0?new pe(ws,Ts(r,t)):void 0}import{createHash as xa}from"node:crypto";var vs={ContentVersion:"VersionData",Attachment:"Body"},Ma=3,Fs=class extends Error{constructor(t,r,o){super(t);this.code=r;this.storage=o;this.name="ForgeFilesRefusedError"}code;storage};function Y(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function Ps(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function In(n,e,t){return{objectApiName:n,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:e,messages:[H(t)]}]}}async function bf(n){let{scope:e,sourceOrgId:t,maxFileBytes:r,queryRecords:o}=n,s=new Map;for(let l of e.values())for(let p of l)s.has(p)||s.set(p,s.size);let i={files:[],leftOut:[],errors:[]},a=[...s.keys()];if(a.length===0)return i;let d=l=>s.get(l)??Number.MAX_SAFE_INTEGER,c=new Map;try{for(let l of X(a)){let p=await o(t,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN (${l})`);for(let u of p){let m=Y(u,"ContentDocumentId"),g=Y(u,"LinkedEntityId");if(!m||!g||!s.has(g))continue;let h=c.get(m)??[];h.some(y=>y.id===g)||h.push({id:g,shareType:Y(u,"ShareType"),visibility:Y(u,"Visibility")}),c.set(m,h)}}}catch(l){i.errors.push(In("ContentDocument","(links of the records in scope)",l))}let f=[];try{for(let l of X([...c.keys()])){let p=await o(t,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SharingPrivacy FROM ContentVersion WHERE ContentDocumentId IN (${l}) AND IsLatest = true`);for(let u of p){let m=Y(u,"ContentDocumentId"),g=Y(u,"Id"),h=m?c.get(m):void 0;if(!m||!g||!h)continue;let y=Y(u,"Title")??m;f.push({external:(Y(u,"ContentLocation")??"S")!=="S",file:{objectApiName:"ContentDocument",sourceId:m,body:{objectApiName:"ContentVersion",id:g},name:y,bytes:Ps(u,"ContentSize"),hosts:[...h].sort((R,S)=>d(R.id)-d(S.id)),fields:{Title:y,PathOnClient:Y(u,"PathOnClient")??y,...Y(u,"SharingPrivacy")==="P"?{SharingPrivacy:"P"}:{}}}})}}}catch(l){i.errors.push(In("ContentDocument","(latest versions of the files)",l))}try{for(let l of X(a)){let p=await o(t,`SELECT Id, ParentId, Name, ContentType, BodyLength, IsPrivate FROM Attachment WHERE ParentId IN (${l})`);for(let u of p){let m=Y(u,"Id"),g=Y(u,"ParentId");if(!m||!g||!s.has(g))continue;let h=Y(u,"Name")??m;f.push({external:!1,file:{objectApiName:"Attachment",sourceId:m,body:{objectApiName:"Attachment",id:m},name:h,bytes:Ps(u,"BodyLength"),hosts:[{id:g}],fields:{Name:h,...Y(u,"ContentType")?{ContentType:Y(u,"ContentType")}:{},IsPrivate:u.IsPrivate===!0}}})}}}catch(l){i.errors.push(In("Attachment","(attachments of the records in scope)",l))}f.sort((l,p)=>d(l.file.hosts[0].id)-d(p.file.hosts[0].id));for(let{file:l,external:p}of f){let u=p?"external":l.bytes>r?"too-large":void 0;u?i.leftOut.push({objectApiName:l.objectApiName,sourceId:l.sourceId,name:l.name,bytes:l.bytes,reason:u}):i.files.push(l)}return i}function Rf(n){return n.errors.length===0?null:`The files of the records to clone could not all be looked up in the source (${[...new Set(n.errors.flatMap(t=>t.samples.flatMap(r=>r.messages)))].join("; ")}). Run it again, or leave the files out.`}async function Sf(n){let{files:e,targetOrgId:t,copiedBefore:r,queryRecords:o}=n,s={files:[],errors:[]},i=new Map;for(let u of e){let m=r(u.sourceId);m&&i.set(u.sourceId,m)}if(i.size===0)return{...s,files:[...e]};let a=new Map,d,c=new Map;for(let[u,m]of i)m.objectApiName==="ContentVersion"&&c.set(m.targetId,u),m.objectApiName==="ContentDocument"&&a.set(u,m.targetId);try{for(let u of X([...c.keys()])){let m=await o(t,`SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN (${u})`);for(let g of m){let h=Y(g,"Id"),y=Y(g,"ContentDocumentId"),R=h?c.get(h):void 0;R&&y&&a.set(R,y)}}}catch(u){d=H(u)}let f=new Map,l;try{for(let u of X([...new Set(a.values())])){let m=await o(t,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${u})`);for(let g of m){let h=Y(g,"ContentDocumentId"),y=Y(g,"LinkedEntityId");h&&y&&f.set(h,[...f.get(h)??[],y])}}}catch(u){l=H(u)}let p=(u,m)=>{s.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`${u.name} (${Oe(u.bytes)})`,messages:[m]}]})};for(let u of e){let m=i.get(u.sourceId);if(!m){s.files.push(u);continue}if(u.body.objectApiName==="Attachment")continue;let g=a.get(u.sourceId);if(!g){p(u,`Copied as ContentVersion ${m.targetId} by the run this one takes up, and its document still cannot be read back`+(d?` (${d})`:"")+": the file is not copied again, nor linked to the records it lacks.");continue}if(l){p(u,`Copied by the run this one takes up; its links could not be read (${l}): it is not linked to the records it lacks.`);continue}s.files.push({...u,into:{documentId:g,linked:f.get(g)??[],unchanged:!0}})}return s}function Of(n){return{objectApiName:"__files__",stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(files)",messages:[n]}]}}function Af(n){return n.reduce((e,t)=>e+t.bytes,0)}function kf(n,e){return n<=e?null:`The files to copy take ${Oe(n)} and the target has ${Oe(Math.max(0,e))} of file storage left. Lower the largest file copied, or leave the files out.`}async function If(n,e){let t=await n.remainingFileStorageMB(e);if(!Number.isFinite(t))throw new Error("The target did not say how much file storage it has left.");return t*1048576}function jf(n,e,t){let r=[];for(let o of n.files){let s=r.find(i=>i.objectApiName===o.objectApiName);s||(s={objectApiName:o.objectApiName,planned:0,plannedBytes:0,copied:0,failed:0},r.push(s)),s.planned++,s.plannedBytes+=o.bytes}return{maxFileBytes:e,objects:r,links:0,leftOut:[...n.leftOut],...t===void 0?{}:{remainingStorageBytes:t}}}function jn(n,e){let t=n==="Attachment"?"attachment":"file";return e===1?t:`${t}s`}function Nf(n){return`[dry-run] ${n.objectApiName}: ${n.planned} ${jn(n.objectApiName,n.planned)} would be copied (${Oe(n.plannedBytes)})`}function La(n,e,t){return n.body.objectApiName==="Attachment"?{Name:n.fields.Name??n.name,BodyLength:n.bytes,ParentId:t}:{Title:n.fields.Title??n.name,Checksum:xa("md5").update(Buffer.from(e,"base64")).digest("hex"),ContentSize:n.bytes}}function _a(n){let e={};for(let[t,r]of Object.entries(n))t!=="SharingPrivacy"&&(e[t]=r);return e}async function Ef(n){let{files:e,sourceOrgId:t,targetOrgId:r,remapper:o,deps:s,report:i,errors:a,onProgress:d,onCopied:c}=n,f=0,l=w=>{let b=i.objects.find(A=>A.objectApiName===w);return b||(b={objectApiName:w,planned:0,plannedBytes:0,copied:0,failed:0},i.objects.push(b)),b},p=(w,b)=>a.find(A=>A.objectApiName===w&&A.stage===b),u=new Map,m=(w,b,A=1)=>{let j=`${w}/${b}`;u.set(j,(u.get(j)??0)+A);let L=p(w,b);L&&(L.attemptedCount+=A)},g=(w,b,A,j,L=!1)=>{let v=p(w,b);v||(v={objectApiName:w,stage:b,failedCount:0,attemptedCount:u.get(`${w}/${b}`)??0,samples:[]},a.push(v)),L||(v.failedCount++,f++),v.samples.length<Ma&&v.samples.push({recordSummary:A,messages:[j]})},h=(w,b,A)=>{g(w.objectApiName,b,`${w.name} (${Oe(w.bytes)})`,A),l(w.objectApiName).failed++},y=async(w,b,A)=>{let j=A.flatMap(v=>{let P=o.get(v.id);return P?[{ContentDocumentId:b,LinkedEntityId:P,ShareType:v.shareType??"V",Visibility:v.visibility??"AllUsers"}]:[]});if(j.length===0)return[];let L=[];m("ContentDocumentLink","insert",j.length);try{let v=await s.insertRecords(r,"ContentDocumentLink",j);j.forEach((P,k)=>{let N=v[k];if(N?.success){i.links++,L.push(P.LinkedEntityId);return}g("ContentDocumentLink","insert",w.name,N?.errors.join("; ")||"The target gave no reason.")})}catch(v){for(let P=0;P<j.length;P++)g("ContentDocumentLink","insert",w.name,H(v))}return L},R=e.filter(w=>!(w.body.objectApiName==="ContentVersion"&&w.into?.unchanged)).length,S=0;for(let w of e){await n.waitIfPaused();let b=w.hosts.filter(O=>o.isCreated(O.id)),A=w.body.objectApiName==="ContentVersion"?w.into:void 0,j=A?b.filter(O=>{let C=o.get(O.id);return C!==void 0&&!A.linked.includes(C)}):[];if(A?.unchanged){let O=await y(w,A.documentId,j);O.length>0&&c?.(w,{targetId:A.documentId,linked:O,asVersion:!1});continue}let L=S++,v=b.length>0?o.get(b[0].id):void 0;if(!v&&!A){i.leftOut.push({objectApiName:w.objectApiName,sourceId:w.sourceId,name:w.name,bytes:w.bytes,reason:"record-not-created"});continue}d({objectName:w.objectApiName,status:"running",progress:Math.round(L/R*100),message:`Copying ${jn(w.objectApiName,1)} ${L+1} of ${R} (${Oe(w.bytes)})`});let P;m(w.objectApiName,"query");try{P=await s.readFileBody(t,w.body.objectApiName,w.body.id)}catch(O){h(w,"query",H(O));continue}let k=Buffer.byteLength(P,"base64");if(k!==w.bytes){h(w,"query",`Read ${k} bytes of the ${w.bytes} the source reports: the file was not written.`);continue}let N=A?{..._a(w.fields),VersionData:P,ContentDocumentId:A.documentId}:w.body.objectApiName==="ContentVersion"?{...w.fields,VersionData:P,FirstPublishLocationId:v}:{...w.fields,Body:P,ParentId:v},M;m(w.objectApiName,"insert");let D=n.calls?.sending(w.body.objectApiName,[{sourceId:w.sourceId,payload:La(w,P,v)}]),E=()=>{D!==void 0&&n.calls?.answered(D)};try{M=await s.insertFile(r,w.body.objectApiName,N)}catch(O){xo(O)!=="may-have-written"&&E(),h(w,"insert",H(O));continue}if(!M.success||!M.id){E(),h(w,"insert",M.errors.join("; ")||"The target gave no reason.");continue}if(l(w.objectApiName).copied++,w.body.objectApiName==="Attachment"){o.add(w.sourceId,M.id,"Attachment"),E(),o.persist?.(),c?.(w,{targetId:M.id,linked:v?[v]:[],asVersion:!1});continue}if(A){o.add(w.sourceId,A.documentId,"ContentDocument"),E(),o.persist?.();let O=await y(w,A.documentId,j);c?.(w,{targetId:A.documentId,linked:O,asVersion:!0});continue}o.add(w.sourceId,M.id,"ContentVersion"),E(),o.persist?.();let T;try{let O=await s.queryRecords(r,`SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${xe(M.id)}'`);T=O[0]?Y(O[0],"ContentDocumentId"):void 0}catch{T=void 0}if(!T){g("ContentDocument","query",`${w.name} (${Oe(w.bytes)})`,`Copied as ContentVersion ${M.id}, but its document could not be read back: the run keeps the version, which a removal of the run takes with its document, and links it to no other record.`,!0);continue}o.add(w.sourceId,T,"ContentDocument"),o.persist?.();let I=await y(w,T,b.slice(1));c?.(w,{targetId:T,linked:v?[v,...I]:I,asVersion:!1})}for(let w of i.objects)d({objectName:w.objectApiName,status:w.failed>0&&w.copied===0?"error":"done",progress:100,message:`Copied ${w.copied} ${jn(w.objectApiName,w.copied)} of ${w.planned}`+(w.failed>0?`, ${w.failed} failed`:"")});return f}function Mf(n,e,t={},r){if(!n)return;let o={};for(let s of e.nodes)ns(s)&&(o[s.objectApiName]=[...s.anonymizeFields]);return{fields:o,methods:{...t},...r?{personalFieldsOf:r}:{}}}var Da=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ba=/@example\.com$/i,Nn="@example.invalid",$a=64,Wa=new Set(["fake","mask","preserve_format","shuffle"]);function qa(n,e,t){return typeof n!="string"||n===""?n:Da.test(n)?e.email(n.replace(Ba,Nn),t):`${n.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,$a).replace(/^[._]+|[._]+$/g,"")||"anonymized"}${Nn}`}var Cs=class{smartAnonymizer;contactPoints;constructor(e,t){this.smartAnonymizer=new Po(e),this.contactPoints=new Rs(t)}categorizeField(e,t){let r=t.toLowerCase();if(r==="email")return"email";if(r==="phone")return"phone";let o=Co(e,t);if(o)return o;let s=e.toLowerCase();return s.includes("email")?"email":s.includes("phone")||s.includes("fax")||s.includes("mobile")?"phone":s.includes("firstname")||s.includes("lastname")||s==="name"||vo(e)?"name":s.includes("street")||s.includes("address")||s.includes("city")||s.includes("state")||s.includes("postalcode")||s.includes("zip")||s.includes("country")?"address":s.includes("ssn")||s.includes("national_id")||s.includes("passport")||s.includes("driver")||s.includes("license")?"ssn_id":s.includes("credit")||s.includes("card")||s.includes("cvv")||s.includes("iban")||s.includes("routing")||s.includes("bank")?"financial":"other"}getDefaultMethod(e){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}[e]}getDefaults(){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}}anonymize(e){if(e.fields.length===0)return e.records;let t={...this.getDefaults(),...e.methods},r=e.records.map((a,d)=>({...a,Id:e.sourceIds[d]??""})),o=this.anonymizeRecords(r,e.fields,t,e.objectApiName),s=e.fields.filter(a=>this.categorizeField(a.name,a.type)==="email"),i=Wa.has(t.phone)?e.fields.filter(a=>this.categorizeField(a.name,a.type)==="phone"):[];return o.map((a,d)=>{let c=e.records[d],f={...a};for(let l of s)f[l.name]=this.undeliverable(f[l.name],l);for(let l of i)f[l.name]=this.fictionalNumber(c[l.name],f[l.name],l);return"Id"in c?f.Id=c.Id:delete f.Id,f})}undeliverable(e,t){let r=t.length!==void 0&&t.length>0?t.length:void 0;return t.type.toLowerCase()==="email"?qa(e,this.contactPoints,r??bs):typeof e!="string"?e:this.contactPoints.addressesIn(e.replace(/@example\.com(?![\w.-])/gi,Nn),r)}fictionalNumber(e,t,r){if(typeof e!="string")return t;if(!/\d/.test(e))return e;let o=r.length!==void 0&&r.length>0?r.length:void 0;return this.contactPoints.phone(e,o)}anonymizeRecords(e,t,r,o){let s=t.map(a=>{let d=this.categorizeField(a.name,a.type);return{objectApiName:o,fieldApiName:a.name,method:r[d],piiCategory:"PII",aiConfidence:1,userOverridden:!1}}),i=e.map(a=>({...a}));return this.smartAnonymizer.anonymize(i,s,o)}};var xs=new WeakMap;function _f(n,e){typeof n=="object"&&n!==null&&xs.set(n,e)}function Df(n){return typeof n=="object"&&n!==null?xs.get(n):void 0}var En=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ms=/^[A-Za-z][A-Za-z0-9_]*$/;function nt(n){if(!n.startsWith('["'))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[t,r,o,s]=e;if(!(t!=="c"&&t!=="e"&&t!=="u")&&!(typeof r!="string"||!En.test(r))&&!(typeof o!="string"||!En.test(o)))return{tag:t,sourceId:r,targetId:o,object:typeof s=="string"&&Ms.test(s)?s:""}}function _e(n){if(!n.startsWith(`["${kt}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[,t,r]=e;if(!(typeof t!="string"||!Ms.test(t)||!Array.isArray(r)))return{object:t,ids:r.filter(o=>typeof o=="string"&&En.test(o))}}function rt(n){return n.slice(0,15)}var ot=class{offsets=new Float64Array(64);lengths=new Uint16Array(64);size=0;push(e,t){if(this.size===this.offsets.length){let r=new Float64Array(this.size*2);r.set(this.offsets),this.offsets=r;let o=new Uint16Array(this.size*2);o.set(this.lengths),this.lengths=o}this.offsets[this.size]=e,this.lengths[this.size]=t,this.size++}offsetAt(e){return this.offsets[e]}lengthAt(e){return this.lengths[e]}},be=class{capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);taken=new Uint8Array(this.capacity);add(e){let t=se(e),r=ie(e);if(this.slotOf(t,r)>=0)return;this.used+1>this.capacity*.6&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=t,this.h2[o]=r,this.taken[o]=1,this.used++}has(e){return this.slotOf(se(e),ie(e))>=0}get size(){return this.used}slotOf(e,t){let r=this.capacity-1;for(let o=t&r;;o=o+1&r){if(this.taken[o]===0)return-1;if(this.h1[o]===e&&this.h2[o]===t)return o}}freeSlotFor(e){let t=this.capacity-1,r=e&t;for(;this.taken[r]!==0;)r=r+1&t;return r}grow(){let{h1:e,h2:t,taken:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.taken=new Uint8Array(this.capacity);for(let o=0;o<r.length;o++){if(r[o]===0)continue;let s=this.freeSlotFor(t[o]);this.h1[s]=e[o],this.h2[s]=t[o],this.taken[s]=1}}},Ua=2e3,st=class n{constructor(e,t,r,o,s){this.file=e;this.all=t;this.mine=r;this.firstInPart=o;this.unattributed=s}file;all;mine;firstInPart;unattributed;static read(e,t){let r=(f,l)=>nt(e.read(f,l).toString("utf8"))?.sourceId??"",o=new It(r),s=new It(r),i=new ot,a=new ot,d=!1,c=-1;for(let f of we(e)){if(!d){if(!f.text.startsWith('{"run":'))return;d=!0;continue}if(f.text.startsWith('{"part":')){c++;continue}if(f.text.startsWith('{"object":'))return;if(c===t&&_e(f.text)){a.push(f.offset,f.length);continue}let l=nt(f.text);if(!l)continue;let p=se(l.sourceId),u=ie(l.sourceId);if(o.put(o.find(l.sourceId,p,u),p,u,f.offset,f.length,0),c!==t)continue;let m=s.find(l.sourceId,p,u);m<0&&i.push(f.offset,f.length);let g=l.tag==="c"&&l.object!=="";s.put(m,p,u,f.offset,f.length,g?1:0)}return d?new n(e,o,s,i,a):void 0}mappingAt(e,t){return nt(this.file.read(e,t).toString("utf8"))}wordsOn(e){let t=se(e),r=ie(e),o=this.all.find(e,t,r),s=this.mine.find(e,t,r);return{latest:o>=0?{offset:this.all.offsetOf(o),length:this.all.lengthOf(o)}:void 0,createdByThePart:s>=0&&this.mine.codeOf(s)===1,inThePart:s>=0?{offset:this.mine.offsetOf(s),length:this.mine.lengthOf(s)}:void 0}}createdByObject(){let e=new Map;for(let t=0;t<this.firstInPart.size;t++){let r=this.mappingAt(this.firstInPart.offsetAt(t),this.firstInPart.lengthAt(t));if(!r)continue;let o=this.wordsOn(r.sourceId);if(!o.createdByThePart||!o.latest||!o.inThePart)continue;let s=this.mappingAt(o.inThePart.offset,o.inThePart.length);if(!s)continue;let i=e.get(s.object)??new ot;i.push(o.latest.offset,o.latest.length),e.set(s.object,i)}return e}runRecords(e,t=Ua){let{file:r}=this,o=(g,h)=>nt(r.read(g,h).toString("utf8")),s=(g,h)=>{let y=o(g,h);return y?rt(y.targetId):""},i=new It(s),a=this.createdByObject(),d=[];for(let g of[...a.keys()].reverse()){let h=a.get(g);if(!h)continue;let y=0;for(let R=h.size-1;R>=0;R--){let S=h.offsetAt(R),w=o(S,h.lengthAt(R));if(!w||w.object==="")continue;let b=rt(w.targetId),A=se(b),j=ie(b),L=i.find(b,A,j);L>=0||(i.put(L,A,j,S,h.lengthAt(R),0),(!e||e.has(b))&&y++)}y>0&&d.push({objectApiName:g,count:y})}let c=(g,h)=>{let y=i.find(g,se(g),ie(g),h);return y>=0&&(h===void 0||i.offsetOf(y)===h)&&(!e||e.has(g))},f=g=>_e(r.read(this.unattributed.offsetAt(g),this.unattributed.lengthAt(g)).toString("utf8")),l=new be,p=this.unattributed.size,u=new Map;for(let g=0;g<p;g++){let h=f(g);if(h)for(let y of h.ids){let R=rt(y);l.has(R)||i.find(R,se(R),ie(R))>=0||(l.add(R),(!e||e.has(R))&&u.set(h.object,(u.get(h.object)??0)+1))}}for(let[g,h]of u){let y=d.find(R=>R.objectApiName===g);y?y.count+=h:d.unshift({objectApiName:g,count:h})}let m=g=>l.size>0&&l.has(g)&&(!e||e.has(g));return{objects:d,pages:async function*(g){let h=a.get(g),y=[];if(h)for(let R=h.size-1;R>=0;R--){let S=h.offsetAt(R),w=o(S,h.lengthAt(R));if(!w||w.object==="")continue;let b=rt(w.targetId);c(b,S)&&(y.push(w.targetId),y.length>=t&&(yield y,y=[]))}if(u.has(g)){let R=new be;for(let S=0;S<p;S++){let w=f(S);if(w?.object===g)for(let b of w.ids){let A=rt(b);R.has(A)||!m(A)||i.find(A,se(A),ie(A))>=0||(R.add(A),y.push(b),y.length>=t&&(yield y,y=[]))}}}y.length>0&&(yield y)},has:g=>c(g)||m(g)}}*idMapRows(){let e=new Map;for(let[r,o]of this.createdByObject())for(let s=0;s<o.size;s++){let i=this.mappingAt(o.offsetAt(s),o.lengthAt(s));i&&e.set(i.sourceId.slice(0,3),r)}let t=new Uint8Array(Math.ceil(this.all.slots/8));for(let r of we(this.file)){let o=nt(r.text);if(!o)continue;let s=this.all.find(o.sourceId,se(o.sourceId),ie(o.sourceId));if(s<0||(t[s>>3]&1<<(s&7))!==0)continue;t[s>>3]|=1<<(s&7);let i=this.wordsOn(o.sourceId);if(!i.latest)continue;let a=this.mappingAt(i.latest.offset,i.latest.length);if(!a||a.object==="")continue;yield{objectApiName:(i.createdByThePart&&i.inThePart?this.mappingAt(i.inThePart.offset,i.inThePart.length):void 0)?.object??e.get(a.sourceId.slice(0,3)),sourceId:a.sourceId,targetId:a.targetId,outcome:i.createdByThePart?"created":"linked to existing"}}}};var Ie=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,it=/^[A-Za-z][A-Za-z0-9_]*$/,za=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,Va=255,Ga=40,Ja=2*6e4,Ha=10*6e4;function Yf(n){let[e]=n;return e?Object.keys(e).filter(t=>t!=="Id"&&it.test(t)).filter(t=>n.every(r=>Ka(r[t]))).sort().slice(0,Ga):[]}function Ka(n){return typeof n=="string"?n.trim()!==""&&n.length<=Va:typeof n=="number"?Number.isFinite(n):typeof n=="boolean"}function Ya(n){if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number")return Number.isFinite(n)?String(n):"";if(typeof n!="string")return"";let e=n.trim();if(Ie.test(e))return e.slice(0,15);if(za.test(e)){let r=Date.parse(e);if(Number.isFinite(r))return new Date(r).toISOString()}if(e!==""&&Number.isFinite(Number(e)))return String(Number(e));let t=e.replace(/\s+/g," ").toLowerCase();return t.includes(";")?t.split(";").map(r=>r.trim()).sort().join(";"):t}function Fn(n,e){return Pn(e.map(t=>`${t}${Ya(n[t])}`).join(""))}function Pn(n){return se(n).toString(36).padStart(7,"0")+ie(n).toString(36).padStart(7,"0")}function Zf(n){let e=So("insert",n);return e.rows.map(t=>Pn(hn(e.columns.map((r,o)=>[r,t[o]??""]))))}var Za=/^sf__/;function Ls(n){let e=[];for(let[t,r]of Object.entries(n))Za.test(t)||e.push([t,typeof r=="string"?r:r==null?"":String(r)]);return Pn(hn(e))}function Ds(n,e){return Fn(n,[e])}function Qa(n,e){if(!Array.isArray(n))return!1;for(let t of n){if(!Array.isArray(t)||t.length<4)return!1;let[r,o,s,i]=t;if(typeof r!="number"||!Number.isInteger(r)||!e[r]||typeof o!="string"||!it.test(o)||typeof s!="string"||!Ie.test(s))return!1;e[r].owes.push({field:o,sourceRefId:s,...i===1?{insertOnly:!0}:{}})}return!0}function Tn(n){if(!n.startsWith(`["${At}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e)||e.length<6)return;let[,t,r,o,s,i,a,d]=e;if(typeof t!="string"||typeof r!="string"||!it.test(r)||typeof o!="string")return;let c=Date.parse(o);if(!Number.isFinite(c)||!Array.isArray(s)||!Array.isArray(i)||!s.every(p=>typeof p=="string"&&it.test(p))||d!==void 0&&(typeof d!="string"||!it.test(d)))return;let f=[];for(let p of i){if(!Array.isArray(p)||p.length<2)return;let[u,m,g,h]=p;if(typeof u!="string"||!Ie.test(u)||typeof m!="string"||g!==void 0&&typeof g!="string"||h!==void 0&&typeof h!="string")return;f.push({sourceId:u,fingerprint:m,owes:[],...typeof g=="string"&&g!==""?{externalKey:g}:{},...typeof h=="string"&&h!==""?{jobKey:h}:{}})}let l=a!==void 0;if(!(l&&!Qa(a,f)))return{callId:t,objectApiName:r,at:c,fields:s,rows:f,owesKept:l,...typeof d=="string"?{upsertField:d}:{}}}function Bs(n){if(n.startsWith(`["${Ee}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function Xa(n){if(n.startsWith(`["${$o}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function ed(n){if(n.startsWith(`["${Bo}"`))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r]=e;return typeof t!="string"||typeof r!="string"||r===""?void 0:{callId:t,jobId:r}}catch{return}}function td(n){if(!(!n.startsWith('["c"')&&!n.startsWith('["e"')&&!n.startsWith('["u"')))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r,o]=e;return typeof t!="string"||typeof r!="string"||!Ie.test(t)||!Ie.test(r)?void 0:{sourceId:t,targetId:r,object:typeof o=="string"?o:""}}catch{return}}function nd(n){let e=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(n);return e?Date.parse(e[1]):Number.NaN}function Qf(n,e={}){return{queryPages:t=>lo({query:async r=>n.query(r),queryMore:async r=>n.queryMore(r)},t),userId:async()=>(await n.identity()).user_id,serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp,readJob:t=>Oo(Ao(n),t,e.leaveOpen?{leaveOpen:!0}:{})}}function rd(){return{calls:0,found:[],notFound:[],uncertain:[],unread:[]}}function K(n,e,t=1){if(t<=0)return;let r=n.find(o=>o.objectApiName===e);r?r.rows+=t:n.push({objectApiName:e,rows:t})}function _s(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function vn(n,e,t){return[JSON.stringify(["c",e.sourceId,t,n.objectApiName,n.owesKept?Uo:qo]),...e.owes.map(({field:r,sourceRefId:o,insertOnly:s})=>Go({objectApiName:n.objectApiName,newId:t,sourceId:e.sourceId,fieldName:r,sourceRefId:o,...s?{insertOnly:s}:{}}))]}function od(n,e,t,r){let{call:o,rows:s,read:i}=n,{objectApiName:a}=o,d=JSON.stringify([Ee,o.callId]);if(i.state==="never-closed")return K(r.notFound,a,s.length),{lines:[d],taken:[]};if(i.state==="running")return K(r.uncertain,a,s.length),(r.underway??=[]).push({objectApiName:a,jobId:n.jobId,rows:s.length,...i.info?{state:i.info.state}:{},...i.info?.numberRecordsProcessed!==void 0?{processed:i.info.numberRecordsProcessed}:{},...i.openUntil?{openUntil:i.openUntil}:{},...i.graceLeftMs!==void 0?{graceLeftMs:i.graceLeftMs}:{}}),{lines:[],taken:[]};if(i.state==="unread")return r.unread.push({objectApiName:a,reason:i.reason}),K(r.uncertain,a,s.length),{lines:[],taken:[]};let c=o.upsertField===void 0&&s.every(l=>l.jobKey!==void 0)?sd(o,s,i.results,e,t,r):id(o,s,i.results,e,t,r),f=Date.parse(i.info.systemModstamp??"");return!n.endKept&&c.taken.length>0&&Number.isFinite(f)&&c.lines.unshift(zo(o.callId,n.jobId,new Date(f).toISOString(),new Date(f-n.ahead).toISOString())),c}function sd(n,e,t,r,o,s){let{objectApiName:i}=n,a=new Map,d=new Set;for(let S of t.successfulResults??[]){let w=S.sf__Id,b=Ls(S);if(typeof w!="string"||!Ie.test(w)){d.add(b);continue}let A=w.slice(0,15);r.has(A)&&!o.has(A)||a.set(b,[...a.get(b)??[],w])}let c=new Set,f=t.unprocessedRecords;for(let S of[...t.failedResults??[],...Array.isArray(f)?f:[]])c.add(Ls(S));let l=new Map;for(let S of e){let w=S.jobKey??"";l.set(w,[...l.get(w)??[],S])}let p=[],u=[],m=[],g=0,h=!1,y=0;for(let[S,w]of l){let b=a.get(S)??[];a.delete(S);let A=d.delete(S);if(w.length===1&&b.length===1&&!A){p.push(...vn(n,w[0],b[0])),u.push(b[0]),K(s.found,i);continue}if(b.length>0||A){K(s.uncertain,i,w.length),w.length>1&&K(s.untold??=[],i,w.length),A||(y+=w.length),m.push(...b),h=!0;continue}if(w.length>1||c.has(S)){K(s.notFound,i,w.length);continue}g+=w.length}let R=d.size>0;for(let S of a.values())m.push(...S),S.length>0&&(R=!0);return g>0&&(K(R?s.uncertain:s.notFound,i,g),R&&(h=!0,d.size===0&&(y+=g))),y>0&&K(s.ofEndedJobs??=[],i,y),p.push(...$s(n,m,o,h,s)),{lines:p,taken:[...u,...m]}}function $s(n,e,t,r,o){e.length>0&&K(o.unattributed??=[],n.objectApiName,e.length);let s=e.filter(i=>!t.has(i.slice(0,15)));return[...s.length>0?[JSON.stringify([kt,n.objectApiName,s])]:[],...r?[]:[JSON.stringify([Ee,n.callId])]]}function id(n,e,t,r,o,s){let{objectApiName:i}=n,a=n.upsertField,d=new Map;for(let h of t.successfulResults??[]){let y=h.sf__Id;if(typeof y!="string"||!Ie.test(y))continue;let R=y.slice(0,15);if(r.has(R)&&!o.has(R)||a!==void 0&&String(h.sf__Created).toLowerCase()!=="true")continue;let S=a!==void 0?Ds(h,a):Fn(h,n.fields);d.set(S,[...d.get(S)??[],y])}let c=new Map;for(let h of e){let y=a!==void 0?h.externalKey??"":h.fingerprint;c.set(y,[...c.get(y)??[],h])}let f=[],l=[],p=[],u=0,m=!1;for(let[h,y]of c){let R=h===""?[]:d.get(h)??[];if(d.delete(h),R.length===0){u+=y.length;continue}if(y.length===1&&R.length===1){f.push(...vn(n,y[0],R[0])),l.push(R[0]),K(s.found,i);continue}K(s.uncertain,i,y.length),K(s.ofEndedJobs??=[],i,y.length),y.length>1&&K(s.untold??=[],i,y.length),p.push(...R),m=!0}let g=!1;for(let h of d.values())p.push(...h),h.length>0&&(g=!0);return u>0&&(K(g?s.uncertain:s.notFound,i,u),g&&(m=!0,K(s.ofEndedJobs??=[],i,u))),f.push(...$s(n,p,o,m,s)),{lines:f,taken:[...l,...p]}}function Ws(n){let e=new Set;for(let t of we(n)){let r=Bs(t.text);if(r!==void 0)e.delete(r);else{let o=t.text.startsWith(`["${At}"`)?Tn(t.text):void 0;o&&e.add(o.callId)}}return e.size}async function qs(n,e,t=()=>new Date,r={}){let o=rd(),s=new Map,i=new Map,a=new Set,d=Number.NEGATIVE_INFINITY;for(let b of we(n)){let A=Bs(b.text);if(A!==void 0){s.delete(A);continue}let j=ed(b.text);if(j){i.set(j.callId,j.jobId);continue}let L=Xa(b.text);if(L!==void 0){a.add(L);continue}if(b.text.startsWith(`["${At}"`)){let v=Tn(b.text);v&&(s.set(v.callId,{offset:b.offset,length:b.length}),d=Math.max(d,v.at));continue}if(b.text.startsWith("{")){let v=nd(b.text);Number.isFinite(v)&&(d=Math.max(d,v))}}if(s.size===0)return o;let c=[];for(let{offset:b,length:A}of s.values()){let j=Tn(n.read(b,A).toString("utf8"));j&&c.push(j)}o.calls=c.length;let f=new Set(c.map(b=>b.objectApiName)),l=new Set(c.flatMap(b=>b.rows.map(A=>A.sourceId)));o.lookedFor=l;let p=new Set,u=new be,m=new be;for(let b of we(n)){let A=_e(b.text);if(A){if(f.has(A.object))for(let L of A.ids)u.add(L.slice(0,15)),m.add(L.slice(0,15));continue}let j=td(b.text);j&&(l.has(j.sourceId)&&p.add(j.sourceId),(j.object===""||f.has(j.object))&&u.add(j.targetId.slice(0,15)))}let g=0;if(e.serverTime)try{let b=t().getTime(),A=Date.parse(await e.serverTime());Number.isFinite(A)&&(g=A-(b+t().getTime())/2)}catch{}let h,y,R=[],S=e.readJob?.bind(e),w=new Set;if(S)for(let b of c){let A=i.get(b.callId);if(A===void 0)continue;w.add(b.callId);let j=b.rows.filter(v=>!p.has(v.sourceId));if(j.length===0){R.push(JSON.stringify([Ee,b.callId]));continue}let L=od({call:b,rows:j,jobId:A,read:await S(A),ahead:g,endKept:a.has(b.callId)},u,m,o);R.push(...L.lines);for(let v of L.taken)u.add(v.slice(0,15))}for(let b of f){let A=c.filter(O=>O.objectApiName===b&&!w.has(O.callId));if(A.length===0)continue;let j=A.map(O=>({call:O,rows:O.rows.filter(C=>!p.has(C.sourceId))})),L=j.reduce((O,{rows:C})=>O+C.length,0);if(L===0){for(let{call:O}of j)R.push(JSON.stringify([Ee,O.callId]));continue}let v=new Map;for(let O of A)v.set(O.fields.join(","),O.fields);let P=[...new Set(A.flatMap(O=>O.upsertField?[O.upsertField]:[]))],k=[...new Set([...A.flatMap(O=>O.fields),...P])].sort(),N;try{if(h===void 0&&y===void 0)try{h=await e.userId()}catch(x){y=H(x)}if(h===void 0)throw new Error(`the user the run writes as is not known: ${y}`);let O=Math.min(...A.map(x=>x.at))+g-Ja,C=d+g+Ha,B=k.includes("CreatedDate")?"SystemModstamp":"CreatedDate",F=k.includes("CreatedById")?"":`CreatedById = '${h}' AND `,_=`SELECT ${["Id",...k.filter(x=>x!=="Id")].join(", ")} FROM ${J(b)} WHERE ${F}${B} >= ${_s(O)} AND ${B} <= ${_s(C)} ORDER BY Id`;N=[];for await(let x of e.queryPages(_))for(let $ of x){let q=$.Id;if(typeof q!="string"||!Ie.test(q)||u.has(q.slice(0,15)))continue;let Q=new Map;for(let[je,he]of v)Q.set(je,Fn($,he));let Re=new Map;for(let je of P)Re.set(je,Ds($,je));N.push({id:q,fingerprints:Q,externalKeys:Re,taken:!1})}}catch(O){o.unread.push({objectApiName:b,reason:H(O)}),K(o.uncertain,b,L);continue}N.sort((O,C)=>O.id<C.id?-1:O.id>C.id?1:0);let M=new Map;for(let O of v.keys()){let C=new Map;for(let B of N){let F=B.fingerprints.get(O)??"",_=C.get(F)??[];_.push(B),C.set(F,_)}M.set(O,C)}let D=(O,C,B)=>{B.taken=!0,R.push(...vn(O,C,B.id)),K(o.found,b)},E=new Set;for(let{call:O,rows:C}of j){let B=O.upsertField;if(B===void 0)continue;let F=new Map;for(let x of N){let $=x.externalKeys.get(B);x.taken||$===void 0||F.set($,[...F.get($)??[],x])}let _=new Map;for(let x of C){let $=x.externalKey??"";_.set($,[..._.get($)??[],x])}for(let[x,$]of _){let q=x===""?[]:F.get(x)??[];if(x===""||$.length>1||q.length>1){K(o.uncertain,b,$.length),E.add(O.callId);continue}q.length===1?D(O,$[0],q[0]):K(o.notFound,b)}}let T=[];for(let{call:O,rows:C}of j){if(O.upsertField!==void 0)continue;let B=O.fields.join(","),F=new Map;for(let _ of C){let x=F.get(_.fingerprint)??[];x.push(_),F.set(_.fingerprint,x)}for(let[_,x]of F){let $=(M.get(B)?.get(_)??[]).filter(q=>!q.taken);if($.length>x.length){for(let q of x)T.push({callId:O.callId,sourceId:q.sourceId});E.add(O.callId);continue}$.forEach((q,Q)=>D(O,x[Q],q));for(let q of x.slice($.length))T.push({callId:O.callId,sourceId:q.sourceId})}}let I=N.some(O=>!O.taken);for(let O of T)I||E.has(O.callId)?(K(o.uncertain,b),E.add(O.callId)):K(o.notFound,b);for(let{call:O}of j)E.has(O.callId)||R.push(JSON.stringify([Ee,O.callId]))}return R.length>0&&r.keep!==!1&&n.append(`${R.join(`
|
|
11
|
+
`)}
|
|
12
|
+
`),o}function Xf(n,e,t="resume"){if(n.calls===0)return[];let r=i=>i.map(({objectApiName:a,rows:d})=>`${d} ${a}`).join(", "),o={resume:"kept as written by the run and not written again",removal:"kept as written by the run and removed with its records",preview:"which a removal keeps as written by the run and removes with its records, not counted here"}[t],s=[`${n.calls} insert or upsert call(s) were under way when the run stopped, their answer never kept: their rows were looked for in ${e}`+(t==="preview"?", as a removal looks for them first":"")];n.found.length>0&&s.push(` found in ${e}, ${o}: ${r(n.found)}`),n.notFound.length>0&&s.push(t==="resume"?` not in ${e}, written by the resume: ${r(n.notFound)}`:` not in ${e}, nothing of them to remove: ${r(n.notFound)}`),n.uncertain.length>0&&s.push(` may already be in ${e}: ${r(n.uncertain)}`);for(let i of n.underway??[])s.push(` ${dd(i,t==="resume"?"resume":"removal")}`);for(let{objectApiName:i,rows:a}of n.untold??[])s.push(` ${i}: ${a} row(s) the journal cannot tell apart, several under one fingerprint, under which the Bulk API job wrote records: none of those records is linked to a row`);(n.unattributed??[]).length>0&&s.push(` written by a Bulk API job and matched to no row, ${t==="resume"?"kept as written by the run":o}: `+r(n.unattributed??[]));for(let{objectApiName:i,reason:a}of n.unread)s.push(` ${i} could not be read in ${e}: ${a}`);return s}function ad(n){return Math.max(1,Math.ceil(n/6e4))}function dd(n,e){let t=`${n.objectApiName}: Bulk API job ${n.jobId} is ${n.state??"not ended"}`+(n.processed!==void 0?`, ${n.processed} row(s) processed`:"");if(n.state==="Open"){let r=n.openUntil!==void 0?` from ${n.openUntil}`+(n.graceLeftMs!==void 0&&n.graceLeftMs>0?`, in about ${ad(n.graceLeftMs)} minute(s),`:""):" an hour after it was opened";return`${t}: the run stopped before it closed it, and closed, it would still write them; ${e==="resume"?"a resume":"a removal"}${r} aborts it if it is open still`+(e==="resume"?", then writes its rows":"")}return`${t}: the org writes it to its end whatever became of the run; `+(e==="resume"?"a resume once it has ended reads what it wrote":"a removal once it has ended takes what it wrote")}function cd(n){return n.uncertain.reduce((e,{rows:t})=>e+t,0)}function ep(n){let e=(n.ofEndedJobs??[]).reduce((t,{rows:r})=>t+r,0);return Math.max(0,cd(n)-e)}import{createReadStream as ud}from"node:fs";import{appendFile as ld,mkdir as fd,readdir as pd,rename as md,rm as Us}from"node:fs/promises";import*as ae from"node:path";import{createInterface as gd}from"node:readline";var hd=10*6e4;function lp(n){return new Ln({storagePath:n,appendFile:(e,t)=>ld(e,t,"utf8"),readLines:e=>wd(e),mkdir:async e=>{await fd(e,{recursive:!0})},rm:e=>Us(e,{force:!0}),rename:(e,t)=>md(e,t),listFiles:e=>pd(e).catch(t=>{if(t.code==="ENOENT")return[];throw t}),openRunFile:e=>_o(e),rmDir:e=>Us(e,{recursive:!0,force:!0})})}async function*wd(n){let e=ud(n,{encoding:"utf8"}),t=gd({input:e,crlfDelay:1/0});try{for await(let r of t)yield r}catch(r){if(r.code!=="ENOENT")throw r}finally{t.close(),e.destroy()}}var fp=5e4,pp=2e3,ee=W().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),xt=W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),yd=V({sourceOrgId:W().min(1).max(128),fingerprint:W().regex(/^[a-f0-9]{64}$/),targetSalesforceOrgId:ee.optional(),recordId:ee.optional(),muteAutomation:Ye(!0).optional(),files:vr.optional()}),bd=V({graph:Fr,config:Tr,anonymizationRules:Pr.optional()});function zs(n){let e=yd.safeParse(n);if(!e.success)return;let t=bd.safeParse(n.startedWith);return{...e.data,...t.success?{startedWith:t.data}:{}}}var Pt=V({run:V({journalId:W().min(1).max(200),targetOrgId:W().min(1).max(128),startedAt:W().min(1).max(40),resume:Ne().optional(),runUserId:Ne().optional()})}),Vs=V({objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),reason:W().max(2e3),...Cr}),Gs=V({checkpoint:V({state:Ye("taken"),checkpointId:W().min(1).max(200),name:W().max(500),takenAt:W().min(1).max(40),expiresAt:W().min(1).max(40).nullable(),objects:Z(W().regex(/^[A-Za-z][A-Za-z0-9_]*$/)),records:te().nonnegative(),bytes:te().nonnegative(),requests:te().nonnegative(),added:Z(Vs),notHeld:Z(Vs)})}),Rd=V({part:V({n:te().int().nonnegative(),startedAt:W().max(40).optional()})}),Cn=V({end:V({status:ve(["success","cancelled","failure","interrupted"]),forgeId:W().min(1).max(200),at:W().max(40).optional()})}),Sd=V({object:xt,created:Z(Er([ee,ee]))});function xn(n){return ee.safeParse(n).success?n:void 0}function De(n){return n.replace(/\.ndjson$/,"")+".end.json"}function vt(n){return n.replace(/\.ndjson$/,"")+".checkpoint.json"}function Ct(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.left`}function Js(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.stamps`}var Od=W().max(40).refine(n=>Number.isFinite(Date.parse(n)),"not a date"),Be=1e4;function Ad(n,e){let t=n.map(s=>({...s,ids:[...s.ids]}));if(!e||e.length===0)return t;let r=new Set(n.flatMap(({ids:s})=>s.map(i=>i.slice(0,15)))),o=[];for(let{objectApiName:s,ids:i}of e){let a=i.filter(c=>!r.has(c.slice(0,15)));for(let c of a)r.add(c.slice(0,15));if(a.length===0)continue;let d=t.find(c=>c.objectApiName===s);d?d.ids.push(...a):o.push({objectApiName:s,ids:a})}return[...o,...t]}function Mn(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}var Ln=class{constructor(e){this.deps=e;this.dir=ae.join(e.storagePath,"forge-runs")}deps;dir;get storagePath(){return this.deps.storagePath}pathOf(e){return ae.join(this.dir,`${Mn(e)}.ndjson`)}filePath(e){return this.pathOf(e)}async begin(e,t,r,o,s){await this.deps.mkdir(this.dir);let i=xn(s),a={run:{journalId:e,targetOrgId:t,startedAt:r.toISOString(),...o?{resume:o}:{},...i?{runUserId:i}:{}}};await this.deps.appendFile(this.filePath(e),`${JSON.stringify(a)}
|
|
13
|
+
`)}async keepCheckpoint(e,t){let r=Gs.safeParse({checkpoint:t});if(!r.success)return;let o=vt(this.filePath(e));await this.deps.rm(o),await this.deps.appendFile(o,`${JSON.stringify(r.data)}
|
|
14
|
+
`)}async checkpointAt(e){for await(let t of this.deps.readLines(vt(e)))if(t.trim()!=="")try{let r=Gs.safeParse(JSON.parse(t));return r.success?r.data.checkpoint:void 0}catch{return}}open(e){return this.openAt(this.filePath(e))}openAt(e){return Jo.open(this.deps.openRunFile(e))}reconcile(e,t){return this.reconcileAt(this.filePath(e),t)}async reconcileAt(e,t,r={}){let o=this.deps.openRunFile(e);try{return await qs(o,t,void 0,r)}finally{o.close()}}writeBoundsAt(e,t){let r=this.deps.openRunFile(e);try{let o,s,i,a,d=-1,c,f,l=Number.NEGATIVE_INFINITY,p=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY,m=new Map;for(let h of we(r)){let y=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(h.text)?.[1],R=h.text.startsWith('["x"')?/^\["x","[^"]*","[^"]*","([^"]+)"/.exec(h.text)?.[1]:void 0,S=Vo(h.text);for(let v of[y,R,S?.at]){let P=v===void 0?Number.NaN:Date.parse(v);Number.isFinite(P)&&(l=Math.max(l,P))}if(S){let v=Date.parse(S.orgAt);Number.isFinite(v)&&(p=Math.max(p,v),d===t&&(u=Math.max(u,v)));continue}if(h.text.startsWith('{"part":')&&d++,!h.text.startsWith('["c"')&&!h.text.startsWith('["p"')&&!h.text.startsWith('["g"'))continue;let w;try{w=JSON.parse(h.text)}catch{continue}if(!Array.isArray(w))continue;let[b,A,j,L]=w;if(b==="c"){if(!ee.safeParse(j).success||!xt.safeParse(L).success)continue;let v={objectApiName:String(L),id:String(j)};o??=v,s=v,d===t&&(i??=v,a=v),m.set(String(j).slice(0,3),String(L))}else if(b==="g"){if(!ee.safeParse(j).success||!xt.safeParse(A).success)continue;c={objectApiName:String(A),id:String(j)},f=void 0}else ee.safeParse(A).success&&(f=String(A))}let g=f?m.get(f.slice(0,3)):void 0;return f&&g&&(c={objectApiName:g,id:f}),{...o?{first:o}:{},...s?{lastCreated:s}:{},...i?{firstInPart:i}:{},...a?{lastCreatedInPart:a}:{},...c?{lastUpdated:c}:{},...Number.isFinite(l)?{lastAt:new Date(l).toISOString()}:{},...Number.isFinite(p)?{jobEnded:new Date(p).toISOString()}:{},...Number.isFinite(u)?{jobEndedInPart:new Date(u).toISOString()}:{}}}finally{r.close()}}writtenBetween(e,t,r,o="run"){return this.writtenBetweenAt(this.filePath(e),t,r,o)}async writtenBetweenAt(e,t,r,o="run"){let s=this.writeBoundsAt(e,r),{firstInPart:i,lastCreatedInPart:a,lastAt:d}=s,[c,f,l]=o==="part"?[i,a,void 0]:[s.first,s.lastCreated,s.lastUpdated];if(!c||!f)return;let p=async({objectApiName:S,id:w},b)=>{try{let j=(await t.query(`SELECT ${b} FROM ${J(S)} WHERE Id = '${w}'`)).records[0]?.[b],L=typeof j=="string"?Date.parse(j):Number.NaN;return Number.isFinite(L)?L:void 0}catch{return}},u=d===void 0?Number.NaN:Date.parse(d)+hd,m=await p(c,"CreatedDate")??(i&&i.id!==c.id?await p(i,"CreatedDate"):void 0),g=[],h=a?.id!==f.id?a:void 0;for(let S of[f,h]){let w=S?await p(S,"CreatedDate"):void 0;if(S&&w!==void 0&&m!==void 0&&w<m){let b=await p(S,"SystemModstamp");w=b!==void 0&&b>=m&&(!Number.isFinite(u)||b<=u)?b:void 0}w!==void 0&&g.push(w)}let y=g.length>0?Math.max(...g):void 0;if(m===void 0||y===void 0||y<m)return;if(l){let S=await p(l,"LastModifiedDate");S!==void 0&&S>y&&(!Number.isFinite(u)||S<=u)&&(y=S)}let R=Date.parse((o==="part"?s.jobEndedInPart:s.jobEnded)??"");return Number.isFinite(R)&&R>y&&(y=R),{first:new Date(m).toISOString(),last:new Date(y).toISOString()}}callsInFlight(e){return this.callsInFlightAt(this.filePath(e))}callsInFlightAt(e){let t=this.deps.openRunFile(e);try{return Ws(t)}finally{t.close()}}stop(e,t,r){return this.stopAt(this.filePath(e),t,r)}async stopAt(e,t,r){let o=`${JSON.stringify({end:{status:t,forgeId:r,at:new Date().toISOString()}})}
|
|
15
|
+
`;await this.deps.appendFile(e,o),await this.deps.rm(De(e)),await this.deps.appendFile(De(e),o)}resuming(e){return this.resumingAt(this.filePath(e))}resumingAt(e){return this.deps.rm(De(e))}lastEnd(e){return this.lastEndAt(this.filePath(e))}async lastEndAt(e){for await(let t of this.deps.readLines(De(e)))if(t.trim()!=="")try{let r=Cn.safeParse(JSON.parse(t));return r.success?r.data.end:void 0}catch{return}}async partsOf(e){let t=new Set,r;for await(let o of this.deps.readLines(this.filePath(e)))if(o.trim()!==""){if(!r){try{let s=Pt.safeParse(JSON.parse(o));if(!s.success||s.data.run.journalId!==e)return[];r=s.data.run}catch{return[]}continue}if(o.startsWith('{"end":'))try{let s=Cn.safeParse(JSON.parse(o));s.success&&t.add(s.data.end.forgeId)}catch{}}return[...t]}async wroteIn(e,t){let r=new Set,o=!1,s=-1;for await(let i of this.deps.readLines(this.filePath(e)))if(i.trim()!==""){if(!o){try{let a=Pt.safeParse(JSON.parse(i));if(!a.success||a.data.run.journalId!==e)return[]}catch{return[]}o=!0;continue}if(i.startsWith('{"part":')){if(s++,s>t)break;continue}if(!(s!==t||!(i.startsWith('["p"')||i.startsWith('["g"'))))try{let a=JSON.parse(i);if(!Array.isArray(a))continue;let d=a[0]==="p"?a[1]:a[2];ee.safeParse(d).success&&r.add(String(d))}catch{}}return[...r]}async end(e){let t=this.filePath(e);await this.deps.rm(t),await this.deps.rm(De(t)),await this.deps.rm(vt(t));let r=`${ae.basename(t).replace(/\.ndjson$/,"")}.part`;for(let o of await this.deps.listFiles(this.dir))o.startsWith(r)&&(o.endsWith(".left")||o.endsWith(".stamps"))&&await this.deps.rm(ae.join(this.dir,o));await this.deps.rmDir?.(Ss(this.deps.storagePath,e))}fileNameOf(e){return`${Mn(e)}.ndjson`}async present(e){let t=new Set(await this.deps.listFiles(this.dir));return new Set(e.filter(r=>t.has(this.fileNameOf(r))))}async endedFiles(){let e=await this.deps.listFiles(this.dir),t=new Set(e.filter(r=>r.endsWith(".end.json")));return e.filter(r=>r.endsWith(".ndjson")&&t.has(r.replace(/\.ndjson$/,".end.json")))}async forgetFile(e){let t=ae.join(this.dir,e),r=await this.headAt(t);r?await this.end(r.journalId):(await this.deps.rm(t),await this.deps.rm(De(t)),await this.deps.rm(vt(t)))}async idsOf(e,t){let r=this.filePath(e),o=await this.readAt(r,"all");if(o?.journalId!==e)return;let s=await this.readAt(r,t);if(!s)return;let i=new Set(s.remap.createdByObject.flatMap(({sourceIds:a})=>a));return{table:o.remap.table,createdByObject:s.remap.createdByObject,existing:Object.keys(o.remap.table).filter(a=>!i.has(a)),...s.remap.withTheirRecord?{withTheirRecord:s.remap.withTheirRecord}:{}}}async keepLeft(e,t,r){let o=Ct(this.filePath(e),t);await this.deps.rm(o);for(let s=0;s<r.length;s+=Be)await this.deps.appendFile(o,`${r.slice(s,s+Be).join(`
|
|
16
|
+
`)}
|
|
17
|
+
`);r.length===0&&await this.deps.appendFile(o,"")}async recordsOf(e,t,r=!1){if(!await this.head(e))return;let o=r?void 0:await this.leftKeysOf(e,t),s=this.deps.openRunFile(this.filePath(e)),i=st.read(s,t);if(!i){s.close();return}return{records:i.runRecords(o),close:()=>s.close()}}async idMapRowsOf(e,t){if(!await this.head(e))return;let r=this.deps.openRunFile(this.filePath(e)),o=st.read(r,t);if(!o){r.close();return}return{rows:o.idMapRows(),close:()=>r.close()}}async leftKeysOf(e,t){let r=Ct(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return;let s=new be;for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.add(a.slice(0,15))}return s}async keepLeftPages(e,t,r){let o=Ct(this.filePath(e),t),s=this.deps.rename,i=s?`${o}.next`:o;await this.deps.rm(i),await this.deps.appendFile(i,"");let a=new Map;for await(let{objectApiName:d,ids:c}of r)if(c.length!==0){a.set(d,(a.get(d)??0)+c.length);for(let f=0;f<c.length;f+=Be)await this.deps.appendFile(i,`${c.slice(f,f+Be).join(`
|
|
18
|
+
`)}
|
|
19
|
+
`)}return s&&await s(i,o),[...a].map(([d,c])=>({objectApiName:d,count:c}))}async stampsOf(e,t){let r=Js(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return{};let s={};for await(let i of this.deps.readLines(r)){let[a,d]=i.trim().split(" ");ee.safeParse(a).success&&Od.safeParse(d).success&&(s[a]=d)}return s}async keepStamps(e,t,r){if(Object.keys(r).length===0)return;let o=Js(this.filePath(e),t),s=Object.entries({...await this.stampsOf(e,t),...r}),i=this.deps.rename,a=i?`${o}.next`:o;await this.deps.rm(a);for(let d=0;d<s.length;d+=Be){let c=s.slice(d,d+Be).map(([f,l])=>`${f} ${l}`);await this.deps.appendFile(a,`${c.join(`
|
|
20
|
+
`)}
|
|
21
|
+
`)}i&&await i(a,o)}async leftOf(e,t){let r=Ct(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return;let s=[];for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.push(a)}return s}async head(e){let t=await this.headAt(this.filePath(e));return t?.journalId===e?t:void 0}async headAt(e){for await(let t of this.deps.readLines(e)){if(t.trim()==="")continue;let r;try{r=JSON.parse(t)}catch{return}let o=Pt.safeParse(r);if(!o.success)return;let{resume:s,runUserId:i,...a}=o.data.run,d=zs(s),c=xn(i);return{...a,...d?{resume:d}:{},...c?{runUserId:c}:{}}}}async read(e){let t=await this.deps.listFiles(this.dir),r=`${Mn(e)}.ndjson`;if(!t.includes(r))return;let o=await this.readAt(ae.join(this.dir,r));return o?.journalId===e?o:void 0}readAt(e,t="last"){return this.readFile(e,t)}async leftOver(e=new Set){let t=[],r=await this.deps.listFiles(this.dir),o=new Set(r.filter(s=>s.endsWith(".end.json")));for(let s of r){if(!s.endsWith(".ndjson")||o.has(s.replace(/\.ndjson$/,".end.json")))continue;let i=await this.readFile(ae.join(this.dir,s),"last");!i||e.has(i.journalId)||i.lastEnd||t.push(i)}return t}static planOf(e,t=e.journalId){let r=Ad(e.created,e.unattributed);if(r.length!==0)return{forgeId:t,targetOrgId:e.targetOrgId,timestamp:e.startedAt,duration:0,status:"partial",objects:r,linked:0}}forget(e){return this.end(e)}async readFile(e,t){let r,o=0,s,i,a,d=new Map,c=new Map,f=new Set,l,p=()=>{o++,i=s,s=void 0,t==="last"&&(d=new Map,c=new Map,f=new Set)},u=()=>typeof t!="number"||o-1===t;for await(let j of this.deps.readLines(e)){if(j.trim()==="")continue;let L;try{L=JSON.parse(j)}catch{continue}if(!r){let N=Pt.safeParse(L);if(!N.success)return;r=N.data.run;continue}if(Array.isArray(L)){let N=_e(j);if(N){if(!u())continue;let I=c.get(N.object)??new Set;for(let O of N.ids)I.add(O);c.set(N.object,I);continue}let[M,D,E,T]=L;if(M===Wo){u()&&ee.safeParse(D).success&&f.add(String(D));continue}if(M!=="c"&&M!=="e"&&M!=="u"||!u()||!ee.safeParse(D).success||!ee.safeParse(E).success)continue;d.set(String(D),{targetId:String(E),object:typeof T=="string"&&xt.safeParse(T).success?T:"",created:M==="c"});continue}if(typeof L=="object"&&L!==null&&"roots"in L){l=Do(L.roots)??l;continue}let v=Rd.safeParse(L);if(v.success){p(),a=v.data.part.startedAt;continue}let P=Cn.safeParse(L);if(P.success){s=P.data.end;continue}let k=Sd.safeParse(L);if(k.success){if(o===0&&p(),!u())continue;for(let[N,M]of k.data.created)d.set(N,{targetId:M,object:k.data.object,created:!0})}}if(!r)return;let m=zs(r.resume),g=xn(r.runUserId),h=await this.checkpointAt(e),y={},R=new Map,S=[];for(let[j,{targetId:L,object:v,created:P}]of d){if(!v)continue;if(y[j]=L,!P){S.push(j);continue}let k=R.get(v)??[];k.push(j),R.set(v,k)}let w=[...R].map(([j,L])=>({objectApiName:j,sourceIds:L})),b=new Set([...d.values()].filter(({created:j})=>j).map(({targetId:j})=>j.slice(0,15))),A=[...c].map(([j,L])=>({objectApiName:j,ids:[...L].filter(v=>!b.has(v.slice(0,15)))})).filter(({ids:j})=>j.length>0);return{journalId:r.journalId,targetOrgId:r.targetOrgId,startedAt:r.startedAt,...m?{resume:m}:{},...g?{runUserId:g}:{},...h?{checkpoint:h}:{},...l?{roots:l}:{},parts:o,partStartedAt:a??r.startedAt,...s?{lastEnd:s}:{},...i?{endBefore:i}:{},created:_r({idRemapTable:y,idRemapExisting:S,idRemapCreated:w}),remap:{table:y,createdByObject:w,linked:S,...S.some(j=>f.has(j))?{withTheirRecord:S.filter(j=>f.has(j))}:{}},...A.length>0?{unattributed:A}:{}}}};import{randomBytes as kd}from"node:crypto";import{chmod as Id,open as jd,readFile as Nd,readdir as Ed,rename as Td,rm as Hs,stat as Fd}from"node:fs/promises";import{dirname as Pd,join as Dn}from"node:path";var vd=1440*6e4,Cd="forge-roots",xd=/^[A-Za-z0-9_-]{1,128}$/,We=class extends Error{constructor(t,r){super(r);this.fault=t;this.name="RootPlanError"}fault},Md=on({where:W().min(1).max(512).optional(),orderBy:W().min(1).max(200).optional(),limit:te().int().min(1).max(dn).optional()}),Ks=on({version:Ye(1),sourceOrgId:W().min(1).max(128),fingerprint:W().max(128),objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),query:Md.optional(),from:ve(["query","records"]),readAt:W().refine(n=>Number.isFinite(Date.parse(n)),"not a date"),ids:Z(W().refine(es,"not a record id")).max(dn),sha256:W().regex(/^[0-9a-f]{64}$/)});function Ys(n){return Dn(n,Cd)}function Sp(n,e){if(!xd.test(e))throw new We("gone","Not the fingerprint of a setup of a run.");return Dn(Ys(n),`${e}.json`)}function _n(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Op(n,e){let t=Xo(e.ids),r={version:1,sourceOrgId:e.sourceOrgId,fingerprint:e.fingerprint,objectApiName:e.objectApiName,...e.query!==void 0?{query:{...e.query}}:{},from:e.from,readAt:e.readAt,ids:t,sha256:On(t)},o=Ks.parse(r);await Ho(Pd(n));let s=`${n}.${process.pid}-${kd(4).toString("hex")}.tmp`;try{let i=await jd(s,"wx",bn);try{await i.writeFile(`${JSON.stringify(o)}
|
|
22
|
+
`,"utf8")}finally{await i.close()}await Id(s,bn),await Td(s,n)}catch(i){throw await Hs(s,{force:!0}),i}return o}async function Ld(n){let e;try{e=await Nd(n,"utf8")}catch(r){throw _n(r)?new We("gone",`No plan of roots is at ${n}.`):r}let t;try{t=Ks.parse(JSON.parse(e))}catch{throw new We("changed",`The plan of roots at ${n} no longer reads as one.`)}if(On(t.ids)!==t.sha256)throw new We("changed",`The ids of the plan of roots at ${n} are no longer those it was kept with.`);return t}function Ap(n,e){return e.getTime()-Date.parse(n.readAt)}async function kp(n,e){let t=Ys(n),r;try{r=await Ed(t)}catch(s){if(_n(s))return 0;throw s}let o=0;for(let s of r){let i=Dn(t,s),a;try{a=Date.parse((await Ld(i)).readAt)}catch{try{a=(await Fd(i)).mtimeMs}catch(d){if(_n(d))continue;throw d}}e.getTime()-a<vd||(await Hs(i,{force:!0}),o++)}return o}import{createHash as _d}from"node:crypto";function Dd(n,e){return Qs(n,e,t=>t.included||Dr(t))}function Bd(n,e){if(n!==void 0)return{...$n(n),...e?{planSha256:e}:{}}}function $n(n){let e=Object.entries(n.rootWhere??{}).map(([r,o])=>[r,o.trim()]),t=[...new Set(n.strata??[])].sort();return{...n.withinMB!==void 0?{withinMB:n.withinMB}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},seed:n.seed??Se.seed,draw:n.draw??Se.draw,parents:n.parents??Se.parents,children:n.children??Se.children,floor:n.floor??Se.floor,whole:[...new Set(n.whole??[])].sort(),...n.window?{window:$d(n.window)}:{},...e.length>0?{rootWhere:Object.fromEntries(e)}:{},...t.length>0?{strata:t}:{}}}function $d(n){return{field:n.field,...n.from!==void 0?{from:n.from}:{},...n.to!==void 0?{to:n.to}:{},...n.lastDays!==void 0?{lastDays:n.lastDays}:{}}}function Mt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Zs(n){if(!Mt(n))return n;let e=typeof n.planSha256=="string"?n.planSha256:void 0;return Bd(n,e)}function Wd(n){if(!Mt(n))return n;let e=n.config;return{...n,..."sample"in n?{sample:Zs(n.sample)}:{},..."roots"in n?{roots:qd(n.roots)}:{},...Mt(e)&&"sample"in e?{config:{...e,sample:Zs(e.sample)}}:{}}}function qd(n){if(!Mt(n))return n;let{objectApiName:e,sha256:t}=n;return typeof e!="string"||typeof t!="string"?n:{objectApiName:e,sha256:t}}function Ep(n,e,t){return n===Dd(e,t)||n===Qs(e,t,r=>r.included)}function Qs(n,e,t){let r=n.nodes.map(s=>({objectApiName:s.objectApiName,included:t(s),anonymizeFields:[...s.anonymizeFields??[]].sort()})).sort((s,i)=>s.objectApiName.localeCompare(i.objectApiName)),o=n.edges.map(s=>({sourceObject:s.sourceObject,targetObject:s.targetObject,relationshipName:s.relationshipName,required:s.required===!0})).sort((s,i)=>`${s.sourceObject}|${s.targetObject}|${s.relationshipName}`.localeCompare(`${i.sourceObject}|${i.targetObject}|${i.relationshipName}`));return _d("sha256").update(Bn({nodes:r,edges:o,setup:Wd(e)})).digest("hex")}function Bn(n){return Array.isArray(n)?`[${n.map(e=>Bn(e??null)).join(",")}]`:n!==null&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${Bn(r)}`).join(",")}}`:JSON.stringify(n??null)}function Cp(n){let e={filters:Object.keys(n.objectSoqlFilters??{}).sort(),excluded:[...new Set(n.excludedObjects??[])].sort(),heldBack:[...new Set((n.skippedRows??[]).map(t=>t.object))].sort(),fieldsLeftOut:Object.entries(n.fieldExclusions??{}).filter(([,t])=>t.length>0).map(([t])=>t).sort()};return n.sample?{...e,sample:$n(n.sample)}:Object.values(e).some(t=>t.length>0)?e:void 0}var qn=class extends Error{constructor(t){super("The dry run of a clone of the whole org stops at its write gate: nothing was read past the counts, nothing written.");this.dryRun=t;this.name="WholeOrgDryRunStop"}dryRun},Ud="NOTHING_TO_CLONE";function xp(n){if(n.nodes.some(t=>t.included))return;let e=new Set([...n.nodes.filter(t=>t.leftOutByUser===!0).map(t=>t.objectApiName),...(n.leftOut??[]).filter(t=>t.reason==="excludedByUser").map(t=>t.objectApiName)]).size;return{code:Ud,message:e>0?`Nothing to clone: every object of the source that holds records is left out, ${e} of them by name. Leave fewer out. Nothing was written.`:"Nothing to clone: no object of the source holds records the target can take. Nothing was written."}}function Mp(n){return n instanceof qn||n instanceof Error&&n.name==="WholeOrgDryRunStop"&&"dryRun"in n}function Wn(n){return n.verdict==="unread"?{estimate:n.estimate,unread:n.unread}:{estimate:n.estimate,remaining:n.remaining,max:n.max,...n.verdict==="near"?{near:!0}:{}}}function Lp(n){return{api:n.targetRequests,wholeOrg:{source:n.sourceRequests,...n.bulkBatches?{bulkBatches:n.bulkBatches}:{},cost:{durationSeconds:n.durationSeconds}}}}function zd(n,e){let t=a=>a.reduce((d,c)=>d+c.rows,0),r=n.objects.reduce((a,d)=>a+d.sourceRows,0)+n.noRecordDrawn.reduce((a,d)=>a+d.sourceRows,0),o=t(n.leftEmpty),{plan:s}=n,i=Date.parse(s.drawnAt);return{rows:n.rows,objects:n.objects.length,sourceRows:r,storageMB:n.storageBytes/1048576,budgetMB:n.budget.bytes/1048576,...n.budget.automationMB!==void 0&&n.budget.automationMB>0?{automationMB:n.budget.automationMB}:{},seed:n.seed,draw:n.draw,share:n.share,limitedBy:n.budget.limitedBy,parents:n.parents,children:n.children,drawnAt:s.drawnAt,drawnBy:s.drawnBy,...s.drawnBy==="dryRun"&&Number.isFinite(i)?{minutesBefore:Math.max(1,Math.ceil((e-i)/6e4))}:{},...s.drawnAgain?{drawnAgain:s.drawnAgain}:{},...s.ofTheRunRetried?{ofTheRunRetried:!0}:{},...o>0?{leftEmpty:o}:{},...n.heavyRoots.length>0?{heavyRoots:n.heavyRoots.length}:{},...n.noRecordDrawn.length>0?{noRecordDrawn:n.noRecordDrawn.length}:{},...n.newestByIds&&n.newestByIds.length>0?{newestByIds:[...n.newestByIds]}:{},...n.oldestByIds&&n.oldestByIds.length>0?{oldestByIds:[...n.oldestByIds]}:{},...n.roots?{roots:Vd(n.roots)}:{}}}function Vd(n){return{...n.window?{window:{...n.window}}:{},...n.where&&n.where.length>0?{where:n.where.map(({objectApiName:e,where:t})=>({objectApiName:e,where:t}))}:{},...n.strata&&n.strata.length>0?{strata:n.strata.map(({objectApiName:e,field:t,values:r,more:o})=>({objectApiName:e,field:t,values:r.length+(o??0)}))}:{},...n.notWindowed&&n.notWindowed.length>0?{notWindowed:[...n.notWindowed]}:{}}}function _p(n){let{run:e,measures:t,plan:r,budget:o}=n,s=new Set(r.objects.filter(({rows:g})=>g>0).map(({objectApiName:g})=>g)),i=t.writes.filter(({rows:g})=>g>0),a=g=>i.reduce((h,y)=>h+y[g],0),d=a("jobs"),c=[...s].filter(g=>to(g)!==void 0).sort(),f=us(e.graph.nodes,s,e.anonymizePII),l=n.files&&"check"in n.files?n.files:void 0,p=l?.check,u=t.contactPointsBlanked??0,m=o.wholeOrg.bulkBatches;return{source:e.source,leftOut:ls(e.graph).objects.length,...e.carried?{carried:e.carried}:{},...n.sample?{sample:zd(n.sample,n.now??Date.now())}:{},targetApi:Wn(o.api),sourceApi:Wn(o.wholeOrg.source),...d>0?{bulk:{jobs:d,jobRows:a("jobRows"),restRows:a("restRows"),...m?{batches:Wn(m)}:{}}}:{},durationSeconds:o.wholeOrg.cost.durationSeconds,restObjects:i.filter(g=>g.jobs===0).map(g=>g.objectApiName),...l&&p&&p.verdict!=="unread"?{fileStorage:{files:l.count,estimateMB:p.estimateMB,overCeiling:t.files&&"overCeiling"in t.files?t.files.overCeiling:0,remainingMB:p.remainingMB,maxMB:p.maxMB,...p.verdict==="near"?{near:!0}:{}}}:{},...c.length>0?{managedPackages:c}:{},...u>0?{contactPointsBlanked:u}:{},...f.length>0?{personalAsIs:f}:{}}}var Gd=10*6e4,Jd=3e4,Hd=5e3,Xs=500,Kd=new Set(["JobComplete","Failed","Aborted"]),ei=class{constructor(e,t={}){this.stateOf=e;this.options=t}stateOf;options;kept=[];noted=0;get count(){return this.noted}note(e){this.noted++,this.kept.push({seq:this.noted,job:{...e}}),this.kept.length>Xs&&this.kept.splice(0,this.kept.length-Xs)}since(e,t){return this.kept.filter(({seq:r,job:o})=>r>e&&o.orgId===t).map(({job:r})=>({...r}))}async stillRunning(e,t){let r=this.options.now??(()=>Date.now()),o=this.options.sleep??(c=>new Promise(f=>setTimeout(f,c))),s=this.options.pollDelay??ko,i=r()+(this.options.waitMs??Gd),a=e.filter(c=>c.jobId===void 0),d=e.filter(c=>!!c.jobId);for(let c=0;d.length>0;c++){let f=new Ot(Math.max(1,Math.min(Jd,i-r())));d=(await Promise.all(d.map(async u=>{t?.();let m=await f.withTimeout("forge:lost-bulk-job",()=>this.stateOf(u.orgId,u.jobId)).catch(()=>{});return m!==void 0&&Kd.has(m)?void 0:u}))).filter(u=>u!==void 0);let p=i-r()-Hd;if(d.length===0||p<=0)break;await o(Math.min(s(c),p))}return[...a,...d]}};function Wp(n){let e=new Map;for(let{objectApiName:t,jobId:r}of n)e.set(t,[...e.get(t)??[],{recordSummary:r?`Bulk API job ${r}`:"Bulk API job (the org gave no id)",messages:[r?"Still being written by the org when the run gave back the mute of its automation, after waiting for it: the rows it wrote from then went in with the flows, triggers and rules the mute kept quiet. Look the job up in the target\u2019s Bulk Data Load Jobs.":"Closed before the org gave its id, so it could not be waited for: the rows it wrote after the run gave back the mute of its automation went in with the flows, triggers and rules the mute kept quiet."]}]);return[...e].map(([t,r])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:r}))}var Yd="SELECT SobjectType FROM DuplicateRule WHERE IsActive = true",Up=new Set(["Account","Contact","Lead"]);function zp(n){if(typeof n.unread=="string")return;let e=n;if(e.unread.some(o=>o.part==="duplicateRules"))return;let t=new Map(e.objects.map(o=>[o.objectApiName.toLowerCase(),o.duplicateRules])),r=new Map;for(let o of e.objectsRead){let s=o.toLowerCase();if(!t.has(s)){r.set(o,!1);continue}let i=t.get(s);i!==void 0&&r.set(o,i.length>0)}return r}async function Vp(n){try{let e=await n.query(Yd);return new Set(e.records.flatMap(t=>typeof t.SobjectType=="string"?[t.SobjectType]:[]))}catch{return}}var ti=class{constructor(e=3){this.maxDiscoveries=e}maxDiscoveries;discoveries=new Map;awaitingGuard=new Map;run=null;beginDiscovery(e,t,r){let o=[],s=c=>{this.discoveries.delete(c.requestId),c.stop="superseded",o.push(c)},i=this.discoveries.get(e);i&&s(i);let a=[...this.discoveries.values()].filter(c=>!c.controller.signal.aborted);for(;a.length>=this.maxDiscoveries;){let c=a.shift();c&&s(c)}let d={requestId:e,controller:t,operationId:r};return this.discoveries.set(e,d),{discovery:d,superseded:o}}endDiscovery(e){this.discoveries.get(e.requestId)===e&&this.discoveries.delete(e.requestId)}awaitGuard(e,t){return this.awaitingGuard.set(e,t),()=>{this.awaitingGuard.get(e)===t&&this.awaitingGuard.delete(e)}}beginRun(e,t){this.run={requestId:e,controller:t}}endRun(e){this.run?.requestId===e&&(this.run=null)}resolve(e){let t=e===void 0?this.onlyLive():this.named(e);return"refused"in t?t:(t.kind==="discovery"&&(this.discoveries.delete(t.discovery.requestId),t.discovery.stop="stopped"),{stops:t})}stop(e,t){let r=this.resolve(e);if("refused"in r)return r;let o=r.stops;return o.kind==="discovery"?t.discovery(o.discovery):o.kind==="awaiting-guard"?o.controller.abort():t.run(),r}named(e){let t=this.discoveries.get(e);if(t)return{kind:"discovery",discovery:t};let r=this.awaitingGuard.get(e);return r?{kind:"awaiting-guard",controller:r}:this.run?.requestId===e?{kind:"run"}:{refused:"none"}}onlyLive(){let e=[...[...this.discoveries.values()].filter(t=>!t.controller.signal.aborted).map(t=>({kind:"discovery",discovery:t})),...[...this.awaitingGuard.values()].filter(t=>!t.signal.aborted).map(t=>({kind:"awaiting-guard",controller:t})),...this.run&&!this.run.controller.signal.aborted?[{kind:"run"}]:[]];return e.length===0?{refused:"none"}:e.length>1?{refused:"several",live:e.length}:e[0]}};function Un(n){let e=0,t=new Map,r=new Map,o=[],s=new Set,i=new Map,a=[],d=p=>{t.set(p,e),r.set(p,e),e++,o.push(p),s.add(p);for(let u of[...n.get(p)??[]].sort())n.has(u)&&(t.has(u)?s.has(u)&&r.set(p,Math.min(r.get(p)??0,t.get(u)??0)):(d(u),r.set(p,Math.min(r.get(p)??0,r.get(u)??0))));if(r.get(p)===t.get(p)){let u=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),i.set(m,a.length),u.push(m)}while(m!==p);a.push(u.sort())}};for(let p of[...n.keys()].sort())t.has(p)||d(p);let c=a.map((p,u)=>{let m=new Set;for(let g of p)for(let h of n.get(g)??[]){let y=i.get(h);y!==void 0&&y!==u&&m.add(y)}return m}),f=new Set,l=[];for(;f.size<a.length;){let p=a.map((u,m)=>({component:u,i:m})).filter(({i:u})=>!f.has(u)&&[...c[u]].every(m=>f.has(m))).sort((u,m)=>u.component[0].localeCompare(m.component[0]));for(let{component:u,i:m}of p)f.add(m),l.push(u)}return l}function zn(n,e){let t=new Set(n),r=new Map(n.map(s=>[s,new Set([...e.get(s)??[]].filter(i=>t.has(i)))])),o=[];for(;;){let s=[...r.entries()].filter(([,i])=>i.size===0).map(([i])=>i).sort();if(s.length===0)break;for(let i of s){o.push(i),r.delete(i);for(let a of r.values())a.delete(i)}}return[...o,...[...r.keys()].sort()]}function Zd(n,e,t){let r=new Set(n),o=new Map;for(let s of e){if(!r.has(s.to)||!r.has(s.from))continue;let i=t(s.to)?.find(d=>d.name===s.fieldApiName),a=i!==void 0&&pt(i);!s.required&&!Mr(s.to,s.fieldApiName)&&!a||o.set(s.to,(o.get(s.to)??new Set).add(s.from))}return o}function Qd(n,e){let t=new Set(n),r=e.filter(s=>s.from!==s.to&&t.has(s.from)&&t.has(s.to)),o=new Map(n.map(s=>[s,new Set]));for(let s of r)o.get(s.to)?.add(s.from);return{within:r,deps:o,groups:Un(o)}}function Kp(n,e,t){return n.flatMap(r=>{let{groups:o,within:s}=Qd(r,e);return o.flatMap(i=>i.length>1?zn(i,Zd(i,s,t)):i)})}var Xd=100,ec=.25,tc=2048;function Pe(n,e){return typeof n!="string"||n===""?!1:e.prefix===void 0||e.prefix!==null&&n.startsWith(e.prefix)}function nc(n){let e=new Set(n.map(o=>o.objectApiName)),t=new Map,r=new Map;for(let o of n){let s=new Set,i=new Set;for(let a of o.fields){if(a.referenceTo.length===0||!Qe(a))continue;let d=Vn(o.objectApiName,a)||pt(a);for(let c of a.referenceTo)c===o.objectApiName||!e.has(c)||(s.add(c),d&&i.add(c))}t.set(o.objectApiName,s),r.set(o.objectApiName,i)}return Un(t).flatMap(o=>o.length>1?zn(o,r):o)}function Vn(n,e){return Lr(n,e.name,e.nillable)}function rc(n){let e=new Map(n.objects.map(u=>[u.objectApiName,u])),t=new Map;for(let u of e.keys())n.referenceData?.has(u)&&t.set(u,"referenceData");for(let u of n.whole??[])e.has(u)&&!t.has(u)&&t.set(u,"asked");let r=ec*Math.max(0,n.roomBytes),o=u=>u.rows===void 0?void 0:n.wholeBytes(u.objectApiName,u.rows),s=[...e.values()].filter(u=>Et.has(u.objectApiName)&&!t.has(u.objectApiName)),i=s.reduce((u,m)=>{let g=o(m);return u===void 0||g===void 0?void 0:u+g},0);if(s.length>0&&i!==void 0&&i<=r&&s.every(u=>n.maxRecordsPerObject===void 0||(u.rows??0)<=n.maxRecordsPerObject))for(let u of s)t.set(u.objectApiName,"catalog");let d=Math.max(Xd,Math.floor(.01*Math.max(0,n.roomBytes)/tc)),c=u=>e.has(u)&&!t.has(u),f=new Set;for(let u of e.values())if(c(u.objectApiName)){for(let m of u.fields)if(Qe(m))for(let g of m.referenceTo)g!==u.objectApiName&&f.add(g)}let l=[...e.values()].filter(u=>!t.has(u.objectApiName)&&!Et.has(u.objectApiName)&&u.rows!==void 0&&u.rows>0&&u.rows<=d&&(n.maxRecordsPerObject===void 0||u.rows<=n.maxRecordsPerObject)&&f.has(u.objectApiName)).map(u=>({object:u,bytes:o(u)??1/0})).sort((u,m)=>u.bytes-m.bytes||(u.object.objectApiName<m.object.objectApiName?-1:1)),p=0;for(let{object:u,bytes:m}of l){if(p+m>r)break;u.fields.some(h=>Qe(h)&&Vn(u.objectApiName,h)&&h.referenceTo.some(y=>c(y)))||(t.set(u.objectApiName,"smallParent"),p+=m)}return t}function Lt(n){let e=new Map(n.objects.map(l=>[l.objectApiName,l])),t=rc(n),r=[...t.values()].includes("catalog"),o=new Map;for(let l of e.keys()){let p=t.get(l);o.set(l,p!==void 0?{kind:"whole",why:p}:{kind:"drawn",rooted:!(Et.has(l)&&!r)})}let s=n.order?[...n.order]:nc(n.objects),i=new Map(s.map((l,p)=>[l,p])),a=(l,p)=>(i.get(l)??1/0)<(i.get(p)??1/0),d=l=>{let p=o.get(l);return p?.kind==="drawn"&&p.rooted},c=new Map,f=new Map;for(let l of[...e.values()].sort((p,u)=>p.objectApiName<u.objectApiName?-1:1)){let p=l.objectApiName,u=[];for(let m of[...l.fields].sort((g,h)=>g.name<h.name?-1:1)){if(m.referenceTo.length===0||!Qe(m))continue;let g=Vn(p,m),h=m.referenceTo.length>1;for(let y of[...m.referenceTo].sort()){let R=o.get(y),S=ts(p,m,e.get(y)?.childRelationships),w=n.excluded?.get(y),b=v=>h?{prefix:v??null}:{};if(!R){g&&n.excluded?.has(y)&&u.push({objectApiName:p,field:m.name,parent:y,target:"excluded",carries:!1,owed:!1,required:g,masterDetail:S,...b(w)});continue}let A=y===p,j=A||!a(y,p),L={objectApiName:p,field:m.name,parent:y,target:R.kind==="whole"?"whole":"drawn",carries:!A&&d(y)&&d(p)&&(g||!j),owed:j,required:g,masterDetail:S,...b(e.get(y)?.keyPrefix)};if(u.push(L),L.carries){let v=f.get(y)??[];v.push(L),f.set(y,v)}}}c.set(p,u)}return{classes:o,whole:[...t.entries()].map(([l,p])=>({objectApiName:l,why:p})).sort((l,p)=>l.objectApiName<p.objectApiName?-1:1),linksOf:c,carriersInto:f,order:s}}function Gn(n,e){return[...new Set((n.linksOf.get(e)??[]).map(t=>t.field))].sort()}function ni(n,e){let t=(n.linksOf.get(e)??[]).filter(s=>s.carries),r=new Set,o=new Set;for(let s of t)(s.prefix===void 0?r:o).add(s.field);return{empty:[...r].sort(),told:[...o].sort()}}function ri(n,e,t,r){return(n.linksOf.get(e)??[]).find(o=>o.field===t&&Pe(r,o))}var me=2e3,sc=500,Kn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ic=et;function qe(n){return n.length===0?"":` WHERE ${n.join(" AND ")}`}function Ue(n){return oo(n)+2*(n.match(/'/g)?.length??0)}function oi(n,e,t){let r=Ue(n)+Ue(t),o=Ue(", "),s=[],i=[],a=r;for(let d of e){let c=Ue(`'${d}'`);i.length>0&&(a+o+c>14e3||i.length>=sc)&&(s.push(i),i=[],a=r),a+=(i.length>0?o:0)+c,i.push(d)}return i.length>0&&s.push(i),s}function at(n){let e=new Set,t=[];for(let r of n){if(!Kn.test(r))continue;let o=U(r);e.has(o)||(e.add(o),t.push(r))}return t}function _t(n){return wt(H(n))==="QUERY_TIMEOUT"}var ac=new Set(["MALFORMED_QUERY","INVALID_FIELD"]);function si(n){let e=wt(H(n));return e!==void 0&&ac.has(e)}var dc=new Set(["MALFORMED_QUERY","INVALID_FIELD","EXCEEDED_MAX_SEMIJOIN_SUBSELECTS"]),cc="SAMPLE_DRAW_INVALID";function uc(n,e,t){if(n.where===void 0)return"strata";if(n.stratifiedBy===void 0||e==="EXCEEDED_MAX_SEMIJOIN_SUBSELECTS")return"where";if(/can ?not be grouped/i.test(t))return"strata";let r=/No such column '([^']+)'/i.exec(t)?.[1]?.toLowerCase();if(r===void 0)return"either";let o=a=>a.toLowerCase().split(/\W+/).includes(r),s=o(n.where),i=o(n.stratifiedBy);return s===i?"either":s?"where":"strata"}var ge="CreatedDate",lc="LastModifiedDate",ii="SystemModstamp";function ci(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function fc(n){return/\(\s*SELECT\b/i.test(ci(n))}function pc(n){let e=0,t="";for(let r of ci(n))r==="("&&e++,t+=e===0?r:" ",r===")"&&(e=Math.max(0,e-1));return/\bOR\b/i.test(t)}function ai(n){let e=n.trim();return fc(e)&&!pc(e)?e:`(${e})`}function ui(n){return n==null||n===""}function Hn(n){return ui(n)?null:typeof n=="boolean"?n:String(n)}function dt(n){return n===null?"\0":`${typeof n}:${String(n)}`}function mc(n,e){return e===null?`${n} = null`:typeof e=="boolean"?`${n} = ${String(e)}`:`${n} = '${xe(e)}'`}function gc(n){let e=n.trim();return/[.!?]$/.test(e)?e:`${e}.`}function hc(n,e){let t=typeof n=="string"?Date.parse(n):Number.NaN;return!Number.isFinite(t)||e.from!==void 0&&t<Date.parse(e.from)?!1:e.to===void 0||t<Date.parse(e.to)}var Dt=class{constructor(e,t){this.source=e;this.options=t}source;options;sent=0;rowsRead=0;slow=new Set;ungrouped=new Set;counted=new Map;countedStrata=new Map;standardBook;get requests(){return this.sent}async*pages(e,t){this.options.signal?.throwIfAborted();let r=0;try{for await(let o of this.source.pages(e,t))r++,this.sent++,this.rowsRead+=o.length,yield o}catch(o){throw this.sent++,o}r===0&&this.sent++}async gather(e,t){let r=[];for await(let o of this.pages(e,t))for(let s of o)r.push(s);return r}async count(e,t){this.options.signal?.throwIfAborted();try{return await this.source.count(e,t)}finally{this.sent++}}progress(e,t){this.options.onProgress?.({step:e,rows:this.rowsRead,requests:this.sent,...t})}columnsOf(e,t){let r=this.options.fieldsOf(e);if(r===void 0)throw new Error(`No describe of ${e}: its records cannot be read for a sample.`);let o=new Set(r.map(a=>a.toLowerCase())),s=["Id"],i=new Set(["id"]);for(let a of t){let d=a.toLowerCase();i.has(d)||!o.has(d)||(i.add(d),s.push(J(a)))}return s}readOptionsOf(e){return et.has(e)?{all:!0}:void 0}termsOf(e){let t=this.options.filterOf?.(e);return[...t!==void 0&&t.trim()!==""?[ai(t)]:[],...et.has(e)?["IsDeleted = false"]:[]]}lists(e,t){let r=t.toLowerCase();return(this.options.fieldsOf(e)??[]).some(o=>o.toLowerCase()===r)}fieldOf(e,t){if((this.options.fieldsOf(e)??[]).find(s=>s.toLowerCase()===t.toLowerCase())===void 0)throw new Error(`${e}.${t} is no field of the source's describe.`);return J(t)}rootShapeOf(e,t={}){let r=J(e.objectApiName),o=t.slow??this.slow.has(r),s=e.carriers.map(S=>({field:this.fieldOf(r,S.field),prefixes:S.drawnPrefixes===void 0?void 0:[...S.drawnPrefixes]})),i=o?[]:s.filter(S=>S.prefixes===void 0),a=s.filter(S=>!i.includes(S)),d=(S,w)=>!ui(S)&&(w===void 0||w.some(b=>String(S).startsWith(b))),c=t.natural?void 0:e.window,f=c?this.fieldOf(r,c.field):void 0,l=c?.field===lc,p=c!==void 0&&l&&o,u=c&&f&&!p?[...c.from!==void 0?[`${f} >= ${Ae(c.from)}`]:[],...c.to!==void 0?[`${f} < ${Ae(c.to)}`]:[],...l&&c.from!==void 0&&this.lists(r,ii)?[`${ii} >= ${Ae(c.from)}`]:[]]:[],m=t.natural||e.where?.trim()===""?void 0:e.where,g=e.stratifiedBy!==void 0&&(t.stratum!==void 0||t.values)?this.fieldOf(r,e.stratifiedBy):void 0,h=t.stratum?.value===null,y=t.stratum!==void 0&&g!==void 0&&!(h&&o)?[mc(g,t.stratum.value)]:[],R=[];return p&&c&&f&&R.push(S=>hc(S[f],c)),h&&o&&g!==void 0&&R.push(S=>Hn(S[g])===null),{object:r,select:this.columnsOf(r,[...a.map(S=>S.field),...p&&f?[f]:[],...g!==void 0&&(t.values||h&&o)?[g]:[]]),terms:[...this.termsOf(r),...i.map(S=>`${S.field} = null`),...u,...m!==void 0?[ai(m)]:[],...y],held:i.length>0||l&&u.length>0||h&&y.length>0,tested:a.length>0||R.length>0,isRoot:S=>!a.some(w=>d(S[w.field],w.prefixes))&&R.every(w=>w(S))}}async countRoots(e){let t=new Array(e.length),r=0;return await Te(e,async(o,s)=>{let i=await this.countRootsOf(o);t[s]=i,this.counted.set(o.objectApiName,i.rows),i.strata&&this.countedStrata.set(o.objectApiName,new Map(i.strata.map(a=>[dt(a.value),a.rows]))),r++,this.progress("counting",{objectApiName:o.objectApiName,done:r,total:e.length})}),t}async countRootsOf(e){let t=e.objectApiName,r=this.readOptionsOf(t);e.stratifiedBy!==void 0&&this.refuseUngroupedStratum(e,e.stratifiedBy);let o=!1;for(;;){let s=this.rootShapeOf(e),i;try{i=e.stratifiedBy===void 0?{rows:await this.count(`SELECT COUNT() FROM ${s.object}${qe(s.terms)}`,r)}:await this.countByStratum(e,e.stratifiedBy,s,r)}catch(d){if(o||!s.held||!_t(d))throw this.drawRefusalOf(e,d);o=!0,this.slow.add(t);continue}let a=this.restricts(e)?await this.countInTheSource(e,{terms:s.terms,rows:i.rows,exact:!s.tested}):void 0;return{objectApiName:t,rows:i.rows,exact:!s.tested,...o?{timedOut:!0}:{},...i.strata?{strata:i.strata}:{},...a?{inTheSource:a}:{}}}}restricts(e){return e.window!==void 0||e.where!==void 0&&e.where.trim()!==""}async countInTheSource(e,t){let r=this.readOptionsOf(e.objectApiName),o=this.slow.has(e.objectApiName);for(;;){let s=this.rootShapeOf(e,{natural:!0,slow:o});if(s.terms.join(`
|
|
23
|
+
`)===t.terms.join(`
|
|
24
|
+
`))return{rows:t.rows,exact:t.exact};try{return{rows:await this.count(`SELECT COUNT() FROM ${s.object}${qe(s.terms)}`,r),exact:!s.tested}}catch(i){if(o||!s.held||!_t(i))throw i;o=!0}}}async countByStratum(e,t,r,o){let s=this.fieldOf(r.object,t),i=`SELECT ${s}, COUNT(Id) n FROM ${r.object}${qe(r.terms)} GROUP BY ${s}`,a=[],d=0;try{for await(let f of this.pages(i,o)){if(d++,d>1)break;for(let l of f)a.push(l)}}catch(f){if(d===0)throw f;d=2}if(d>1||a.length>=me)throw this.drawRefused(e,"strata",`${e.objectApiName}.${t} has too many values among the roots of the draw to stratify them: the source counts them in one answer of fewer than ${me}, and this one ${d>1?"had more after it":`held ${a.length}`}.`);let c=[];for(let f of a){let l=Number(f.n);Number.isFinite(l)&&c.push({value:Hn(f[s]),rows:l})}return{rows:c.reduce((f,l)=>f+l.rows,0),strata:c}}refuseUngroupedStratum(e,t){if(this.options.countsBy?.(e.objectApiName,t)===!1)throw this.drawRefused(e,"strata",`The source's describe says the records of ${e.objectApiName} are not counted by ${t}.`)}drawRefusalOf(e,t){let r=H(t),o=wt(r);return o===void 0||!dc.has(o)||!this.restricts(e)&&e.stratifiedBy===void 0?t:this.drawRefused(e,uc(e,o,r),`The source refused to count the roots of ${e.objectApiName} in the draw: ${r}`)}drawRefused(e,t,r){let o=e.objectApiName,s=[];return e.where!==void 0&&t!=="strata"&&s.push(`The source reads the condition of its roots (--fit-where ${o}=\u2026) as it is written: its fields are those of the object, and with the filter it holds two semi-joins at most, none in parentheses an OR is part of.`),e.stratifiedBy!==void 0&&t!=="where"&&s.push(`Stratify ${o} by a field of few values the source groups by \u2014 a picklist, a checkbox, a record type or an owner (--fit-strata ${o}.<Field>) \u2014, or narrow its roots first (--fit-where ${o}=\u2026).`),new pe(cc,[gc(r),`Nothing was written, and the counts sent ${this.sent} request(s) of the source.`,...s].join(" "),void 0,void 0,void 0,{sample:{requests:this.sent}})}async drawUniform(e,t){let r=0;await Te(e,async o=>{this.counted.get(o.objectApiName)!==0&&await this.scanRoots(o,t),r++,this.progress("drawing",{objectApiName:o.objectApiName,done:r,total:e.length})})}async scanRoots(e,t){let r=this.readOptionsOf(e.objectApiName),o=e.stratifiedBy;for(;;){let s=this.rootShapeOf(e,o===void 0?{}:{values:!0}),i=`SELECT ${s.select.join(", ")} FROM ${s.object}${qe(s.terms)}`,a=!1;try{for await(let d of this.pages(i,r)){a=!0;let c=d.filter(s.isRoot);if(o===void 0){let f=c.map(l=>String(l.Id));f.length>0&&await t(e.objectApiName,f);continue}for(let{value:f,ids:l}of bc(c,o))await t(e.objectApiName,l,f)}return}catch(d){if(a||!s.held||!_t(d))throw d;this.slow.add(e.objectApiName)}}}async drawByDate(e,t,r){let o=e.map(i=>({objectApiName:i.objectApiName,by:this.orderedBy(i.objectApiName)})),s=0;return await Te(e,async(i,a)=>{let d=i.objectApiName;if(this.counted.get(d)!==0){let c=o[a].by;if(typeof i.take=="number")i.take>0&&await this.rootsByDate(i,t,c,i.take,void 0,r);else{let f=this.countedStrata.get(d);for(let l of i.take)l.take<=0||f?.get(dt(l.value))===0||await this.rootsByDate(i,t,c,l.take,l,r)}}s++,this.progress("drawing",{objectApiName:d,done:s,total:e.length})}),o}orderedBy(e){return this.lists(e,ge)&&this.options.sorts?.(e,ge)!==!1?"created":"id"}async rootsByDate(e,t,r,o,s,i){let a=e.objectApiName,d=this.readOptionsOf(a),c=0,f;for(;c<o;){let l=this.rootShapeOf(e,s===void 0?{}:{stratum:s}),p=l.tested?me:Math.min(me,o-c),u=r==="created"?this.columnsOf(a,[...l.select,ge]):l.select,{after:m,order:g}=yc(r,t,f),h=`SELECT ${u.join(", ")} FROM ${l.object}${qe([...l.terms,...m])} ORDER BY ${g} LIMIT ${p}`,y;try{y=await this.gather(h,d)}catch(S){if(!l.held||!_t(S))throw S;this.slow.add(a);continue}let R=y.filter(l.isRoot).map(S=>String(S.Id)).slice(0,o-c);if(c+=R.length,R.length>0&&await(s===void 0?i(a,R):i(a,R,s.value)),y.length<p)return;f=Rc(a,y[y.length-1],r)}}async readParents(e){let t=new Array(e.length);return await Te(e,async(r,o)=>{t[o]=await this.parentsOf(r)}),t}async parentsOf(e){let t=J(e.objectApiName),r=this.columnsOf(t,e.columns),o=at(e.ids),s=this.readOptionsOf(t),i=await this.byList(t,r,"Id",o,this.termsOf(t),s),a=new Set(i.map(p=>U(String(p.Id)))),d=o.filter(p=>!a.has(U(p))),c=this.options.filterOf?.(t),f=[];if(d.length>0&&c!==void 0&&c.trim()!==""){let p=et.has(t)?["IsDeleted = false"]:[];f=await this.byList(t,r,"Id",d,p,s)}let l=new Set(f.map(p=>U(String(p.Id))));return{objectApiName:e.objectApiName,rows:i,columns:r,absent:d.filter(p=>!l.has(U(p))),outsideFilter:f}}async readStandardPrices(e,t){let r=at(e);if(r.length===0)return[];if(this.standardBook===void 0){let[i]=await this.gather("SELECT Id FROM Pricebook2 WHERE IsStandard = true"),a=i?.Id;this.standardBook=typeof a=="string"&&Kn.test(a)?a:null}if(this.standardBook===null)return[];let o=this.columnsOf("PricebookEntry",["Product2Id",...t]),s=[...this.termsOf("PricebookEntry"),`Pricebook2Id = '${this.standardBook}'`];return this.byList("PricebookEntry",o,"Product2Id",r,s,void 0)}async readPricesIn(e,t,r,o){if(!/^[A-Z]{3}$/.test(e))return[];let s=at(t),i=at(r);if(s.length===0||i.length===0)return[];let a=this.columnsOf("PricebookEntry",["Product2Id","Pricebook2Id",...o]),d=[...this.termsOf("PricebookEntry"),`Pricebook2Id IN (${i.map(c=>`'${c}'`).join(", ")})`,`CurrencyIsoCode = '${e}'`];return this.byList("PricebookEntry",a,"Product2Id",s,d,void 0)}async byList(e,t,r,o,s,i){let a=[...s,`${r} IN (`].join(" AND "),d=`SELECT ${pn(t).join(", ")} FROM ${e} WHERE ${a}`,c=[];for(let f of oi(d,o,")")){let l=`SELECT ${t.join(", ")} FROM ${e} WHERE ${a}${f.map(p=>`'${p}'`).join(", ")})`;for(let p of await mn(l,u=>this.gather(u,i)))c.push(p)}return c}async readChildren(e){let t=new Array(e.length);return await Te(e,async(r,o)=>{t[o]=await this.childrenOf(r)}),t}async childrenOf(e){let t=J(e.objectApiName),r=this.fieldOf(t,e.field),o=e.cap,s=this.orderedBy(t),i=o!=="all"&&s==="created",a=this.columnsOf(t,[r,...e.columns,...i?[ge]:[]]),d=at(e.parentIds),c=this.readOptionsOf(t),f=this.termsOf(t),l=new Map,p={objectApiName:t,field:r,rows:[],columns:a,cut:[],counts:new Map,newestBy:s},u=()=>{for(let b of d)p.counts.set(b,l.get(U(b))??0);return p};if(d.length===0)return p;if(o==="all"){let b=Jn(await this.byList(t,a,r,d,f,c),r,1/0,s);p.rows=b.rows;for(let[A,j]of b.counts)l.set(A,j);return u()}let m=[...f,`${r} IN (`].join(" AND "),g={head:`SELECT ${r}, COUNT(Id) n FROM ${t} WHERE ${m}`,tail:`) GROUP BY ${r}`},h={head:`SELECT ${pn(a).join(", ")} FROM ${t} WHERE ${m}`,tail:")"},y=Ue(g.head+g.tail)>Ue(h.head+h.tail)?g:h,R=[],S=[];for(let b of oi(y.head,d,y.tail)){let A=e.sourceRows<=o*b.length||this.ungrouped.has(t)||this.options.countsBy?.(t,r)===!1?void 0:await this.countedByParent(t,g,r,b,c);if(A===void 0){R.push(...b);continue}for(let j of A)j.rows>o?S.push(j):R.push(j.parentId)}let w=Jn(await this.byList(t,a,r,R,f,c),r,o,s);p.rows.push(...w.rows),p.cut.push(...w.cut);for(let[b,A]of w.counts)l.set(b,A);for(let b of S){let A=`SELECT ${a.join(", ")} FROM ${t} WHERE ${[...f,`${r} = '${b.parentId}'`].join(" AND ")} ORDER BY ${wc(s)} LIMIT ${o}`,j;try{j=await mn(A,L=>this.gather(L,c))}catch(L){if(!si(L))throw L;let v=Jn(await this.byList(t,a,r,[b.parentId],f,c),r,o,s);p.rows.push(...v.rows),p.cut.push(...v.cut);for(let[P,k]of v.counts)l.set(P,k);continue}p.rows.push(...j),p.cut.push({parentId:b.parentId,rows:Math.max(0,b.rows-j.length)}),l.set(U(b.parentId),b.rows)}return u()}async countedByParent(e,t,r,o,s){let i=`${t.head}${o.map(c=>`'${c}'`).join(", ")}${t.tail}`,a;try{a=await this.gather(i,s)}catch(c){if(!si(c))throw c;this.ungrouped.add(e);return}let d=[];for(let c of a){let f=c[r],l=Number(c.n);typeof f=="string"&&Number.isFinite(l)&&d.push({parentId:f,rows:l})}return d}async readWhole(e,t){await Te(e,async r=>{let o=J(r.objectApiName),s=this.columnsOf(o,r.columns),i=this.readOptionsOf(o),a=`SELECT ${s.join(", ")} FROM ${o}${qe(this.termsOf(o))}`;for await(let d of uo(a,c=>this.pages(c,i),c=>this.gather(c,i)))await t(r.objectApiName,d)})}};function wc(n){return n==="created"?`${ge} DESC, Id DESC`:"Id DESC"}function yc(n,e,t){let r=e==="recent",o=r?"<":">",s=r?"DESC":"ASC";if(n==="id")return{after:t?[`Id ${o} '${t.id}'`]:[],order:`Id ${s}`};let i=`${ge} ${s}, Id ${s}`;return t?{after:[`(${ge} ${o} ${t.at} OR (${ge} = ${t.at} AND Id ${o} '${t.id}'))`],order:i}:{after:[],order:i}}function bc(n,e){let t=new Map;for(let r of n){let o=Hn(r[e]),s=dt(o),i=t.get(s)??{value:o,ids:[]};i.ids.push(String(r.Id)),t.set(s,i)}return[...t.values()]}function Rc(n,e,t){let r=e.Id;if(typeof r!="string"||!Kn.test(r))throw new Error(`A record of ${n} came back without its id.`);if(t==="id")return{at:"",id:r};let o=e[ge];if(typeof o!="string"||!Number.isFinite(Date.parse(o)))throw new Error(`A record of ${n} came back without the date it was made.`);return{at:Ae(o),id:r}}function di(n){let e=n[ge],t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Sc(n,e){let t=di(n),r=di(e);return t!==r?t===void 0?1:r===void 0?-1:r-t:ue(String(e.Id),String(n.Id))}function Jn(n,e,t,r){let o=new Map;for(let d of n){let c=d[e];if(typeof c!="string")continue;let f=U(c),l=o.get(f);l?l.rows.push(d):o.set(f,{parentId:c,rows:[d]})}let s=[],i=[],a=new Map;for(let[d,{parentId:c,rows:f}]of o)f.sort(r==="created"?Sc:(l,p)=>ue(String(p.Id),String(l.Id))),s.push(...f.slice(0,t)),f.length>t&&i.push({parentId:c,rows:f.length-t}),a.set(d,f.length);return{rows:s,cut:i,counts:a}}function Bt(n,e,t=0){if(n.rows<=0)return 0;if(e==="uniform")return Math.ceil(n.rows/me);let r=(s,i)=>Math.ceil(Math.min(Math.max(0,s),i)/me);if(typeof t=="number")return r(t,n.rows);let o=new Map((n.strata??[]).map(s=>[dt(s.value),s.rows]));return t.reduce((s,i)=>s+r(i.take,o.get(dt(i.value))??i.take),0)}function um(n){let e=J(n.objectApiName),t=n.columns.some(p=>p.toLowerCase()==="systemmodstamp"),r=so(n.columns,t?["Id","SystemModstamp"]:["Id"]),o=Math.max(0,n.planRows),s=Math.max(0,n.sourceRows),i=r.map(p=>ao(e,p)),a=i.reduce((p,u)=>p+Math.ceil(o/u),0),d=Math.max(1,Math.ceil(s/me)),c=Math.floor(s/me),f=s%me,l=d+i.slice(1).reduce((p,u)=>p+c*Math.ceil(me/u)+(f>0?Math.ceil(f/u):0),0);return ic.has(e)?{by:"cursor",requests:l,byIds:a,byCursor:l,cursorAlone:!0}:a<=l?{by:"ids",requests:a,byIds:a,byCursor:l}:{by:"cursor",requests:l,byIds:a,byCursor:l}}var Oc=new Set(["BusinessHours","OperatingHours"]);function li(n,e){if(!(!n||"unread"in n))return Math.floor(n.remaining-ke*n.max-e)}function Ac(n){let e=li(n.requests,Math.max(0,n.sentBefore??0)+fs),t=li(n.bulkBatches,0);if(e===void 0&&t===void 0)return;let r=n.updatedAfterInsert?{updatedAfterInsert:n.updatedAfterInsert}:{};return o=>{let s=[...o].map(([i,a])=>({objectApiName:i,rows:a,storageBytes:0}));if(e!==void 0&&as({plan:{objects:s},...r,bulk:{}}).run>e)return"targetRequests";if(t!==void 0&&ds({plan:{objects:s},...r,measures:{}}).bulkBatches>t)return"bulkBatches"}}function kc(n){let{storage:e,withinMB:t}=n,r=new Map;for(let c of n.automation??[])r.set(c.objectApiName,(r.get(c.objectApiName)??0)+c.bytes);let o=n.allowances?Ac(n.allowances):void 0,s={...r.size>0?{automationBytes:c=>r.get(c)??0}:{},...o?{requests:o}:{}};if("unread"in e){if(t===void 0)return;let c=Math.floor(Math.max(0,t)*1048576);return{budget:{bytes:c,withinMB:t,limitedBy:"within"},bytesLimit:"within",roomBytes:c,...s}}let i=As({storage:e,...t!==void 0?{withinMB:t}:{}});if("unread"in i)return;let a=i.terms.limitedBy==="within"?"within":"storage",d=Math.floor(Fe*Tt(e)*1048576);return{budget:{bytes:i.bytes,remainingMB:e.remainingMB,maxMB:e.maxMB,share:Fe,roundingMB:tt,...i.terms.uncountedMB!==void 0?{uncountedMB:i.terms.uncountedMB}:{},...t!==void 0?{withinMB:t}:{},limitedBy:a},bytesLimit:a,roomBytes:d,storageBytes:d,...s}}function Ic(n,e){let t=n.nodes.filter(o=>o.included&&!Br(o)&&!e.has(o.objectApiName)),r=new Set(t.map(o=>o.objectApiName));return t.map(o=>({objectApiName:o.objectApiName,rows:o.recordCountUnknown===!0?void 0:o.recordCount,fields:n.edges.filter(s=>s.targetObject===o.objectApiName&&r.has(s.sourceObject)).map((s,i)=>({name:`${s.relationshipName||s.sourceObject}${i}`,referenceTo:[s.sourceObject],isMasterDetail:s.type==="master-detail",nillable:s.required!==!0&&s.type!=="master-detail",createable:s.settable!==!1,updateable:s.settable!==!1}))}))}function bm(n){let e=n.options??{},t=Ic(n.graph,new Set(n.excludedObjects??[])),r=t.reduce((m,g)=>m+ye(g.objectApiName,{rows:g.rows??0}),0),o=cs({storageBytes:r},n.storage),s=kc({storage:n.storage,...e.withinMB!==void 0?{withinMB:e.withinMB}:{}}),i=Lt({objects:t,referenceData:Oc,...e.whole?{whole:e.whole}:{},roomBytes:s?.roomBytes??0,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(m,g)=>ye(m,{rows:g})}),a=e.draw??Se.draw,d=s?Nt(s.budget.bytes,e.maxTotal):0,c=t.filter(m=>{let g=i.classes.get(m.objectApiName);return g?.kind==="drawn"&&g.rooted}),f=new Set(Object.keys(e.rootWhere??{}).map(m=>m.toLowerCase())),l=m=>e.window!==void 0||f.has(m.toLowerCase()),p=c.reduce((m,g)=>{let y=(i.linksOf.get(g.objectApiName)??[]).some(R=>R.carries&&R.required)?0:g.rows??0;return m+1+(l(g.objectApiName)?1:0)+Bt({objectApiName:g.objectApiName,rows:y,exact:!1},a,Math.min(y,d))},0),u=e.window!==void 0||f.size>0;return{wholeOrg:o,...s?{budget:s.budget}:{},whole:i.whole.filter(m=>m.why!=="asked"),planReads:{source:jc(p,n.source),seconds:p*Ko,...u?{atMost:!0}:{}}}}function jc(n,e){if("unread"in e)return{verdict:"unread",estimate:n,unread:e.unread};let t=ss(n,e);if(t.verdict==="unread")return t;let r=n>Math.floor(ke*e.remaining);return{...t,verdict:r?"exceeds":t.verdict}}var fi=V({value:W(),validFor:Z(te().int().nonnegative()).optional()}).loose(),pi=V({controllerValues:sn(W(),te().int().nonnegative()).optional(),defaultValue:fi.nullable().optional(),values:Z(fi)}).loose(),Nc=V({picklistFieldValues:sn(W(),Ne())}).loose(),Ec=/^[A-Za-z][A-Za-z0-9_]*$/,Tc=/^012[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/;function Fc(n){let e=n.values.map(s=>s.value),t=n.defaultValue?.value??null,r=Object.entries(n.controllerValues??{});if(r.length===0)return{values:e,defaultValue:t};let o=new Map;for(let[s,i]of r)o.set(s,new Set(n.values.filter(a=>(a.validFor??[]).includes(i)).map(a=>a.value)));return{values:e,defaultValue:t,allowedByControllingValue:o}}function Pc(n){let e=Nc.parse(n),t=new Map;for(let[r,o]of Object.entries(e.picklistFieldValues)){let s=pi.safeParse(o);s.success&&t.set(r,Fc(s.data))}return t}function vc(n){return pi.parse(n).values.map(e=>e.value)}function mi(n,e,t,r){for(let s of r===void 0?[e]:[e,r])if(!Ec.test(s))throw new Error(`Not an API name: "${s}"`);if(!Tc.test(t))throw new Error(`Not a record type id: "${t}"`);let o=`/services/data/v${n.version}/ui-api/object-info/${e}/picklist-values/${t}`;return r===void 0?o:`${o}/${r}`}async function Sm(n,e,t){return Pc(await n.request(mi(n,e,t)))}async function Om(n,e,t,r){return vc(await n.request(mi(n,e,t,r)))}var Cc=V({FileStorageMB:V({Remaining:te()}).loose()}).loose(),xc=Z(V({errorCode:W().optional(),message:W().optional()}).loose());function Mc(n){if(!(n instanceof Error))return new Error(String(n));try{let e=xc.safeParse(JSON.parse(Buffer.from(n.message,"base64").toString("utf8"))),t=e.success?e.data[0]:void 0;if(t?.message)return new Error(t.errorCode?`${t.errorCode}: ${t.message}`:t.message)}catch{}return n}async function Nm(n,e,t){if(!wo(t))throw new Error(`Not a record id: ${t}`);try{let r=await n.request({method:"GET",url:`/sobjects/${e}/${t}/${vs[e]}`},{encoding:"base64",responseType:"application/octet-stream"});if(typeof r!="string")throw new Error("The org answered with no file content.");return r}catch(r){throw Mc(r)}}async function Em(n,e,t){try{let r=await n.request({method:"POST",url:`/sobjects/${e}`,body:JSON.stringify(t),headers:{"content-type":"application/json"}}),o=Rt(r,e);return{id:o.id,success:o.success,errors:o.errors}}catch(r){return{id:"",success:!1,errors:[bo(r)]}}}async function Tm(n){return Cc.parse(await n.request({method:"GET",url:"/limits"})).FileStorageMB.Remaining}var Bc=["Task","Event","FeedItem","FeedComment","EmailMessage","ContentDocumentLink","Note","CaseComment"],wi=["Account","Contact","Lead","Opportunity","Case","Campaign","Contract","Order","Asset","Product2"],Zn=["User","Group","GroupMember","PermissionSet","PermissionSetAssignment","PermissionSetGroup","RecordType","Profile","UserRole"],$c=1e3,Wc=6e4,Yn=1e4,qc=300,gi=2e3,Uc=50,zc=3,yi=3,Vc=5,Gc=new Set(["flows","processes","triggers","conditions","definitions"]),bi=new Set(["OwnerId","CreatedById","LastModifiedById","RecordTypeId"]),ct=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function z(n){return n.slice(0,15)}function ne(n){return typeof n=="string"?Date.parse(n):Number.NaN}function ze(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Jc(n){let e=ne(n?.first),t=ne(n?.last);if(!(!Number.isFinite(e)||!Number.isFinite(t)))return{from:Math.floor((e-$c)/1e3)*1e3,to:Math.ceil((Math.max(e,t)+Wc)/1e3)*1e3}}function qm(n){if("error"in n)return{creates:[],gaps:{flowsNotRead:0,triggers:0,error:n.error}};let e=[],t=0,r=0;for(let s of n.objects){for(let i of[...s.flows,...s.processes??[]])if(i.startsOn!=="delete"){i.condition!=="read"&&t++;for(let a of i.creates??[])e.some(d=>d.toLowerCase()===a.toLowerCase())||e.push(a)}r+=s.triggers.filter(i=>i.events.some(a=>a!=="beforeDelete"&&a!=="afterDelete")).length}let o=n.unread.filter(s=>Gc.has(s.part)).map(s=>s.reason);return t===0&&r===0&&o.length===0?{creates:e}:{creates:e,gaps:{flowsNotRead:t,triggers:r,...o.length>0?{error:[...new Set(o)].join("; ")}:{}}}}function Um(n){return e=>Promise.all(e.map(async t=>{let r=n.lane({oneRow:!0});try{let o=await r.query(t);return o.totalSize??o.records.length}catch(o){return{reason:H(o)}}finally{r.close()}}))}async function Hc(n,e,t){let r=new Map,o=0,s;for(let{objectApiName:i,ids:a}of e){if(o>=zc||r.size>1||t())break;let d=a.slice(0,Uc);if(d.length!==0)try{let[c]=X(d,d.length),f=await n.queryDeleted(`SELECT CreatedById FROM ${J(i)} WHERE Id IN (${c})`),l=!1;for(let p of f.records){let u=p?.CreatedById;typeof u=="string"&&ct.test(u)&&(r.has(z(u))||r.set(z(u),u),l=!0)}l&&o++}catch(c){s??=H(c)}}return r.size===1?{user:[...r.values()][0]}:r.size>1?{refusal:`The run's records were created by ${r.size} different users: whose records came with the run cannot be told, and nothing is swept.`}:{refusal:`The user the run wrote as could not be read: none of its records is left in the org or its recycle bin to tell it${s?` (${s})`:""}. Nothing is swept.`}}async function Kc(n){try{let e=await n.describeGlobal(),t=Array.isArray(e?.sobjects)?e.sobjects:[],r=new Map;for(let o of t){let s=o??{};if(typeof s.name!="string")continue;let i=a=>typeof s[a]=="boolean"?{[a]:s[a]}:{};r.set(s.name.toLowerCase(),{name:s.name,...i("queryable"),...i("deletable"),...i("createable"),...i("layoutable")})}return r}catch{return}}function Yc(n){return n.queryable!==!1&&n.deletable!==!1&&n.createable!==!1&&n.layoutable!==!1&&!Zn.some(e=>e.toLowerCase()===n.name.toLowerCase())}async function Ri(n,e){let t;try{t=await e(n)}catch(i){return{reason:H(i)}}if(t.queryable===!1)return{reason:"The org does not let it be queried."};if(t.deletable!==!0)return{reason:"The org does not let its records be deleted."};let r=new Set(t.fields.map(i=>i.name));if(!r.has("CreatedById")||!r.has("CreatedDate"))return{reason:"It keeps no creator or creation date to tell what the run\u2019s user created in the window: its records go with the records they belong to."};let o=r.has("LastModifiedDate")?"LastModifiedDate":r.has("SystemModstamp")?"SystemModstamp":"CreatedDate",s=t.fields.find(i=>i.nameField===!0)?.name;return{name:t.name,modified:o,...r.has("LastModifiedById")?{modifiedBy:"LastModifiedById"}:{},...s&&s!=="Id"?{nameField:s}:{},references:Zc(t)}}function Zc(n){return n.fields.filter(e=>e.type==="reference"&&!bi.has(e.name)&&!((e.referenceTo??[]).length>0&&(e.referenceTo??[]).every(t=>Zn.includes(t)))).map(e=>e.name)}function Qc(n,e){return`CreatedById = '${n}' AND CreatedDate >= ${ze(e.from)} AND CreatedDate <= ${ze(e.to)}`}function Si(n,e){return n.length===1?Qc(n[0],e):`CreatedById IN (${n.map(t=>`'${t}'`).join(", ")}) AND CreatedDate >= ${ze(e.from)} AND CreatedDate <= ${ze(e.to)}`}async function Oi(n,e,t=[]){let r=()=>e.signal?.aborted===!0,o={looked:[],found:[],unread:[],handWork:[],...e.automation.gaps?{automationGaps:e.automation.gaps}:{}},s={listing:o,rows:new Map,stopped:!1},i=Jc(e.writtenBetween);if(!i)return o.refusal="The target did not date this run\u2019s writes: the window its automation wrote in cannot be told, and nothing is swept.",s;s.window=i,s.lastWrite=Math.max(ne(e.writtenBetween?.first),ne(e.writtenBetween?.last)),o.window={from:ze(i.from),to:ze(i.to)};let a=e.runUserId!==void 0&&ct.test(e.runUserId)?e.runUserId:void 0,d=e.user!==void 0&&ct.test(e.user)?e.user:void 0,c=e.created.some(l=>l.ids.length>0),f=a?{user:a}:c?await Hc(n,e.created,r):d!==void 0?{user:d}:{refusal:"The run created nothing, and none of the records it wrote over still says, in its window, who last modified it: the user it wrote as cannot be told, and nothing is swept."};return"refusal"in f?(o.refusal=f.refusal,s.stopped=r(),s):du(n,e,e.ties,f.user,s,i,t)}function Xc(n){return n.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}async function eu(n,e,t){if(e.length===0)return[];if(n.counts)try{return await n.counts(e)}catch(o){let s=H(o);return e.map(()=>({reason:s}))}let r=[];for(let o of e){if(t()){r.push(void 0);continue}try{r.push((await n.query(o)).totalSize)}catch(s){r.push({reason:H(s)})}}return r}async function tu(n){try{return(await n.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t?.Id).filter(t=>typeof t=="string"&&ct.test(t))}catch{return[]}}async function nu(n,e,t,r,o,s){let i=J(e.name),a=[...new Set(["Id","CreatedById","CreatedDate",e.modified,e.modifiedBy,e.nameField,...e.references].filter(l=>l!==void 0).map(J))],d=async l=>(await n.query(l)).records.filter(p=>typeof p=="object"&&p!==null),c=[],f;for(;;){if(s())return{rows:c,overBound:!1,stopped:!0};let l=`SELECT ${a.join(", ")} FROM ${i} WHERE ${Si([...t.values()],r)}${f?` AND Id > '${f}'`:""} ORDER BY Id LIMIT ${gi}`,p;try{let u=io(l);p=u?await co(await d(u.first),u,d):await d(l)}catch(u){return{reason:H(u)}}for(let u of p){if(typeof u.Id!="string")continue;f=u.Id;let m=typeof u.CreatedById=="string"?z(u.CreatedById):"",g=ne(u.CreatedDate);if(!t.has(m)||!(g>=r.from&&g<=r.to)||o(z(u.Id)))continue;let h=e.modifiedBy?u[e.modifiedBy]:void 0,y=e.nameField?u[e.nameField]:void 0,R=[];for(let S of e.references){let w=u[S];typeof w=="string"&&ct.test(w)&&R.push({field:S,key:z(w)})}if(c.push({id:u.Id,modified:ne(u[e.modified]),created:g,creator:m,references:R,...typeof h=="string"?{modifiedBy:z(h)}:{},...typeof y=="string"&&y.trim()!==""?{name:y.trim().slice(0,80)}:{}}),c.length>Yn)return{rows:c.slice(0,Yn),overBound:!0,stopped:!1}}if(p.length<gi)return{rows:c,overBound:!1,stopped:!1}}}function ru(n){let e=new Map,t=o=>{let s=o.toLowerCase(),i=e.get(s);return i||(i=(async()=>yt.parse(await n.describe(o)))(),i.catch(()=>{}),e.set(s,i)),i},r=async o=>{try{return await t(o)}catch{return}};return{of:t,now:r,async relation(o,s,i){let a=(await r(o))?.childRelationships?.find(d=>d.childSObject.toLowerCase()===s.toLowerCase()&&d.field===i);return{cascade:a?.cascadeDelete===!0,restricted:a?.restrictedDelete===!0}}}}async function ou(n,e,t,r,o,s){let i=await Kc(n),a=u=>i?i.get(u.toLowerCase()):{name:u},d=[],c=[],f=u=>d.some(m=>m.toLowerCase()===u.toLowerCase()),l=u=>Zn.some(m=>m.toLowerCase()===u.toLowerCase()),p=(u,m)=>{if(f(u)||l(u))return;let g=a(u)?.name;if(!g){m&&o.unread.push({objectApiName:u,reason:"The org has no such object."});return}if(d.length>=qc){c.includes(g)||c.push(g);return}d.push(g)};for(let u of e)p(u,!0);for(let u of Bc)p(u,!1);for(let u of t)p(u,!0);for(let u of wi)p(u,!1);for(let u of e){if(s())return;for(let m of(await r.now(u))?.childRelationships??[]){let g=a(m.childSObject);g&&Yc(g)&&!f(g.name)&&p(g.name,!1)}}return{looked:d,notLooked:c}}async function su(n,e,t,r,o,s,i){let a=[],d=new Map([...r.keys()].map(c=>[c.toLowerCase(),c]));for(let c of e){let f=((await o.now(c))?.fields??[]).filter(l=>l.type==="reference"&&!bi.has(l.name));for(let l of f)for(let p of l.referenceTo??[]){let u=d.get(p.toLowerCase());if(!u)continue;let m=(r.get(u)??[]).map(y=>y.id),{restricted:g}=await o.relation(u,c,l.name),h=J(l.name);for(let y of X(m)){if(i())return;let R;try{R=(await n.query(`SELECT Id, ${h} FROM ${J(c)} WHERE ${h} IN (${y})`)).records}catch(S){s.unread.push({objectApiName:c,reason:`What its ${l.name} points at among the records found could not be read (${H(S)}): what only it ties is left as tied to nothing.`});continue}for(let S of R){let{Id:w,[l.name]:b}=S??{};typeof w!="string"||typeof b!="string"||t.has(z(w))&&a.push({from:z(w),to:z(b),restricted:g})}}}}return a}async function iu(n,e,t,r){let o=new Map;for(let s of t){let i=e.get(s);i?.kind==="created"&&o.set(i.objectApiName,[...o.get(i.objectApiName)??[],i.id])}for(let[s,i]of o)for(let a of X(i)){if(r())return!1;try{let d=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${J(s)} WHERE Id IN (${a})`);for(let c of d.records){let{Id:f,CreatedDate:l}=c??{},p=typeof f=="string"?e.get(z(f)):void 0,u=ne(l);p&&Number.isFinite(u)&&(p.from=u,p.to=u)}}catch{}}return!0}function au(n,e,t,r,o,s){let{listing:i}=r,a=new Set(wi.map(u=>u.toLowerCase())),d=[],c=[],f=["made","madeOver","late","untied"];for(let[u,m]of n){let g=[],h=0;for(let b of m){let A=e.get(z(b.id));if(A){if(A.class==="untied"&&a.has(u.toLowerCase())){h++;continue}g.push({id:b.id,modified:b.modified,created:b.created,class:A.class,sameSave:A.sameSave,turn:A.turn,...b.modifiedBy!==void 0?{modifiedBy:b.modifiedBy}:{},...b.name!==void 0?{name:b.name}:{}})}}if(h>0&&i.handWork.push({objectApiName:u,count:h}),g.length===0)continue;let y={made:0,madeOver:0,late:0,untied:0},R=0,S=0,w={};for(let b of g)y[b.class]++,b.sameSave&&R++,$t(b,o,s)&&(S++,w[b.class]=(w[b.class]??0)+1);i.found.push({objectApiName:u,count:g.length,names:f.flatMap(b=>g.filter(A=>A.class===b)).flatMap(b=>b.name?[b.name]:[]).slice(0,yi),classes:{...y,...R>0?{sameSave:R}:{},...S>0?{changed:S,changedIn:w}:{}}}),y.untied>0&&d.push({objectApiName:u,count:y.untied}),y.late>0&&c.push({objectApiName:u,count:y.late}),r.rows.set(u,g)}let l=[];i.handWork.length>0&&l.push(`The run's user created records in the run's window tied to nothing of the run, on objects people make by hand (${Xc(i.handWork)}): hand work, likely, in the same span. They are left, and so is everything tied to nothing: what was made by hand could not be told from what the automation made.`);let p=(t.otherRuns??[]).filter(u=>u.ids.length>0||u.idsUntold===!0).length;p>0&&l.push(`${p===1?"Another run":`${p} other runs`} of this machine wrote to the target in this run\u2019s window: what is tied to nothing of this run may be theirs, and is left.`),l.length>0&&l.push("The runs of another machine, or of a CI, in the same window are not seen."),i.untied={objects:d,...l.length>0?{refusal:l.join(" ")}:{}},i.late=c}async function du(n,e,t,r,o,s,i){let{listing:a}=o,d=()=>e.signal?.aborted===!0,c=()=>(o.stopped=!0,o),f=ne(e.writtenBetween?.first),l=Math.max(f,ne(e.writtenBetween?.last)),p=Math.min(Number.POSITIVE_INFINITY,...[t.removalBegan,...i.map(F=>F.first)].map(ne).filter(Number.isFinite)),u=Math.ceil((l+9e5)/1e3)*1e3,m={from:s.from,to:Math.max(s.to,Math.min(u,Math.floor(p/1e3)*1e3))},g=new Map,h={from:f,to:l};for(let{objectApiName:F,ids:_}of e.created)for(let x of _)g.set(z(x),{kind:"created",objectApiName:F,id:x,from:Number.NaN,to:Number.NaN});for(let{objectApiName:F,ids:_,between:x}of t.writtenOver??[]){let $=ne(x?.first),q=ne(x?.last);for(let Q of _)g.has(z(Q))||g.set(z(Q),{kind:"overwritten",objectApiName:F,id:Q,from:$,to:q})}let y=[...new Set([...e.created,...t.writtenOver??[]].filter(F=>F.ids.length>0).map(F=>F.objectApiName))],R=new Set([...(t.otherRuns??[]).flatMap(F=>F.ids.map(z)),...(t.leased??[]).map(z)]),S=F=>e.remap.has(F)||g.has(F)||R.has(F),w=await tu(n),b=new Map([[z(r),r]]);for(let F of w)b.has(z(F))||b.set(z(F),F);let A=new Set(w.map(z).filter(F=>F!==z(r))),j=ru(n),L=await ou(n,y,e.automation.creates,j,a,d);if(!L)return c();let{looked:v,notLooked:P}=L;a.looked=v,P.length>0&&(a.notLooked=P);let k=await eu(n,v.map(F=>`SELECT COUNT() FROM ${J(F)} WHERE ${Si([...b.values()],m)}`),d);if(d())return c();let N=new Map,M=[];for(let[F,_]of v.entries()){let x=k[F];if(x===void 0)return c();if(x===0)continue;if(d())return c();let $=await Ri(_,j.of);if("reason"in $){a.unread.push({objectApiName:_,reason:$.reason});continue}if(typeof x=="object"){a.unread.push({objectApiName:_,reason:x.reason});continue}let q=await nu(n,$,b,m,S,d);if("reason"in q){a.unread.push({objectApiName:_,reason:q.reason});continue}if(q.stopped)return c();q.overBound?M.push({objectApiName:_,count:q.rows.length,names:q.rows.flatMap(Q=>Q.name?[Q.name]:[]).slice(0,yi),overBound:!0}):q.rows.length>0&&N.set(_,q.rows)}let D=new Map;for(let{part:F,created:_}of e.otherParts??[])for(let{objectApiName:x,ids:$}of _)for(let q of $)D.set(z(q),{part:F,objectApiName:x});let E=new Map;for(let[F,_]of D.size>0?[...N]:[]){let x=[];for(let $ of _){let q,Q=!1;for(let he of $.references){let Nr=g.get(he.key)??D.get(he.key);if(!Nr)continue;let{cascade:Aa}=await j.relation(Nr.objectApiName,F,he.field);Aa&&(g.has(he.key)?Q=!0:q??=D.get(he.key)?.part)}if(q===void 0||Q){x.push($);continue}let Re=E.get(q)??[],je=Re.find(he=>he.objectApiName===F);je?je.count++:Re.push({objectApiName:F,count:1}),E.set(q,Re)}x.length>0?N.set(F,x):N.delete(F)}E.size>0&&(a.otherParts=[...E].map(([F,_])=>({part:F,objects:_})));let T=new Map;for(let[F,_]of g)T.set(F,_.objectApiName);for(let[F,_]of N)for(let x of _)T.set(z(x.id),F);let I=[],O=new Set;for(let[F,_]of N)for(let x of _){let $=[];for(let q of x.references){let Q=T.get(q.key);if(!Q)continue;g.has(q.key)&&O.add(q.key);let{cascade:Re}=await j.relation(Q,F,q.field);$.push({key:q.key,cascade:Re})}I.push({key:z(x.id),created:x.created,automatedProcess:A.has(x.creator),references:$})}let C=await su(n,y,g,N,j,a,d);if(!C)return c();for(let F of C)O.add(F.from);if(!await iu(n,g,O,d))return c();let B=Eo({anchors:g,candidates:I,pointers:C,runSpan:h,window:s,removalBegan:p,madeEarlier:new Set((t.madeEarlier??[]).map(z)),lateEarlier:new Set((t.lateEarlier??[]).map(z))});return au(N,B,t,o,l,i),d()?c():(await cu(n,j,o,{user:r,span:m,lastWrite:l,removalSpans:i,isRun:F=>g.has(F)||e.remap.has(F)}),a.found.push(...M),t.muted&&(a.muted=t.muted),o.ordering={query:F=>n.query(F),queryDeleted:F=>n.queryDeleted(F),describe:async F=>await j.now(F)??n.describe(F),describeGlobal:()=>n.describeGlobal(),destroy:(F,_)=>n.destroy(F,_),update:(F,_)=>n.update(F,_),serverTime:()=>n.serverTime(),userId:()=>n.userId()},o)}var hi={untied:0,late:1,madeOver:2,made:3};async function cu(n,e,t,r){let o=new Map;for(let u of t.rows.values())for(let m of u)o.set(z(m.id),m);if(o.size===0||t.rows.has(ce))return;let s=(await To(n,{has:u=>o.has(u)||r.isRun(u),start:r.span.from,end:r.span.to,user:r.user})).filter(u=>!r.isRun(z(u.id))&&u.names.some(m=>o.has(m)));if(s.length===0)return;let i=await Ri(ce,e.of);if("reason"in i){t.listing.unread.push({objectApiName:ce,reason:i.reason});return}let a=new Map,d=s.map(u=>{let m=u.names.flatMap(R=>{let S=o.get(R);return S?[S]:[]});a.set(u.id,m.map(R=>z(R.id)));let g=m.reduce((R,S)=>hi[S.class]<hi[R]?S.class:R,"made"),h=Math.max(...m.map(R=>R.created)),y=u.modifiedBy!==void 0&&z(u.modifiedBy)===z(r.user)&&u.modified<=h+6e4;return{id:u.id,created:u.created,modified:y?Math.min(u.modified,u.created):u.modified,...u.modifiedBy!==void 0?{modifiedBy:z(u.modifiedBy)}:{},class:g,turn:"before"}});t.rows.set(ce,d),t.reports=a;let c={made:0,madeOver:0,late:0,untied:0},f=0,l={};for(let u of d)c[u.class]++,$t(u,r.lastWrite,r.removalSpans)&&(f++,l[u.class]=(l[u.class]??0)+1);let{listing:p}=t;p.found.push({objectApiName:ce,count:d.length,names:[],classes:{...c,...f>0?{changed:f,changedIn:l}:{}}}),c.late>0&&(p.late=[...p.late??[],{objectApiName:ce,count:c.late}]),c.untied>0&&p.untied&&(p.untied={...p.untied,objects:[...p.untied.objects,{objectApiName:ce,count:c.untied}]})}function $t(n,e,t){let r=Math.max(e,n.created)+2e3;return!(n.modified<=r)&&!uu(n,t)}function uu(n,e){return n.modifiedBy!==void 0&&e.some(t=>n.modifiedBy===z(t.userId)&&n.modified>=ne(t.first)&&n.modified<=ne(t.last))}async function zm(n,e,t=[]){return(await Oi(n,e,t)).listing}function lu(n,e){let t=[],r=n.late??[];r.length>0&&e.sweepLate!==!0&&t.push({class:"late",objects:r,option:"--sweep-late"});let{objects:o=[],refusal:s}=n.untied??{};return o.length>0&&(e.sweepUntied!==!0||s!==void 0)&&t.push({class:"untied",objects:o,option:"--sweep-untied",...s!==void 0?{refusal:s}:{}}),t}function Vm(n,e,t){let r=()=>e.signal?.aborted===!0,o=yo(),s=new Set,i=new Set,a=new Set,d=new Set,c=[],f="new",l,p,u,m=new Map,g={unread:[],handWork:[]},h=new Map,y=new Map,R=async(P,k)=>{let N=P.lastWrite??Number.NaN,M=new Set,D=new Map;for(let[C,B]of k){let F=B.filter(_=>t.includeChanged||!$t(_,N,t.removalSpans)).map(_=>_.id);for(let _ of F)M.add(_);D.set(C,F)}if(M.size===0||!P.window)return;let E=new Set(e.created.flatMap(({ids:C})=>C.map(z))),T=P.ordering??n,I=Fo(T,{runStart:P.window.from,runEnd:N,runRecords:{has:C=>E.has(C)},taken:M,removalSpans:t.removalSpans,includeChanged:t.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{}}),O=await wn(T,[...k.keys()].map(C=>({objectApiName:C})));for(let{objectApiName:C}of O){if(C===ce)continue;let B=D.get(C)??[];if(B.length===0)continue;if(r())return;let F=await I(C,B);F.reason!==void 0&&y.set(C,F.reason);for(let _ of B)F.held.has(z(_))&&(M.delete(_),h.set(_,F.holders))}S(P,k,M)},S=(P,k,N)=>{let M=P.reports;if(!M)return;let D=new Set([...k].filter(([E])=>E!==ce).flatMap(([,E])=>E.filter(T=>N.has(T.id)).map(T=>z(T.id))));for(let E of k.get(ce)??[])h.has(E.id)||(M.get(E.id)??[]).every(T=>D.has(T))||(N.delete(E.id),h.set(E.id,["DuplicateRecordItem"]))},w=(P,k)=>{P.result.alreadyGone++,P.along.has(k)&&(P.result.withRemoval=(P.result.withRemoval??0)+1)},b=(P,k,N)=>{k.forEach((M,D)=>{let E=N[D];if((E.lockResends!==void 0||P.lockResent.has(M))&&P.lockResent.set(M,E.kind),E.kind==="refused"){P.refused.set(M,E.reason),E.limit&&P.limited.add(M);return}P.refused.delete(M),P.limited.delete(M),d.add(M),E.kind==="deleted"?P.result.deleted++:w(P,M)})},A=async(P,k,N)=>{for(let M=0;M<k.length;M+=Le){if(r())return!1;let D=k.slice(M,M+Le),E=P.result.deleted,T=await Io(n,P.result.objectApiName,D,o,{stopped:r,settle:(I,O)=>b(P,I,[...O])});if(N&&P.result.deleted>E){let I=P.result.deleted-E;P.result.afterRemoval=(P.result.afterRemoval??0)+I,N==="under"&&(P.result.afterRemovalUnder=(P.result.afterRemovalUnder??0)+I)}if(T)return!1}return!0},j=()=>c.reduce((P,k)=>P+k.result.deleted,0),L=async()=>{let P=g.left??[];if(P.length===0||!u)return;let k=u.rows,N=[],M=[];for(let E of P){let T=[],I=[];for(let O of E.objects){let C=(k.get(O.objectApiName)??[]).filter(_=>_.class===E.class).map(_=>_.id),B=r()?[]:(await yn(C,_=>fe(n,O.objectApiName,[],_),()=>!0)).gone;for(let _ of B)d.add(_);let F=Math.min(B.length,O.count);O.count>F&&T.push({...O,count:O.count-F}),F>0&&I.push({objectApiName:O.objectApiName,count:F})}T.length>0&&N.push({...E,objects:T}),I.length>0&&M.push({class:E.class,objects:I})}if(M.length===0)return;let D={...g};delete D.left,g={...D,...N.length>0?{left:N}:{},goneAlong:M}},v=()=>(p??=(async()=>{let P=await Oi(n,e,t.removalSpans);u=P;let{listing:k}=P;if(g={...k.window?{window:k.window}:{},unread:[...k.unread,...k.found.filter(E=>E.overBound).map(E=>({objectApiName:E.objectApiName,reason:`More than ${Yn} records created by the run's user in the window: none is swept, as that many are more than the run\u2019s side effects come to.`}))],...k.automationGaps?{automationGaps:k.automationGaps}:{},handWork:k.handWork},P.stopped){f="cancelled";return}for(let E of P.rows.values())for(let T of E)T.class==="made"||T.class==="madeOver"?i.add(T.id):T.class==="late"&&a.add(T.id);if(k.refusal!==void 0){f="refused",l=k.refusal;return}let N=t.sweepUntied===!0&&k.untied?.refusal===void 0,M=E=>E.class==="made"||E.class==="madeOver"||E.class==="late"&&t.sweepLate===!0||E.class==="untied"&&N;if(m=new Map([...P.rows].map(([E,T])=>[E,T.filter(M)]).filter(([,E])=>E.length>0)),await R(P,m),r()){f="cancelled";return}if(t.approve&&m.size>0){let E=await t.approve(k);if(E!==void 0){f="refused",l=E;return}}let D=lu(k,t);D.length>0&&(g={...g,left:D}),f="asked"})(),p);return{automationMade:s,made:i,late:a,gone:d,get listing(){return u&&!u.stopped?u.listing:void 0},get takes(){return f==="asked"?[...m.keys()]:[]},ask:v,async first(P){if(P&&(o=P),await v(),f!=="asked"||!u)return!1;let k=u,N=m,M=k.lastWrite??Number.NaN,D=await wn(k.ordering??n,[...N.keys()].map(T=>({objectApiName:T}))),E=[];for(let{objectApiName:T}of D){let I=N.get(T)??[],O={result:{objectApiName:T,found:I.length,deleted:0,alreadyGone:0,keptChanged:0,refused:0,reasons:[]},refused:new Map,limited:new Set,later:[],along:new Set,lockResent:new Map};c.push(O);let C=[];for(let B of I){if($t(B,M,t.removalSpans)&&!t.includeChanged){O.result.keptChanged++;continue}let F=h.get(B.id);if(F){O.result.keptDependents=(O.result.keptDependents??0)+1,O.result.heldBy=[...new Set([...O.result.heldBy??[],...F])];continue}s.add(B.id),B.turn==="before"?C.push(B.id):O.later.push(B.id),B.turn==="with"&&O.along.add(B.id)}E.push([O,C])}for(let[T,I]of E)if(!await A(T,I))return f="cancelled",j()>0;return f="first",j()>0},async afterRemoval(P){if(P&&(o=P),f!=="first")return!1;let k=j();for(let N of c){let M=N.later.splice(0),D=M.filter(T=>N.along.has(T)),E=M.filter(T=>!N.along.has(T));if(!await A(N,E,"pointedAt")||!await A(N,D,"under"))return f="cancelled",j()>k}if(j()>0)for(let N of c){let M=[...N.refused.keys()].filter(D=>!N.limited.has(D));if(!await A(N,M))return f="cancelled",j()>k}for(let N of c){if(r())break;let{gone:M}=await yn([...N.refused.keys()],D=>fe(n,N.result.objectApiName,[],D),()=>!0);for(let D of M)N.refused.delete(D),N.lockResent.has(D)&&N.lockResent.set(D,"gone"),w(N,D),d.add(D)}return await L(),f="done",j()>k},result(){if(f==="refused")return{status:"refused",refusal:l??"",objects:[],...g};if(f==="new"||f==="asked")return{status:"cancelled",objects:[],...g};let P=c.map(({result:N,refused:M,lockResent:D})=>{N.refused=M.size;let E=y.get(N.objectApiName);return N.reasons=[...new Set([...E!==void 0&&(N.keptDependents??0)>0?[`What hangs from them could not be read, and they were kept: ${E}`]:[],...jo(N.objectApiName,o),...No(D.values()),...M.values()])].slice(0,Vc),N}),k=c.some(N=>N.later.length>0);return{status:fu(P,f==="cancelled",k,pu(g,t)),objects:P,...g}}}}function fu(n,e,t=!1,r=!1){return e?"cancelled":t||r||n.some(s=>s.keptChanged+(s.keptDependents??0)+s.refused>0)?n.some(s=>s.deleted>0)?"partial":"failure":"success"}function pu(n,e){return(n.left??[]).some(t=>t.class==="late"&&e.sweepLate===!0||t.class==="untied"&&e.sweepUntied===!0)}function Gm(n,e,t){if(n.status==="refused")return;let r=o=>n.objects.reduce((s,i)=>s+o(i),0);return{sweptAt:e,deleted:(t?.deleted??0)+r(o=>o.deleted),keptChanged:r(o=>o.keptChanged),refused:r(o=>o.refused)}}function Jm(n){return n.objects.filter(e=>e.deleted+e.refused>0).map(e=>({...ro(e.objectApiName),deleted:e.deleted,failed:e.refused}))}function Hm(n,e){let t=r=>n.objects.reduce((o,s)=>o+r(s),0);return{sweep:!0,forgeId:e,found:t(r=>r.found),deleted:t(r=>r.deleted),keptChanged:t(r=>r.keptChanged),refused:t(r=>r.refused),handWork:n.handWork.reduce((r,o)=>r+o.count,0)}}function Km(n){return n.found.reduce((e,t)=>e+t.count,0)}function Ym(n){return n.found.map(e=>e.objectApiName)}var mu=15e3,Xm=2,gu=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function hu(n,e){try{let{user_id:t}=await new Ot(mu).withTimeout(`${e} run user`,async()=>n());return typeof t=="string"&&gu.test(t)?t:void 0}catch{return}}function eg(n,e,t){n?.runUser&&hu(e,t).then(r=>{r!==void 0&&n.runUser?.(r)})}var Xn=class extends pe{constructor(t){super("SAMPLE_DRAW_INVALID",`${t.join(" ")} Nothing was written, and no root was counted or read: the requests sent before the draw were discovery\u2019s and the target\u2019s.`,void 0,void 0,void 0,{sample:{requests:0}});this.problems=t}problems},wu=1440*60*1e3,Ai=2,Ni=new Set(["picklist","boolean","reference"]),yu=6,Qn=12;function bu(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function ki(n){return n===void 0?0:bu(n).match(/\(\s*SELECT\b/gi)?.length??0}function Ve(n,e){let t=e.toLowerCase();return n?.find(r=>r.name.toLowerCase()===t)}function Wt(n){if(n.length===0)return"none";let e=n.slice(0,Qn).join(", ");return n.length>Qn?`${e} and ${n.length-Qn} more`:e}function Ru(n,e){if(n.lastDays!==void 0&&n.from===void 0&&n.to===void 0)return{window:{field:n.field,from:Ae(e-n.lastDays*wu),lastDays:n.lastDays}};let t=s=>{if(s!==void 0)try{return Ae(s)}catch{return null}},r=t(n.from),o=t(n.to);return r===null||o===null?{problem:`The window's bound ${r===null?n.from:n.to} is no instant: write it in UTC, as 2025-07-01T00:00:00Z.`}:r!==void 0&&o!==void 0&&Date.parse(r)>=Date.parse(o)?{problem:`The window starts at ${r} and ends before it, at ${o}: its start is before its end.`}:{window:{field:n.field,...r!==void 0?{from:r}:{},...o!==void 0?{to:o}:{}}}}function Ii(n,e){let t=(n.linksOf.get(e)??[]).find(r=>r.carries&&r.required&&r.prefix===void 0);return t?{field:t.field,parent:t.parent}:void 0}function Ei(n,e,t){let r=t.toLowerCase(),o=(n.linksOf.get(e)??[]).find(s=>s.carries&&s.field.toLowerCase()===r);return o?{parent:o.parent}:void 0}function Su(n,e){let t=(n.fieldsOf(e)??[]).filter(s=>s.groupable!==!1&&Ni.has(s.type??"")&&Ei(n.links,e,s.name)===void 0),r=["RecordTypeId","OwnerId"].flatMap(s=>{let i=Ve(t,s);return i?[i.name]:[]}),o=t.filter(s=>s.type==="picklist").map(s=>s.name).sort();return[...r,...o].slice(0,yu)}function qt(n,e){let t=Su(n,e);return"Its roots are stratified by a field of few values \u2014 a picklist, a checkbox, the record type (RecordTypeId) or the owner (OwnerId)"+(t.length>0?`: of ${e}, ${t.join(", ")}.`:".")}function ji(n,e,t){let r=n.fieldsOf(e),o=Ve(r,t);if(!o)return{problem:`${e} has no field ${t}. ${qt(n,e)}`};if(!Ni.has(o.type??""))return{problem:(o.type?`${e}.${o.name} is a ${o.type} field, of too many values to stratify by. `:`The describe does not say what type ${e}.${o.name} is, and a stratum is of a known few. `)+qt(n,e)};let s=Ei(n.links,e,o.name);return s?{problem:`${e}.${o.name} names the ${s.parent} a record of ${e} comes under, and a root of ${e} never fills it: it stratifies nothing. `+qt(n,e)}:o.groupable===!1?{problem:`The source does not group ${e} by ${o.name}, which its strata are counted by. ${qt(n,e)}`}:Ve(r,"Id")?.aggregatable===!1?{problem:`The source does not count the records of ${e} by a field (COUNT(Id)), which its strata are counted by: its roots cannot be stratified.`}:{field:o.name}}function Ti(n){let{links:e,options:t}=n,r=[],o;if(t.window!==void 0){let h=Ru(t.window,n.now);"problem"in h?r.push(h.problem):o=h.window}let s=[...e.classes].filter(([,h])=>h.kind==="drawn"&&h.rooted).map(([h])=>h).sort(),i=s.filter(h=>!Ii(e,h)),a=new Map([...e.classes.keys()].map(h=>[h.toLowerCase(),h])),d=new Map([...n.excluded??[]].map(h=>[h.toLowerCase(),h])),c=(h,y)=>{let R=y==="where"?"filter on its roots":"strata",S=a.get(h.toLowerCase()),w=S===void 0?void 0:e.classes.get(S);if(S===void 0||w===void 0){let A=d.get(h.toLowerCase());r.push(A!==void 0?`${A} is left out of the run (--exclude-object), and has no root to draw: take it out of one option or the other.`:`${h} is no object of the run, and takes no ${R}. The objects whose roots are drawn are ${Wt(i)}.`);return}if(w.kind==="whole"){r.push(`Every record of ${S} comes, as the sample copies it whole: it has no root drawn, and takes no ${R}. `+(y==="where"?"--filter leaves records of it out of the copy.":`The objects whose roots are drawn are ${Wt(i)}.`));return}if(!w.rooted){r.push(`${S} has no root of its own: its records come as the records the sample keeps name them, and it takes no ${R}. The objects whose roots are drawn are ${Wt(i)}.`);return}let b=Ii(e,S);if(b){r.push(`Every record of ${S} comes under the ${b.parent} it cannot be written without (${b.field}): it has no root, and takes no ${R}. `+(y==="where"?`Filter the roots of ${b.parent} instead: --fit-where "${b.parent}=Id IN (SELECT ${b.field} FROM ${S} WHERE \u2026)".`:`Stratify the roots of ${b.parent} instead.`));return}return S},f=new Map;for(let[h,y]of Object.entries(t.rootWhere??{})){let R=c(h,"where");if(R===void 0)continue;if(f.has(R)){r.push(`The roots of ${R} are given two filters: give one.`);continue}let S=ki(n.filterOf?.(R))+ki(y);if(S>Ai){r.push(`A statement of ${R} takes ${Ai} semi-joins at most (IN (SELECT \u2026)), and its filter and the filter on its roots hold ${S}: write one of them without, or fold them into fewer.`);continue}f.set(R,y.trim())}let l,p=new Map;for(let h of t.strata??[]){let y=h.indexOf(".");if(y<0){l=h;continue}let R=c(h.slice(0,y),"strata");if(R!==void 0){if(p.has(R)){r.push(`The roots of ${R} are stratified by one field at most: give one.`);continue}p.set(R,h.slice(y+1))}}let u=new Map;for(let[h,y]of p){let R=ji(n,h,y);"problem"in R?r.push(R.problem):u.set(h,R.field)}if(l!==void 0){let h=!1;for(let y of i){if(p.has(y))continue;let R=n.fieldsOf(y),S=Ve(R,l);if(!S||S.groupable===!1||Ve(R,"Id")?.aggregatable===!1)continue;h=!0;let w=ji(n,y,S.name);"problem"in w?r.push(`${w.problem} Or name each object ${l} stratifies, as Object.${l}.`):u.set(y,w.field)}h||r.push(`No object whose roots are drawn \u2014 ${Wt(i)} \u2014 has a field ${l} it groups by. Name the object and its field, as ${i[0]??"Account"}.RecordTypeId.`)}if(r.length>0)throw new Xn(r);let m=[],g=new Map;for(let h of s){let y=f.get(h),R=u.get(h),S={objectApiName:h,...y!==void 0?{where:y}:{},...R!==void 0?{stratifiedBy:R}:{}};o!==void 0&&(Ve(n.fieldsOf(h),o.field)?S.window={field:o.field,...o.from!==void 0?{from:o.from}:{},...o.to!==void 0?{to:o.to}:{}}:(S.notWindowed=!0,m.push(h))),g.set(h,S)}return{...o!==void 0?{window:o}:{},objects:g,notWindowed:m,where:[...f].map(([h,y])=>({objectApiName:h,where:y})).sort((h,y)=>h.objectApiName<y.objectApiName?-1:1),restricted:o!==void 0||f.size>0,stratified:u.size>0}}function Fi(n){return{...n.window!==void 0?{window:n.window}:{},...n.notWindowed.length>0?{notWindowed:[...n.notWindowed]}:{},...n.where.length>0?{where:n.where.map(e=>({...e}))}:{}}}function Ou(n,e){return n.created!==e.created?n.created===void 0?1:e.created===void 0?-1:e.created-n.created:ue(e.id,n.id)}var Au=1e6,er=class extends Error{constructor(t,r){super(`Drawing the sample read ${t} records, more than the ${r} it holds at once. Nothing was written. Lower the bound (--fit-within or --max-total), or leave objects out (--exclude-object) or narrow them (--filter).`);this.rows=t;this.most=r;this.name="SampleTooLarge"}rows;most},tr=class extends Error{constructor(){super("The sample was cancelled before it was drawn. Nothing was written."),this.name="SampleCancelled"}},ku="AccountId",nr=class{values=[];rows=[];get size(){return this.rows.length}push(e,t){let{values:r,rows:o}=this;r.push(e),o.push(t);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(r[i]<=r[s])break;[r[s],r[i]]=[r[i],r[s]],[o[s],o[i]]=[o[i],o[s]],s=i}}pop(){let{values:e,rows:t}=this,r=[e[0],t[0]],o=e.pop(),s=t.pop();if(t.length>0){e[0]=o,t[0]=s;let i=0;for(;;){let a=2*i+1,d=a+1,c=i;if(a<t.length&&e[a]<e[c]&&(c=a),d<t.length&&e[d]<e[c]&&(c=d),c===i)break;[e[i],e[c]]=[e[c],e[i]],[t[i],t[c]]=[t[c],t[i]],i=c}}return r}},Ut=class{constructor(e,t,r){this.links=e;this.reader=t;this.options=r}links;reader;options;rows=[];objectOf=[];rootOf=[];whole=[];dead=[];out=[];index=new Map;absent=new Map;wholeRead=new Set;below=new Map;cuts=new Map;needs=new Map;waiting=new Map;pending=new Map;upCursor=0;optionalCursor=0;descended=[];toDescend=[];rowOf(e,t){return this.index.get(e)?.get(U(t))}isAbsent(e,t){return this.absent.get(e)?.has(U(t))===!0}wasReadWhole(e){return this.wholeRead.has(e)}alive(e){return this.dead[e]===void 0}get cut(){return this.cuts}belowOf(e){return this.below.get(e)??[]}async openWhole(){let e=new Set;for(let t of this.links.linksOf.values())for(let r of t)r.target==="whole"&&e.add(r.parent);for(let[t,r]of this.links.classes){if(r.kind!=="whole"||r.why==="referenceData"||!(this.links.linksOf.get(t)??[]).some(i=>i.target==="drawn"&&(i.required||this.options.parents==="all"))&&!e.has(t))continue;this.checkSignal();let s=await this.reader.whole(t);this.wholeRead.add(t);for(let i of s){let a=this.register(t,i);this.whole[a]=!0}this.told()}await this.close()}async addRoots(e,t){let r=new Map;e.forEach((o,s)=>{let i=r.get(o.objectApiName)??[];i.push({id:o.id,index:t+s}),r.set(o.objectApiName,i)});for(let[o,s]of[...r].sort(([i],[a])=>i<a?-1:1)){let i=s.filter(({id:a})=>this.rowOf(o,a)===void 0).map(({id:a})=>a).sort(ue);if(i.length>0){this.checkSignal();let a=await this.reader.rows(o,i);for(let d of a)this.register(o,d);this.markAbsent(o,i),this.told()}for(let{id:a,index:d}of s){let c=this.rowOf(o,a);c===void 0||this.rootOf[c]>=0||(this.rootOf[c]=d,this.toDescend.push(c))}}await this.close()}async close(){for(;;)if(await this.readUp(),!await this.readOptionalParents()&&!await this.readDown())return}requiredHere(e,t){return e.required?!0:e.objectApiName===oe&&e.field===ku&&e.parent===de&&this.rows[t].personAccount===!0}requiredOf(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[],i;for(let a of this.links.linksOf.get(t)??[]){if(!this.requiredHere(a,e))continue;let d=r[a.field];Pe(d,a)&&(a.target==="excluded"?i??="excludedObject":(a.target==="drawn"||this.wholeRead.has(a.parent))&&s.push({objectApiName:a.parent,id:d}))}for(let a of o??[])a.id===null?i??="noParentInSource":this.readable(a.objectApiName)&&s.push({objectApiName:a.objectApiName,id:a.id});return{named:s,...i?{dies:i}:{}}}readable(e){let t=this.links.classes.get(e);return t!==void 0&&(t.kind==="drawn"||this.wholeRead.has(e))}optionalOf(e){let t=this.objectOf[e],{refs:r}=this.rows[e],o=[];for(let s of this.links.linksOf.get(t)??[]){if(s.target!=="drawn"||this.requiredHere(s,e))continue;let i=r[s.field];Pe(i,s)&&o.push({objectApiName:s.parent,id:i})}return o}upTargets(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[];for(let i of this.links.linksOf.get(t)??[]){if(i.target==="excluded"||i.target==="whole"&&!this.wholeRead.has(i.parent)||!this.requiredHere(i,e)&&this.options.parents!=="all")continue;let a=r[i.field];if(!Pe(a,i))continue;let d=this.rowOf(i.parent,a);d!==void 0&&s.push({row:d,field:i.field})}for(let i of o??[]){if(i.id===null||!this.readable(i.objectApiName))continue;let a=this.rowOf(i.objectApiName,i.id);a!==void 0&&s.push({row:a,field:`(${i.objectApiName})`})}return s}async readUp(){for(;;){for(;this.upCursor<this.rows.length;this.upCursor++){let e=this.upCursor,{named:t,dies:r}=this.requiredOf(e);r&&this.kill(e,r);for(let o of t)this.need(e,o)}if(this.pending.size===0)return;await this.readPending()}}async readOptionalParents(){if(this.options.parents!=="all")return!1;for(;this.optionalCursor<this.upCursor;this.optionalCursor++){let e=this.optionalCursor;if(this.alive(e))for(let t of this.optionalOf(e))this.ask(t)}return this.pending.size===0?!1:(await this.readPending(),!0)}async readDown(){let e=new Map,t=this.toDescend;this.toDescend=[];for(let r of t)if(!(this.descended[r]||!this.alive(r))){this.descended[r]=!0;for(let o of this.links.carriersInto.get(this.objectOf[r])??[]){let s=`${o.objectApiName}.${o.field}`,i=e.get(s);i||(i={masterDetail:o.masterDetail,parents:new Map,objects:new Set},e.set(s,i)),i.objects.add(o.parent),i.parents.set(U(this.rows[r].id),r)}}if(e.size===0)return!1;for(let[r,o]of[...e].sort(([s],[i])=>s<i?-1:1)){let s=r.indexOf("."),i={objectApiName:r.slice(0,s),field:r.slice(s+1),parents:[...o.objects].sort(),masterDetail:o.masterDetail},a=i.masterDetail?"all":this.options.children,d=[...o.parents.values()].map(u=>this.rows[u].id).sort(ue);this.checkSignal();let c=await this.reader.children(i,d,a),f=new Map;for(let u of c.rows){let m=u.refs[i.field];if(typeof m!="string"||m==="")continue;let g=o.parents.get(U(m));if(g===void 0)continue;let h=f.get(g)??new Map;h.has(U(u.id))||h.set(U(u.id),u),f.set(g,h)}let l=new Map;for(let[u,m]of c.counts??[])l.set(U(u),m);let p=this.cuts.get(r)??new Map;for(let[u,m]of[...f].sort(([g],[h])=>g-h)){let g=[...m.values()].sort(Ou),h=a==="all"?g:g.slice(0,a),y=this.below.get(u)??[];for(let S of h){let w=this.register(i.objectApiName,S);y.push({child:w,relation:r}),this.descended[w]||this.toDescend.push(w)}this.below.set(u,y);let R=l.get(U(this.rows[u].id))??m.size;R>h.length&&p.set(u,R-h.length)}p.size>0&&this.cuts.set(r,p),this.told()}return!0}need(e,t){let r=this.rowOf(t.objectApiName,t.id);if(r!==void 0){this.tie(r,e);return}if(this.isAbsent(t.objectApiName,t.id)){this.kill(e,"noParentInSource");return}let o=`${t.objectApiName}
|
|
25
|
+
${U(t.id)}`,s=this.waiting.get(o)??[];s.push(e),this.waiting.set(o,s),this.ask(t)}ask(e){if(this.rowOf(e.objectApiName,e.id)!==void 0||this.isAbsent(e.objectApiName,e.id))return;let t=this.pending.get(e.objectApiName)??new Map;t.set(U(e.id),e.id),this.pending.set(e.objectApiName,t)}async readPending(){let e=[...this.pending].sort(([t],[r])=>t<r?-1:1);this.pending.clear();for(let[t,r]of e){let o=[...r.values()].sort(ue);this.checkSignal();let s=await this.reader.rows(t,o);for(let i of s)this.register(t,i);this.markAbsent(t,o),this.told()}}markAbsent(e,t){for(let r of t){if(this.rowOf(e,r)!==void 0)continue;let o=this.absent.get(e)??new Set;o.add(U(r)),this.absent.set(e,o);let s=`${e}
|
|
26
|
+
${U(r)}`;for(let i of this.waiting.get(s)??[])this.kill(i,"noParentInSource");this.waiting.delete(s)}}register(e,t){let r=this.index.get(e);r||(r=new Map,this.index.set(e,r));let o=U(t.id),s=r.get(o);if(s!==void 0)return s;let i=this.rows.length;this.rows.push(t),this.objectOf.push(e),this.rootOf.push(-1),this.whole.push(!1),this.dead.push(void 0),this.out.push(!1),this.descended.push(!1),r.set(o,i);let a=this.options.maxRows??Au;if(this.rows.length>a)throw new er(this.rows.length,a);if(t.outsideFilter)this.out[i]=!0,this.kill(i,"outsideFilter");else if(typeof t.recordTypeId=="string"&&t.recordTypeId!==""){let c=this.options.recordTypeVerdict?.(e,t.recordTypeId);c&&this.kill(i,c)}let d=this.waiting.get(`${e}
|
|
27
|
+
${o}`);if(d){this.waiting.delete(`${e}
|
|
28
|
+
${o}`);for(let c of d)this.tie(i,c)}return i}tie(e,t){let r=this.needs.get(e)??[];r.push(t),this.needs.set(e,r),this.alive(e)||this.kill(t,this.out[e]?"outsideFilter":"withoutParent")}kill(e,t){if(!this.alive(e))return;this.dead[e]=t;let r=[e];for(;r.length>0;){let o=r.pop(),s=this.out[o]?"outsideFilter":"withoutParent";for(let i of this.needs.get(o)??[])this.alive(i)&&(this.dead[i]=s,r.push(i))}}checkSignal(){if(this.options.signal?.aborted)throw new tr}told(){this.options.onRows?.(this.rows.length)}thresholds(e=new Set){let t=this.rows.length,r=new Float64Array(t).fill(1/0),o=new Array(t),s=new Array(t),i=new nr;for(let c=0;c<t;c++){let f=this.rootOf[c];f>=0&&!e.has(f)&&(r[c]=f,i.push(f,c))}let a=new Uint8Array(t);for(;i.size>0;){let[c,f]=i.pop();if(!(a[f]||c>r[f]||!this.alive(f))){a[f]=1;for(let{child:l,relation:p}of this.below.get(f)??[])c<r[l]?(r[l]=c,s[l]=p,i.push(c,l)):c===r[l]&&p<(s[l]??"")&&(s[l]=p)}}let d=new Float64Array(r);for(let c=0;c<t;c++)this.whole[c]&&(d[c]=-1),d[c]!==1/0&&i.push(d[c],c),o[c]=s[c];for(a.fill(0);i.size>0;){let[c,f]=i.pop();if(!(a[f]||c>d[f]||!this.alive(f))){a[f]=1;for(let{row:l,field:p}of this.upTargets(f)){let u=`${this.objectOf[f]}.${p}`;c<d[l]?(d[l]=c,o[l]=u,i.push(c,l)):c===d[l]&&o[l]!==void 0&&u<o[l]&&(o[l]=u)}}}return{threshold:d,above:r,via:o}}};var Ci={bytes:(n,e)=>e.bytes??os(n,e.personAccount?{IsPersonAccount:!0}:{}),wholeBytes:(n,e)=>ye(n,{rows:e})},Iu=[{objectApiName:oe,field:"AccountId",writes:"AccountContactRelation",ownField:"ContactId",pairField:"AccountId"},{objectApiName:"Opportunity",field:"ContactId",writes:"OpportunityContactRole",ownField:"OpportunityId",pairField:"ContactId"}],ju=.1,Nu=256,Eu=5;function rr(n,e){return e<0?-1/0:e===1/0?1/0:n[e].rank}function xi(n,e){let t=n.rows[e];return t.matched||t.replaced||n.objectOf[e]===oe&&t.personAccount===!0?0:1}function Tu(n,e,t){let r=new Map,{links:o}=n,s=t.filter(i=>o.classes.has(i.writes)&&(o.linksOf.get(i.objectApiName)??[]).some(a=>a.field===i.field));if(s.length===0)return r;for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.objectApiName)continue;let d=n.rows[i];if(a.objectApiName===oe&&d.personAccount)continue;let c=d.refs[a.field],f=ri(o,a.objectApiName,a.field,c);if(!f||typeof c!="string")continue;let l=n.rowOf(f.parent,c);if(l===void 0||!n.alive(l))continue;let p=Math.max(e.threshold[i],e.threshold[l]);p!==1/0&&r.set(`${a.writes}
|
|
29
|
+
${U(d.id)}
|
|
30
|
+
${U(c)}`,{objectApiName:a.writes,threshold:p,rows:[]})}for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.writes)continue;let{refs:d}=n.rows[i],c=d[a.ownField],f=d[a.pairField];if(typeof c!="string"||typeof f!="string")continue;let l=r.get(`${a.writes}
|
|
31
|
+
${U(c)}
|
|
32
|
+
${U(f)}`);l&&l.rows.push(i)}for(let i of r.values())i.rows.sort((a,d)=>e.threshold[a]-e.threshold[d]||ue(n.rows[a].id,n.rows[d].id));return r}function Fu(n,e,t){let{measure:r,draw:o}=t,s=[],i=new Float64Array(n.rows.length),a=new Map,d=(l,p)=>{l>=0&&l!==1/0&&a.set(l,(a.get(l)??0)+p)},c=Tu(n,e,t.platformPairs??Iu),f=new Set;for(let l of c.values())l.rows.length>0&&f.add(l.rows[0]);for(let l=0;l<n.rows.length;l++){if(!n.alive(l))continue;let p=n.objectOf[l],u=n.rows[l],m=f.has(l)?0:xi(n,l),h=(u.matched||u.replaced||f.has(l)?0:r.bytes(p,u))+m*(r.roomBytes?.(p)??0);i[l]=h;let y=e.threshold[l];y!==1/0&&(s.push({rank:rr(o.roots,y),bytes:h,records:m,objectApiName:p}),d(y,h))}for(let l of c.values()){let p=r.bytes(l.objectApiName,{id:"",refs:{}});s.push({rank:rr(o.roots,l.threshold),bytes:p,records:0,objectApiName:l.objectApiName}),d(l.threshold,p)}for(let[l,p]of n.links.classes){if(p.kind!=="whole"||n.wasReadWhole(l))continue;let u=t.sourceRows.get(l)??0,m=p.why==="referenceData",g=m?0:u;s.push({rank:-1/0,bytes:(m?0:r.wholeBytes(l,u))+g*(r.roomBytes?.(l)??0),records:g,objectApiName:l})}return s.sort((l,p)=>l.rank-p.rank),{items:s,rowBytes:i,parts:a,pairs:c}}function Mi(n,e,t){let r=0,o=0,s=new Map;for(let i of n){if(i.rank>e)break;r+=i.bytes,o+=i.records,t&&i.records>0&&s.set(i.objectApiName,(s.get(i.objectApiName)??0)+i.records)}return{bytes:r,records:o,written:s}}function zt(n,e,t){let r=Mi(n,e,t.requests!==void 0);return r.bytes>t.bytes?ks(r.bytes,t):t.maxTotal!==void 0&&r.records>t.maxTotal?"maxTotal":t.requests?.(r.written)}function Pi(n,e,t){let r=ju*Math.max(0,e.roomBytes),o=new Set;e.draw.floor>0&&e.draw.roots.forEach((i,a)=>{i.rank===0&&o.add(a)});let s=Li(n);for(s!==void 0&&o.add(s);;){let i=n.thresholds(t),a=Fu(n,i,e),d=[...a.parts].filter(([c,f])=>f>r&&!t.has(c)&&!o.has(c)).map(([c])=>c);if(d.length===0)return{thresholds:i,weighed:a};for(let c of d)t.add(c)}}function Li(n){let e;for(let t=0;t<n.rows.length;t++){let r=n.rootOf[t];r>=0&&n.alive(t)&&(e===void 0||r<e)&&(e=r)}return e}function vi(n,e,t,r){let o=Mi(e,t,!1),s=new Map;for(let i of e){if(i.rank>t)break;let a=s.get(i.objectApiName)??{rows:0,storageBytes:0};a.rows+=i.records,a.storageBytes+=i.bytes,s.set(i.objectApiName,a)}return{kind:"cannotFit",limitedBy:zt(e,t,r)??r.bytesLimit,rows:o.records,storageBytes:o.bytes,heaviest:[...s].sort(([i,a],[d,c])=>c.storageBytes-a.storageBytes||(i<d?-1:i>d?1:0)).slice(0,Eu).map(([i,a])=>({objectApiName:i,...a,...n.links.classes.get(i)?.kind==="whole"?{whole:!0}:{}}))}}async function _i(n){let e=n.draw.roots.filter(c=>c.rank<n.draw.beyond),t={...n,draw:{...n.draw,roots:e}},{bounds:r}=t,o=new Ut(t.links,t.reader,{...t.options,onRows:c=>{t.options.onRows?.(c),t.onStep?.("closing",c)}});await o.openWhole();let s=new Set,i=0,a=Nu,d=Pi(o,t,s);for(;i<e.length;){let c=Math.min(e.length,i+a);for(;c<e.length&&e[c].rank===e[c-1].rank;)c++;if(await o.addRoots(e.slice(i,c),i),i=c,a*=2,d=Pi(o,t,s),zt(d.weighed.items,e[i-1].rank,r)!==void 0)break}return t.onStep?.("fitting",o.rows.length),Pu(o,d,s,t,e.slice(0,i),i===e.length)}function Pu(n,e,t,r,o,s){let{bounds:i,draw:a}=r,{items:d}=e.weighed,c=[...new Set(o.map(h=>h.rank))].sort((h,y)=>h-y),f=a.floor>0&&c[0]===0?c:[-1/0,...c],l=Is(f.length,h=>zt(d,f[h-1],i)===void 0);if(l===0)return vi(n,d,f[0],i);let p=f[l-1],u=Li(n);if(u!==void 0&&o[u].rank>p)return{...vi(n,d,o[u].rank,i),noRoot:!0};let m=Cu(n,e,t,r,p),g=l<f.length?zt(d,f[l],i)??i.bytesLimit:!s||a.beyond!==1/0?a.heldBy:m.heavyRoots.length>0?"heavyRoots":a.restricted===!0?"draw":"whole";return{kind:"sample",share:g==="whole"||g==="heavyRoots"||g==="draw"?1:Math.max(0,p),limitedBy:g,wholeOrgFits:vu(n,r),...m}}function vu(n,e){let t=0,r=0,o=new Map;for(let[i,a]of n.links.classes){let d=e.sourceRows.get(i)??0;a.kind==="whole"&&a.why==="referenceData"||(t+=e.measure.wholeBytes(i,d),r+=d,o.set(i,d))}let{bounds:s}=e;return t<=s.bytes&&(s.maxTotal===void 0||r<=s.maxTotal)&&s.requests?.(o)===void 0}function Cu(n,e,t,r,o){let{links:s}=n,{thresholds:i,weighed:a}=e,d=r.draw.roots,c=k=>rr(d,k),f=k=>n.alive(k)&&c(i.threshold[k])<=o,l=k=>{if(n.whole[k])return"whole";let N=n.rootOf[k];return N>=0&&!t.has(N)&&c(N)<=o?"root":c(i.above[k])<=o?"below":"parent"},p=new Map,u=k=>{let N=p.get(k);return N||(N={objectApiName:k,sourceRows:r.sourceRows.get(k)??0,kept:0,roots:0,below:0,asParents:0},s.classes.get(k)?.kind==="whole"&&(N.whole=!0),p.set(k,N)),N},m=new Map,g=new Map,h=new Map,y=new Map,R=new Map,S=new Set;for(let k of a.pairs.values())k.rows.length>0&&S.add(k.rows[0]);let w=0,b=0,A=0,j=k=>r.measure.roomBytes?.(k)??0;for(let k=0;k<n.rows.length;k++){let N=n.objectOf[k];if(!n.alive(k)){let T=n.dead[k];if(n.out[k]||T===void 0||c(i.threshold[k])>o)continue;let I=`${N}
|
|
33
|
+
${T}`,O=y.get(I)??{objectApiName:N,rows:0,reason:T};O.rows++,y.set(I,O);continue}if(!f(k))continue;let M=n.rows[k],D=m.get(N)??[];D.push(M.id),m.set(N,D),b+=a.rowBytes[k];let E=S.has(k)?0:xi(n,k);if(w+=E,A+=E*j(N),M.personAccount&&(N===de||N===oe)&&h.set(N,(h.get(N)??0)+1),!M.matched){let T=u(N);T.kept++;let I=l(k);if(I==="root"){T.roots++;let O=g.get(N)??new Set;O.add(U(M.id)),g.set(N,O)}else I==="below"?T.below++:I==="parent"&&T.asParents++}for(let T of s.linksOf.get(N)??[]){if(T.target==="excluded"||T.target==="whole"&&!n.wasReadWhole(T.parent))continue;let I=M.refs[T.field];if(!Pe(I,T))continue;let O=n.rowOf(T.parent,I);if(O!==void 0&&f(O))continue;let C=`${N}
|
|
34
|
+
${T.field}`,B=R.get(C)??{objectApiName:N,field:T.field,rows:0};B.rows++,R.set(C,B)}}for(let[k,N]of s.classes){if(N.kind!=="whole"||n.wasReadWhole(k))continue;let M=r.sourceRows.get(k)??0,D=u(k);D.kept=M,N.why!=="referenceData"&&(w+=M,b+=r.measure.wholeBytes(k,M)+M*j(k),A+=M*j(k))}let L=new Map;for(let k of a.pairs.values()){if(c(k.threshold)>o)continue;let N=L.get(k.objectApiName)??{objectApiName:k.objectApiName,inPlan:0,beyond:0};k.rows.length>0&&f(k.rows[0])?N.inPlan++:N.beyond++,b+=r.measure.bytes(k.objectApiName,{id:"",refs:{}}),L.set(k.objectApiName,N)}for(let[k,N]of n.cut){let M=0;for(let[T,I]of N)f(T)&&c(i.above[T])<=o&&(M+=I);if(M===0)continue;let D=k.indexOf("."),E=u(k.slice(0,D));E.childrenCut=[...E.childrenCut??[],{field:k.slice(D+1),rows:M}]}let v=[...p.values()].filter(k=>k.kept>0).sort((k,N)=>N.kept-k.kept||(k.objectApiName<N.objectApiName?-1:1)),P=[...s.classes].filter(([k,N])=>{let M=r.sourceRows.get(k)??0;return N.kind==="drawn"&&M>0&&(p.get(k)?.kept??0)===0}).map(([k])=>({objectApiName:k,sourceRows:r.sourceRows.get(k)??0})).sort((k,N)=>k.objectApiName<N.objectApiName?-1:1);return{rows:v.reduce((k,N)=>k+N.kept,0),storageBytes:b,automationBytes:A,written:w,objects:v,heavyRoots:Mu(n,e,t,d,o),dropped:[...y.values()].sort(or(k=>k.reason)),leftEmpty:[...R.values()].sort(or(k=>k.field)),noRecordDrawn:P,partialMasters:xu(s,p,r.sourceRows),ids:new Map([...m].map(([k,N])=>[k,N.sort(ue)])),rootIds:g,personAccounts:h,byThePlatform:[...L.values()].sort((k,N)=>k.objectApiName<N.objectApiName?-1:1)}}function xu(n,e,t){let r=[];for(let[o,s]of n.linksOf){if(n.classes.get(o)?.kind!=="drawn")continue;let i=e.get(o)?.kept??0;for(let a of s){if(!a.masterDetail||a.target==="excluded"||a.parent===o)continue;let d=e.get(a.parent);if(!d||d.kept===0)continue;let c={objectApiName:a.parent,details:o,field:a.field};if(a.target==="whole"){let f=t.get(o)??0;i<f&&r.push({...c,kept:i,sourceRows:f})}else a.carries&&d.asParents>0&&r.push({...c,asParents:d.asParents})}}return r.sort(or(o=>`${o.details}
|
|
35
|
+
${o.field}`))}function or(n){return(e,t)=>{if(e.objectApiName!==t.objectApiName)return e.objectApiName<t.objectApiName?-1:1;let r=n(e),o=n(t);return r<o?-1:r>o?1:0}}function Mu(n,e,t,r,o){let s=[...t].filter(a=>r[a].rank<=o).sort((a,d)=>a-d);if(s.length===0)return[];let i=[];for(let a of s){let d=new Set(t);d.delete(a);let c=n.thresholds(d),f=0,l=new Map;for(let m=0;m<n.rows.length;m++){if(!n.alive(m)||c.threshold[m]!==a)continue;f++;let g=c.via[m];g!==void 0&&l.set(g,(l.get(g)??0)+e.weighed.rowBytes[m])}let[p]=[...l].sort(([m,g],[h,y])=>y-g||(m<h?-1:m>h?1:0))[0]??[`${r[a].objectApiName}.Id`],u=p.indexOf(".");i.push({objectApiName:r[a].objectApiName,id:r[a].id,rows:f,relation:{objectApiName:p.slice(0,u),field:p.slice(u+1)}})}return i}var Di=50;function sr(n){return n===null?"none":typeof n=="boolean"?n?"true":"false":`=${n}`}function Bi(n,e){return(n+.5)/Math.max(e,n+1)}function $i(n,e,t){let r=n.reduce((s,i)=>s+Math.max(0,i),0),o=Math.max(0,e)+n.length;return n.map(s=>s<=0?0:Math.min(s,Math.ceil(o*s/r)+1+Math.max(0,t)))}var Vt=class{constructor(e){this.input=e;for(let t of e.strata){let r=sr(t.value),o=this.strata.get(r);if(o){o.counted+=Math.max(0,t.roots),o.take+=Math.max(0,t.take);continue}this.strata.set(r,{key:r,value:t.value,counted:Math.max(0,t.roots),scanned:0,take:Math.max(0,t.take),heap:new Sn,read:[]})}}input;strata=new Map;get objectApiName(){return this.input.objectApiName}get field(){return this.input.field}reads(){return[...this.strata.values()].filter(e=>e.take>0).sort((e,t)=>e.key<t.key?-1:e.key>t.key?1:0).map(e=>({value:e.value,key:e.key,roots:e.counted,take:e.take}))}scanned(e,t){let r=sr(t),o=this.strata.get(r);o||(o={key:r,value:t,counted:0,scanned:0,take:Math.max(0,this.input.floor)+2,heap:new Sn,read:[]},this.strata.set(r,o)),o.scanned++,o.heap.push({objectApiName:this.input.objectApiName,id:e,rank:jt(this.input.seed,e)}),o.heap.size>o.take&&o.heap.pop()}read(e,t){let r=this.strata.get(sr(e));if(!r)throw new Error(`${this.input.objectApiName}.${this.input.field} was not counted with that value: its roots are not read.`);r.read.push(...t)}rootsOf(e){return this.input.draw==="uniform"?e.scanned:e.counted}orderOf(e){return this.input.draw!=="uniform"?e.read:[...e.heap.values()].sort(Zo).map(t=>t.id)}ranked(){let e=[];for(let t of this.strata.values()){let r=this.rootsOf(t);this.orderOf(t).forEach((o,s)=>{e.push({id:o,rank:Bi(s,r),stratum:t.key})})}return e}get firstUnread(){let e=1/0;for(let t of this.strata.values()){let r=this.input.draw==="uniform";if(!(r?t.scanned>t.take:t.read.length>=t.take&&t.take<t.counted))continue;let s=r?t.take:t.read.length;e=Math.min(e,Bi(s,this.rootsOf(t)))}return e}report(e,t){let r=[...this.strata.values()].map(s=>{let i=t?.(s.value);return{key:s.key,entry:{value:s.value,...i!==void 0?{label:i}:{},roots:this.rootsOf(s),kept:this.orderOf(s).filter(a=>e(a)).length}}}).sort((s,i)=>s.entry.roots!==i.entry.roots?i.entry.roots-s.entry.roots:s.key<i.key?-1:s.key>i.key?1:0),o=r.length-Di;return{objectApiName:this.input.objectApiName,field:this.input.field,values:r.slice(0,Di).map(s=>s.entry),...o>0?{more:o}:{}}}};var Wi=class extends Error{constructor(t,r,o){super(r);this.code=t;this.heaviest=o;this.name="SampleRefusedError"}code;heaviest},ir=[mt,Ce,ht,gt,"IsActive"];function qi(n){return n===!0||n==="true"}function Gt(n){return typeof n=="string"&&n!==""?n:null}function Lu(n){let e=n.CreatedDate,t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Ui(n){let e=t=>{let r=n[t];return typeof r=="string"?U(r):""};return[e(mt),e(Ce),e(gt)].join(`
|
|
36
|
+
`)}function zi(n){let e=t=>{let r=n[t];return typeof r=="string"?r:""};return[U(e(Ce)),e(ht),U(e(gt))].join(`
|
|
37
|
+
`)}var ar=class{constructor(e,t,r,o){this.reader=e;this.links=t;this.sourceRows=r;this.priceCurrencyWrittenIn=o}reader;links;sourceRows;priceCurrencyWrittenIn;cappedByIds=new Set;columnsOf(e){let t=[...Gn(this.links,e),"RecordTypeId"];return(e===de||e===oe)&&t.push("IsPersonAccount"),e===Xe&&t.push(...ir),e===cn&&t.push("IsStandard"),t}rowOf(e,t,r=!1){let o={};for(let a of Gn(this.links,e))o[a]=Gt(t[a]);let s=t.RecordTypeId,i=Lu(t);return{id:String(t.Id),refs:o,...typeof s=="string"||s===null?{recordTypeId:Gt(s)}:{},...(e===de||e===oe)&&qi(t.IsPersonAccount)?{personAccount:!0}:{},...e===cn&&qi(t.IsStandard)?{matched:!0}:{},...r?{outsideFilter:!0}:{},...i!==void 0?{created:i}:{}}}async sampleRowsOf(e,t,r=[]){let o=[...t.map(f=>this.rowOf(e,f)),...r.map(f=>this.rowOf(e,f,!0))];if(e!==Xe||t.length===0)return o;let s=[...new Set(t.flatMap(f=>{let l=Gt(f[Ce]);return l?[l]:[]}))],i=await this.reader.readStandardPrices(s,ir.slice(1)),a=new Set(i.map(f=>U(String(f.Id)))),d=new Map;for(let f of i)d.set(zi(f),String(f.Id));let c=await this.pricesWrittenFor(t);return o.map((f,l)=>{let p=t[l];if(p===void 0)return f;let u=[];a.has(U(f.id))||u.push({objectApiName:Xe,id:d.get(zi(p))??null});let m=c.get(f.id);return m!==void 0&&u.push({objectApiName:Xe,id:m}),u.length===0?f:{...f,also:u,...m!==void 0?{replaced:!0}:{}}})}async pricesWrittenFor(e){let t=new Map,r=this.priceCurrencyWrittenIn;if(!r)return t;let o=new Map;for(let s of e){let i=s[ht];if(typeof i!="string")continue;let a=r(i);a===void 0||a===i||o.set(a,[...o.get(a)??[],s])}for(let[s,i]of o){let a=f=>i.flatMap(l=>{let p=Gt(l[f]);return p?[p]:[]}),d=await this.reader.readPricesIn(s,a(Ce),a(mt),ir),c=new Map(d.map(f=>[Ui(f),String(f.Id)]));for(let f of i){let l=c.get(Ui(f));l!==void 0&&t.set(String(f.Id),l)}}return t}async rows(e,t){let[r]=await this.reader.readParents([{objectApiName:e,ids:t,columns:this.columnsOf(e)}]);return r?this.sampleRowsOf(e,r.rows,r.outsideFilter):[]}async children(e,t,r){let[o]=await this.reader.readChildren([{objectApiName:e.objectApiName,field:e.field,parentIds:t,columns:this.columnsOf(e.objectApiName),cap:r,sourceRows:this.sourceRows.get(e.objectApiName)??Number.MAX_SAFE_INTEGER}]);return o?(o.newestBy==="id"&&o.cut.some(s=>s.rows>0)&&this.cappedByIds.add(e.objectApiName),{rows:await this.sampleRowsOf(e.objectApiName,o.rows),counts:o.counts}):{rows:[]}}async whole(e){let t=[];return await this.reader.readWhole([{objectApiName:e,columns:this.columnsOf(e)}],(r,o)=>{for(let s of o)t.push(s)}),this.sampleRowsOf(e,t)}};function _u(n,e){let{empty:t,told:r}=ni(n,e),o=n.linksOf.get(e)??[];return[...t.map(s=>({field:s})),...r.map(s=>({field:s,drawnPrefixes:new Set(o.flatMap(i=>i.field===s&&i.carries&&typeof i.prefix=="string"?[i.prefix]:[]))}))]}function Du(n){let e=n.field==="LastModifiedDate"?"last modified":"made";if(n.lastDays!==void 0)return`roots ${e} in the last ${n.lastDays} days`+(n.from!==void 0?`, from ${n.from}`:"");let t=n.from!==void 0?` from ${n.from}`:"",r=n.to!==void 0?` to before ${n.to}`:"";return`roots ${e}${t}${r}`}function Bu(n,e,t){let r=[...n.window?[Du(n.window)]:[],...n.where.map(({objectApiName:i,where:a})=>`${i} where ${a}`)],o=e.filter(i=>(i.inTheSource?.rows??0)>0).map(i=>`${i.objectApiName} ${i.inTheSource?.exact===!1?"at most ":""}${i.inTheSource?.rows??0}`),s=[...n.window?["widen the window (--fit-window)"]:[],...n.where.length>0?["loosen the filters on the roots (--fit-where)"]:[],"draw without them"].join(", or ");return new pe("SAMPLE_DRAW_EMPTY",`No object has a root in the draw: ${r.join("; ")}.`+(n.notWindowed.length>0?` The window does not date ${n.notWindowed.join(", ")}, which have no root in it.`:"")+(o.length>0?` The source holds roots outside them: ${o.join(", ")}.`:"")+` Nothing was written, and the counts sent ${t} request(s) of the source. ${s.charAt(0).toUpperCase()}${s.slice(1)}.`,void 0,void 0,void 0,{sample:{requests:t}})}function $u(n,e){let t=e.restricted?"narrow the window or the filters on the roots (--fit-window, --fit-where)":"draw among fewer roots (--fit-window, --fit-where)";return n==="uniform"?`Draw the most recent records (--fit-draw recent) or the oldest (--fit-draw oldest), ${t}, or narrow the large objects (--filter).`:`${t.charAt(0).toUpperCase()}${t.slice(1)}`+(e.stratified?", stratify fewer objects (--fit-strata)":"")+", narrow the large objects (--filter), or draw it once the source has more to spare."}async function Ng(n){let{options:e,budget:t}=n,r=I=>n.averageBytes?.get(I),o=(I,O)=>{let C=r(I);return C!==void 0?O*C:ye(I,{rows:O})},s=new Map(n.objects.flatMap(I=>I.rows===void 0?[]:[[I.objectApiName,I.rows]])),i=Lt({objects:n.objects,order:n.order,...n.excluded?{excluded:n.excluded}:{},...n.referenceData?{referenceData:n.referenceData}:{},...e.whole?{whole:e.whole}:{},roomBytes:t.roomBytes,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(I,O)=>o(I,O)}),a=Ti({options:{...e.window?{window:e.window}:{},...e.rootWhere?{rootWhere:e.rootWhere}:{},...e.strata?{strata:e.strata}:{}},now:n.now??Date.now(),links:i,...n.excluded?{excluded:n.excluded.keys()}:{},fieldsOf:I=>n.fieldsOf(I),...n.filterOf?{filterOf:n.filterOf}:{}}),d=(I,O)=>n.fieldsOf(I)?.find(C=>C.name.toLowerCase()===O.toLowerCase()),c=new Dt(n.source,{fieldsOf:I=>n.fieldsOf(I)?.map(O=>O.name),...n.filterOf?{filterOf:n.filterOf}:{},countsBy:(I,O)=>{let C=d(I,"Id")?.aggregatable,B=d(I,O)?.groupable;return C===!1||B===!1?!1:C===!0&&B===!0?!0:void 0},sorts:(I,O)=>d(I,O)?.sortable,...n.onProgress?{onProgress:n.onProgress}:{},...n.signal?{signal:n.signal}:{}}),f=[...i.classes].filter(([,I])=>I.kind==="drawn"&&I.rooted).map(([I])=>I).sort(),l=f.filter(I=>a.objects.get(I)?.notWindowed!==!0).map(I=>{let O=a.objects.get(I);return{objectApiName:I,carriers:_u(i,I),...O?.window?{window:O.window}:{},...O?.where!==void 0?{where:O.where}:{},...O?.stratifiedBy!==void 0?{stratifiedBy:O.stratifiedBy}:{}}}),p=await c.countRoots(l),u=Nt(t.budget.bytes,t.budget.maxTotal),m=new Map;p.forEach((I,O)=>{let C=l[O].stratifiedBy;if(C===void 0||!I.strata)return;let B=$i(I.strata.map(F=>F.rows),u,e.floor);m.set(I.objectApiName,new Vt({objectApiName:I.objectApiName,field:C,strata:I.strata.map((F,_)=>({value:F.value,roots:F.rows,take:B[_]})),draw:e.draw,seed:e.seed,floor:e.floor}))});let g=I=>m.get(I.objectApiName)?.reads()??Math.min(I.rows,u),h=p.reduce((I,O)=>I+Bt(O,e.draw,g(O)),0),y=n.sourceRequestsLeft;if(y!==void 0&&c.requests+h>Math.floor(ke*y)){let I=c.requests+h;throw new pe(is,`Drawing the sample reads about ${I} requests of the source, more than a tenth of the ${y} it has left today. Nothing was written, and no id was read past the counts. ${$u(e.draw,a)}`,void 0,void 0,void 0,{api:{kind:"requests",org:"source",estimate:I,remaining:y,drawing:{share:ke,draw:e.draw,...a.restricted?{restricted:!0}:{}}}})}let R=new Qo(u,e.floor),S=[],w=new Map,b=new Map;if(e.draw==="uniform")await c.drawUniform(l,(I,O,C)=>{w.set(I,(w.get(I)??0)+O.length);let B=m.get(I);if(B){for(let F of O)B.scanned(F,C??null);return}for(let F of O)R.offer(I,F,jt(e.seed,F))});else{let I=new Map(p.map(C=>[C.objectApiName,C.rows]));S=(await c.drawByDate(p.map((C,B)=>({...l[B],take:g(C)})),e.draw,(C,B,F)=>{let _=m.get(C);if(_){_.read(F??null,B);return}let x=b.get(C)??0;for(let $ of B)R.offer(C,$,Rn(x,I.get(C)??0)),x++;b.set(C,x)})).filter(C=>C.by==="id").map(C=>C.objectApiName);for(let C of p){if(m.has(C.objectApiName))continue;let B=Math.min(C.rows,u);B<C.rows&&(b.get(C.objectApiName)??0)>=B&&R.leftUnread(Rn(B,C.rows))}}for(let I of m.values()){for(let O of I.ranked())R.offer(I.objectApiName,O.id,O.rank,O.stratum);R.leftUnread(I.firstUnread)}let A=R.drawn();if(a.restricted&&A.length===0)throw Bu(a,p,c.requests);let{maxTotal:j}=t.budget,L=j!==void 0&&j<Math.floor(t.budget.bytes/Yo)?"maxTotal":t.bytesLimit,v=new ar(c,i,s,n.priceCurrencyWrittenIn),P=await _i({links:i,reader:v,draw:{roots:A,beyond:R.beyond,heldBy:L,floor:e.floor,...a.restricted?{restricted:!0}:{}},sourceRows:s,options:{parents:e.parents,children:e.children,...n.recordTypeVerdict?{recordTypeVerdict:n.recordTypeVerdict}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...n.signal?{signal:n.signal}:{}},measure:{bytes:(I,O)=>O.bytes??r(I)??Ci.bytes(I,O),wholeBytes:o,...t.automationBytes?{roomBytes:t.automationBytes}:{}},bounds:{bytes:t.budget.bytes,bytesLimit:t.bytesLimit,...t.storageBytes!==void 0?{storageBytes:t.storageBytes}:{},...j!==void 0?{maxTotal:j}:{},...t.requests?{requests:t.requests}:{}},roomBytes:t.roomBytes,onStep:(I,O)=>n.onProgress?.({step:I,rows:O,requests:c.requests})}),k=[...new Set([...e.draw==="recent"?S:[],...v.cappedByIds])].sort(),N=e.draw==="oldest"?[...S].sort():[],M=new Map,D=new Set;for(let I of f){let O=a.objects.get(I);if(!O||O.window===void 0&&O.where===void 0&&!O.notWindowed)continue;let C=p.find(x=>x.objectApiName===I),B=x=>{let $=b.get(I)??0;return!m.has(I)&&$<Math.min(x.rows,u)?$:void 0},F=O.notWindowed||!C?0:e.draw==="uniform"?w.get(I)??0:C.exact&&C.timedOut!==!0?C.rows:B(C),_=C?.inTheSource?.exact===!0?C.inTheSource.rows:void 0;M.set(I,{...F!==void 0?{inTheDraw:F}:{},..._!==void 0?{inTheSource:_}:{}}),F===0&&(O.notWindowed||(_??C?.inTheSource?.rows??0)>0)&&D.add(I)}let E;if(a.restricted||a.stratified){let I=[];for(let O of m.values()){let C=P.kind==="sample"?P.rootIds.get(O.objectApiName):void 0,B=await n.labelsOf?.(O.objectApiName,O.field);I.push(O.report(F=>C?.has(U(F))===!0,B))}E={...Fi(a),...I.length>0?{strata:I}:{}}}let T;if(e.floor>0&&m.size>0){let I=0,O=0;for(let C of m.values())for(let B of C.reads())I++,O+=Math.min(B.roots,e.floor);I>0&&(T={roots:O,values:I})}return{links:i,cut:P,planRequests:c.requests,newestByIds:k,oldestByIds:N,...E?{roots:E}:{},rootsCounted:M,noRootInTheDraw:D,...T?{strataFloors:T}:{}}}function Vi(n){if(!n)return;let e=(n.where??[]).map(o=>o.objectApiName),t=(n.strata??[]).map(o=>`${o.objectApiName}.${o.field}`),r={...n.window?{window:{...n.window}}:{},...e.length>0?{whereObjects:e}:{},...t.length>0?{strataFields:t}:{}};return Object.keys(r).length>0?r:void 0}function Eg(n,e,t){let{cut:r,links:o}=n;return{seed:e.seed,draw:e.draw,floor:e.floor,parents:e.parents,children:e.children,share:r.share,budget:{...t,...r.automationBytes>0?{automationMB:r.automationBytes/1048576}:{},limitedBy:r.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(s=>{let i=n.rootsCounted.get(s.objectApiName);return i?{...s,...i.inTheSource!==void 0?{rootsInTheSource:i.inTheSource}:{},...i.inTheDraw!==void 0?{rootsInTheDraw:i.inTheDraw}:{}}:s}),whole:o.whole,heavyRoots:r.heavyRoots,dropped:r.dropped,leftEmpty:r.leftEmpty,noRecordDrawn:r.noRecordDrawn.map(s=>n.noRootInTheDraw.has(s.objectApiName)?{...s,noRootInTheDraw:!0}:s),...n.roots?{roots:n.roots}:{},...r.partialMasters.length>0?{partialMasters:r.partialMasters}:{},planRequests:{source:n.planRequests},...n.newestByIds.length>0?{newestByIds:[...n.newestByIds]}:{},...n.oldestByIds.length>0?{oldestByIds:[...n.oldestByIds]}:{}}}var Wu=30*6e4,qu=16,Uu=["map_value","leave_empty","set_default","truncate","map_record_type","exclude_object","skip_rows","ignore"];function vg(n,e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null,n.nodes.map(t=>t.objectApiName).sort(),...e.queryScope==="records"?["records"]:[]])}var Gi=class{tried=new Map;note(e,t,r=Date.now()){let o=this.tried.get(t)??{};this.tried.delete(t),this.tried.set(t,{...o,[e]:r});for(let s of this.tried.keys()){if(this.tried.size<=qu)break;this.tried.delete(s)}}before(e,t=Date.now()){let r=this.tried.get(e),o=a=>a===void 0||t-a>Wu||t<a?void 0:Math.max(1,Math.ceil((t-a)/6e4)),s=o(r?.simulation),i=o(r?.rehearsal);return{...s!==void 0?{simulatedMinutesBefore:s}:{},...i!==void 0?{rehearsedMinutesBefore:i}:{}}}};function zu(n){let e={flow:0,trigger:0,process:0,workflowRule:0,unread:[]};if(!("automation"in n))return{...e,unread:["automation"]};for(let t of ms(n.automation))e[t.kind]++;return e.unread=hs(n.automation).map(t=>t.part),e}function Vu(n,e){let t={flow:0,trigger:0,process:0,workflowRule:0};if(!("automation"in n))return t;let r=e.map(o=>o.objectApiName);for(let o of gs(n.automation,r))t[o.kind]++;return t}function Gu(n,e=[]){let t=new Map,r=(i,a)=>{a>0&&t.set(i,(t.get(i)??0)+a)},o=n.picklistValueMappings??[];r("map_value",o.filter(i=>i.to!==null).length),r("leave_empty",o.filter(i=>i.to===null).length),r("leave_empty",Object.values(n.fieldExclusions??{}).reduce((i,a)=>i+a.length,0)),r("set_default",n.defaultValues?.length??0),r("truncate",n.truncateFields?.length??0),r("map_record_type",n.recordTypeMappings?.length??0),r("exclude_object",n.excludedObjects?.length??0),r("skip_rows",n.skippedRows?.length??0),r("ignore",n.ignoredGaps?.length??0);let s=new Map;for(let i of e)s.set(i.kind,(s.get(i.kind)??0)+i.rows);return Uu.filter(i=>t.has(i)||s.has(i)).map(i=>({kind:i,count:t.get(i)??0,...s.has(i)?{rows:s.get(i)}:{}}))}function Ju(n){let e=n.objects.reduce((r,o)=>r+o.sourceRows,0)+n.noRecordDrawn.reduce((r,o)=>r+o.sourceRows,0),t=Vi(n.roots);return{module:"forge",share:n.share,...n.budget.withinMB!==void 0?{withinMB:n.budget.withinMB}:{},seed:n.seed,draw:n.draw,limitedBy:n.budget.limitedBy,...t?{roots:t}:{},kept:n.rows,inSource:e}}var Ji=class{constructor(e,t){this.config=e;this.before=t}config;before;confirmed=[];fired;firedOnUpdate;deliverability;sampleFit;automationRead(e,t=[]){this.fired=zu(e),this.firedOnUpdate=Vu(e,t)}emailsRead(e){this.deliverability=e}confirm(e){this.confirmed.includes(e)||this.confirmed.push(e)}sampled(e){this.sampleFit=Ju(e)}fit(){return this.sampleFit?{...this.sampleFit}:void 0}context(e){let t=Gu(this.config,e);return{anonymized:this.config.anonymizePII,contactPoints:this.config.keepContactPoints===!0?"kept":"neutralized",...this.before,...this.fired?{firedOnInsert:{...this.fired,unread:[...this.fired.unread]}}:{},...this.firedOnUpdate?{firedOnUpdate:{...this.firedOnUpdate}}:{},...this.confirmed.length>0?{confirmed:[...this.confirmed]}:{},...t.length>0?{decisions:t}:{},...this.deliverability!==void 0?{deliverability:this.deliverability}:{}}}};var Hu=V({...Mo,journalId:W().min(1).max(200),ranFrom:ve(["commandLine","editor"]),target:W().min(1).max(255).optional(),resumes:Ke().optional(),removes:Ke().optional()}),Hi=Lo(n=>{let e=Hu.safeParse(n);return e.success?e.data:void 0});function Ki(n){return`${n.replace(/\.ndjson$/,"")}.lock`}function Yi({version:n,token:e,...t}){return t}function Mg(n,e,t={}){let r=Hi.acquire(Ki(n),o=>({...o,journalId:e.journalId.slice(0,200),ranFrom:e.ranFrom,...e.target!==void 0&&e.target!==""?{target:e.target.slice(0,255)}:{},...e.resumes?{resumes:!0}:{},...e.removes?{removes:!0}:{}}),t);return"busy"in r?{busy:Yi(r.busy)}:r}function Lg(n,e={}){let t=Hi.holder(Ki(n),e);return t!==void 0?Yi(t):void 0}function _g(n){let e=n.ranFrom==="commandLine"?"from the command line":"in VS Code";if(n.removes){let o=n.target!==void 0?` from ${n.target}`:"";return`a removal of the run ${n.journalId} deletes what it wrote${o}: started ${e} at ${n.acquiredAt} (process ${n.pid} on ${n.host})`}let t=n.target!==void 0?` to ${n.target}`:"",r=n.resumes?", taking up an earlier part of it":"";return`the run ${n.journalId} still writes this journal: started ${e}${t} at ${n.acquiredAt} (process ${n.pid} on ${n.host})${r}`}function Dg(n){return n.removes&&n.ranFrom==="editor"?"let it end on the Forge page that removes it":n.ranFrom==="commandLine"?"stop it with Ctrl-C in the terminal it runs in, or let it end":"stop it on the Forge page that runs it, or let it end"}var Ku="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Yu="RHZ",Zu=/[A-Za-z0-9]{3}RHZ[A-Za-z0-9]{12}/g,dr="000",Zi=62**8;function Jt(n,e){let t=n!==null&&/^[A-Za-z0-9]{3}$/.test(n)?n:dr,r="";for(let s=e;r.length===0||s>0;s=Math.floor(s/62))r=Ku[s%62]+r;let o=bt(`${t}${Yu}${r.padStart(9,"0")}`);if(o===void 0)throw new Error(`No placeholder id for record ${e}`);return o}var Ht=class{constructor(e,t){this.keyPrefixOf=e;this.runningUser=t}keyPrefixOf;runningUser;rows=[];updated=[];byId=new Map;personContacts=new Map;platformTeam=new Map;platformRoles=new Map;prefixes=new Map;writesAs;insertRecords=async(e,t,r)=>{let o=await this.prefixOf(t);return r.map(s=>{let i=this.rows.length,a={seq:i,objectApiName:t,fields:{...s},placeholderId:Jt(o,i)};return this.rows.push(a),this.byId.set(a.placeholderId.slice(0,15),a),{id:a.placeholderId,success:!0,errors:[]}})};get updates(){return this.updated.length}updateRecords=async(e,t,r)=>r.map(o=>{let s=typeof o.Id=="string"?o.Id:"",i={};for(let[a,d]of Object.entries(o))a!=="Id"&&a!=="attributes"&&(i[a]=d);return this.updated.push({seq:this.updated.length,objectApiName:t,recordId:s,fields:i}),{id:s,success:!0,errors:[]}});rowOf(e){if(!(typeof e!="string"||e.length!==15&&e.length!==18))return this.byId.get(e.slice(0,15))}personContactOf(e){if(!(typeof e!="string"||e.length!==15&&e.length!==18))return this.personContacts.get(e.slice(0,15))}guardQueries(e){return async(t,r,o)=>{let s=Wr(r);if(s)return this.personContactsOf(s,c=>e(t,$r(c),o));let i=Zr(r);if(i)return this.ownersOf(i,c=>e(t,Yr(c),o));let a=Xr(r);if(a)return this.teamOf(a,c=>e(t,Qr(a.objectApiName,a.fields,c)),()=>e(t,Kr));let d=Gr(r);return d?this.rolesOf(d,c=>e(t,Vr(c,d.fields),o)):this.namesAPlaceholder(r)?[]:e(t,r,o)}}async rolesOf(e,t){let r=e.opportunities.filter(d=>!this.rowOf(d)),o=r.length>0?await t(r):[],s=e.opportunities.flatMap(d=>{let c=this.rowOf(d),f=c?.objectApiName==="Opportunity"?c.fields[fn]:void 0;return c&&typeof f=="string"&&f!==""?[{id:d,row:c,contact:f}]:[]});if(s.length===0)return o;let i=await this.prefixOf(zr),a=new Date().toISOString();return[...o,...s.map(({id:d,row:c,contact:f})=>{let l=Jt(i,Zi+this.platformTeam.size+this.platformRoles.size);return this.platformRoles.set(l.slice(0,15),c),Jr({...Object.fromEntries(e.fields.map(p=>[p,null])),Id:l,OpportunityId:d,[fn]:f,...e.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},a)})]}async ownersOf(e,t){let r=e.filter(i=>!this.rowOf(i)),o=r.length>0?await t(r):[],s=[];for(let i of e){let a=await this.ownerOf(i);a!==void 0&&s.push({Id:i,OwnerId:a})}return[...o,...s]}async teamOf(e,t,r){let{objectApiName:o,fields:s,opportunities:i}=e,a=i.filter(h=>!this.rowOf(h)),d=a.length>0?await t(a):[],c=i.filter(h=>this.rowOf(h)?.objectApiName==="Opportunity");if(c.length===0)return d;let f=Ur[o],l=o===ln,p=l?(await r()).flatMap(h=>typeof h.Id=="string"&&(h.IsTotalValidated===!0||h.IsTotalValidated==="true")?[h.Id]:[]):[void 0],u=await this.prefixOf(l?ln:qr),m=Hr[o]??{},g=[];for(let h of c){let y=await this.ownerOf(h);if(y!==void 0)for(let R of p){let S=Jt(u,Zi+this.platformTeam.size+this.platformRoles.size);this.platformTeam.set(S.slice(0,15),this.rowOf(h)),g.push({Id:S,OpportunityId:h,[f]:y,...R!==void 0?{SplitTypeId:R}:{},...Object.fromEntries(s.map(w=>[w,m[w]??null]))})}}return[...d,...g]}async ownerOf(e){let t=this.rowOf(e);if(t?.objectApiName!=="Opportunity")return;let r=t.fields.OwnerId;return typeof r=="string"&&r!==""?r:(this.writesAs??=this.runningUser?this.runningUser().catch(()=>{}):Promise.resolve(void 0),this.writesAs)}async personContactsOf(e,t){let r=e.filter(a=>!this.rowOf(a)),o=r.length>0?await t(r):[],s=e.flatMap(a=>this.rowOf(a)?.objectApiName===de?[a]:[]);if(s.length===0)return o;let i=await this.prefixOf(oe);return[...o,...s.map(a=>{let d=this.rowOf(a);if("Name"in d.fields)return{Id:a,[Me]:null};let c=Jt(i,d.seq);return this.personContacts.set(c.slice(0,15),d),{Id:a,[Me]:c}})]}namesAPlaceholder(e){for(let[t]of e.matchAll(Zu))if(this.rowOf(t)||this.personContactOf(t)||this.platformTeam.has(t.slice(0,15))||this.platformRoles.has(t.slice(0,15)))return!0;return!1}prefixOf(e){let t=this.prefixes.get(e);return t||(t=this.keyPrefixOf(e).catch(()=>null),this.prefixes.set(e,t)),t}};function qg(n,e){return{queryRecords:e.guardQueries(n.queryRecords),describeFields:n.describeFields,isObjectCreatable:n.isObjectCreatable,describeObject:n.describeObject,recordTypePicklists:n.recordTypePicklists,batchStrategy:n.batchStrategy,anonymize:n.anonymize,requestsSent:n.requestsSent,insertRecords:e.insertRecords,updateRecords:e.updateRecords}}var ea="UNKNOWN_ERROR",ta="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",Qu=new Set(["STRING_TOO_LONG","INVALID_EMAIL_ADDRESS","INVALID_TYPE_ON_FIELD_IN_RECORD","NUMBER_OUTSIDE_VALID_RANGE","MALFORMED_ID","INVALID_ID_FIELD","DUPLICATE_VALUE"]),Qi=new Set(["FIELD_CUSTOM_VALIDATION_EXCEPTION","INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST","FIELD_FILTER_VALIDATION_EXCEPTION"]),Xu=new Map([["REQUIRED_FIELD_MISSING",{kind:"required_field_missing",severity:"blocking",decisions:["set_default","exclude_object"]}],["INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",{kind:"picklist_value_refused",severity:"warning",decisions:["map_value","leave_empty","ignore"]}],["STRING_TOO_LONG",{kind:"value_too_long",severity:"blocking",decisions:["truncate","leave_empty","exclude_object"]}],["NUMBER_OUTSIDE_VALID_RANGE",{kind:"number_out_of_range",severity:"blocking",decisions:["leave_empty","exclude_object"]}],["DUPLICATE_VALUE",{kind:"unique_value_collision",severity:"warning",decisions:["leave_empty","exclude_object","ignore"]}],["FIELD_FILTER_VALIDATION_EXCEPTION",{kind:"lookup_filter",severity:"warning",decisions:["leave_empty","ignore"]}]]),cr="FIELD_CUSTOM_VALIDATION_EXCEPTION";function Vg(n){return n.flatMap(e=>{let t=e.detail?.rule,r=e.detail?.message;return e.kind!=="validation_rule"||typeof t!="string"||typeof r!="string"?[]:[{objectApiName:e.objectApiName,name:t,message:r,...e.field!==void 0?{field:e.field}:{}}]})}function el(n,e,t){if(e.statusCode!==cr||e.message.trim()==="")return;let r=e.fields[0]?.toLowerCase(),o=t.filter(s=>s.objectApiName.toLowerCase()===n.toLowerCase()&&s.message.trim()===e.message.trim()&&(s.field===void 0||r===void 0||s.field.toLowerCase()===r));return o.length===1?o[0].name:void 0}function Kt(n,e){let t=n.detail?.[e];return typeof t=="number"?t:0}function Xi(n){let e=n.detail?.fields;return Array.isArray(e)?e:[]}function tl(n,e,t){if(!n)return;let r=new Set(n.values);if(e.split(";").some(o=>!r.has(o)))return"not-in-target";if(n.controllerName===void 0)return t!==void 0?"record-type":void 0}function nl(n,e){if(Qu.has(e.statusCode)||e.message==="")return;let t=e.message;for(let r of Object.values(n.fields))typeof r=="string"&&r.length>=3&&(t=t.split(r).join("\u2026"));return t}function rl(n,e){let t=n.fields.RecordTypeId;return typeof t=="string"?e.get(t.slice(0,15)):void 0}function ol(n,e,t,r){let{row:o}=n,s=e.fields[0],i=t===xr?"unique_value_collision":"rehearsal_refusal";return{id:Ze(i,o.objectApiName,s,void 0,i==="rehearsal_refusal"?t:void 0),kind:i,severity:"warning",source:"rehearsal",objectApiName:o.objectApiName,...s!==void 0?{field:s}:{},...i==="rehearsal_refusal"?{value:t}:{},rows:1,detail:{...r(s),linkedToTheRecordItNames:!0},decisions:s!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],defaultDecision:"ignore"}}function sl(n,e,t,r,o){let{row:s}=n,i=e.statusCode||ea,a=nl(s,e),d=n.onUpdate?void 0:el(s.objectApiName,e,o),c=u=>{let m=u===void 0?void 0:s.fields[u];return{statusCode:i,fields:[...e.fields],...a!==void 0?{message:a}:{},...d!==void 0?{rule:d}:{},rowsOfTheRun:n.standsFor,...i==="STRING_TOO_LONG"&&typeof m=="string"?{valueLength:m.length}:{},...Qi.has(i)&&u!==void 0&&!n.onUpdate?{writtenWithoutTheField:!0}:{}}};if(n.onUpdate){let u=e.fields[0];return[{id:Ze("rehearsal_update_refusal",s.objectApiName,u,void 0,i),kind:"rehearsal_update_refusal",severity:"warning",source:"rehearsal",objectApiName:s.objectApiName,...u!==void 0?{field:u}:{},value:i,rows:1,detail:c(u),decisions:["exclude_object","ignore"]}]}if(n.linked)return[ol(n,e,i,c)];let f=Xu.get(i);if(f&&e.fields.length>0)return(f.kind==="required_field_missing"?e.fields:e.fields.slice(0,1)).map(m=>{let g=s.fields[m],h=f.kind==="picklist_value_refused",y=h?rl(s,t):void 0,R=h&&typeof g=="string"?g:void 0,S=R!==void 0?tl(r.get(s.objectApiName)?.get(m),R,y):void 0;return{id:Ze(f.kind,s.objectApiName,m,y,R),kind:f.kind,severity:f.severity,source:"rehearsal",objectApiName:s.objectApiName,field:m,...y!==void 0?{recordType:y}:{},...R!==void 0?{value:R}:{},rows:1,detail:{...c(m),...S!==void 0?{reason:S}:{}},decisions:[...f.decisions],...f.severity==="warning"?{defaultDecision:"leave_empty"}:{}}});let l=e.fields[0],p=l!==void 0&&Qi.has(i);return[{id:Ze("rehearsal_refusal",s.objectApiName,l,void 0,i),kind:"rehearsal_refusal",severity:p?"warning":"blocking",source:"rehearsal",objectApiName:s.objectApiName,...l!==void 0?{field:l}:{},value:i,rows:1,detail:c(l),decisions:l!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],...p?{defaultDecision:"leave_empty"}:{}}]}function na(n,e=new Map,t=new Map,r=[]){let o=new Map;for(let s of n){let i=s.errors.length>0?s.errors:[{statusCode:ea,message:"",fields:[]}],a=an(...i.map(d=>sl(s,d,e,t,r)));for(let d of a){let c=o.get(d.id);if(!c){o.set(d.id,d);continue}let f=Math.max(Kt(c,"valueLength"),Kt(d,"valueLength"));o.set(d.id,{...c,rows:c.rows+1,detail:{...d.detail,...c.detail,rowsOfTheRun:Kt(c,"rowsOfTheRun")+Kt(d,"rowsOfTheRun"),fields:[...new Set([...Xi(c),...Xi(d)])],...f>0?{valueLength:f}:{}}})}}return an([...o.values()])}function il(n){return n!=null&&n!==""}function al(n){let e=n.fields.RecordTypeId,t=Object.keys(n.fields).filter(r=>r!=="attributes"&&il(n.fields[r])).sort();return[n.objectApiName,typeof e=="string"?e:"",t.join(",")].join("|")}function ra(n){if(n.length<=200)return{rows:[...n],standsFor:new Map(n.map(r=>[r.seq,1]))};let e=new Map,t=new Map;for(let r of n){let o=al(r),s=e.get(o);if(s){t.set(s.seq,(t.get(s.seq)??1)+1);continue}e.set(o,r),t.set(r.seq,1)}return{rows:[...e.values()],standsFor:t}}function dl(n){let e=n.fields.Status;return[n.objectApiName,Object.keys(n.fields).sort().join(","),typeof e=="string"?e:""].join("|")}function oa(n){if(n.length<=19)return{updates:[...n],standsFor:new Map(n.map(r=>[r.seq,1]))};let e=new Map,t=new Map;for(let r of n){let o=dl(r),s=e.get(o);if(s){t.set(s.seq,(t.get(s.seq)??1)+1);continue}e.set(o,r),t.set(r.seq,1)}return{updates:[...e.values()],standsFor:t}}function sa(n,e,t=()=>{}){let r=new Map(n.map(a=>[a.seq,a])),o=new Map,s=new Map,i=new Map;for(let a of[...n].sort((d,c)=>d.seq-c.seq)){let d=new Set,c=new Set;for(let l of Object.values(a.fields)){let p=e(l);p&&p.seq!==a.seq&&d.add(p.seq);let u=p?void 0:t(l);u&&u.seq!==a.seq&&r.has(u.seq)&&(d.add(u.seq),c.add(u.seq))}let f=[...d].sort((l,p)=>l-p);o.set(a.seq,f),c.size>0&&i.set(a.seq,[...c].sort((l,p)=>l-p)),s.set(a.seq,f.reduce((l,p)=>Math.max(l,(s.get(p)??0)+1),0))}return{bySeq:r,parents:o,levels:s,...i.size>0?{personContactsNamed:i}:{}}}function ia(n,e){if(e.size===0)return n;let t=new Map;for(let[o,s]of n.parents){let i=new Set;for(let a of s){let d=e.get(a);d===void 0?i.add(a):"seq"in d&&d.seq!==o&&i.add(d.seq)}t.set(o,[...i].sort((a,d)=>a-d))}let r=new Map;for(let o of[...n.bySeq.keys()].sort((s,i)=>s-i))r.set(o,(t.get(o)??[]).reduce((s,i)=>Math.max(s,(r.get(i)??0)+1),0));return{bySeq:n.bySeq,parents:t,levels:r,...n.personContactsNamed?{personContactsNamed:n.personContactsNamed}:{}}}function Ge(n,e){let t=new Set,r=[...e.parents.get(n)??[]];for(let o=r.shift();o!==void 0;o=r.shift())t.has(o)||(t.add(o),r.push(...e.parents.get(o)??[]));return[...t]}function ur(n,e){let t=new Set;for(let r of n){t.add(r.seq);for(let o of Ge(r.seq,e))t.add(o)}return[...t].sort((r,o)=>r-o).flatMap(r=>{let o=e.bySeq.get(r);return o?[o]:[]})}var fr=5,pr=25,cl=200,ul=10,ll="PROCESSING_HALTED",fl="SandForge_Rehearsal_Rollback__c";function mr(n,e=0){return Math.max(0,pr-n-e-1)}function en(n,e){let t=new Set;for(let r of n)for(let o of e.personContactsNamed?.get(r)??[])t.add(o);return[...t]}function aa(n,e,t=[],r=new Map){let o=new Map;n.collections.forEach((a,d)=>a.seqs.forEach(c=>o.set(c,d)));let s=new Set([...en(n.collections.flatMap(a=>a.seqs),e),...t.flatMap(a=>a.contacts??[])]),i=[];for(let a of s){let d=o.get(a),c=r.get(a),f=d??(c===void 0?void 0:"id"in c?-1:o.get(c.seq));f!==void 0&&i.push({account:a,after:f})}return i.sort((a,d)=>a.after-d.after||a.account-d.account)}function pl(n,e,t){let r=[...e].flatMap(a=>{let d=t.get(a);return d?[d]:[]}).sort((a,d)=>a.objectApiName.localeCompare(d.objectApiName)||a.seq-d.seq),o=[],s,i=new Set;for(let a of r){let d=!i.has(a.objectApiName);(!s||s.seqs.length>=cl||d&&i.size>=ul)&&(s={level:n,seqs:[]},i=new Set,o.push(s)),s.seqs.push(a.seq),i.add(a.objectApiName)}return o}function lr(n,e){return[...n.keys()].sort((t,r)=>t-r).flatMap(t=>pl(t,n.get(t)??[],e))}function tn(n,e){let t=f=>e.levels.get(f)??0,r=[...n].sort((f,l)=>t(l.seq)-t(f.seq)||f.seq-l.seq),o=[],s=[],i=new Set,a=new Map,d=(f,l)=>{let p=new Map([...f].map(([u,m])=>[u,new Set(m)]));for(let u of l){let m=p.get(t(u))??new Set;m.add(u),p.set(t(u),m)}return p},c=f=>{let l=lr(f,e.bySeq).length,p=en([...f.values()].flatMap(u=>[...u]),e).length;return l<=fr&&l+p<pr};for(let f of r){if(i.has(f.seq))continue;let l=[f.seq,...Ge(f.seq,e)],p=d(new Map,l);if(!c(p)){s.push(f.seq);continue}let u=d(a,l);c(u)?a=u:(o.push({collections:lr(a,e.bySeq)}),a=p);for(let m of l)i.add(m)}return a.size>0&&o.push({collections:lr(a,e.bySeq)}),{calls:o,beyond:s.sort((f,l)=>f-l)}}function Qt(n){return`rows${n}`}function gr(n){return`update${n}`}var da="rollback";function Xt(n){return`contact${n}`}function ml(n,e,t){let r=o=>t.filter(s=>s.after===o).map(s=>Xt(s.account));return[...r(-1),...n.collections.flatMap((o,s)=>[Qt(s),...r(s)]),...Array.from({length:e},(o,s)=>gr(s)),da]}function ca(n,e,t,r,o,s=[],i=new Map,a={of:()=>{},reads:[]}){let{reads:d}=a;if(s.length>mr(n.collections.length,d.length))throw new Error(`A rehearsal call of ${n.collections.length} Collections request(s) has no room for ${s.length} update(s): a call holds ${pr} subrequests`);let c=new Map;n.collections.forEach((w,b)=>w.seqs.forEach((A,j)=>c.set(A,`@{${Qt(b)}[${j}].id}`)));let f=w=>{let b=c.get(w.seq);if(b!==void 0)return b;let A=i.get(w.seq);if(A!==void 0)return"id"in A?A.id:c.get(A.seq)},l=new Set(d.map(w=>w.account)),p=w=>{let b=t(w);if(b){let j=f(b);return j===void 0?void 0:{sent:j}}let A=a.of(w);return A?l.has(A.seq)?{sent:`@{${Xt(A.seq)}.${Me}}`}:void 0:{sent:w}},u=w=>w.seqs.map(b=>{let A=e.bySeq.get(b);if(!A)throw new Error(`Row ${b} is not among the rows the run creates`);return A}),m=(w,b)=>({method:"POST",url:`${r}/composite/sobjects`,referenceId:Qt(b),body:{allOrNone:!1,records:u(w).map(A=>{let j={attributes:{type:A.objectApiName}};for(let[L,v]of Object.entries(A.fields)){if(L==="attributes"||L==="Id")continue;let P=p(v);if(P===void 0)throw new Error(`${A.objectApiName} row ${A.seq} names a record the run creates that its call does not hold`);j[L]=P.sent}return j})},httpHeaders:{...o}}),g=({account:w})=>{let b=e.bySeq.get(w),A=b?f(b):void 0;if(A===void 0)throw new Error("A read of a person account's contact names an account its call does not hold");return{method:"GET",url:`${r}/sobjects/${de}/${A}?fields=${Me}`,referenceId:Xt(w)}},h=w=>d.filter(b=>b.after===w).map(g),y=[...h(-1),...n.collections.flatMap((w,b)=>[m(w,b),...h(b)])];s.forEach((w,b)=>{let A=c.get(w.rowSeq);if(A===void 0)throw new Error(`An update of ${w.objectApiName} names a record its call does not create`);let j={};for(let[L,v]of Object.entries(w.fields)){if(L==="attributes"||L==="Id")continue;let P=p(v);if(P===void 0)throw new Error(`An update of ${w.objectApiName} names a record the run creates that its call does not hold`);j[L]=P.sent}y.push({method:"PATCH",url:`${r}/sobjects/${w.objectApiName}/${A}`,referenceId:gr(b),body:j,httpHeaders:{...o}})});let R=n.collections[0]?.seqs[0],S=R===void 0?void 0:e.bySeq.get(R);if(!S)throw new Error("A rehearsal call holds no row");return y.push({method:"PATCH",url:`${r}/sobjects/${S.objectApiName}/${gl(S.placeholderId)}`,referenceId:da,body:{[fl]:!0}}),{allOrNone:!0,collateSubrequests:!1,compositeRequest:y}}function gl(n){return bt(`${n.slice(0,3)}000000000000`)??"000000000000000AAA"}var hl=V({body:Ne(),httpStatusCode:te(),referenceId:W().optional()}).loose(),wl=V({compositeResponse:Z(hl)}).loose(),Zt=Z(V({errorCode:W().optional(),statusCode:W().optional()}).loose()),yl=Z(V({success:Ke()}).loose());function Yt(n){let e=Zt.safeParse(n.body);return n.httpStatusCode>=400&&e.success&&e.data.length>0&&e.data.every(t=>(t.errorCode??t.statusCode)===ll)}function ua(n,e,t=0,r=()=>{},o=[]){let s=wl.safeParse(n);if(!s.success)throw new Error("The target answered the rehearsal with no composite answer");let i=s.data.compositeResponse,a=ml(e,t,o),d=a.length,c=i[d-1];if(i.length!==d||!c)throw new Error(`The target answered ${i.length} subrequests of the ${d} the rehearsal sent`);let f=i.findIndex((m,g)=>m.referenceId!==void 0&&m.referenceId!==a[g]);if(f!==-1)throw new Error(`The target ran the rehearsal's subrequests out of the order sent (${String(i[f]?.referenceId)} in place of ${a[f]}): no verdict can be read from it`);let l=m=>i[a.indexOf(m)];for(let{account:m}of o){let g=l(Xt(m));if(g.httpStatusCode<400||Yt(g))continue;let h=Zt.safeParse(g.body),y=h.success?h.data[0]?.errorCode??h.data[0]?.statusCode:"";throw new Error(`The target refused to read back the contact the platform wrote with a person account (status ${g.httpStatusCode}${y?`, ${y}`:""}): no verdict can be read past it`)}let p=e.collections.map((m,g)=>{let h=l(Qt(g));if(Yt(h))return{kind:"halted"};let y=yl.safeParse(h.body);if(h.httpStatusCode<400&&y.success){if(y.data.length!==m.seqs.length)throw new Error(`The target answered ${y.data.length} rows of the ${m.seqs.length} a request sent`);return{kind:"rows",outcomes:y.data.map((S,w)=>Rt(S,r(m.seqs[w])??""))}}let R=Zt.safeParse(h.body);if(h.httpStatusCode>=400&&R.success&&R.data.length>0)return{kind:"refused",errors:R.data.map(gn)};throw new Error(`The target answered a request of the rehearsal with status ${h.httpStatusCode}`)}),u=Array.from({length:t},(m,g)=>{let h=l(gr(g));if(Yt(h))return{kind:"halted"};if(h.httpStatusCode<400)return{kind:"saved"};let y=Zt.safeParse(h.body);if(y.success&&y.data.length>0)return{kind:"refused",errors:y.data.map(gn)};throw new Error(`The target answered an update of the rehearsal with status ${h.httpStatusCode}`)});if(c.httpStatusCode<400)return{kind:"not_rolled_back",ids:p.flatMap(m=>m.kind==="rows"?m.outcomes.filter(g=>g.success).map(g=>g.id):[])};if(Yt(c)&&hr(p)===-1&&!u.some(m=>m.kind==="refused"))throw new Error("The target stopped the rehearsal at a request whose answer names no refusal");return{kind:"rolled_back",collections:p,updates:u}}function hr(n){return n.findIndex(e=>e.kind==="refused"||e.kind==="rows"&&e.outcomes.some(t=>!t.success))}function la(n,e,t=()=>{}){let r=new Map,o=hr(e);return n.collections.forEach((s,i)=>{if(o!==-1&&i>o)return;let a=e[i];s.seqs.forEach((d,c)=>{if(a.kind==="refused"){r.set(d,{passed:!1,errors:a.errors});return}let f=a.kind==="rows"?a.outcomes[c]:void 0;if(!f||f.success){r.set(d,{passed:!0});return}let l=Ro(f,t(d));r.set(d,{passed:!1,errors:f.errorDetails??[],...l.kind==="linked"?{linkedTo:l.id}:{}})})}),r}function fa(n,e){let t=new Map;if(hr(e.collections)!==-1)return t;for(let[r,o]of n.entries()){let s=e.updates[r];if(s?.kind==="refused"){t.set(o.seq,{passed:!1,errors:s.errors});break}t.set(o.seq,{passed:!0})}return t}async function bl(n,e){let t=e.targetRecordTypes;if(!t)return n;let r=new Set(n.flatMap(s=>s.recordType!==void 0&&fo(s.recordType).namespacePrefix?[s.objectApiName]:[]));if(r.size===0)return n;let o=new Map;for(let s of r){let i=await t(s).catch(()=>{});o.set(s,i?po(i):void 0)}return n.map(s=>mo(s,o.get(s.objectApiName)))}async function Rl(n,e){let t=[...new Set(n.filter(({errors:r})=>r.some(o=>o.statusCode===cr)).map(({row:r})=>r.objectApiName))];if(t.length===0||!e.validationRules)return[];try{return await e.validationRules(t)}catch{return[]}}async function Sl(n,e){let t=new Map;for(let{row:s,errors:i,onUpdate:a}of n)if(!a)for(let d of i){let c=d.fields[0];d.statusCode!==ta||c===void 0||t.set(s.objectApiName,(t.get(s.objectApiName)??new Set).add(c))}let r=new Map,o=e.targetFields;if(!o)return r;for(let[s,i]of t){let a;try{a=await o(s)}catch{continue}let d=new Map;for(let c of a)!i.has(c.name)||!c.picklistValues||d.set(c.name,{values:c.picklistValues,...c.controllerName?{controllerName:c.controllerName}:{}});r.set(s,d)}return r}var wr=class extends Error{constructor(t,r=[]){super(`A rehearsal call was not rolled back: the ${t.length} record(s) it created stay in the target (${t.join(", ")}). The rehearsal stopped there; remove them from the target.`);this.ids=t;this.objects=r;this.name="RehearsalNotRolledBackError"}ids;objects},nn=class extends Error{constructor(t){super(t>0?`The rehearsal was cancelled after ${t} call(s), each rolled back whole: nothing stays in the target.`:"The rehearsal was cancelled before its first call. Nothing was sent to the target.");this.calls=t;this.name="RehearsalCancelledError"}calls};function Ol(n,e){let t=new Map;for(let o of e)t.set(o.placeholderId.slice(0,3),o.objectApiName);let r=new Map;for(let o of n){let s=t.get(o.slice(0,3))??o.slice(0,3);r.set(s,(r.get(s)??0)+1)}return[...r].map(([o,s])=>({objectApiName:o,created:s}))}function pa(n){let e=new Map;for(let{objectApiName:t}of n)e.set(t,(e.get(t)??0)+1);return[...e].map(([t,r])=>({objectApiName:t,count:r})).sort((t,r)=>r.count-t.count||t.objectApiName.localeCompare(r.objectApiName))}function Al(n,e,t){let r=n.slice(0,15);for(let[o,s]of e.collections.entries()){let i=t[o];if(i?.kind==="rows")for(let[a,d]of i.outcomes.entries()){let c=s.seqs[a];if(d.success&&d.id.slice(0,15)===r&&c!==void 0)return{seq:c}}}return{id:n}}function kl(n,e,t){let r=e(n.recordId);if(!r)return;let o=new Set([r.seq]),s=new Set;for(let i of Object.values(n.fields)){let a=e(i);a&&o.add(a.seq);let d=a?void 0:t(i);d&&(o.add(d.seq),s.add(d.seq))}return{seq:n.seq,objectApiName:n.objectApiName,rowSeq:r.seq,fields:n.fields,needs:[...o],...s.size>0?{contacts:[...s]}:{}}}function yr(n,e,t){let r=new Set(n.collections.flatMap(i=>i.seqs)),o=new Set(en(r,t)),s=[];for(let i of e){if(!i.needs.every(d=>r.has(d)))continue;let a=(i.contacts??[]).filter(d=>!o.has(d));if(s.length+1>mr(n.collections.length,o.size+a.length))break;for(let d of a)o.add(d);s.push(i)}return s}function ma(n,e){let t=o=>{let s=ur(o.flatMap(d=>d.needs.flatMap(c=>{let f=e.bySeq.get(c);return f?[f]:[]})),e),i=tn(s,e),[a]=i.calls;return i.calls.length===1&&i.beyond.length===0&&a&&yr(a,o,e).length===o.length?a:void 0},r=[];for(let[o,s]of n.entries()){let i=[s],a=t(i);if(!a){r.push(s);continue}for(let d of n.slice(o+1)){let c=t([...i,d]);c&&(i=[...i,d],a=c)}return{call:a,beyond:r}}return{beyond:r}}function Il(n,e,t){let r=[...e],o=i=>{let a=new Set(yr(i,r,t));return r=r.filter(d=>!a.has(d)),a.size};for(let i of n)o(i);let s=0;for(;r.length>0;){let{call:i,beyond:a}=ma(r,t),d=new Set(a);if(r=r.filter(c=>!d.has(c)),!i||o(i)===0)break;s++}return n.length+s}async function oh(n){let e=new Ht(n.keyPrefixOf,n.runningUser);await n.prepare(e);let t=e.rows,r=E=>e.rowOf(E),o=E=>e.personContactOf(E),s=sa(t,r,o),i=ra(t),a=oa(e.updated.flatMap(E=>{let T=kl(E,r,o);return T?[T]:[]})),d=a.updates,c=ur([...i.rows,...d.flatMap(E=>E.needs.flatMap(T=>{let I=s.bySeq.get(T);return I?[I]:[]}))],s),f=E=>i.standsFor.get(E)??1,l=E=>{let T=s.bySeq.get(E)?.placeholderId.slice(0,3);return T===void 0||T===dr?null:T},p=new Map,u=new Map,m=new Map,g=new Map,h=new Map,y=s,R=tn(c,s);for(let E of R.beyond)u.set(E,"beyond_a_call");let S=Il(R.calls,d,s),w=S*fr,b=0;if(S>0){if(n.signal?.aborted)throw new nn(0);n.onProgress?.({phase:"confirming",calls:S}),await n.confirm({rows:t.length,sampled:c.length,updates:pa(d).map(({objectApiName:E,count:T})=>({objectApiName:E,updates:T})),calls:S,maxCalls:w,objects:pa(c).map(({objectApiName:E,count:T})=>({objectApiName:E,rows:T}))})}let A=E=>{let T=p.get(E);return T?.passed===!1&&T.linkedTo===void 0},j=E=>[E,...Ge(E,y)].some(A),L=E=>{if(h.has(E.rowSeq))return"record_linked";for(let T of E.needs){if(j(T))return"parent_refused";let I=u.get(T);if(I)return I}};for(;;){if(n.signal?.aborted)throw new nn(b);let E=c.filter(x=>p.has(x.seq)||u.has(x.seq)?!1:Ge(x.seq,y).some(A)?(u.set(x.seq,"parent_refused"),!1):!0),T=d.filter(x=>{if(m.has(x.seq)||g.has(x.seq))return!1;let $=L(x);return $?(g.set(x.seq,$),!1):!0});if(E.length===0&&T.length===0)break;if(b>=w){for(let x of E)u.set(x.seq,"call_budget");for(let x of T)g.set(x.seq,"call_budget");break}let I;if(E.length>0){let x=tn(E,y);for(let $ of x.beyond)u.set($,"beyond_a_call");I=x.calls[0]}else{let x=ma(T,y);for(let $ of x.beyond)g.set($.seq,"beyond_a_call");I=x.call}if(!I)continue;let O=yr(I,T.filter(x=>!g.has(x.seq)),y);b++,n.onProgress?.({phase:"rehearsing",call:b,calls:Math.max(S,b)});let C=aa(I,y,O,h),B=ca(I,s,r,n.apiPath,n.writeHeaders,O,h,{of:o,reads:C}),F=ua(await n.composite(B),I,O.length,x=>s.bySeq.get(x)?.objectApiName,C);if(F.kind==="not_rolled_back")throw new wr(F.ids,Ol(F.ids,t));let _=new Map;for(let[x,$]of la(I,F.collections,l))p.set(x,$),!$.passed&&$.linkedTo!==void 0&&_.set(x,Al($.linkedTo,I,F.collections));for(let[x,$]of fa(O,F))m.set(x,$);if(_.size>0){for(let[x,$]of _)h.set(x,$);y=ia(s,h),d=d.map(x=>({...x,needs:x.needs.flatMap($=>{let q=h.get($);return q===void 0?[$]:"seq"in q?[q.seq]:[]})}))}}let v=[],P=0,k=0;for(let E of c){let T=p.get(E.seq);if(!T)continue;if(T.passed){P++;continue}let I=T.linkedTo!==void 0;I&&k++,v.push({row:E,errors:T.errors,standsFor:f(E.seq),...I?{linked:!0}:{}})}let N=0,M=0;for(let E of d){let T=m.get(E.seq),I=s.bySeq.get(E.rowSeq);if(!T||!I)continue;let O=a.standsFor.get(E.seq)??1;if(M+=O,T.passed){N++;continue}v.push({row:{...I,fields:{...I.fields,...E.fields}},errors:T.errors,standsFor:O,onUpdate:!0})}let D=new Map;for(let[E,T]of u){let O=`${s.bySeq.get(E)?.objectApiName??""}|${T}`;D.set(O,(D.get(O)??0)+1)}return{gaps:await bl(na(v,n.recordTypeNames,await Sl(v,n),await Rl(v,n)),n),rows:t.length,sampled:c.length,judged:p.size,passed:P,linked:k,notJudged:u.size,notJudgedWhy:[...D].map(([E,T])=>{let[I,O]=E.split("|");return{objectApiName:I,rows:T,reason:O}}),updates:e.updates,updatesJudged:m.size,updatesPassed:N,updatesNotRehearsed:e.updates-M,calls:b,plannedCalls:S}}var jl="QuoteLineItem",br="Quote",rn="Opportunity",Rr="OpportunityLineItem",Ar="SyncedQuoteId",kr="QuoteId",Ir="OpportunityLineItemId",Or=new Set(["Id",kr,Ir]);function ut(n){return n.slice(0,15)}function Sr(n,e){let t=n[e];return typeof t=="string"&&t!==""?ut(t):void 0}function ah(n,e){return!n.has(rn)||!n.has(br)||!n.has(Rr)?[]:e.get(rn)?.some(r=>r.name===Ar)!==!0?[]:[{sourceObject:br,targetObject:Rr,relationshipName:`${br}Before${Rr}`,type:"lookup",required:!0}]}function Nl(n,e,t){let r=[...Or,...t.filter(s=>!Or.has(s))].map(J).join(", "),o=s=>s.map(i=>`'${xe(i)}'`).join(", ");return`SELECT ${r} FROM ${jl} WHERE ${kr} IN (${o(n)}) AND ${Ir} IN (${o(e)})`}var El=200;function Tl(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function dh(n,e,t){let r=[],o=[...new Set(e.map(s=>s.product))];for(let s of Tl(o,El)){let i=new Set(s.map(ut)),a=[...new Set(e.filter(d=>i.has(ut(d.product))).map(d=>d.quote))];r.push(...await n(Nl(a,s,t)))}return r}function ch(n,e,t){let r=new Map;for(let s of e){let i=Sr(s,"Id"),a=Sr(s,kr),d=Sr(s,Ir);if(!i||!a||!d||t.has(i))continue;let c=`${a}:${d}`;r.set(c,[...r.get(c)??[],s])}let o=new Map;for(let s of n){let i=r.get(`${ut(s.quote)}:${ut(s.product)}`)?.shift();i&&o.set(s.index,i)}return o}var ga=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Fl(n,e){let t=r=>r==null||r==="";if(t(n)||t(e))return t(n)&&t(e);if(n===e)return!0;if(typeof n=="number"||typeof e=="number"){let r=Number(n),o=Number(e);return Number.isFinite(r)&&Number.isFinite(o)&&r===o}if(typeof n=="string"&&typeof e=="string"){if(ga.test(n)&&ga.test(e)){let r=Date.parse(n),o=Date.parse(e);return Number.isFinite(r)&&r===o}return!1}return String(n)===String(e)}function uh(n,e,t,r=new Set){let o={};for(let[s,i]of Object.entries(n))Or.has(s)||r.has(s)||!t(s)||Fl(i,e[s])||(o[s]=i??null);return o}function lh(n,e,t){let r=n===1,o=`the platform's ${r?"copy":"copies"} of ${r?"its":"their"} opportunity product${r?"":"s"}`,s=e>0?`, ${e} given the fields the copy lacked`:"";return`${n} of them ${t?"would be ":""}${o}, made as the quote syncs with its opportunity: taken rather than written twice${s}`}var Pl=2e3,vl=3,Cl=20,lt=20;function Sh(n,e){let t=ho(n,e);return{query:r=>t.query(r),describe:r=>t.describe(r),describeGlobal:()=>t.describeGlobal(),queryAll:async r=>{let o=await n.query(r,{scanAll:!0});return go(n.limitInfo,e),{totalSize:o.totalSize,records:o.records}},serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp}}function ha(n,e,t){return`${n}:${e.slice(0,15)}:${t}`}function wa(n,e){return`${n}.${e}`}var xl=[{modified:"LastModifiedDate",by:"LastModifiedById",created:!0},{modified:"LastModifiedDate",by:"LastModifiedById"},{modified:"SystemModstamp",created:!0},{modified:"SystemModstamp"},{}],le="CreatedById",He="CreatedDate",Ml=V({sobjects:Z(V({name:W(),keyPrefix:W().nullish()}).loose())}).loose(),Ll=n=>new Promise(e=>setTimeout(e,n));function G(n){return n.slice(0,15)}function ya(n){return n.slice(0,3)}function ba(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function _l(n,e,t){let r=n[le],o=ft(n[He]);if(typeof r!="string"||!Number.isFinite(o))return;let s=i=>Math.floor(i/1e3)*1e3;return G(r)===G(e)&&s(o)>=s(t.from)&&s(o)<=s(t.to)}function ft(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Je(n){return typeof n.Id=="string"?n.Id:void 0}function jr(n){return Array.isArray(n)?`[${n.map(jr).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${jr(r)}`).join(",")}}`:JSON.stringify(n)}var Ra=class{constructor(e){this.deps=e}deps;describes=new Map;async verify(e,t={}){let r=t.now??(()=>new Date),o=t.sleep??Ll,s=t.intervalMs??Pl,i=Math.max(1,t.maxAttempts??vl),a=t.linkSample??Cl,d=await this.runEnd(e),c=this.deps.source,f="unavailable"in c?c.unavailable:void 0,l=new Map;if(!("unavailable"in c))for(let b of e.records)l.set(b.objectApiName,await this.linkPlan(c,e,b,a));let p=null,u=null,m=[],g=0,h=this.explaining(e,d),y=h.window?await this.runUser(e):void 0,R=await this.writtenByThePlatformAlone(e,h);for(let b=1;b<=i;b++){g=b,await o(s),m=[];for(let j of e.records)m.push(await this.read(e,j,d,l.get(j.objectApiName),h,y));for(let j of R)m.push(await this.readWrittenByThePlatform(j,h,y));let A=jr(m);if(p!==null&&A===p){u=m;break}p=A}let S=(u??m).map(Bl),w=e.roots?Dl(e,e.roots,u??m):void 0;return{verdict:$l(u!==null,S,f),verifiedAt:r().toISOString(),attempts:g,objects:S,...f!==void 0?{linksUnchecked:f}:{},...w?{roots:w}:{}}}async runEnd(e){if(e.runEndedAt)return e.runEndedAt.getTime();if(!e.runRecordedAt)return Number.NaN;let t=0,r=this.deps.target.serverTime;if(r){let o=Date.now();try{let s=ft(await r.call(this.deps.target));Number.isFinite(s)&&(t=s-(o+Date.now())/2)}catch{}}return e.runRecordedAt.getTime()+t+St}explaining(e,t){let r=new Set;for(let{objectApiName:c,field:f,recordIds:l}of e.leftEmptyByFilter??[])for(let p of l)r.add(ha(c,p,f));let o=new Set(Object.entries(e.leftEmptyByTheRun??{}).flatMap(([c,f])=>f.map(l=>wa(c,l)))),s=[...new Set((e.withTheirRecord??[]).flatMap(c=>{let f=e.remapTable[c];return f===void 0?[]:[f]}))],i=e.runStartedAt?.getTime()??Number.NaN,a=Number.isFinite(i)&&Number.isFinite(t),d={from:i-St,to:t+St};return{emptiedByFilter:r,emptiedByTheRun:o,withTheirRecord:s,createdByRun:new Set(Object.values(e.remapTable).map(G)),...a?{window:d,counted:e.runEndedAt?{from:d.from,to:t}:d}:{}}}async setByAutomation(e,t,r){let o=r.window,s=e.filter(({link:f,createdBy:l})=>o!==void 0&&typeof l=="string"&&f.found!==null&&!r.createdByRun.has(G(f.found)));if(!o||s.length===0)return{explained:[],broken:e.map(({link:f})=>f)};let i=new Map,a=new Map;for(let{link:f}of s){let l=await this.objectOfId(t.referenceTo?.get(f.field)??[],f.found);l!==void 0&&a.set(l,[...a.get(l)??[],f.found])}for(let[f,l]of a)try{let p=await fe(this.deps.target,f,[le,He],[...new Set(l)]);for(let u of p){let m=Je(u);m&&i.set(G(m),u)}}catch{}let d=[],c=[];for(let f of e){let{link:l,createdBy:p}=f,u=l.found===null?void 0:i.get(G(l.found)),m=ft(u?.[He]);s.includes(f)&&typeof p=="string"&&typeof u?.[le]=="string"&&G(u[le])===G(p)&&m>=o.from&&m<=o.to?d.push({...l,cause:"automation"}):c.push(l)}return{explained:d,broken:c}}async objectOfId(e,t){if(e.length===1)return e[0];for(let r of e)try{if((await this.describe(this.deps.target,"target",r)).keyPrefix===t.slice(0,3))return r}catch{}}describe(e,t,r){let o=`${t}:${r}`,s=this.describes.get(o);return s||(s=e.describe(r),this.describes.set(o,s)),s.then(i=>yt.parse(i))}async linkPlan(e,t,r,o){let s=r.objectApiName,i={fields:[],expected:new Map,sample:[]};try{let[a,d]=await Promise.all([this.describe(this.deps.target,"target",s),this.describe(e,"source",s)]),c=new Set(a.fields.filter(w=>w.type==="reference"&&(w.createable===!0||w.updateable===!0)).map(w=>w.name)),f=new Set(t.fieldExclusions?.[s]??[]),l=t.fieldMappings?.[s]??{},p=d.fields.filter(w=>w.type==="reference"&&!f.has(w.name)).map(w=>({from:w.name,to:l[w.name]??w.name})).filter(({to:w})=>c.has(w)&&!f.has(w));if(p.length===0)return i;let u=new Map,m=new Map;for(let[w,b]of Object.entries(t.remapTable))u.set(G(b),w),m.set(G(w),b);let g=r.ids.slice(0,o).filter(w=>u.has(G(w)));if(g.length===0)return i;let h=await fe(e,s,p.map(w=>w.from),g.map(w=>u.get(G(w)))),y=new Map;for(let w of h){let b=Je(w),A=b?m.get(G(b)):void 0;if(!A)continue;let j=[];for(let{from:L,to:v}of p){let P=w[L],k=typeof P=="string"?m.get(G(P)):void 0;k&&j.push({field:v,expected:k})}j.length>0&&y.set(G(A),j)}let R=[...new Set([...y.values()].flat().map(w=>w.field))],S=new Map(a.fields.filter(w=>R.includes(w.name)).map(w=>[w.name,w.referenceTo??[]]));return{fields:R,expected:y,sample:R.length>0?g:[],referenceTo:S,createdBy:a.fields.some(w=>w.name===le)}}catch(a){return{...i,unchecked:H(a)}}}async runUser(e){for(let t of e.records){let r=t.ids[0];if(r!==void 0)try{let[o]=await fe(this.deps.target,t.objectApiName,[le],[r]),s=o?.[le];if(typeof s=="string"&&/^[A-Za-z0-9]{15,18}$/.test(s))return s}catch{}}}async countInTheWindow(e,t,r,o){try{return(await this.deps.target.query(`SELECT COUNT() FROM ${J(e)} WHERE ${le} = '${t}' AND ${He} >= ${ba(r.from)} AND ${He} <= ${ba(r.to)}`+(o?` AND ${J(o.field)} = '${o.value}'`:""))).totalSize}catch{return}}async withTheirRecordThere(e,t,r=e.ids[0]?.slice(0,3)){if(r===void 0)return 0;let o=new Set(e.ids.map(G)),s=t.withTheirRecord.filter(i=>i.slice(0,3)===r&&!o.has(G(i)));if(s.length===0)return 0;try{let i=await fe(this.deps.target,e.objectApiName,[],s);return new Set(i.map(Je).filter(a=>a!==void 0).map(G)).size}catch{return 0}}async writtenByThePlatformAlone(e,t){let r=new Set(e.records.flatMap(i=>i.ids.slice(0,1)).map(ya)),o=[...new Set(t.withTheirRecord.map(ya))].filter(i=>!r.has(i)),s=this.deps.target.describeGlobal;if(o.length===0||!s)return[];try{let{sobjects:i}=Ml.parse(await s.call(this.deps.target));return o.flatMap(a=>{let d=i.find(c=>c.keyPrefix===a);return d?[{objectApiName:d.name,prefix:a}]:[]})}catch{return[]}}async readWrittenByThePlatform(e,t,r){let o={objectApiName:e.objectApiName,expected:0,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:await this.withTheirRecordThere({objectApiName:e.objectApiName,ids:[]},t,e.prefix)};if(r!==void 0&&t.counted){let s=await this.countInTheWindow(e.objectApiName,r,t.counted);s!==void 0&&(o.createdInTheWindow=s)}return o}async read(e,t,r,o,s,i){let a=t.objectApiName,d={objectApiName:a,expected:t.ids.length,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:0,...o?.unchecked!==void 0?{linksUnchecked:o.unchecked}:{}},c,f={},l,p=a===un.objectApiName?un:void 0;for(let y of xl)try{let R=[y.modified,y.by,...y.created?[He,le,...p?[p.field]:[]]:[]].filter(S=>!!S);c=await fe(this.deps.target,a,R,t.ids),f=y;break}catch(R){l??=H(R)}if(!c)return{...d,error:l??"The org gave no reason."};let u=new Map;for(let y of c){let R=Je(y);R&&u.set(G(R),y)}let m=t.ids.filter(y=>!u.has(G(y))),g=0;if(m.length>0){let y=await this.recycleBin(a,m);if("unread"in y)d.notVisibleIds=m,d.recycleBinUnread=y.unread;else for(let R of m){let S=y.found.get(G(R));S==="deleted"?d.deletedIds.push(R):S==="there"?g++:d.notVisibleIds.push(R)}}if(d.present=u.size+g,d.withTheirRecord=await this.withTheirRecordThere(t,s),i!==void 0&&s.counted){let y=s.counted,R=await this.countInTheWindow(a,i,y);if(R!==void 0){d.createdInTheWindow=R;let S=g,w=0;for(let b of u.values())_l(b,i,y)!==!1&&(S++,p&&b[p.field]===p.value&&w++);if(d.ofTheRunInTheWindow=S,p){let b=await this.countInTheWindow(a,i,y,p);b!==void 0&&b>w&&(d.postedWithTheirRecord=b-w)}}}let h=new Map(Object.entries(e.removalStamps??{}).map(([y,R])=>[G(y),ft(R)]));if(f.modified&&Number.isFinite(r))for(let y of t.ids){let R=u.get(G(y));if(!R)continue;let S=ft(R[f.modified]);if(!Number.isFinite(S)||S<=r||S<=(h.get(G(y))??Number.NaN))continue;let w=f.by?R[f.by]:void 0;d.changed.push({recordId:y,modifiedAt:String(R[f.modified]),...typeof w=="string"?{modifiedById:w}:{}})}if(o&&o.sample.length>0)try{let y=await fe(this.deps.target,a,o.createdBy?[...o.fields,le]:o.fields,o.sample),R=new Set(e.writtenWithout?.[a]??[]),S=[];for(let w of y){let b=Je(w);if(b)for(let{field:A,expected:j}of o.expected.get(G(b))??[]){let L=w[A],v=typeof L=="string"&&L!==""?L:null;if(v!==null&&G(v)===G(j)){d.linksChecked++;continue}if(v===null&&s.emptiedByFilter.has(ha(a,b,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:j,found:v,cause:"lookup-filter"});continue}if(v===null&&s.emptiedByTheRun.has(wa(a,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:j,found:v,cause:"run"});continue}if(v===null&&R.has(A))continue;d.linksChecked++;let P={recordId:b,field:A,expected:j,found:v};v===null?d.broken.push(P):S.push({link:P,createdBy:w[le]})}}if(S.length>0){let{explained:w,broken:b}=await this.setByAutomation(S,o,s);d.explained.push(...w),d.broken.push(...b)}}catch(y){d.linksUnchecked=H(y)}return d}async recycleBin(e,t){let r=new Map;try{let o=J(e);for(let s of X(t)){let i=await this.deps.target.queryAll(`SELECT Id, IsDeleted FROM ${o} WHERE Id IN (${s})`);for(let a of i.records){if(typeof a!="object"||a===null)continue;let d=a,c=Je(d);if(!c)continue;let f=d.IsDeleted===!0||d.IsDeleted==="true";r.set(G(c),f?"deleted":"there")}}}catch(o){return{unread:H(o)}}return{found:r}}};function Dl(n,e,t){let r=t.find(d=>d.objectApiName===e.objectApiName);if(r?.error!==void 0)return;let o=new Set(n.records.filter(d=>d.objectApiName===e.objectApiName).flatMap(d=>d.ids.map(G))),s=new Set([...r?.deletedIds??[],...r?.notVisibleIds??[]].map(G)),i=0,a=0;for(let d of e.sourceIds){let c=n.remapTable[d];if(c===void 0)continue;i++;let f=G(c);(!o.has(f)||r!==void 0&&!s.has(f))&&a++}return{inTarget:a,of:i}}function Bl(n){let e=n.explained.filter(s=>s.cause==="run").length,t=n.postedWithTheirRecord??0,r=n.withTheirRecord+t,o=(n.ofTheRunInTheWindow??n.present)+r;return{objectApiName:n.objectApiName,expected:n.expected,present:n.present,deleted:n.deletedIds.length,notVisible:n.notVisibleIds.length,changed:n.changed.length,changedRecords:n.changed.slice(0,lt),deletedIds:n.deletedIds.slice(0,lt),notVisibleIds:n.notVisibleIds.slice(0,lt),linksChecked:n.linksChecked,linksBroken:n.broken.length,brokenLinks:n.broken.slice(0,lt),...n.explained.length>0?{linksLeftEmptyByFilter:n.explained.filter(s=>s.cause==="lookup-filter").length,linksSetByAutomation:n.explained.filter(s=>s.cause==="automation").length,...e>0?{linksLeftEmptyByTheRun:e}:{},explainedLinks:n.explained.slice(0,lt)}:{},...n.error!==void 0?{error:n.error}:{},...n.linksUnchecked!==void 0?{linksUnchecked:n.linksUnchecked}:{},...n.recycleBinUnread!==void 0?{recycleBinUnread:n.recycleBinUnread}:{},...r>0?{withTheirRecord:r}:{},...n.createdInTheWindow!==void 0&&n.createdInTheWindow>o?{moreInTheWindow:n.createdInTheWindow-o}:{}}}function $l(n,e,t){return n?e.some(o=>o.error!==void 0||o.linksUnchecked!==void 0||o.deleted>0||o.notVisible>0||o.linksBroken>0||(o.moreInTheWindow??0)>0)||t!==void 0?"partial":"verified":"unstable"}function Oh(n){let e=s=>n.objects.reduce((i,a)=>i+s(a),0),t=e(s=>s.linksLeftEmptyByFilter??0),r=e(s=>s.linksSetByAutomation??0),o=e(s=>s.linksLeftEmptyByTheRun??0);return{expected:e(s=>s.expected),present:e(s=>s.present),deleted:e(s=>s.deleted),notVisible:e(s=>s.notVisible),changed:e(s=>s.changed),linksChecked:e(s=>s.linksChecked),linksBroken:e(s=>s.linksBroken),...t>0?{linksLeftEmptyByFilter:t}:{},...r>0?{linksSetByAutomation:r}:{},...o>0?{linksLeftEmptyByTheRun:o}:{},attempts:n.attempts}}function Ah(n){return n?{[rn]:[Ar]}:{}}function kh(n){let e={};for(let{objectApiName:t,fields:r}of n){let o=e[t]??=[];for(let{field:s}of r)o.includes(s)||o.push(s)}return e}var Sa=class{map=new Map;readScopes=new Map;reached=new Map;add(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r));for(let o of t)o&&r.add(o)}addRead(e,t){this.add(e,t),this.readScopes.set(e,new Set(this.map.get(e)))}addReadAgain(e,t){let r=[...t].filter(o=>o);this.add(e,r),this.readScopes.set(e,new Set([...this.readScopes.get(e)??[],...r]))}forget(e,t){let r=this.map.get(e);if(r)for(let o of t)r.delete(o)}get(e){return this.map.get(e)}scopeOf(e){return this.readScopes.get(e)??this.map.get(e)}isRead(e){return this.readScopes.has(e)}addReached(e,t){let r=this.reached.get(e);r||(r=new Set,this.reached.set(e,r));for(let o of t)o&&r.add(o)}reachedOf(e){return this.reached.get(e)}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}get size(){let e=0;for(let t of this.map.values())e+=t.size;return e}get objectCount(){let e=0;for(let t of this.map.values())t.size>0&&e++;return e}entries(){return this.map.entries()}clear(){this.map.clear(),this.readScopes.clear(),this.reached.clear()}};var Oa=class{cache=new Map;sizeMap=new Map;maxSize;defaultTtl;maxSizeBytes;currentBytes=0;releaseExpired;releaseTimer;constructor(e){this.maxSize=e?.maxSize??100,this.defaultTtl=e?.defaultTtl??3e5,this.maxSizeBytes=e?.maxSizeBytes??5242880,this.releaseExpired=e?.releaseExpired===!0}get(e){let t=this.cache.get(e);if(t){if(this.isExpired(t)){this.deleteEntry(e);return}return t.accessCount++,t.lastAccessedAt=Date.now(),t.data}}set(e,t,r){this.cache.has(e)&&this.removeSize(e);let o=this.maxSizeBytes<Number.POSITIVE_INFINITY,s=o?this.estimateSize(t):0;if(this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),o)for(;this.cache.size>0&&this.currentBytes+s>this.maxSizeBytes;)this.evictLRU();this.cache.set(e,{data:t,cachedAt:Date.now(),ttl:r??this.defaultTtl,accessCount:1,lastAccessedAt:Date.now()}),o&&(this.sizeMap.set(e,s),this.currentBytes+=s),this.releaseExpired&&this.scheduleRelease()}has(e){let t=this.cache.get(e);return t?this.isExpired(t)?(this.deleteEntry(e),!1):!0:!1}invalidate(e){return this.cache.has(e)?(this.deleteEntry(e),!0):!1}invalidateByPrefix(e){let t=0;for(let r of this.cache.keys())r.startsWith(e)&&(this.deleteEntry(r),t++);return t}clear(){this.cache.clear(),this.sizeMap.clear(),this.currentBytes=0,clearTimeout(this.releaseTimer),this.releaseTimer=void 0}get size(){return this.cache.size}get activeSize(){let e=0;for(let t of this.cache.values())this.isExpired(t)||e++;return e}get estimatedBytes(){return this.currentBytes}keys(){let e=[];for(let[t,r]of this.cache)this.isExpired(r)||e.push(t);return e}purgeExpired(){let e=0;for(let[t,r]of this.cache)this.isExpired(r)&&(this.deleteEntry(t),e++);return e}scheduleRelease(){if(this.releaseTimer!==void 0)return;let e=1/0;for(let r of this.cache.values())e=Math.min(e,r.cachedAt+r.ttl);if(e===1/0)return;let t=setTimeout(()=>{this.releaseTimer=void 0,this.purgeExpired(),this.scheduleRelease()},Math.max(0,e-Date.now())+1);t.unref?.(),this.releaseTimer=t}isExpired(e){return Date.now()-e.cachedAt>e.ttl}evictLRU(){let e,t=1/0;for(let[r,o]of this.cache)o.lastAccessedAt<t&&(t=o.lastAccessedAt,e=r);e&&this.deleteEntry(e)}deleteEntry(e){this.cache.delete(e),this.removeSize(e)}removeSize(e){let t=this.sizeMap.get(e);t!==void 0&&(this.currentBytes-=t,this.sizeMap.delete(e))}estimateSize(e){if(e==null)return 16;if(typeof e=="string")return e.length*2;if(typeof e=="number"||typeof e=="boolean")return 8;if(typeof e!="object")return 64;let t=e;if(Array.isArray(t.fields)||Array.isArray(t.childRelationships)){let r=512;if(Array.isArray(t.fields))for(let o of t.fields)r+=this.estimateEntrySize(o,250);if(Array.isArray(t.childRelationships))for(let o of t.childRelationships)r+=this.estimateEntrySize(o,100);return r}return Array.isArray(e)?e.length*64+64:Object.keys(e).length*64+128}estimateEntrySize(e,t){if(e==null||typeof e!="object")return 16;let r=t;for(let o of Object.values(e))if(typeof o=="string")r+=16+o.length*2;else if(typeof o=="number"||typeof o=="boolean")r+=8;else if(Array.isArray(o)){r+=16;for(let s of o)r+=typeof s=="string"?16+s.length*2:this.estimateEntrySize(s,64)}else r+=16;return r}};export{Un as a,zn as b,Zd as c,Qd as d,Kp as e,Ul as f,zl as g,As as h,Vl as i,Gl as j,Jl as k,Is as l,Hl as m,Ql as n,Sa as o,jl as p,rn as q,Rr as r,Ar as s,kr as t,Ir as u,ah as v,dh as w,ch as x,uh as y,lh as z,rf as A,of as B,sf as C,uf as D,lf as E,Fs as F,bf as G,Rf as H,Sf as I,Of as J,Af as K,kf as L,If as M,jf as N,Nf as O,Ef as P,Mf as Q,Cs as R,_f as S,Df as T,er as U,tr as V,um as W,Wi as X,Ng as Y,Vi as Z,Eg as _,Yf as $,Fn as aa,Zf as ba,Ds as ca,Qf as da,Xf as ea,cd as fa,ep as ga,hd as ha,lp as ia,fp as ja,pp as ka,Ad as la,Ln as ma,vd as na,We as oa,Ys as pa,Sp as qa,Op as ra,Ld as sa,Ap as ta,kp as ua,Oa as va,Dd as wa,Bd as xa,Ep as ya,Cp as za,qn as Aa,xp as Ba,Mp as Ca,Lp as Da,_p as Ea,ei as Fa,Wp as Ga,Up as Ha,zp as Ia,Vp as Ja,ti as Ka,kc as La,bm as Ma,Sm as Na,Om as Oa,Nm as Pa,Em as Qa,Tm as Ra,$c as Sa,Wc as Ta,qc as Ua,qm as Va,Um as Wa,zm as Xa,Vm as Ya,Gm as Za,Jm as _a,Hm as $a,Km as ab,Ym as bb,Xm as cb,hu as db,eg as eb,vg as fb,Gi as gb,Ji as hb,Mg as ib,Lg as jb,_g as kb,Dg as lb,qg as mb,Vg as nb,wr as ob,nn as pb,oh as qb,Sh as rb,Ra as sb,Oh as tb,Ah as ub,kh as vb};
|