sandforge 1.79.0 → 1.81.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/bin/sandforge-pipeline.mjs +12 -0
- package/lib/{chunk-BN7A4GRQ.mjs → chunk-2IB7I3IQ.mjs} +1 -1
- package/lib/{chunk-PBI4BYWW.mjs → chunk-2NAIUKVL.mjs} +1 -1
- package/lib/chunk-2OIRJEYE.mjs +7 -0
- package/lib/{chunk-FOVVHGEP.mjs → chunk-2OZG6GRW.mjs} +1 -1
- package/lib/{chunk-5CD257T7.mjs → chunk-2Z54GB6X.mjs} +1 -1
- package/lib/chunk-2ZMGVBLW.mjs +7 -0
- package/lib/{chunk-4NAHW2D3.mjs → chunk-33ZX3A56.mjs} +1 -1
- package/lib/{chunk-4SNDMJP2.mjs → chunk-3AOKLIVE.mjs} +1 -1
- package/lib/{chunk-SIOZXPFG.mjs → chunk-3B5H24ZG.mjs} +1 -1
- package/lib/chunk-43K2C6H2.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/chunk-4L7FBOJS.mjs +8 -0
- package/lib/chunk-5344TZBT.mjs +11 -0
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/chunk-55LQD3Y3.mjs +7 -0
- package/lib/chunk-56MPPWLA.mjs +7 -0
- package/lib/chunk-5C5XEVZN.mjs +11 -0
- package/lib/chunk-5CKWGZX4.mjs +9 -0
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/{chunk-GNC27UEU.mjs → chunk-5UT2ZBGF.mjs} +1 -1
- package/lib/chunk-5VQNKDFU.mjs +7 -0
- package/lib/chunk-5WGA5CZB.mjs +7 -0
- package/lib/chunk-5ZKCLBTN.mjs +474 -0
- package/lib/chunk-67CC7RAE.mjs +7 -0
- package/lib/{chunk-5O6JOMHS.mjs → chunk-6CDIIFNX.mjs} +1 -1
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-7UQD6V6F.mjs → chunk-6FMLW7PH.mjs} +1 -1
- package/lib/chunk-6IGEASOF.mjs +7 -0
- package/lib/{chunk-H2PJNIYJ.mjs → chunk-6NADW3OI.mjs} +1 -1
- package/lib/chunk-6SEDOIO3.mjs +10 -0
- package/lib/{chunk-AUTM6H6Z.mjs → chunk-742SSN7I.mjs} +1 -1
- package/lib/chunk-7DALDJMO.mjs +7 -0
- package/lib/chunk-7PK5QDQI.mjs +7 -0
- package/lib/chunk-AELFEK3G.mjs +7 -0
- package/lib/chunk-AITNZWLB.mjs +9 -0
- package/lib/{chunk-HV2MXMGI.mjs → chunk-AJPSGVMD.mjs} +1 -1
- package/lib/{chunk-OTWRDD6L.mjs → chunk-BNO5GIJ6.mjs} +1 -1
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/chunk-BZFIOZS3.mjs +156 -0
- package/lib/{chunk-XBG5SP6Q.mjs → chunk-C4YGSK6W.mjs} +1 -1
- package/lib/chunk-CAFUNR6D.mjs +7 -0
- package/lib/chunk-CULAOP3U.mjs +7 -0
- package/lib/chunk-D62KWDDT.mjs +7 -0
- package/lib/{chunk-BILZ3SSR.mjs → chunk-D7P7DTWL.mjs} +1 -1
- package/lib/chunk-DHGPDSXS.mjs +7 -0
- package/lib/{chunk-ZXH4MBWP.mjs → chunk-DHIW4IO5.mjs} +1 -1
- package/lib/{chunk-NM4MDLK4.mjs → chunk-DMBR24CK.mjs} +1 -1
- package/lib/chunk-DPYTG6DM.mjs +48 -0
- package/lib/chunk-DQR5NDMI.mjs +7 -0
- package/lib/chunk-DXOXLUZA.mjs +7 -0
- package/lib/chunk-E2OBAWSH.mjs +7 -0
- package/lib/chunk-E2YJVSX6.mjs +10 -0
- package/lib/chunk-EAFLDSQ2.mjs +7 -0
- package/lib/{chunk-HCIDVIOW.mjs → chunk-EH5YUA5W.mjs} +1 -1
- package/lib/{chunk-2BVTCNWA.mjs → chunk-EOSEMFPU.mjs} +1 -1
- package/lib/chunk-ETT5GP4P.mjs +13 -0
- package/lib/{chunk-3SRXFZSD.mjs → chunk-FDGFUEK3.mjs} +1 -1
- package/lib/{chunk-3DCUADVK.mjs → chunk-FLNLG43R.mjs} +1 -1
- package/lib/{chunk-HTJ5OGP5.mjs → chunk-FSDO4DJA.mjs} +1 -1
- package/lib/{chunk-HJKM3E56.mjs → chunk-FSZTXLNW.mjs} +1 -1
- package/lib/chunk-FTA5LOVX.mjs +7 -0
- package/lib/chunk-G4VXPS3A.mjs +7 -0
- package/lib/chunk-GF247DA7.mjs +7 -0
- package/lib/{chunk-QRV2OSIS.mjs → chunk-GK7VEYFM.mjs} +1 -1
- package/lib/{chunk-5MMXFWPD.mjs → chunk-GR3NGDVM.mjs} +1 -1
- package/lib/{chunk-P7GSGFJO.mjs → chunk-GTIXJCGS.mjs} +1 -1
- package/lib/{chunk-342FN7AO.mjs → chunk-GWRKS3AL.mjs} +1 -1
- package/lib/{chunk-LQ4DRFUH.mjs → chunk-GYKNCYES.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/chunk-HVC5CYIB.mjs +7 -0
- package/lib/{chunk-EQF2IJS2.mjs → chunk-HYBH5PFM.mjs} +1 -1
- package/lib/chunk-HYOOJVR6.mjs +7 -0
- package/lib/{chunk-TQX3PURV.mjs → chunk-IBURU7T7.mjs} +1 -1
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/{chunk-K22PA4XL.mjs → chunk-IKGHRYCN.mjs} +1 -1
- package/lib/chunk-IM2XA6JI.mjs +7 -0
- package/lib/{chunk-P2PJYWGQ.mjs → chunk-J6G23RUI.mjs} +1 -1
- package/lib/{chunk-JVL444U5.mjs → chunk-JU2XEKEO.mjs} +1 -1
- package/lib/{chunk-H45UXY6G.mjs → chunk-K55LH4ZQ.mjs} +1 -1
- package/lib/chunk-K5HV4YRO.mjs +7 -0
- package/lib/{chunk-IAZB4WIL.mjs → chunk-K77NR3UK.mjs} +1 -1
- package/lib/chunk-KE2PGD6C.mjs +7 -0
- package/lib/chunk-KGYXLSQ5.mjs +37 -0
- package/lib/{chunk-TEOLMRDO.mjs → chunk-KNIRA333.mjs} +1 -1
- package/lib/chunk-KOQV4WXC.mjs +8 -0
- package/lib/{chunk-PNCONNFJ.mjs → chunk-KRNFVAGC.mjs} +1 -1
- package/lib/chunk-L5FGY6YA.mjs +7 -0
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/{chunk-ZOVSMN5C.mjs → chunk-LO527YLT.mjs} +1 -1
- package/lib/chunk-MAHZMPMZ.mjs +7 -0
- package/lib/{chunk-QQZZMKU3.mjs → chunk-MHW6DV6T.mjs} +1 -1
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-6EBMEGZB.mjs → chunk-MKNAZPOT.mjs} +1 -1
- package/lib/{chunk-NTDN2JQZ.mjs → chunk-MNITSYI2.mjs} +8 -8
- package/lib/chunk-MO3N5XVV.mjs +341 -0
- package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
- package/lib/chunk-MWLFFVQV.mjs +8 -0
- package/lib/chunk-N6HHNR6J.mjs +7 -0
- package/lib/chunk-N7J6NJQ6.mjs +7 -0
- package/lib/chunk-NJ3EOEHS.mjs +9 -0
- package/lib/chunk-NWPQF5XR.mjs +7 -0
- package/lib/{chunk-PUOX4NBJ.mjs → chunk-NWVVCZUK.mjs} +1 -1
- package/lib/{chunk-DLDX6RRC.mjs → chunk-O6ADMP36.mjs} +1 -1
- package/lib/chunk-O7DAFE6M.mjs +14 -0
- package/lib/chunk-OEHVAJAB.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-OIIL4NVI.mjs +7 -0
- package/lib/chunk-OMZJ37JI.mjs +15 -0
- package/lib/{chunk-NZ5ZZLKS.mjs → chunk-ONMBSACW.mjs} +1 -1
- package/lib/chunk-OQQHNYR7.mjs +272 -0
- package/lib/{chunk-AAVJ5XVX.mjs → chunk-OU5W7SCB.mjs} +1 -1
- package/lib/{chunk-RSYICMZG.mjs → chunk-OVOLG3AL.mjs} +1 -1
- package/lib/{chunk-F74IHMGL.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
- package/lib/{chunk-W7KFAY55.mjs → chunk-OZNLOV4U.mjs} +1 -1
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-RACDTRZA.mjs → chunk-PYUEHBA6.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-PZTSVQSF.mjs → chunk-QXLZINZB.mjs} +1 -1
- package/lib/chunk-R2BJWO5N.mjs +20 -0
- package/lib/chunk-R6TF26V4.mjs +10 -0
- package/lib/{chunk-P42X3B4D.mjs → chunk-RKALOKAU.mjs} +1 -1
- package/lib/chunk-SQGP46QS.mjs +7 -0
- package/lib/chunk-SU65Z2BA.mjs +7 -0
- package/lib/chunk-SW2NUKQL.mjs +9 -0
- package/lib/chunk-T26C576X.mjs +9 -0
- package/lib/{chunk-3OHPD72J.mjs → chunk-T3PLRQ2T.mjs} +1 -1
- package/lib/chunk-T5VAULLQ.mjs +7 -0
- package/lib/chunk-TEIBWMJM.mjs +7 -0
- package/lib/chunk-TKQQVB2D.mjs +9 -0
- package/lib/{chunk-RAAANPPG.mjs → chunk-TPHXRHOA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-IEYG5ATY.mjs → chunk-TQM2XJ27.mjs} +1 -1
- package/lib/{chunk-X65MT4W3.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
- package/lib/chunk-UIUPPEFB.mjs +7 -0
- package/lib/{chunk-QPF6C5MX.mjs → chunk-UT27HXE7.mjs} +1 -1
- package/lib/{chunk-J7HVXMSW.mjs → chunk-UUSLTW5V.mjs} +1 -1
- package/lib/chunk-V2QO6KOE.mjs +19 -0
- package/lib/chunk-V473C7LY.mjs +7 -0
- package/lib/chunk-V4RKM4QZ.mjs +8 -0
- package/lib/chunk-VSU74RQ3.mjs +9 -0
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/chunk-W2AAGIZF.mjs +7 -0
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WD47PGUS.mjs +10 -0
- package/lib/{chunk-3CA767QB.mjs → chunk-WEZLXE34.mjs} +1 -1
- package/lib/{chunk-WFEB5X4U.mjs → chunk-WI4HYWV6.mjs} +1 -1
- package/lib/{chunk-AR7BE5O2.mjs → chunk-WM5JI4JI.mjs} +1 -1
- package/lib/chunk-WWTXRWNZ.mjs +7 -0
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-ZJKCWBRJ.mjs → chunk-X2ZVSQ54.mjs} +1 -1
- package/lib/{chunk-SFURUNJM.mjs → chunk-XC2QKQT5.mjs} +1 -1
- package/lib/chunk-XC54KKKC.mjs +7 -0
- package/lib/chunk-XEB6HZ34.mjs +7 -0
- package/lib/chunk-XGKSSCW7.mjs +7 -0
- package/lib/chunk-XIZ5LMQM.mjs +7 -0
- package/lib/{chunk-RFEO2KAN.mjs → chunk-Y5ZCPY36.mjs} +1 -1
- package/lib/{chunk-TBZMC2VV.mjs → chunk-YCSFP6ER.mjs} +4 -4
- package/lib/{chunk-YBU4Z4QV.mjs → chunk-YHIOS2PU.mjs} +1 -1
- package/lib/chunk-YIGFYZQY.mjs +7 -0
- package/lib/chunk-YJEXE6HZ.mjs +925 -0
- package/lib/{chunk-57VHUYNG.mjs → chunk-YOGMP72T.mjs} +4 -4
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-55HEMHEG.mjs → chunk-ZUA5BNAO.mjs} +1 -1
- package/lib/chunk-ZWCRWF7E.mjs +7 -0
- package/lib/{chunk-VHI54FBK.mjs → chunk-ZWZXQTAK.mjs} +53 -53
- package/lib/sandforge-autopilot.mjs +29 -24
- package/lib/sandforge-backup.mjs +67 -32
- package/lib/sandforge-checkpoint.mjs +1 -347
- package/lib/sandforge-cleanup.mjs +14 -10
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +9 -8
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +15 -15
- package/lib/sandforge-env.mjs +101 -101
- package/lib/sandforge-frozen.mjs +1 -257
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +7 -7
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +6 -6
- package/package.json +2 -1
- package/lib/chunk-2S5OMIIA.mjs +0 -7
- package/lib/chunk-36U7IQ6Y.mjs +0 -25
- package/lib/chunk-3F5YMM2F.mjs +0 -7
- package/lib/chunk-3RYLICRX.mjs +0 -7
- package/lib/chunk-42RER7V4.mjs +0 -14
- package/lib/chunk-4GL773D5.mjs +0 -7
- package/lib/chunk-4HFRHFGQ.mjs +0 -7
- package/lib/chunk-4U6NXJNL.mjs +0 -7
- package/lib/chunk-4XZ5YT5O.mjs +0 -7
- package/lib/chunk-5AJRHRXA.mjs +0 -20
- package/lib/chunk-5HMAPZBV.mjs +0 -7
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5QKTYCWE.mjs +0 -11
- package/lib/chunk-6LAXTAVN.mjs +0 -7
- package/lib/chunk-6MUEPV7M.mjs +0 -9
- package/lib/chunk-6QSM2WIH.mjs +0 -10
- package/lib/chunk-75ADZS6B.mjs +0 -7
- package/lib/chunk-ALJVEUUS.mjs +0 -7
- package/lib/chunk-ALUFROGA.mjs +0 -7
- package/lib/chunk-B45CNPUX.mjs +0 -47
- package/lib/chunk-BS5T3MOQ.mjs +0 -7
- package/lib/chunk-CGWXQX75.mjs +0 -7
- package/lib/chunk-D3QRXG63.mjs +0 -787
- package/lib/chunk-EEVVGGM6.mjs +0 -7
- package/lib/chunk-ENLBYECD.mjs +0 -7
- package/lib/chunk-EQOQASDQ.mjs +0 -7
- package/lib/chunk-FQBRBBY4.mjs +0 -7
- package/lib/chunk-GAM726CK.mjs +0 -7
- package/lib/chunk-HJC7AIBK.mjs +0 -7
- package/lib/chunk-HUMEKZT5.mjs +0 -8
- package/lib/chunk-I3JKJTLO.mjs +0 -110
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-KLX67VPL.mjs +0 -7
- package/lib/chunk-L776PUMV.mjs +0 -7
- package/lib/chunk-LRFAIUN7.mjs +0 -7
- package/lib/chunk-LV6G4XTK.mjs +0 -7
- package/lib/chunk-MYTIL2JD.mjs +0 -10
- package/lib/chunk-NEVXIGR6.mjs +0 -10
- package/lib/chunk-NGSMZZDA.mjs +0 -7
- package/lib/chunk-NHWE66K5.mjs +0 -7
- package/lib/chunk-OQOZAPCI.mjs +0 -7
- package/lib/chunk-PA3MKJVH.mjs +0 -7
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-RH3N2H7P.mjs +0 -7
- package/lib/chunk-SRQDABQ2.mjs +0 -15
- package/lib/chunk-SVS6UMDU.mjs +0 -323
- package/lib/chunk-TNXUU6W7.mjs +0 -14
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VXHDBYMI.mjs +0 -7
- package/lib/chunk-WJY54JO7.mjs +0 -13
- package/lib/chunk-WRU5FJFC.mjs +0 -7
- package/lib/chunk-X2PY6MWZ.mjs +0 -7
- package/lib/chunk-XEFDB2R4.mjs +0 -7
- package/lib/chunk-XETCPL7E.mjs +0 -7
- package/lib/chunk-Y5CGXLUB.mjs +0 -7
- package/lib/chunk-Y6J6QFI2.mjs +0 -7
- package/lib/chunk-YMJVMFPY.mjs +0 -7
- package/lib/chunk-YPSRZRIT.mjs +0 -7
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-YW2SBL4Z.mjs +0 -7
- package/lib/chunk-Z7X534S4.mjs +0 -10
- package/lib/chunk-ZE6HKRR4.mjs +0 -9
- package/lib/chunk-ZLZRU6MO.mjs +0 -7
- package/lib/chunk-ZPYJPGDK.mjs +0 -7
- package/lib/chunk-ZQOZ4EFW.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
- package/lib/chunk-ZYEE34WO.mjs +0 -7
package/lib/chunk-36U7IQ6Y.mjs
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
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{o as xo,s as Ko}from"./chunk-Z7X534S4.mjs";import{A as mn,B as hn,H as pe,I as jo,J as Nt,R as No,aa as Mo,e as kt,m as So,qa as ot,ra as Vo,sa as Jo,ta as Ho,v as Ao,w as Io,x as ko}from"./chunk-6QSM2WIH.mjs";import{b as _o,d as Tt,e as De,f as Do,g as Lo,h as Ft,i as Bo,j as $o,k as qo,l as zo,m as Uo,n as Wo,o as de,p as le,q as vt,r as Oe,s as Go}from"./chunk-WJY54JO7.mjs";import{d as rt,x as _e}from"./chunk-NEVXIGR6.mjs";import{b as Eo}from"./chunk-QSRAEUGZ.mjs";import{b as Fo}from"./chunk-F74IHMGL.mjs";import{a as vo}from"./chunk-M6P5ZZLE.mjs";import{a as Co}from"./chunk-YYZL7UGV.mjs";import{a as ho,l as Ro}from"./chunk-SAR5622P.mjs";import{a as St}from"./chunk-6MUEPV7M.mjs";import{f as uo,g as fo}from"./chunk-HJC7AIBK.mjs";import{a as go,b as Ue,c as mo,d as te,h as be}from"./chunk-OTWRDD6L.mjs";import{a as po}from"./chunk-5LFSFYFJ.mjs";import{B as We,D as st,Ka as es,La as ts,M as xt,O as Yo,Qa as ns,Ra as rs,Sa as os,Ta as wn,_ as Zo,ca as Qo,da as Xo,f as eo,o as Po,p as Ct}from"./chunk-VXHDBYMI.mjs";import{a as nt,b as Kr,c as Yr,g as It,j as Zr,n as Qr,r as Xr}from"./chunk-PA3MKJVH.mjs";import{a as Ce}from"./chunk-4TLYUZD5.mjs";import{D as To,a as vr,w as Pt}from"./chunk-ZLZRU6MO.mjs";import{b as ao,c as co}from"./chunk-EADHKH3A.mjs";import{g as lo}from"./chunk-GCOB7K5N.mjs";import{a as to,b as no,c as un,e as ro,f as oo,g as so,i as fn,j as io}from"./chunk-INIT2UKJ.mjs";import{a as yo,c as gn,j as Oo}from"./chunk-PNCONNFJ.mjs";import{A as dn,B as Lr,E as Br,F as ln,I as $r,J as qr,N as zr,Q as Ur,R as Wr,S as Gr,T as Vr,U as Jr,V as Hr,p as At,q as xr,r as ze,w as Mr,x as _r,z as Dr}from"./chunk-CGWXQX75.mjs";import{a as Ot,h as V}from"./chunk-TZE3Y7IQ.mjs";import{a as Et,c as pn,f as wo,i as jt,k as bo}from"./chunk-SIOZXPFG.mjs";import{a as tt,b as U}from"./chunk-CA5NAXSU.mjs";import{$ as cn,Ab as Se,Bb as je,Dc as Tr,Ec as Fr,J as et,O as an,U as Rr,V as Sr,W as Ee,X as Or,Y as Ar,aa as Ir,ba as kr,ca as Er,dc as Ne,rc as Pr,sb as Nr,ya as jr,yb as Cr,zb as qe}from"./chunk-B45CNPUX.mjs";import{b as z,e as J,f as hr,i as Re,k as H,l as q,o as wr,r as br,s as Xe,u as xe,v as Me,z as yr}from"./chunk-7EANH5PY.mjs";var it=.5;function nu(n){return`Salesforce can take several minutes to count a load in what ${n} says it has left: a run started sooner after another may read room it no longer has`}function ss(n){if("unread"in n.storage)return{unread:n.storage.unread};let{remainingMB:e,maxMB:t}=n.storage,r=We*Math.max(0,e-it)*1048576,o=n.withinMB!==void 0?Math.max(0,n.withinMB)*1048576:1/0,s=o<r?"within":"storage",i={remainingMB:e,maxMB:t,share:We,roundingMB:it,...n.withinMB!==void 0?{withinMB:n.withinMB}:{},limitedBy:s},a=Math.floor(Math.min(r,o));if(!n.api)return{bytes:a,terms:i};if("unread"in n.api)return{bytes:a,terms:i,requestsUnread:n.api.unread};let c=Object.values(n.otherRequests??{}).reduce((p,u)=>p+Math.max(0,u??0),0),l=Math.max(0,Math.floor(n.api.remaining-xt*n.api.max-c));return{bytes:a,terms:i,runRequests:l}}var Wi=/__e$/i,Gi=/Share$/;function ru(n,e){let t=new Map,r=new Map,o=(i,a)=>{let c=`${i}
|
|
8
|
-
${a}`,l=t.get(c);return l||(l={objectApiName:i,act:a,bytes:0,creates:[]},t.set(c,l)),l},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 c of i.flow.creates??[]){if(Wi.test(c))continue;if(Gi.test(c)){s({objectApiName:i.objectApiName,kind:"share",name:c});continue}let l=o(i.objectApiName,a);l.bytes+=st(c,{rows:1}),l.creates.push({objectApiName:c,by:i.name})}}}return{perRecord:[...t.values()].filter(i=>i.bytes>0),notCounted:[...r.values()]}}function ou(n,e){return n.perRecord.reduce((t,r)=>t+r.bytes*Math.max(0,e(r.objectApiName,r.act)),0)}function su(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 iu(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 au(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{appendFile as Vi}from"node:fs/promises";var Pe=new Set(["Task","Event"]),Ji=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Hi="an emptying";function Ki(n){let e=V(n.objectApiName),t=Pe.has(n.objectApiName),r=[...n.filter!==void 0&&n.filter.trim()!==""?[`(${n.filter})`]:[],...t?["IsDeleted = false"]:[]];return{soql:`SELECT Id FROM ${e}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,scanAll:t}}async function mu(n,e,t,r={}){let o=()=>r.signal?.aborted===!0,s=[];await _e(e);for(let i of t){let{soql:a,scanAll:c}=Ki(i),l={objectApiName:i.objectApiName,count:0};if(s.push(l),o())return{stopped:!0,read:s};let p=ot(e,i.objectApiName),u=!0,f=0,d=await n.query(a,{scanAll:c});for(;;){let m=d.records.map(h=>{let w=h.Id;if(typeof w!="string"||!Ji.test(w))throw new Error(`The org answered a ${i.objectApiName} row with no record id: its ids are not read.`);return w});if((m.length>0||u)&&(await Vi(p,m.map(h=>`${h}
|
|
11
|
-
`).join(""),{encoding:"utf8",mode:rt,flag:u?"w":"a"}),u=!1),l.count+=m.length,r.onPage?.(i.objectApiName,l.count),f=m.length===0?f+1:0,d.done||!d.nextRecordsUrl)break;if(f>=ao)throw new Error(`The org kept answering empty pages of ${i.objectApiName} without saying it was done: ${l.count} id(s) read, the rest not.`);if(o())return{stopped:!0,read:s};d=await n.queryMore(d.nextRecordsUrl)}}return{stopped:!1,spool:await Vo(e,s,Hi)}}function Mt(n,e,t){return e.nillable!==!1||e.referenceTo.length!==1?!1:e.isMasterDetail||(t??[]).some(r=>r.isCascadeDelete&&r.childSObject===n&&r.field===e.name)}var Yi={clone:"write",empty:"delete"},Zi=["settings","definition"],Qi=new Set(["contentworkspace"]);function Xi(n){if(n.name.includes("__"))return!1;let e=n.name.toLowerCase();return Qi.has(e)||Zi.some(t=>e.endsWith(t))?!0:n.createable===!1&&e!==It.toLowerCase()}function ea(n,e){return n.objectApiName<e.objectApiName?-1:n.objectApiName>e.objectApiName?1:0}function ta(n,e,t,r={}){let o=Qr(n,{mode:"everything",access:Yi[t],...r.excluded!==void 0?{excluded:r.excluded}:{},...r.customSettings!==void 0?{customSettings:r.customSettings}:{}},e),s=new Map(n.map(c=>[c.name.toLowerCase(),c])),i=[],a=[];for(let c of o.candidates){let l=s.get(c.toLowerCase());l!==void 0&&Xi(l)?a.push({objectApiName:c,reason:"configuration"}):i.push(c)}return a.length===0?o:{...o,candidates:i,leftOut:[...o.leftOut,...a].sort(ea)}}var na=new Set([It,Zr].map(n=>n.toLowerCase())),is="withTheirRecords",ra="noLayout";function oa(n){switch(n){case"configuration":return{reason:"setup"};case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"files":case"setup":case"platformCreated":case"metadata":case"notWritable":case"excludedByUser":return{reason:n};case"heldWithFiles":return{reason:"files",detail:is};case"notFound":case"notCustomSetting":return{reason:"missingInTarget"}}}function sa(n){switch(n){case"platform":return{reason:"platformCreated"};case"setup":return{reason:"setup"};case"feature":case"parent":return{reason:"notWritable",detail:n};case"user":return{reason:"notWritable"}}}function ia(n){if(n.createable!==!0||n.queryable!==!0)return;let e=n.updateable===!0,t=n.deletable===!0;if(!(e&&t))return!e&&!t?{reason:"createOnly"}:{reason:"createOnly",detail:e?ca:aa}}var aa="noEdit",ca="noDelete";function da(n,e){return n.objectApiName<e.objectApiName?-1:n.objectApiName>e.objectApiName?1:0}function as(n,e,t,r={}){let o=ta(e,t,"clone",r),s=new Map(n.map(u=>[u.name.toLowerCase(),u])),i=new Map(e.map(u=>[u.name.toLowerCase(),u])),a=[],c=[],l=new Set,p=(u,f,d)=>{l.add(u.toLowerCase()),c.push({objectApiName:u,reason:f,...d!==void 0?{detail:d}:{}})};for(let u of n)i.has(u.name.toLowerCase())||p(u.name,"missingInTarget");for(let u of o.leftOut){let f=u.objectApiName.toLowerCase(),d=s.get(f);if(!d||l.has(f))continue;let m=i.get(f),h=oa(u.reason),w=f!==It.toLowerCase();h.reason==="notWritable"&&w&&m?.createable!==!0&&r.createFacts&&(h=sa(vo(d.name,r.createFacts))),h.reason==="notWritable"&&w&&m&&(h=ia(m)??h);let b=u.reason==="setup"&&m?.layoutable===!1&&!Yr(u.objectApiName);p(d.name,h.reason,b?ra:h.detail??u.detail)}for(let u of o.candidates){let f=u.toLowerCase(),d=s.get(f);d&&(d.queryable!==!0?p(d.name,"notQueryable"):na.has(f)?p(d.name,"files",is):a.push(d.name))}return a.sort(),c.sort(da),{candidates:a,leftOut:c}}var cs=1950,ds=2e4,la=1e6,ua=18,fa=200,pa=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE","REQUEST_LIMIT_EXCEEDED","REQUEST_RUNNING_TOO_LONG","SERVER_UNAVAILABLE","UNKNOWN_EXCEPTION"]);function us(n){if(n instanceof Po||vr(n))return!1;let e=tt(U(n));return e===void 0?!1:!pa.has(e)&&!e.startsWith("ERROR_HTTP_")}function ga(n,e){let t=Pe.has(n),r=[...e?[`(${e})`]:[],...t?["IsDeleted = false"]:[]];return{soql:`SELECT COUNT() FROM ${V(n)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,all:t}}async function Ae(n,e){let t=0,r=!1,o=()=>r,s=async()=>{for(;!r&&t<n.length;){let i=t++;try{await e(n[i],i,o)}catch(a){throw r=!0,a}}};await Promise.all(Array.from({length:Math.min(6,n.length)},s))}async function ma(n,e){try{return await n()}catch(t){if(t instanceof ae||St(t)||us(t))throw t;return Ce.warn(`[forge-discover] whole org: describe of ${e} unanswered, asked again: ${U(t)}`),n()}}function ls(n){if(!(n<=cn))throw new Error(`The source org lists ${n} objects a clone of the whole org leaves out, more than the ${cn} one graph says. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`)}var ha=q({name:z().min(1),count:J().int().nonnegative()});function wa(n){let e=q({sObjects:H(Re())}).safeParse(n);if(!e.success)return;let t=new Map;for(let r of e.data.sObjects){let o=ha.safeParse(r);o.success&&t.set(o.data.name,o.data.count)}return t}function ba(n){let e=new Map;for(let[t,r]of n)for(let o of r.fields){if(o.referenceTo.length===0)continue;let s=Se(o),i=s&&qe(t,o.name,o.nillable),a=je(o);for(let c of o.referenceTo){if(c===t||!n.has(c))continue;let l=`${c}|${t}`,p={sourceObject:c,targetObject:t,relationshipName:o.relationshipName??o.name,type:Mt(t,o,n.get(c)?.childRelationships)?"master-detail":"lookup",required:i},u=e.get(l);if(!u){e.set(l,{edge:p,noneSettable:!s,insertOnly:a});continue}let f=p.type==="master-detail"&&u.edge.type==="lookup"?p:u.edge;u.edge={...f,required:u.edge.required===!0||i},u.noneSettable=u.noneSettable&&!s,u.insertOnly=u.insertOnly||a}}return[...e.values()].map(({edge:t,noneSettable:r,insertOnly:o})=>({...t,...r?{settable:!1}:{},...o?{insertOnly:!0}:{}}))}function ya(n,e){let t=e.filter(To),r=Fo(n,t).reverse(),o=new Map;r.forEach((a,c)=>{for(let l of a)o.set(l,c)});let s=new Map;for(let a of t){let c=s.get(a.targetObject)??[];c.push(a.sourceObject),s.set(a.targetObject,c)}let i=r.map(()=>0);return r.forEach((a,c)=>{for(let l of a)for(let p of s.get(l)??[]){let u=o.get(p);u!==void 0&&u!==c&&(i[c]=Math.max(i[c],i[u]+1))}}),new Map(n.map(a=>[a,Math.min(ua,1+i[o.get(a)??0])]))}async function fs(n,e,t){let r=Ar(e);if(r!==void 0)throw new Error(r);let o=t?.signal;if(o?.aborted)return ct();try{return await Ra(n,e,t)}catch(s){if(s instanceof ae||o?.aborted)return ct();throw s}}async function Ra(n,e,t){let r=t?.signal,o=R=>t?.onProgress?.(R),s=Date.now(),i=R=>k=>{if(k instanceof ae)throw k;return Ce.warn(`[forge-discover] whole org: ${U(k)}`),R},{toolingObjects:a,recordCounts:c,createFacts:l}=n;o({phase:"listing",discoveredCount:0,queueRemaining:0});let[p,u,f,d,m]=await Promise.all([ge(()=>n.describeGlobal(e.sourceOrgId,r),r),ge(()=>n.describeGlobal(e.targetOrgId,r),r),a?ge(()=>a(e.targetOrgId,r),r).catch(i([])):Promise.resolve([]),l?ge(()=>l(e.targetOrgId),r).catch(i(void 0)):Promise.resolve(void 0),c?ge(()=>c(e.sourceOrgId,r),r).catch(i(void 0)):Promise.resolve(void 0)]),h=wa(m),{candidates:w,leftOut:b}=as(p,u,f,d?{createFacts:d}:{}),O=[...b];ls(O.length);let A=w.map(()=>{}),g=0;o({phase:"counting",discoveredCount:0,queueRemaining:w.length,total:w.length}),await Ae(w,async(R,k,I)=>{let j=h?.get(R),L=e.objectSoqlFilters?.[R];if(j!==void 0&&j>la&&!L)A[k]={objectApiName:R,rows:j,approximate:!0};else try{let{soql:B,all:P}=ga(R,L),v=await ge(()=>n.queryCount(e.sourceOrgId,B,r,P?{all:!0}:void 0),r);if(I())return;v>0?A[k]={objectApiName:R,rows:v}:O.push({objectApiName:R,reason:"empty"})}catch(B){if(B instanceof ae||St(B))throw B;if(I())return;us(B)?O.push({objectApiName:R,reason:"unreadable",detail:U(B)}):(Ce.warn(`[forge-discover] whole org: ${R} not counted, kept: ${U(B)}`),A[k]=j!==void 0&&j>0&&!L?{objectApiName:R,rows:j,approximate:!0}:{objectApiName:R,rows:0,unknown:!0})}g++,o({phase:"counting",objectApiName:R,discoveredCount:g,queueRemaining:w.length-g,total:w.length})});let y=A.filter(R=>R!==void 0);if(y.length>cs)throw new Error(`The source org holds records in ${y.length} objects a clone of the whole org would take, more than the ${cs} one run writes. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`);let S=y.map(()=>{}),E=0;o({phase:"describing",discoveredCount:0,queueRemaining:y.length,total:y.length}),await Ae(y,async({objectApiName:R},k,I)=>{try{let j=await ma(()=>ge(()=>n.describeObject(e.sourceOrgId,R,r),r),R);if(I())return;S[k]=j}catch(j){if(j instanceof ae||St(j))throw j;if(I())return;O.push({objectApiName:R,reason:"notDescribed",detail:U(j)})}E++,o({phase:"describing",objectApiName:R,discoveredCount:E,queueRemaining:y.length-E,total:y.length})}),await yn();let T=new Map,x=new Map;y.forEach((R,k)=>{let I=S[k];I&&(T.set(R.objectApiName,I),x.set(R.objectApiName,R))});let N=ba(T);if(N.length>ds)throw new Error(`The ${T.size} objects of the source org a clone of the whole org would take relate ${N.length} pairs of objects, more than the ${ds} one run writes in order. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`);let C=[...T.keys()],F=ya(C,N),_=C.map(R=>{let k=T.get(R),I=x.get(R),j=I.rows,L=n.detectPII(k.fields);return{objectApiName:R,...k.label?{label:k.label}:{},recordCount:j,...I.approximate?{recordCountApproximate:!0}:{},...I.unknown?{recordCountUnknown:!0}:{},fieldCount:k.fields.length,status:"idle",progress:0,included:!0,piiFields:L,anonymizeFields:e.anonymizePII?[...L]:[],level:F.get(R)??1,successCount:0,failureCount:0,errors:[],createableFieldCount:k.fields.filter(B=>B.type!=="id").length,estimatedSizeMB:j*at,estimatedApiCalls:Math.ceil(j/fa),batchStrategy:"auto"}});ls(O.length);let D=_.reduce((R,k)=>R+k.recordCount,0);return O.sort((R,k)=>R.objectApiName<k.objectApiName?-1:R.objectApiName>k.objectApiName?1:0),Ce.info(`[forge-discover] whole org: ${_.length} object(s), ${N.length} relation(s), ${O.length} left out, ${D} record(s), in ${Date.now()-s}ms`),{nodes:_,edges:N,totalRecords:D,estimatedSizeMB:D*at,estimatedDurationSeconds:D*bn,truncated:!1,leftOut:O}}var at=.001,bn=.01,Sa=50,Oa=5,Aa=2,Ia=4;function ka(n){return n.level===0||n.recordCount>0||n.status==="error"}var yn=typeof setImmediate=="function"?()=>new Promise(n=>setImmediate(n)):()=>new Promise(n=>setTimeout(n,0)),ae=class extends Error{constructor(){super("Discovery cancelled"),this.name="DiscoveryCancelled"}};function ge(n,e){return e?e.aborted?Promise.reject(new ae):new Promise((t,r)=>{let o=()=>r(new ae);e.addEventListener("abort",o,{once:!0}),n().then(s=>{e.removeEventListener("abort",o),t(s)},s=>{e.removeEventListener("abort",o),r(s)})}):n()}function Ea(n){return n.fieldCount>0||n.piiFields.length>0}function ct(){return{nodes:[],edges:[],totalRecords:0,estimatedSizeMB:0,estimatedDurationSeconds:0,truncated:!1}}var ps=class{deps;constructor(e){this.deps=e}async discover(e,t){if(e.inputMode==="org"||e.depth==="all")return fs(this.deps,e,t);let r=t?.signal;if(r?.aborted)return ct();t?.onProgress?.({phase:"resolving-root",discoveredCount:0,queueRemaining:1});let o=Date.now(),s;try{s=await this.resolveRootObject(e,r)}catch(C){if(C instanceof ae)return ct();throw C}let i=Date.now();i-o>2e3&&Ce.warn(`[forge-discover] resolveRootObject took ${i-o}ms (cold path, consider verifying describeGlobal cache state)`);let a=this.resolveMaxDepth(e),c=t?.maxNodes??Sa,l=c,p=c*Aa,u=new Set,f=[],d=c*Ia,m=0,h=0,w=new Set,b=[],O=new Map,A=()=>m+h+T.length<l&&b.length+h+T.length<d,g=(C,F)=>{u.has(C)||f.push([C,F]),u.add(C)},y=C=>{u.delete(C)&&(f=f.filter(([F])=>F!==C))},S=new Map,E=(C,F,_,D)=>{if(nt(C.sourceObject)||nt(C.targetObject)||C.sourceObject===C.targetObject)return;let R=`${C.sourceObject}|${C.targetObject}`,k=S.get(R)??new Map;(_!==void 0||!k.has(F))&&k.set(F,{settable:_,insertOnly:D}),S.set(R,k);let I=O.get(R);if(!I){O.set(R,C);return}let j=C.type==="master-detail"&&I.type==="lookup"?C:I,L=I.required===!0||C.required===!0;O.set(R,L?{...j,required:L}:j)},T=[[s,0]];for(w.add(s);T.length>0&&!r?.aborted;){await yn();let C=l-m;if(C<=0)break;let F=Math.min(6,C,T.length),_=T.splice(0,F),D=await Promise.all(_.map(async([R,k])=>{let I,j=e.objectSoqlFilters?.[R],L=`SELECT COUNT() FROM ${V(R)}${j?` WHERE (${j})`:""}`;try{let[B,P]=await Promise.all([ge(()=>this.deps.describeObject(e.sourceOrgId,R,r),r),ge(()=>this.deps.queryCount(e.sourceOrgId,L,r),r).catch(v=>{if(v instanceof ae)throw v;return I=U(v),-1})]);return{objectName:R,depth:k,describe:B,recordCount:P,countError:I}}catch(B){return B instanceof ae||r?.aborted?{objectName:R,depth:k,describe:null,recordCount:-1,cancelled:!0}:{objectName:R,depth:k,describe:null,recordCount:-1,describeError:U(B)}}}));h=D.length;for(let R of D){if(h--,R.cancelled)continue;let{objectName:k,depth:I,describe:j,recordCount:L,countError:B,describeError:P}=R;if(!j){b.push({objectApiName:k,recordCount:0,fieldCount:0,status:"error",progress:0,included:!1,piiFields:[],anonymizeFields:[],level:I,successCount:0,failureCount:0,errors:[`Describe unavailable: ${P??"unknown error"}`],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}),m++,t?.onProgress?.({phase:"object",objectApiName:k,discoveredCount:b.length,queueRemaining:T.length});continue}let v=L<0,M=v?0:L,$=this.deps.detectPII(j.fields),G=j.fields.filter(K=>K.type!=="id").length,ee={objectApiName:k,...j.label?{label:j.label}:{},recordCount:M,fieldCount:j.fields.length,status:v?"error":"idle",progress:0,included:v?!1:!e.skipEmpty||M>0,piiFields:$,anonymizeFields:e.anonymizePII?$:[],level:I,successCount:0,failureCount:0,errors:v?[`Record count unavailable: ${B??"unknown error"}`]:[],createableFieldCount:G,estimatedSizeMB:M*at,estimatedApiCalls:Math.ceil(M/200),batchStrategy:"auto"};b.push(ee);let se=ka(ee);if(se&&m++,I<a&&se){for(let K of j.fields){if(K.referenceTo.length===0)continue;let we=Se(K),ve=we&&qe(k,K.name,K.nillable),sn=je(K);for(let ie of K.referenceTo){E({sourceObject:ie,targetObject:k,relationshipName:K.relationshipName??K.name,type:K.isMasterDetail?"master-detail":"lookup",required:ve},K.name,we,sn);let Ui=u.has(ie);(!w.has(ie)||ve&&Ui)&&!nt(ie)&&(A()?(w.add(ie),y(ie),ve?T.unshift([ie,I+1]):T.push([ie,I+1])):ve&&l<p?(w.add(ie),y(ie),l++,T.unshift([ie,I+1])):(w.add(ie),g(ie,I+1)))}}for(let K of j.childRelationships)E({sourceObject:k,targetObject:K.childSObject,relationshipName:K.relationshipName,type:K.isCascadeDelete?"master-detail":"lookup"},K.field,void 0,void 0),!w.has(K.childSObject)&&!nt(K.childSObject)&&(w.add(K.childSObject),A()?T.push([K.childSObject,I+1]):g(K.childSObject,I+1))}t?.onProgress?.({phase:"object",objectApiName:k,discoveredCount:b.length,queueRemaining:T.length})}for(;f.length>0&&A();){let[R,k]=f.shift();u.delete(R),T.push([R,k])}}let x=b.reduce((C,F)=>C+F.recordCount,0),N=[...O].map(([C,F])=>{let _=[...S.get(C)?.values()??[]],D=F;return _.length>0&&_.every(R=>R.settable===!1)&&(D={...D,settable:!1}),_.some(R=>R.insertOnly===!0)&&(D={...D,insertOnly:!0}),D});return{nodes:b,edges:N,totalRecords:x,estimatedSizeMB:x*at,estimatedDurationSeconds:x*bn,truncated:f.length>0}}personalFields(e){return this.deps.detectPII(e)}async readPersonalFields(e,t,r){let o=e.nodes.filter(i=>!Ea(i)&&i.status!=="error"),s=new Map;for(let i=0;i<o.length&&!r?.aborted;i+=6)await Promise.all(o.slice(i,i+6).map(async({objectApiName:a})=>{try{let c=await this.deps.describeObject(t.sourceOrgId,a,r),l=this.deps.detectPII(c.fields);l.length>0&&s.set(a,l)}catch(c){Ce.warn(`[forge] personal fields of ${a} not read: ${U(c)}`)}}));return s.size===0?e:{...e,nodes:e.nodes.map(i=>{let a=s.get(i.objectApiName);return a?{...i,piiFields:a,anonymizeFields:t.anonymizePII?[...a]:[]}:i})}}async resolveRootObject(e,t){if(e.inputMode==="record"&&e.recordId){let r=e.recordId.substring(0,3),s=(await ge(()=>this.deps.describeGlobal(e.sourceOrgId,t),t)).find(i=>i.keyPrefix===r);if(!s)throw new Error(`No object found for record ID prefix "${r}". The ID may not belong to any accessible object in this org.`);return s.name}if(e.inputMode==="soql"&&e.soqlQuery)return ja(e.soqlQuery);throw new Error(`Cannot resolve root object for inputMode "${e.inputMode}". Provide a valid recordId (for "record" mode) or soqlQuery (for "soql" mode).`)}resolveMaxDepth(e){switch(e.depth){case"direct":return 1;case"full":return Oa;case"custom":return Math.max(1,Math.min(10,e.customDepth??3));case"all":throw new Error("A clone of the whole org is discovered without a walk (WholeOrgDiscovery)")}}};function ja(n){let e=n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--[^\n]*/g,"");for(let r=0;r<32;r++){let o=e.replace(/\([^()]*\)/g,"");if(o===e)break;e=o}let t=/\bFROM\s+(\w+)/i.exec(e);if(!t)throw new Error('Could not parse object name from SOQL query. Ensure the query uses standard "SELECT ... FROM ObjectName" syntax.');return V(t[1])}import{existsSync as Na,readFileSync as Ca,writeFileSync as Pa}from"node:fs";function Ju(n){let e={getData:()=>Na(n)?JSON.parse(Ca(n,"utf8")):{},setData:r=>Pa(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384})},t=new xo(e);return t.initialize(),t}var Rn="User",Ta="005",ms=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Fa(n,e,t=Kr){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 gs=1e5;async function Qu(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,c=new Set;for(let m of i)for(let h of n.rows){let w=h[m.name];if(typeof w!="string"||!ms.test(w)||m.name==="OwnerId"&&t[w]!==void 0||r?.(w)===!0||(c.add(w),e.has(w)))continue;let b=m.referenceTo??[];if(!b.some(O=>o?.has(O)===!0))for(let O of b)a.set(O,(a.get(O)??new Set).add(w))}let l=new Set,p=new Set,u=new Set;for(let[m,h]of a){let w=s!==void 0&&m===Rn,b=w?"Id, IsActive":"Id";for(let O of te([...h]))try{let A=await n.query(`SELECT ${b} FROM ${V(m)} WHERE Id IN (${O})`);for(let g of A){let y=g.Id;typeof y=="string"&&(l.add(y),l.add(y.slice(0,15)),w&&g.IsActive===!1&&(u.add(y),u.add(y.slice(0,15))))}}catch{for(let A of h)p.add(A);o?.add(m);break}}let f=new Map;for(let m of a.values())for(let h of m)l.has(h)||l.has(h.slice(0,15))?f.set(h,!0):!p.has(h)&&!f.has(h)&&f.set(h,!1);for(let[m,h]of f){if(e.size>=gs)break;e.set(m,h)}if(s&&u.size>0){let m=[...a.get(Rn)??[]].filter(h=>u.has(h)||u.has(h.slice(0,15)));for(let h of[...u,...m]){if(s.size>=gs)break;s.add(h)}}let d=new Set;for(let m of c)(f.get(m)??e.get(m))===!1&&d.add(m);return d}function Xu(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 va="SELECT PermissionsUpdateWithInactiveOwner FROM UserPermissionAccess";async function xa(n){try{let[e]=await n(va);return e?.PermissionsUpdateWithInactiveOwner===!0}catch{return!1}}function ef(n){let e;return()=>(e??=xa(n),e)}async function hs(n,e){let t=new Map;for(let[i,a]of Object.entries(n)){if(!ms.test(a))continue;let c=a.slice(0,15),l=t.get(c)??{user:a,sources:[]};l.sources.push(i),t.set(c,l)}let r=[],o=[],s=[...t.values()];for(let i=0;i<s.length;i+=Ue){let a=s.slice(i,i+Ue),[c]=te(a.map(({user:u})=>u)),l;try{l=await e(`SELECT Id, Name, IsActive FROM ${Rn} WHERE Id IN (${c})`)}catch{continue}let p=new Set;for(let u of l){let f=u.Id;if(typeof f!="string"||(p.add(f.slice(0,15)),u.IsActive!==!1))continue;let d=t.get(f.slice(0,15));if(!d)continue;let m=u.Name;r.push({user:d.user,...typeof m=="string"&&m!==""?{name:m}:{},sources:d.sources})}for(let{user:u,sources:f}of a)u.startsWith(Ta)&&!p.has(u.slice(0,15))&&o.push({user:u,sources:f})}return{inactive:r,unknown:o}}var _t=10,Sn="Nothing was read or written.",of="Nothing was written.";function ws(n,e=Sn){let t=n.slice(0,_t).map(({user:o,name:s,sources:i})=>`${s!==void 0?`${s} (${o})`:o}, given the records of `+i.join(", ")).join("; "),r=n.length-_t;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 Ma(n,e=Sn){let t=n.slice(0,_t).map(({user:o,sources:s})=>`${o}, given the records of ${s.join(", ")}`).join("; "),r=n.length-_t;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 sf(n,e,t=Sn){let{inactive:r,unknown:o}=await hs(n,e);if(o.length>0){let s=Ma(o,t);return new wn(os,r.length>0?`${s.slice(0,-t.length)}${ws(r,t)}`:s)}return r.length>0?new wn(rs,ws(r,t)):void 0}import{createHash as _a}from"node:crypto";var Rs={ContentVersion:"VersionData",Attachment:"Body"},Da=3,bs=class extends Error{constructor(t,r,o){super(t);this.code=r;this.storage=o;this.name="ForgeFilesRefusedError"}code;storage};function Q(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function ys(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function On(n,e,t){return{objectApiName:n,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:e,messages:[U(t)]}]}}async function gf(n){let{scope:e,sourceOrgId:t,maxFileBytes:r,queryRecords:o}=n,s=new Map;for(let u of e.values())for(let f of u)s.has(f)||s.set(f,s.size);let i={files:[],leftOut:[],errors:[]},a=[...s.keys()];if(a.length===0)return i;let c=u=>s.get(u)??Number.MAX_SAFE_INTEGER,l=new Map;try{for(let u of te(a)){let f=await o(t,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN (${u})`);for(let d of f){let m=Q(d,"ContentDocumentId"),h=Q(d,"LinkedEntityId");if(!m||!h||!s.has(h))continue;let w=l.get(m)??[];w.some(b=>b.id===h)||w.push({id:h,shareType:Q(d,"ShareType"),visibility:Q(d,"Visibility")}),l.set(m,w)}}}catch(u){i.errors.push(On("ContentDocument","(links of the records in scope)",u))}let p=[];try{for(let u of te([...l.keys()])){let f=await o(t,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SharingPrivacy FROM ContentVersion WHERE ContentDocumentId IN (${u}) AND IsLatest = true`);for(let d of f){let m=Q(d,"ContentDocumentId"),h=Q(d,"Id"),w=m?l.get(m):void 0;if(!m||!h||!w)continue;let b=Q(d,"Title")??m;p.push({external:(Q(d,"ContentLocation")??"S")!=="S",file:{objectApiName:"ContentDocument",sourceId:m,body:{objectApiName:"ContentVersion",id:h},name:b,bytes:ys(d,"ContentSize"),hosts:[...w].sort((O,A)=>c(O.id)-c(A.id)),fields:{Title:b,PathOnClient:Q(d,"PathOnClient")??b,...Q(d,"SharingPrivacy")==="P"?{SharingPrivacy:"P"}:{}}}})}}}catch(u){i.errors.push(On("ContentDocument","(latest versions of the files)",u))}try{for(let u of te(a)){let f=await o(t,`SELECT Id, ParentId, Name, ContentType, BodyLength, IsPrivate FROM Attachment WHERE ParentId IN (${u})`);for(let d of f){let m=Q(d,"Id"),h=Q(d,"ParentId");if(!m||!h||!s.has(h))continue;let w=Q(d,"Name")??m;p.push({external:!1,file:{objectApiName:"Attachment",sourceId:m,body:{objectApiName:"Attachment",id:m},name:w,bytes:ys(d,"BodyLength"),hosts:[{id:h}],fields:{Name:w,...Q(d,"ContentType")?{ContentType:Q(d,"ContentType")}:{},IsPrivate:d.IsPrivate===!0}}})}}}catch(u){i.errors.push(On("Attachment","(attachments of the records in scope)",u))}p.sort((u,f)=>c(u.file.hosts[0].id)-c(f.file.hosts[0].id));for(let{file:u,external:f}of p){let d=f?"external":u.bytes>r?"too-large":void 0;d?i.leftOut.push({objectApiName:u.objectApiName,sourceId:u.sourceId,name:u.name,bytes:u.bytes,reason:d}):i.files.push(u)}return i}function mf(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 hf(n){let{files:e,targetOrgId:t,copiedBefore:r,queryRecords:o}=n,s={files:[],errors:[]},i=new Map;for(let d of e){let m=r(d.sourceId);m&&i.set(d.sourceId,m)}if(i.size===0)return{...s,files:[...e]};let a=new Map,c,l=new Map;for(let[d,m]of i)m.objectApiName==="ContentVersion"&&l.set(m.targetId,d),m.objectApiName==="ContentDocument"&&a.set(d,m.targetId);try{for(let d of te([...l.keys()])){let m=await o(t,`SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN (${d})`);for(let h of m){let w=Q(h,"Id"),b=Q(h,"ContentDocumentId"),O=w?l.get(w):void 0;O&&b&&a.set(O,b)}}}catch(d){c=U(d)}let p=new Map,u;try{for(let d of te([...new Set(a.values())])){let m=await o(t,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${d})`);for(let h of m){let w=Q(h,"ContentDocumentId"),b=Q(h,"LinkedEntityId");w&&b&&p.set(w,[...p.get(w)??[],b])}}}catch(d){u=U(d)}let f=(d,m)=>{s.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`${d.name} (${Ne(d.bytes)})`,messages:[m]}]})};for(let d of e){let m=i.get(d.sourceId);if(!m){s.files.push(d);continue}if(d.body.objectApiName==="Attachment")continue;let h=a.get(d.sourceId);if(!h){f(d,`Copied as ContentVersion ${m.targetId} by the run this one takes up, and its document still cannot be read back`+(c?` (${c})`:"")+": the file is not copied again, nor linked to the records it lacks.");continue}if(u){f(d,`Copied by the run this one takes up; its links could not be read (${u}): it is not linked to the records it lacks.`);continue}s.files.push({...d,into:{documentId:h,linked:p.get(h)??[],unchanged:!0}})}return s}function wf(n){return{objectApiName:"__files__",stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(files)",messages:[n]}]}}function bf(n){return n.reduce((e,t)=>e+t.bytes,0)}function yf(n,e){return n<=e?null:`The files to copy take ${Ne(n)} and the target has ${Ne(Math.max(0,e))} of file storage left. Lower the largest file copied, or leave the files out.`}async function Rf(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 Sf(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 An(n,e){let t=n==="Attachment"?"attachment":"file";return e===1?t:`${t}s`}function Of(n){return`[dry-run] ${n.objectApiName}: ${n.planned} ${An(n.objectApiName,n.planned)} would be copied (${Ne(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:_a("md5").update(Buffer.from(e,"base64")).digest("hex"),ContentSize:n.bytes}}function Ba(n){let e={};for(let[t,r]of Object.entries(n))t!=="SharingPrivacy"&&(e[t]=r);return e}async function Af(n){let{files:e,sourceOrgId:t,targetOrgId:r,remapper:o,deps:s,report:i,errors:a,onProgress:c,onCopied:l}=n,p=0,u=g=>{let y=i.objects.find(S=>S.objectApiName===g);return y||(y={objectApiName:g,planned:0,plannedBytes:0,copied:0,failed:0},i.objects.push(y)),y},f=(g,y)=>a.find(S=>S.objectApiName===g&&S.stage===y),d=new Map,m=(g,y,S=1)=>{let E=`${g}/${y}`;d.set(E,(d.get(E)??0)+S);let T=f(g,y);T&&(T.attemptedCount+=S)},h=(g,y,S,E,T=!1)=>{let x=f(g,y);x||(x={objectApiName:g,stage:y,failedCount:0,attemptedCount:d.get(`${g}/${y}`)??0,samples:[]},a.push(x)),T||(x.failedCount++,p++),x.samples.length<Da&&x.samples.push({recordSummary:S,messages:[E]})},w=(g,y,S)=>{h(g.objectApiName,y,`${g.name} (${Ne(g.bytes)})`,S),u(g.objectApiName).failed++},b=async(g,y,S)=>{let E=S.flatMap(x=>{let N=o.get(x.id);return N?[{ContentDocumentId:y,LinkedEntityId:N,ShareType:x.shareType??"V",Visibility:x.visibility??"AllUsers"}]:[]});if(E.length===0)return[];let T=[];m("ContentDocumentLink","insert",E.length);try{let x=await s.insertRecords(r,"ContentDocumentLink",E);E.forEach((N,C)=>{let F=x[C];if(F?.success){i.links++,T.push(N.LinkedEntityId);return}h("ContentDocumentLink","insert",g.name,F?.errors.join("; ")||"The target gave no reason.")})}catch(x){for(let N=0;N<E.length;N++)h("ContentDocumentLink","insert",g.name,U(x))}return T},O=e.filter(g=>!(g.body.objectApiName==="ContentVersion"&&g.into?.unchanged)).length,A=0;for(let g of e){await n.waitIfPaused();let y=g.hosts.filter(j=>o.isCreated(j.id)),S=g.body.objectApiName==="ContentVersion"?g.into:void 0,E=S?y.filter(j=>{let L=o.get(j.id);return L!==void 0&&!S.linked.includes(L)}):[];if(S?.unchanged){let j=await b(g,S.documentId,E);j.length>0&&l?.(g,{targetId:S.documentId,linked:j,asVersion:!1});continue}let T=A++,x=y.length>0?o.get(y[0].id):void 0;if(!x&&!S){i.leftOut.push({objectApiName:g.objectApiName,sourceId:g.sourceId,name:g.name,bytes:g.bytes,reason:"record-not-created"});continue}c({objectName:g.objectApiName,status:"running",progress:Math.round(T/O*100),message:`Copying ${An(g.objectApiName,1)} ${T+1} of ${O} (${Ne(g.bytes)})`});let N;m(g.objectApiName,"query");try{N=await s.readFileBody(t,g.body.objectApiName,g.body.id)}catch(j){w(g,"query",U(j));continue}let C=Buffer.byteLength(N,"base64");if(C!==g.bytes){w(g,"query",`Read ${C} bytes of the ${g.bytes} the source reports: the file was not written.`);continue}let F=S?{...Ba(g.fields),VersionData:N,ContentDocumentId:S.documentId}:g.body.objectApiName==="ContentVersion"?{...g.fields,VersionData:N,FirstPublishLocationId:x}:{...g.fields,Body:N,ParentId:x},_;m(g.objectApiName,"insert");let D=n.calls?.sending(g.body.objectApiName,[{sourceId:g.sourceId,payload:La(g,N,x)}]),R=()=>{D!==void 0&&n.calls?.answered(D)};try{_=await s.insertFile(r,g.body.objectApiName,F)}catch(j){Co(j)!=="may-have-written"&&R(),w(g,"insert",U(j));continue}if(!_.success||!_.id){R(),w(g,"insert",_.errors.join("; ")||"The target gave no reason.");continue}if(u(g.objectApiName).copied++,g.body.objectApiName==="Attachment"){o.add(g.sourceId,_.id,"Attachment"),R(),o.persist?.(),l?.(g,{targetId:_.id,linked:x?[x]:[],asVersion:!1});continue}if(S){o.add(g.sourceId,S.documentId,"ContentDocument"),R(),o.persist?.();let j=await b(g,S.documentId,E);l?.(g,{targetId:S.documentId,linked:j,asVersion:!0});continue}o.add(g.sourceId,_.id,"ContentVersion"),R(),o.persist?.();let k;try{let j=await s.queryRecords(r,`SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${Ot(_.id)}'`);k=j[0]?Q(j[0],"ContentDocumentId"):void 0}catch{k=void 0}if(!k){h("ContentDocument","query",`${g.name} (${Ne(g.bytes)})`,`Copied as ContentVersion ${_.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(g.sourceId,k,"ContentDocument"),o.persist?.();let I=await b(g,k,y.slice(1));l?.(g,{targetId:k,linked:x?[x,...I]:I,asVersion:!1})}for(let g of i.objects)c({objectName:g.objectApiName,status:g.failed>0&&g.copied===0?"error":"done",progress:100,message:`Copied ${g.copied} ${An(g.objectApiName,g.copied)} of ${g.planned}`+(g.failed>0?`, ${g.failed} failed`:"")});return p}var Ss=new WeakMap;function kf(n,e){typeof n=="object"&&n!==null&&Ss.set(n,e)}function Ef(n){return typeof n=="object"&&n!==null?Ss.get(n):void 0}import{createHash as Ns,randomBytes as Cs}from"node:crypto";import{createReadStream as Wa}from"node:fs";import{chmod as Ga,copyFile as Va,open as Ja,readFile as Ps,readdir as Ts,rename as Bt,rm as $e,stat as Fs}from"node:fs/promises";import{join as me}from"node:path";import{createHash as $a}from"node:crypto";function ce(n){return n.slice(0,15)}function Be(n,e){let t=ce(n),r=ce(e);return t<r?-1:t>r?1:0}var qa=2**21,za=2**53;function Cf(n,e){let t=$a("sha256").update(`${n}:${ce(e)}`).digest(),r=t.readUInt32BE(0),o=t.readUInt32BE(4)>>>11;return(r*qa+o)/za}function Pf(n,e){return n/Math.max(e,n+1)}var Ua=1024;function As(n,e){let t=Math.floor(Math.max(0,n)/Ua);return Math.max(1,Math.min(t,e??1/0))}function Dt(n,e){return n.rank!==e.rank?n.rank<e.rank?-1:1:n.objectApiName!==e.objectApiName?n.objectApiName<e.objectApiName?-1:1:Be(n.id,e.id)}var Lt=class{items=[];get size(){return this.items.length}peek(){return this.items[0]}push(e){let t=this.items;t.push(e);let r=t.length-1;for(;r>0;){let o=r-1>>1;if(Dt(t[r],t[o])<=0)break;[t[r],t[o]]=[t[o],t[r]],r=o}}pop(){let e=this.items,t=e[0],r=e.pop();if(e.length===0||r===void 0)return t;e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Dt(e[s],e[a])>0&&(a=s),i<e.length&&Dt(e[i],e[a])>0&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}return t}values(){return this.items}};function Le(n){return`${n.objectApiName}
|
|
12
|
-
${ce(n.id)}`}var Os=class{constructor(e,t){this.most=e;this.floor=t}most;floor;kept=new Lt;floors=new Map;inKept=new Set;inFloor=new Set;letGo=1/0;offer(e,t,r){let o={objectApiName:e,id:t,rank:r},s=[];if(this.floor>0){let i=this.floors.get(e);if(i||(i=new Lt,this.floors.set(e,i)),i.push(o),this.inFloor.add(Le(o)),i.size>this.floor){let a=i.pop();a&&(this.inFloor.delete(Le(a)),s.push(a))}}if(this.most>0){if(this.kept.push(o),this.inKept.add(Le(o)),this.kept.size>this.most){let i=this.kept.pop();i&&(this.inKept.delete(Le(i)),s.push(i))}}else s.push(o);for(let i of s){let a=Le(i);!this.inKept.has(a)&&!this.inFloor.has(a)&&(this.letGo=Math.min(this.letGo,i.rank))}}keeps(e,t){if(this.floor>0&&(this.floors.get(e)?.size??0)<this.floor||this.kept.size<this.most)return!0;let r=this.kept.peek();return r!==void 0&&t<r.rank}get beyond(){return this.letGo}drawn(){let e=new Map;for(let t of this.kept.values())e.set(Le(t),t);for(let t of this.floors.values())for(let r of t.values())e.set(Le(r),{...r,rank:0});return[...e.values()].sort(Dt)}};var vs=1440*6e4,Ha="forge-samples",xs="forge-runs",In="sample.json",Is="the run of this sample",Ka=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ms=/^[A-Za-z0-9_-]{1,128}$/,ue=class extends Error{constructor(t,r){super(r);this.refusal=t;this.name="SamplePlanError"}refusal};function En(n){return me(n,Ha)}function Ya(n,e){if(!Ms.test(e))throw new ue("otherSetup","Not the fingerprint of a setup of a run.");return me(En(n),e)}function ut(n,e){return me(n,xs,`${e.replace(/[^A-Za-z0-9_-]/g,"_")}.sample`)}var re=z().regex(/^[A-Za-z][A-Za-z0-9_]*$/),X=J().int().nonnegative(),Za=q({seed:J().int().min(0),draw:Rr,floor:X,parents:Sr,children:wr([Me("all"),J().int().min(1)]),share:J().min(0).max(1),budget:q({bytes:J().nonnegative(),remainingMB:J().optional(),maxMB:J().optional(),share:J().optional(),roundingMB:J().optional(),automationMB:J().optional(),withinMB:J().optional(),maxTotal:J().optional(),limitedBy:xe(["storage","within","maxTotal","targetRequests","bulkBatches","sourceRequests","heavyRoots","whole"])}),rows:X,storageBytes:J().nonnegative(),objects:H(q({objectApiName:re,sourceRows:X,kept:X,roots:X,below:X,asParents:X,whole:Me(!0).optional(),childrenCut:H(q({field:z(),rows:X})).optional()})),whole:H(q({objectApiName:re,why:xe(["referenceData","catalog","smallParent","asked"])})),heavyRoots:H(q({objectApiName:re,id:z().regex(Ka),rows:X,relation:q({objectApiName:re,field:z()})})),dropped:H(q({objectApiName:re,rows:X,reason:xe(["noParentInSource","outsideFilter","excludedObject","withoutParent","heldBack","recordTypeNotInTarget"])})),leftEmpty:H(q({objectApiName:re,field:z(),rows:X})),noRecordDrawn:H(q({objectApiName:re,sourceRows:X})),partialMasters:H(q({objectApiName:re,details:re,field:z(),kept:X.optional(),sourceRows:X.optional(),asParents:X.optional()})).optional(),planRequests:q({source:X}),newestByIds:H(re).optional()}),Qa=q({personAccounts:Xe(re,X),byThePlatform:H(q({objectApiName:re,inPlan:X,beyond:X}))}),kn=q({version:Me(1),sourceOrgId:z().min(1),fingerprint:z().regex(Ms),drawnAt:yr.datetime(),drawnBy:xe(["run","dryRun"]),sha256:z().regex(/^[0-9a-f]{64}$/),objects:H(q({objectApiName:re,count:J().int().positive(),sha256:z().regex(/^[0-9a-f]{64}$/)})),sample:Za,newestByIds:H(re).optional(),counts:Qa.optional()});async function ks(n){let e=Ns("sha256");for await(let t of Wa(n))e.update(t);return e.digest("hex")}function Es(n){let e=Ns("sha256"),t=[...n].sort((r,o)=>r.objectApiName<o.objectApiName?-1:r.objectApiName>o.objectApiName?1:0);for(let{objectApiName:r,count:o,sha256:s}of t)e.update(`${r} ${o} ${s}
|
|
13
|
-
`);return e.digest("hex")}async function Xa(n,e){let t=await Ja(n,"wx",rt);try{await t.writeFile(e,"utf8"),await t.sync()}finally{await t.close()}}function jn(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}var Ge=class n{constructor(e,t,r){this.dir=e;this.manifest=t;this.spool=r}dir;manifest;spool;get sha256(){return this.manifest.sha256}get count(){return this.spool.count}countOf(e){return this.manifest.objects.find(t=>t.objectApiName===e)?.count??0}ageMs(e){return e.getTime()-Date.parse(this.manifest.drawnAt)}get place(){return{path:this.dir,sha256:this.manifest.sha256,drawnAt:this.manifest.drawnAt,drawnBy:this.manifest.drawnBy}}async*ids(e,t={}){let r=Math.max(1,Math.floor(t.size??2e3)),o=t.after,s=[];for await(let i of this.spool.pages(e,r))for(let a of i)o!==void 0&&Be(a,o)<=0||(s.push(a),s.length>=r&&(yield s,s=[]));s.length>0&&(yield s)}static async open(e,t={}){let r;try{r=JSON.parse(await Ps(me(e,In),"utf8"))}catch(a){throw jn(a)?new ue("gone","The plan of this sample is no longer on this machine."):new ue("changed","The plan of this sample does not read as one.")}let o=kn.safeParse(r);if(!o.success)throw new ue("changed","The plan of this sample does not read as one.");let s=o.data,i;try{i=await Ho.open(e,Is)}catch{throw new ue("changed","The ids of this sample are not as they were written.")}if(await n.holdToManifest(e,s,i),t.sourceOrgId!==void 0&&t.sourceOrgId!==s.sourceOrgId)throw new ue("otherOrg","This plan was drawn of another org.");if(t.fingerprint!==void 0&&t.fingerprint!==s.fingerprint)throw new ue("otherSetup","This plan was drawn for another setup of the run.");if(t.sha256!==void 0&&t.sha256!==s.sha256)throw new ue("otherSha","This is not the plan the run was drawn with.");return new n(e,s,i)}static async holdToManifest(e,t,r){let o=()=>new ue("changed","The ids of this sample are not as they were written."),s=r.objects.filter(i=>i.count>0);if(s.length!==t.objects.length)throw o();for(let i of t.objects){let a=s.find(l=>l.objectApiName===i.objectApiName);if(!a||a.count!==i.count)throw o();let c;try{c=await ks(ot(e,i.objectApiName))}catch{throw o()}if(c!==i.sha256)throw o()}if(Es(t.objects)!==t.sha256)throw o()}static async keep(e,t){let r=`${e}.${process.pid}-${Cs(4).toString("hex")}.tmp`;try{await _e(r);let o=new Jo(r,Is);for(let{objectApiName:c,ids:l}of t.ids){let p=[...l].sort(Be);for(let u of p)await o.add(c,u)}let s=await o.finish(),i=[];for(let{objectApiName:c,count:l}of s.objects)l!==0&&i.push({objectApiName:c,count:l,sha256:await ks(ot(r,c))});let a={version:1,sourceOrgId:t.sourceOrgId,fingerprint:t.fingerprint,drawnAt:t.drawnAt.toISOString(),drawnBy:t.drawnBy,sha256:Es(i),objects:i,sample:t.sample,...t.newestByIds!==void 0&&t.newestByIds.length>0?{newestByIds:[...t.newestByIds]}:{},...t.counts?{counts:t.counts}:{}};kn.parse(a),await Xa(me(r,In),`${JSON.stringify(a)}
|
|
14
|
-
`),await $e(e,{recursive:!0,force:!0}),await Bt(r,e)}catch(o){throw await $e(r,{recursive:!0,force:!0}),o}return n.open(e)}};function $f(n,e){return Ge.keep(n,e)}async function qf(n,e,t){let r;try{r=await Ge.open(Ya(n,e),{fingerprint:e})}catch(o){if(o instanceof ue)return;throw o}return r.ageMs(t)>=vs?"tooOld":r}async function zf(n,e,t){let r=ut(e,t);return await _e(me(e,xs)),await $e(r,{recursive:!0,force:!0}),await Bt(n.dir,r),Ge.open(r,{sha256:n.sha256})}async function Uf(n,e,t){let r=ut(n,e);return!await js(r)||await js(t)?!1:(await _e(En(n)),await Bt(r,t),!0)}async function Wf(n,e,t){let r=ut(e,t),o=`${r}.${process.pid}-${Cs(4).toString("hex")}.tmp`;try{await _e(o);for(let s of await Ts(n.dir))await Va(me(n.dir,s),me(o,s)),await Ga(me(o,s),rt);await $e(r,{recursive:!0,force:!0}),await Bt(o,r)}catch(s){throw await $e(o,{recursive:!0,force:!0}),s}return Ge.open(r,{sha256:n.sha256})}async function js(n){try{return await Fs(n),!0}catch(e){if(jn(e))return!1;throw e}}async function Gf(n){await $e(n,{recursive:!0,force:!0})}async function Vf(n,e){let t=En(n),r;try{r=await Ts(t)}catch(s){if(jn(s))return 0;throw s}let o=0;for(let s of r){let i=me(t,s),a;try{let c=kn.parse(JSON.parse(await Ps(me(i,In),"utf8")));a=Date.parse(c.drawnAt)}catch{a=(await Fs(i)).mtimeMs}e.getTime()-a<vs||(await $e(i,{recursive:!0,force:!0}),o++)}return o}var Nn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,_s=/^[A-Za-z][A-Za-z0-9_]*$/;function ft(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"||!Nn.test(r))&&!(typeof o!="string"||!Nn.test(o)))return{tag:t,sourceId:r,targetId:o,object:typeof s=="string"&&_s.test(s)?s:""}}function Ve(n){if(!n.startsWith(`["${Ft}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[,t,r]=e;if(!(typeof t!="string"||!_s.test(t)||!Array.isArray(r)))return{object:t,ids:r.filter(o=>typeof o=="string"&&Nn.test(o))}}function pt(n){return n.slice(0,15)}var gt=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]}},Ie=class{capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);taken=new Uint8Array(this.capacity);add(e){let t=de(e),r=le(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(de(e),le(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}}},ec=2e3,mt=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=(p,u)=>ft(e.read(p,u).toString("utf8"))?.sourceId??"",o=new vt(r),s=new vt(r),i=new gt,a=new gt,c=!1,l=-1;for(let p of Oe(e)){if(!c){if(!p.text.startsWith('{"run":'))return;c=!0;continue}if(p.text.startsWith('{"part":')){l++;continue}if(p.text.startsWith('{"object":'))return;if(l===t&&Ve(p.text)){a.push(p.offset,p.length);continue}let u=ft(p.text);if(!u)continue;let f=de(u.sourceId),d=le(u.sourceId);if(o.put(o.find(u.sourceId,f,d),f,d,p.offset,p.length,0),l!==t)continue;let m=s.find(u.sourceId,f,d);m<0&&i.push(p.offset,p.length);let h=u.tag==="c"&&u.object!=="";s.put(m,f,d,p.offset,p.length,h?1:0)}return c?new n(e,o,s,i,a):void 0}mappingAt(e,t){return ft(this.file.read(e,t).toString("utf8"))}wordsOn(e){let t=de(e),r=le(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 gt;i.push(o.latest.offset,o.latest.length),e.set(s.object,i)}return e}runRecords(e,t=ec){let{file:r}=this,o=(h,w)=>ft(r.read(h,w).toString("utf8")),s=(h,w)=>{let b=o(h,w);return b?pt(b.targetId):""},i=new vt(s),a=this.createdByObject(),c=[];for(let h of[...a.keys()].reverse()){let w=a.get(h);if(!w)continue;let b=0;for(let O=w.size-1;O>=0;O--){let A=w.offsetAt(O),g=o(A,w.lengthAt(O));if(!g||g.object==="")continue;let y=pt(g.targetId),S=de(y),E=le(y),T=i.find(y,S,E);T>=0||(i.put(T,S,E,A,w.lengthAt(O),0),(!e||e.has(y))&&b++)}b>0&&c.push({objectApiName:h,count:b})}let l=(h,w)=>{let b=i.find(h,de(h),le(h),w);return b>=0&&(w===void 0||i.offsetOf(b)===w)&&(!e||e.has(h))},p=h=>Ve(r.read(this.unattributed.offsetAt(h),this.unattributed.lengthAt(h)).toString("utf8")),u=new Ie,f=this.unattributed.size,d=new Map;for(let h=0;h<f;h++){let w=p(h);if(w)for(let b of w.ids){let O=pt(b);u.has(O)||i.find(O,de(O),le(O))>=0||(u.add(O),(!e||e.has(O))&&d.set(w.object,(d.get(w.object)??0)+1))}}for(let[h,w]of d){let b=c.find(O=>O.objectApiName===h);b?b.count+=w:c.unshift({objectApiName:h,count:w})}let m=h=>u.size>0&&u.has(h)&&(!e||e.has(h));return{objects:c,pages:async function*(h){let w=a.get(h),b=[];if(w)for(let O=w.size-1;O>=0;O--){let A=w.offsetAt(O),g=o(A,w.lengthAt(O));if(!g||g.object==="")continue;let y=pt(g.targetId);l(y,A)&&(b.push(g.targetId),b.length>=t&&(yield b,b=[]))}if(d.has(h)){let O=new Ie;for(let A=0;A<f;A++){let g=p(A);if(g?.object===h)for(let y of g.ids){let S=pt(y);O.has(S)||!m(S)||i.find(S,de(S),le(S))>=0||(O.add(S),b.push(y),b.length>=t&&(yield b,b=[]))}}}b.length>0&&(yield b)},has:h=>l(h)||m(h)}}*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 Oe(this.file)){let o=ft(r.text);if(!o)continue;let s=this.all.find(o.sourceId,de(o.sourceId),le(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 Te=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ht=/^[A-Za-z][A-Za-z0-9_]*$/,tc=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,nc=255,rc=40,oc=2*6e4,sc=10*6e4;function op(n){let[e]=n;return e?Object.keys(e).filter(t=>t!=="Id"&&ht.test(t)).filter(t=>n.every(r=>ic(r[t]))).sort().slice(0,rc):[]}function ic(n){return typeof n=="string"?n.trim()!==""&&n.length<=nc:typeof n=="number"?Number.isFinite(n):typeof n=="boolean"}function ac(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(Te.test(e))return e.slice(0,15);if(tc.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 Pn(n,e){return Tn(e.map(t=>`${t}${ac(n[t])}`).join(""))}function Tn(n){return de(n).toString(36).padStart(7,"0")+le(n).toString(36).padStart(7,"0")}function sp(n){let e=yo("insert",n);return e.rows.map(t=>Tn(gn(e.columns.map((r,o)=>[r,t[o]??""]))))}var cc=/^sf__/;function Ds(n){let e=[];for(let[t,r]of Object.entries(n))cc.test(t)||e.push([t,typeof r=="string"?r:r==null?"":String(r)]);return Tn(gn(e))}function Bs(n,e){return Pn(n,[e])}function dc(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"||!ht.test(o)||typeof s!="string"||!Te.test(s))return!1;e[r].owes.push({field:o,sourceRefId:s,...i===1?{insertOnly:!0}:{}})}return!0}function Cn(n){if(!n.startsWith(`["${Tt}"`))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,c]=e;if(typeof t!="string"||typeof r!="string"||!ht.test(r)||typeof o!="string")return;let l=Date.parse(o);if(!Number.isFinite(l)||!Array.isArray(s)||!Array.isArray(i)||!s.every(f=>typeof f=="string"&&ht.test(f))||c!==void 0&&(typeof c!="string"||!ht.test(c)))return;let p=[];for(let f of i){if(!Array.isArray(f)||f.length<2)return;let[d,m,h,w]=f;if(typeof d!="string"||!Te.test(d)||typeof m!="string"||h!==void 0&&typeof h!="string"||w!==void 0&&typeof w!="string")return;p.push({sourceId:d,fingerprint:m,owes:[],...typeof h=="string"&&h!==""?{externalKey:h}:{},...typeof w=="string"&&w!==""?{jobKey:w}:{}})}let u=a!==void 0;if(!(u&&!dc(a,p)))return{callId:t,objectApiName:r,at:l,fields:s,rows:p,owesKept:u,...typeof c=="string"?{upsertField:c}:{}}}function $s(n){if(n.startsWith(`["${De}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function lc(n){if(n.startsWith(`["${Lo}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function uc(n){if(n.startsWith(`["${Do}"`))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 fc(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"||!Te.test(t)||!Te.test(r)?void 0:{sourceId:t,targetId:r,object:typeof o=="string"?o:""}}catch{return}}function pc(n){let e=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(n);return e?Date.parse(e[1]):Number.NaN}function ip(n){return{queryPages:e=>co({query:async t=>n.query(t),queryMore:async t=>n.queryMore(t)},e),userId:async()=>(await n.identity()).user_id,serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp,readJob:e=>Ro(So(n),e)}}function gc(){return{calls:0,found:[],notFound:[],uncertain:[],unread:[]}}function Z(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 Ls(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Fn(n,e,t){return[JSON.stringify(["c",e.sourceId,t,n.objectApiName,n.owesKept?qo:$o]),...e.owes.map(({field:r,sourceRefId:o,insertOnly:s})=>Wo({objectApiName:n.objectApiName,newId:t,sourceId:e.sourceId,fieldName:r,sourceRefId:o,...s?{insertOnly:s}:{}}))]}function mc(n,e,t,r){let{call:o,rows:s,read:i}=n,{objectApiName:a}=o,c=JSON.stringify([De,o.callId]);if(i.state==="never-closed")return Z(r.notFound,a,s.length),{lines:[c],taken:[]};if(i.state==="running")return Z(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}),Z(r.uncertain,a,s.length),{lines:[],taken:[]};let l=o.upsertField===void 0&&s.every(u=>u.jobKey!==void 0)?hc(o,s,i.results,e,t,r):wc(o,s,i.results,e,t,r),p=Date.parse(i.info.systemModstamp??"");return!n.endKept&&l.taken.length>0&&Number.isFinite(p)&&l.lines.unshift(zo(o.callId,n.jobId,new Date(p).toISOString(),new Date(p-n.ahead).toISOString())),l}function hc(n,e,t,r,o,s){let{objectApiName:i}=n,a=new Map,c=new Set;for(let A of t.successfulResults??[]){let g=A.sf__Id,y=Ds(A);if(typeof g!="string"||!Te.test(g)){c.add(y);continue}let S=g.slice(0,15);r.has(S)&&!o.has(S)||a.set(y,[...a.get(y)??[],g])}let l=new Set,p=t.unprocessedRecords;for(let A of[...t.failedResults??[],...Array.isArray(p)?p:[]])l.add(Ds(A));let u=new Map;for(let A of e){let g=A.jobKey??"";u.set(g,[...u.get(g)??[],A])}let f=[],d=[],m=[],h=0,w=!1,b=0;for(let[A,g]of u){let y=a.get(A)??[];a.delete(A);let S=c.delete(A);if(g.length===1&&y.length===1&&!S){f.push(...Fn(n,g[0],y[0])),d.push(y[0]),Z(s.found,i);continue}if(y.length>0||S){Z(s.uncertain,i,g.length),g.length>1&&Z(s.untold??=[],i,g.length),S||(b+=g.length),m.push(...y),w=!0;continue}if(g.length>1||l.has(A)){Z(s.notFound,i,g.length);continue}h+=g.length}let O=c.size>0;for(let A of a.values())m.push(...A),A.length>0&&(O=!0);return h>0&&(Z(O?s.uncertain:s.notFound,i,h),O&&(w=!0,c.size===0&&(b+=h))),b>0&&Z(s.ofEndedJobs??=[],i,b),f.push(...qs(n,m,o,w,s)),{lines:f,taken:[...d,...m]}}function qs(n,e,t,r,o){e.length>0&&Z(o.unattributed??=[],n.objectApiName,e.length);let s=e.filter(i=>!t.has(i.slice(0,15)));return[...s.length>0?[JSON.stringify([Ft,n.objectApiName,s])]:[],...r?[]:[JSON.stringify([De,n.callId])]]}function wc(n,e,t,r,o,s){let{objectApiName:i}=n,a=n.upsertField,c=new Map;for(let w of t.successfulResults??[]){let b=w.sf__Id;if(typeof b!="string"||!Te.test(b))continue;let O=b.slice(0,15);if(r.has(O)&&!o.has(O)||a!==void 0&&String(w.sf__Created).toLowerCase()!=="true")continue;let A=a!==void 0?Bs(w,a):Pn(w,n.fields);c.set(A,[...c.get(A)??[],b])}let l=new Map;for(let w of e){let b=a!==void 0?w.externalKey??"":w.fingerprint;l.set(b,[...l.get(b)??[],w])}let p=[],u=[],f=[],d=0,m=!1;for(let[w,b]of l){let O=w===""?[]:c.get(w)??[];if(c.delete(w),O.length===0){d+=b.length;continue}if(b.length===1&&O.length===1){p.push(...Fn(n,b[0],O[0])),u.push(O[0]),Z(s.found,i);continue}Z(s.uncertain,i,b.length),Z(s.ofEndedJobs??=[],i,b.length),b.length>1&&Z(s.untold??=[],i,b.length),f.push(...O),m=!0}let h=!1;for(let w of c.values())f.push(...w),w.length>0&&(h=!0);return d>0&&(Z(h?s.uncertain:s.notFound,i,d),h&&(m=!0,Z(s.ofEndedJobs??=[],i,d))),p.push(...qs(n,f,o,m,s)),{lines:p,taken:[...u,...f]}}function zs(n){let e=new Set;for(let t of Oe(n)){let r=$s(t.text);if(r!==void 0)e.delete(r);else{let o=t.text.startsWith(`["${Tt}"`)?Cn(t.text):void 0;o&&e.add(o.callId)}}return e.size}async function Us(n,e,t=()=>new Date){let r=gc(),o=new Map,s=new Map,i=new Set,a=Number.NEGATIVE_INFINITY;for(let g of Oe(n)){let y=$s(g.text);if(y!==void 0){o.delete(y);continue}let S=uc(g.text);if(S){s.set(S.callId,S.jobId);continue}let E=lc(g.text);if(E!==void 0){i.add(E);continue}if(g.text.startsWith(`["${Tt}"`)){let T=Cn(g.text);T&&(o.set(T.callId,{offset:g.offset,length:g.length}),a=Math.max(a,T.at));continue}if(g.text.startsWith("{")){let T=pc(g.text);Number.isFinite(T)&&(a=Math.max(a,T))}}if(o.size===0)return r;let c=[];for(let{offset:g,length:y}of o.values()){let S=Cn(n.read(g,y).toString("utf8"));S&&c.push(S)}r.calls=c.length;let l=new Set(c.map(g=>g.objectApiName)),p=new Set(c.flatMap(g=>g.rows.map(y=>y.sourceId)));r.lookedFor=p;let u=new Set,f=new Ie,d=new Ie;for(let g of Oe(n)){let y=Ve(g.text);if(y){if(l.has(y.object))for(let E of y.ids)f.add(E.slice(0,15)),d.add(E.slice(0,15));continue}let S=fc(g.text);S&&(p.has(S.sourceId)&&u.add(S.sourceId),(S.object===""||l.has(S.object))&&f.add(S.targetId.slice(0,15)))}let m=0;if(e.serverTime)try{let g=t().getTime(),y=Date.parse(await e.serverTime());Number.isFinite(y)&&(m=y-(g+t().getTime())/2)}catch{}let h,w,b=[],O=e.readJob?.bind(e),A=new Set;if(O)for(let g of c){let y=s.get(g.callId);if(y===void 0)continue;A.add(g.callId);let S=g.rows.filter(T=>!u.has(T.sourceId));if(S.length===0){b.push(JSON.stringify([De,g.callId]));continue}let E=mc({call:g,rows:S,jobId:y,read:await O(y),ahead:m,endKept:i.has(g.callId)},f,d,r);b.push(...E.lines);for(let T of E.taken)f.add(T.slice(0,15))}for(let g of l){let y=c.filter(I=>I.objectApiName===g&&!A.has(I.callId));if(y.length===0)continue;let S=y.map(I=>({call:I,rows:I.rows.filter(j=>!u.has(j.sourceId))})),E=S.reduce((I,{rows:j})=>I+j.length,0);if(E===0){for(let{call:I}of S)b.push(JSON.stringify([De,I.callId]));continue}let T=new Map;for(let I of y)T.set(I.fields.join(","),I.fields);let x=[...new Set(y.flatMap(I=>I.upsertField?[I.upsertField]:[]))],N=[...new Set([...y.flatMap(I=>I.fields),...x])].sort(),C;try{if(h===void 0&&w===void 0)try{h=await e.userId()}catch(v){w=U(v)}if(h===void 0)throw new Error(`the user the run writes as is not known: ${w}`);let I=Math.min(...y.map(v=>v.at))+m-oc,j=a+m+sc,L=N.includes("CreatedDate")?"SystemModstamp":"CreatedDate",B=N.includes("CreatedById")?"":`CreatedById = '${h}' AND `,P=`SELECT ${["Id",...N.filter(v=>v!=="Id")].join(", ")} FROM ${V(g)} WHERE ${B}${L} >= ${Ls(I)} AND ${L} <= ${Ls(j)} ORDER BY Id`;C=[];for await(let v of e.queryPages(P))for(let M of v){let $=M.Id;if(typeof $!="string"||!Te.test($)||f.has($.slice(0,15)))continue;let G=new Map;for(let[se,K]of T)G.set(se,Pn(M,K));let ee=new Map;for(let se of x)ee.set(se,Bs(M,se));C.push({id:$,fingerprints:G,externalKeys:ee,taken:!1})}}catch(I){r.unread.push({objectApiName:g,reason:U(I)}),Z(r.uncertain,g,E);continue}C.sort((I,j)=>I.id<j.id?-1:I.id>j.id?1:0);let F=new Map;for(let I of T.keys()){let j=new Map;for(let L of C){let B=L.fingerprints.get(I)??"",P=j.get(B)??[];P.push(L),j.set(B,P)}F.set(I,j)}let _=(I,j,L)=>{L.taken=!0,b.push(...Fn(I,j,L.id)),Z(r.found,g)},D=new Set;for(let{call:I,rows:j}of S){let L=I.upsertField;if(L===void 0)continue;let B=new Map;for(let v of C){let M=v.externalKeys.get(L);v.taken||M===void 0||B.set(M,[...B.get(M)??[],v])}let P=new Map;for(let v of j){let M=v.externalKey??"";P.set(M,[...P.get(M)??[],v])}for(let[v,M]of P){let $=v===""?[]:B.get(v)??[];if(v===""||M.length>1||$.length>1){Z(r.uncertain,g,M.length),D.add(I.callId);continue}$.length===1?_(I,M[0],$[0]):Z(r.notFound,g)}}let R=[];for(let{call:I,rows:j}of S){if(I.upsertField!==void 0)continue;let L=I.fields.join(","),B=new Map;for(let P of j){let v=B.get(P.fingerprint)??[];v.push(P),B.set(P.fingerprint,v)}for(let[P,v]of B){let M=(F.get(L)?.get(P)??[]).filter($=>!$.taken);if(M.length>v.length){for(let $ of v)R.push({callId:I.callId,sourceId:$.sourceId});D.add(I.callId);continue}M.forEach(($,G)=>_(I,v[G],$));for(let $ of v.slice(M.length))R.push({callId:I.callId,sourceId:$.sourceId})}}let k=C.some(I=>!I.taken);for(let I of R)k||D.has(I.callId)?(Z(r.uncertain,g),D.add(I.callId)):Z(r.notFound,g);for(let{call:I}of S)D.has(I.callId)||b.push(JSON.stringify([De,I.callId]))}return b.length>0&&n.append(`${b.join(`
|
|
15
|
-
`)}
|
|
16
|
-
`),r}function ap(n,e,t="resume"){if(n.calls===0)return[];let r=s=>s.map(({objectApiName:i,rows:a})=>`${a} ${i}`).join(", "),o=[`${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}`];n.found.length>0&&o.push(t==="resume"?` found in ${e}, kept as written by the run and not written again: ${r(n.found)}`:` found in ${e}, kept as written by the run and removed with its records: ${r(n.found)}`),n.notFound.length>0&&o.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&&o.push(` may already be in ${e}: ${r(n.uncertain)}`);for(let s of n.underway??[])o.push(` ${yc(s,t)}`);for(let{objectApiName:s,rows:i}of n.untold??[])o.push(` ${s}: ${i} 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&&o.push(` written by a Bulk API job and matched to no row, kept as written by the run${t==="resume"?"":" and removed with its records"}: `+r(n.unattributed??[]));for(let{objectApiName:s,reason:i}of n.unread)o.push(` ${s} could not be read in ${e}: ${i}`);return o}function bc(n){return Math.max(1,Math.ceil(n/6e4))}function yc(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?`, in about ${bc(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 Rc(n){return n.uncertain.reduce((e,{rows:t})=>e+t,0)}function cp(n){let e=(n.ofEndedJobs??[]).reduce((t,{rows:r})=>t+r,0);return Math.max(0,Rc(n)-e)}import{createReadStream as Sc}from"node:fs";import{appendFile as Oc,mkdir as Ac,readdir as Ic,rename as kc,rm as Ws}from"node:fs/promises";import*as fe from"node:path";import{createInterface as Ec}from"node:readline";var jc=10*6e4;function yp(n){return new _n({storagePath:n,appendFile:(e,t)=>Oc(e,t,"utf8"),readLines:e=>Nc(e),mkdir:async e=>{await Ac(e,{recursive:!0})},rm:e=>Ws(e,{force:!0}),rename:(e,t)=>kc(e,t),listFiles:e=>Ic(e).catch(t=>{if(t.code==="ENOENT")return[];throw t}),openRunFile:e=>_o(e),rmDir:e=>Ws(e,{recursive:!0,force:!0})})}async function*Nc(n){let e=Sc(n,{encoding:"utf8"}),t=Ec({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 Rp=5e4,Sp=2e3,ne=z().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),Ut=z().regex(/^[A-Za-z][A-Za-z0-9_]*$/),Cc=q({sourceOrgId:z().min(1).max(128),fingerprint:z().regex(/^[a-f0-9]{64}$/),targetSalesforceOrgId:ne.optional(),recordId:ne.optional(),muteAutomation:Me(!0).optional(),files:Er.optional()}),Pc=q({graph:Ir,config:Or,anonymizationRules:kr.optional()});function Gs(n){let e=Cc.safeParse(n);if(!e.success)return;let t=Pc.safeParse(n.startedWith);return{...e.data,...t.success?{startedWith:t.data}:{}}}var $t=q({run:q({journalId:z().min(1).max(200),targetOrgId:z().min(1).max(128),startedAt:z().min(1).max(40),resume:Re().optional(),runUserId:Re().optional()})}),Vs=q({objectApiName:z().regex(/^[A-Za-z][A-Za-z0-9_]*$/),reason:z().max(2e3),...jr}),Js=q({checkpoint:q({state:Me("taken"),checkpointId:z().min(1).max(200),name:z().max(500),takenAt:z().min(1).max(40),expiresAt:z().min(1).max(40).nullable(),objects:H(z().regex(/^[A-Za-z][A-Za-z0-9_]*$/)),records:J().nonnegative(),bytes:J().nonnegative(),requests:J().nonnegative(),added:H(Vs),notHeld:H(Vs)})}),Tc=q({part:q({n:J().int().nonnegative(),startedAt:z().max(40).optional()})}),vn=q({end:q({status:xe(["success","cancelled","failure","interrupted"]),forgeId:z().min(1).max(200),at:z().max(40).optional()})}),Fc=q({object:Ut,created:H(br([ne,ne]))});function xn(n){return ne.safeParse(n).success?n:void 0}function Je(n){return n.replace(/\.ndjson$/,"")+".end.json"}function qt(n){return n.replace(/\.ndjson$/,"")+".checkpoint.json"}function zt(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.left`}function Hs(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.stamps`}var vc=z().max(40).refine(n=>Number.isFinite(Date.parse(n)),"not a date"),He=1e4;function xc(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(l=>!r.has(l.slice(0,15)));for(let l of a)r.add(l.slice(0,15));if(a.length===0)continue;let c=t.find(l=>l.objectApiName===s);c?c.ids.push(...a):o.push({objectApiName:s,ids:a})}return[...o,...t]}function Mn(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}var _n=class{constructor(e){this.deps=e;this.dir=fe.join(e.storagePath,"forge-runs")}deps;dir;get storagePath(){return this.deps.storagePath}pathOf(e){return fe.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)}
|
|
17
|
-
`)}async keepCheckpoint(e,t){let r=Js.safeParse({checkpoint:t});if(!r.success)return;let o=qt(this.filePath(e));await this.deps.rm(o),await this.deps.appendFile(o,`${JSON.stringify(r.data)}
|
|
18
|
-
`)}async checkpointAt(e){for await(let t of this.deps.readLines(qt(e)))if(t.trim()!=="")try{let r=Js.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 Go.open(this.deps.openRunFile(e))}reconcile(e,t){return this.reconcileAt(this.filePath(e),t)}async reconcileAt(e,t){let r=this.deps.openRunFile(e);try{return await Us(r,t)}finally{r.close()}}writeBoundsAt(e,t){let r=this.deps.openRunFile(e);try{let o,s,i,a,c=-1,l,p,u=Number.NEGATIVE_INFINITY,f=Number.NEGATIVE_INFINITY,d=Number.NEGATIVE_INFINITY,m=new Map;for(let w of Oe(r)){let b=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(w.text)?.[1],O=w.text.startsWith('["x"')?/^\["x","[^"]*","[^"]*","([^"]+)"/.exec(w.text)?.[1]:void 0,A=Uo(w.text);for(let x of[b,O,A?.at]){let N=x===void 0?Number.NaN:Date.parse(x);Number.isFinite(N)&&(u=Math.max(u,N))}if(A){let x=Date.parse(A.orgAt);Number.isFinite(x)&&(f=Math.max(f,x),c===t&&(d=Math.max(d,x)));continue}if(w.text.startsWith('{"part":')&&c++,!w.text.startsWith('["c"')&&!w.text.startsWith('["p"')&&!w.text.startsWith('["g"'))continue;let g;try{g=JSON.parse(w.text)}catch{continue}if(!Array.isArray(g))continue;let[y,S,E,T]=g;if(y==="c"){if(!ne.safeParse(E).success||!Ut.safeParse(T).success)continue;let x={objectApiName:String(T),id:String(E)};o??=x,s=x,c===t&&(i??=x,a=x),m.set(String(E).slice(0,3),String(T))}else if(y==="g"){if(!ne.safeParse(E).success||!Ut.safeParse(S).success)continue;l={objectApiName:String(S),id:String(E)},p=void 0}else ne.safeParse(S).success&&(p=String(S))}let h=p?m.get(p.slice(0,3)):void 0;return p&&h&&(l={objectApiName:h,id:p}),{...o?{first:o}:{},...s?{lastCreated:s}:{},...i?{firstInPart:i}:{},...a?{lastCreatedInPart:a}:{},...l?{lastUpdated:l}:{},...Number.isFinite(u)?{lastAt:new Date(u).toISOString()}:{},...Number.isFinite(f)?{jobEnded:new Date(f).toISOString()}:{},...Number.isFinite(d)?{jobEndedInPart:new Date(d).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:c}=s,[l,p,u]=o==="part"?[i,a,void 0]:[s.first,s.lastCreated,s.lastUpdated];if(!l||!p)return;let f=async({objectApiName:O,id:A},g)=>{try{let S=(await t.query(`SELECT ${g} FROM ${V(O)} WHERE Id = '${A}'`)).records[0]?.[g],E=typeof S=="string"?Date.parse(S):Number.NaN;return Number.isFinite(E)?E:void 0}catch{return}},d=await f(l,"CreatedDate")??(i&&i.id!==l.id?await f(i,"CreatedDate"):void 0),m=[],h=a?.id!==p.id?a:void 0;for(let O of[p,h]){let A=O?await f(O,"CreatedDate"):void 0;A!==void 0&&m.push(A)}let w=m.length>0?Math.max(...m):void 0;if(d===void 0||w===void 0||w<d)return;if(u){let O=await f(u,"LastModifiedDate"),A=c===void 0?Number.NaN:Date.parse(c)+jc;O!==void 0&&O>w&&(!Number.isFinite(A)||O<=A)&&(w=O)}let b=Date.parse((o==="part"?s.jobEndedInPart:s.jobEnded)??"");return Number.isFinite(b)&&b>w&&(w=b),{first:new Date(d).toISOString(),last:new Date(w).toISOString()}}callsInFlight(e){return this.callsInFlightAt(this.filePath(e))}callsInFlightAt(e){let t=this.deps.openRunFile(e);try{return zs(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()}})}
|
|
19
|
-
`;await this.deps.appendFile(e,o),await this.deps.rm(Je(e)),await this.deps.appendFile(Je(e),o)}resuming(e){return this.resumingAt(this.filePath(e))}resumingAt(e){return this.deps.rm(Je(e))}lastEnd(e){return this.lastEndAt(this.filePath(e))}async lastEndAt(e){for await(let t of this.deps.readLines(Je(e)))if(t.trim()!=="")try{let r=vn.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=$t.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=vn.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=$t.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 c=a[0]==="p"?a[1]:a[2];ne.safeParse(c).success&&r.add(String(c))}catch{}}return[...r]}async end(e){let t=this.filePath(e);await this.deps.rm(t),await this.deps.rm(Je(t)),await this.deps.rm(qt(t));let r=`${fe.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(fe.join(this.dir,o));await this.deps.rmDir?.(ut(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=fe.join(this.dir,e),r=await this.headAt(t);r?await this.end(r.journalId):(await this.deps.rm(t),await this.deps.rm(Je(t)),await this.deps.rm(qt(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=zt(this.filePath(e),t);await this.deps.rm(o);for(let s=0;s<r.length;s+=He)await this.deps.appendFile(o,`${r.slice(s,s+He).join(`
|
|
20
|
-
`)}
|
|
21
|
-
`);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=mt.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=mt.read(r,t);if(!o){r.close();return}return{rows:o.idMapRows(),close:()=>r.close()}}async leftKeysOf(e,t){let r=zt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(fe.basename(r)))return;let s=new Ie;for await(let i of this.deps.readLines(r)){let a=i.trim();ne.safeParse(a).success&&s.add(a.slice(0,15))}return s}async keepLeftPages(e,t,r){let o=zt(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:c,ids:l}of r)if(l.length!==0){a.set(c,(a.get(c)??0)+l.length);for(let p=0;p<l.length;p+=He)await this.deps.appendFile(i,`${l.slice(p,p+He).join(`
|
|
22
|
-
`)}
|
|
23
|
-
`)}return s&&await s(i,o),[...a].map(([c,l])=>({objectApiName:c,count:l}))}async stampsOf(e,t){let r=Hs(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(fe.basename(r)))return{};let s={};for await(let i of this.deps.readLines(r)){let[a,c]=i.trim().split(" ");ne.safeParse(a).success&&vc.safeParse(c).success&&(s[a]=c)}return s}async keepStamps(e,t,r){if(Object.keys(r).length===0)return;let o=Hs(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 c=0;c<s.length;c+=He){let l=s.slice(c,c+He).map(([p,u])=>`${p} ${u}`);await this.deps.appendFile(a,`${l.join(`
|
|
24
|
-
`)}
|
|
25
|
-
`)}i&&await i(a,o)}async leftOf(e,t){let r=zt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(fe.basename(r)))return;let s=[];for await(let i of this.deps.readLines(r)){let a=i.trim();ne.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=$t.safeParse(r);if(!o.success)return;let{resume:s,runUserId:i,...a}=o.data.run,c=Gs(s),l=xn(i);return{...a,...c?{resume:c}:{},...l?{runUserId:l}:{}}}}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(fe.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(fe.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=xc(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,c=new Map,l=new Map,p=new Set,u=()=>{o++,i=s,s=void 0,t==="last"&&(c=new Map,l=new Map,p=new Set)},f=()=>typeof t!="number"||o-1===t;for await(let S of this.deps.readLines(e)){if(S.trim()==="")continue;let E;try{E=JSON.parse(S)}catch{continue}if(!r){let C=$t.safeParse(E);if(!C.success)return;r=C.data.run;continue}if(Array.isArray(E)){let C=Ve(S);if(C){if(!f())continue;let k=l.get(C.object)??new Set;for(let I of C.ids)k.add(I);l.set(C.object,k);continue}let[F,_,D,R]=E;if(F===Bo){f()&&ne.safeParse(_).success&&p.add(String(_));continue}if(F!=="c"&&F!=="e"&&F!=="u"||!f()||!ne.safeParse(_).success||!ne.safeParse(D).success)continue;c.set(String(_),{targetId:String(D),object:typeof R=="string"&&Ut.safeParse(R).success?R:"",created:F==="c"});continue}let T=Tc.safeParse(E);if(T.success){u(),a=T.data.part.startedAt;continue}let x=vn.safeParse(E);if(x.success){s=x.data.end;continue}let N=Fc.safeParse(E);if(N.success){if(o===0&&u(),!f())continue;for(let[C,F]of N.data.created)c.set(C,{targetId:F,object:N.data.object,created:!0})}}if(!r)return;let d=Gs(r.resume),m=xn(r.runUserId),h=await this.checkpointAt(e),w={},b=new Map,O=[];for(let[S,{targetId:E,object:T,created:x}]of c){if(!T)continue;if(w[S]=E,!x){O.push(S);continue}let N=b.get(T)??[];N.push(S),b.set(T,N)}let A=[...b].map(([S,E])=>({objectApiName:S,sourceIds:E})),g=new Set([...c.values()].filter(({created:S})=>S).map(({targetId:S})=>S.slice(0,15))),y=[...l].map(([S,E])=>({objectApiName:S,ids:[...E].filter(T=>!g.has(T.slice(0,15)))})).filter(({ids:S})=>S.length>0);return{journalId:r.journalId,targetOrgId:r.targetOrgId,startedAt:r.startedAt,...d?{resume:d}:{},...m?{runUserId:m}:{},...h?{checkpoint:h}:{},parts:o,partStartedAt:a??r.startedAt,...s?{lastEnd:s}:{},...i?{endBefore:i}:{},created:Pr({idRemapTable:w,idRemapExisting:O,idRemapCreated:A}),remap:{table:w,createdByObject:A,linked:O,...O.some(S=>p.has(S))?{withTheirRecord:O.filter(S=>p.has(S))}:{}},...y.length>0?{unattributed:y}:{}}}};import{createHash as Mc}from"node:crypto";function _c(n,e){return Ys(n,e,t=>t.included||Tr(t))}function Dc(n,e){if(n!==void 0)return{...Bn(n),...e?{planSha256:e}:{}}}function Bn(n){return{...n.withinMB!==void 0?{withinMB:n.withinMB}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},seed:n.seed??Ee.seed,draw:n.draw??Ee.draw,parents:n.parents??Ee.parents,children:n.children??Ee.children,floor:n.floor??Ee.floor,whole:[...new Set(n.whole??[])].sort()}}function Dn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Ks(n){if(!Dn(n))return n;let e=typeof n.planSha256=="string"?n.planSha256:void 0;return Dc(n,e)}function Lc(n){if(!Dn(n))return n;let e=n.config;return{...n,..."sample"in n?{sample:Ks(n.sample)}:{},...Dn(e)&&"sample"in e?{config:{...e,sample:Ks(e.sample)}}:{}}}function kp(n,e,t){return n===_c(e,t)||n===Ys(e,t,r=>r.included)}function Ys(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 Mc("sha256").update(Ln({nodes:r,edges:o,setup:Lc(e)})).digest("hex")}function Ln(n){return Array.isArray(n)?`[${n.map(e=>Ln(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)}:${Ln(r)}`).join(",")}}`:JSON.stringify(n??null)}function Pp(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:Bn(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},Bc="NOTHING_TO_CLONE";function Tp(n){if(n.nodes.some(t=>t.included))return;let e=n.nodes.filter(t=>t.leftOutByUser===!0).length;return{code:Bc,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 Fp(n){return n instanceof qn||n instanceof Error&&n.name==="WholeOrgDryRunStop"&&"dryRun"in n}function $n(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 vp(n){return{api:n.targetRequests,wholeOrg:{source:n.sourceRequests,...n.bulkBatches?{bulkBatches:n.bulkBatches}:{},cost:{durationSeconds:n.durationSeconds}}}}function $c(n,e){let t=a=>a.reduce((c,l)=>c+l.rows,0),r=n.objects.reduce((a,c)=>a+c.sourceRows,0)+n.noRecordDrawn.reduce((a,c)=>a+c.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]}:{}}}function xp(n){let{run:e,measures:t,plan:r,budget:o}=n,s=new Set(r.objects.filter(({rows:h})=>h>0).map(({objectApiName:h})=>h)),i=t.writes.filter(({rows:h})=>h>0),a=h=>i.reduce((w,b)=>w+b[h],0),c=a("jobs"),l=[...s].filter(h=>Xr(h)!==void 0).sort(),p=Qo(e.graph.nodes,s,e.anonymizePII),u=n.files&&"check"in n.files?n.files:void 0,f=u?.check,d=t.contactPointsBlanked??0,m=o.wholeOrg.bulkBatches;return{source:e.source,leftOut:Xo(e.graph).objects.length,...e.carried?{carried:e.carried}:{},...n.sample?{sample:$c(n.sample,n.now??Date.now())}:{},targetApi:$n(o.api),sourceApi:$n(o.wholeOrg.source),...c>0?{bulk:{jobs:c,jobRows:a("jobRows"),restRows:a("restRows"),...m?{batches:$n(m)}:{}}}:{},durationSeconds:o.wholeOrg.cost.durationSeconds,restObjects:i.filter(h=>h.jobs===0).map(h=>h.objectApiName),...u&&f&&f.verdict!=="unread"?{fileStorage:{files:u.count,estimateMB:f.estimateMB,overCeiling:t.files&&"overCeiling"in t.files?t.files.overCeiling:0,remainingMB:f.remainingMB,maxMB:f.maxMB,...f.verdict==="near"?{near:!0}:{}}}:{},...l.length>0?{managedPackages:l}:{},...d>0?{contactPointsBlanked:d}:{},...p.length>0?{personalAsIs:p}:{}}}var qc=10*6e4,zc=3e4,Uc=5e3,Zs=500,Wc=new Set(["JobComplete","Failed","Aborted"]),Qs=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>Zs&&this.kept.splice(0,this.kept.length-Zs)}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??(l=>new Promise(p=>setTimeout(p,l))),s=this.options.pollDelay??Oo,i=r()+(this.options.waitMs??qc),a=e.filter(l=>l.jobId===void 0),c=e.filter(l=>!!l.jobId);for(let l=0;c.length>0;l++){let p=new Ct(Math.max(1,Math.min(zc,i-r())));c=(await Promise.all(c.map(async d=>{t?.();let m=await p.withTimeout("forge:lost-bulk-job",()=>this.stateOf(d.orgId,d.jobId)).catch(()=>{});return m!==void 0&&Wc.has(m)?void 0:d}))).filter(d=>d!==void 0);let f=i-r()-Uc;if(c.length===0||f<=0)break;await o(Math.min(s(l),f))}return[...a,...c]}};function Lp(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 Gc="SELECT SobjectType FROM DuplicateRule WHERE IsActive = true",$p=new Set(["Account","Contact","Lead"]);function qp(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 zp(n){try{let e=await n.query(Gc);return new Set(e.records.flatMap(t=>typeof t.SobjectType=="string"?[t.SobjectType]:[]))}catch{return}}var Xs=class{constructor(e=3){this.maxDiscoveries=e}maxDiscoveries;discoveries=new Map;awaitingGuard=new Map;run=null;beginDiscovery(e,t,r){let o=[],s=l=>{this.discoveries.delete(l.requestId),l.stop="superseded",o.push(l)},i=this.discoveries.get(e);i&&s(i);let a=[...this.discoveries.values()].filter(l=>!l.controller.signal.aborted);for(;a.length>=this.maxDiscoveries;){let l=a.shift();l&&s(l)}let c={requestId:e,controller:t,operationId:r};return this.discoveries.set(e,c),{discovery:c,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 zn(n){let e=0,t=new Map,r=new Map,o=[],s=new Set,i=new Map,a=[],c=f=>{t.set(f,e),r.set(f,e),e++,o.push(f),s.add(f);for(let d of[...n.get(f)??[]].sort())n.has(d)&&(t.has(d)?s.has(d)&&r.set(f,Math.min(r.get(f)??0,t.get(d)??0)):(c(d),r.set(f,Math.min(r.get(f)??0,r.get(d)??0))));if(r.get(f)===t.get(f)){let d=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),i.set(m,a.length),d.push(m)}while(m!==f);a.push(d.sort())}};for(let f of[...n.keys()].sort())t.has(f)||c(f);let l=a.map((f,d)=>{let m=new Set;for(let h of f)for(let w of n.get(h)??[]){let b=i.get(w);b!==void 0&&b!==d&&m.add(b)}return m}),p=new Set,u=[];for(;p.size<a.length;){let f=a.map((d,m)=>({component:d,i:m})).filter(({i:d})=>!p.has(d)&&[...l[d]].every(m=>p.has(m))).sort((d,m)=>d.component[0].localeCompare(m.component[0]));for(let{component:d,i:m}of f)p.add(m),u.push(d)}return u}function Un(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 Vc(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(c=>c.name===s.fieldApiName),a=i!==void 0&&je(i);!s.required&&!Cr(s.to,s.fieldApiName)&&!a||o.set(s.to,(o.get(s.to)??new Set).add(s.from))}return o}function Jc(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:zn(o)}}function Vp(n,e,t){return n.flatMap(r=>{let{groups:o,within:s}=Jc(r,e);return o.flatMap(i=>i.length>1?Un(i,Vc(i,s,t)):i)})}var Hc=100,Kc=.25,Yc=2048;function Zc(n,e){return typeof n!="string"||n===""?!1:e.prefix===void 0||e.prefix!==null&&n.startsWith(e.prefix)}function Qc(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||!Se(a))continue;let c=Wn(o.objectApiName,a)||je(a);for(let l of a.referenceTo)l===o.objectApiName||!e.has(l)||(s.add(l),c&&i.add(l))}t.set(o.objectApiName,s),r.set(o.objectApiName,i)}return zn(t).flatMap(o=>o.length>1?Un(o,r):o)}function Wn(n,e){return qe(n,e.name,e.nillable)}function Xc(n){let e=new Map(n.objects.map(d=>[d.objectApiName,d])),t=new Map;for(let d of e.keys())n.referenceData?.has(d)&&t.set(d,"referenceData");for(let d of n.whole??[])e.has(d)&&!t.has(d)&&t.set(d,"asked");let r=Kc*Math.max(0,n.roomBytes),o=d=>d.rows===void 0?void 0:n.wholeBytes(d.objectApiName,d.rows),s=[...e.values()].filter(d=>Pt.has(d.objectApiName)&&!t.has(d.objectApiName)),i=s.reduce((d,m)=>{let h=o(m);return d===void 0||h===void 0?void 0:d+h},0);if(s.length>0&&i!==void 0&&i<=r&&s.every(d=>n.maxRecordsPerObject===void 0||(d.rows??0)<=n.maxRecordsPerObject))for(let d of s)t.set(d.objectApiName,"catalog");let c=Math.max(Hc,Math.floor(.01*Math.max(0,n.roomBytes)/Yc)),l=d=>e.has(d)&&!t.has(d),p=new Set;for(let d of e.values())if(l(d.objectApiName)){for(let m of d.fields)if(Se(m))for(let h of m.referenceTo)h!==d.objectApiName&&p.add(h)}let u=[...e.values()].filter(d=>!t.has(d.objectApiName)&&!Pt.has(d.objectApiName)&&d.rows!==void 0&&d.rows>0&&d.rows<=c&&(n.maxRecordsPerObject===void 0||d.rows<=n.maxRecordsPerObject)&&p.has(d.objectApiName)).map(d=>({object:d,bytes:o(d)??1/0})).sort((d,m)=>d.bytes-m.bytes||(d.object.objectApiName<m.object.objectApiName?-1:1)),f=0;for(let{object:d,bytes:m}of u){if(f+m>r)break;d.fields.some(w=>Se(w)&&Wn(d.objectApiName,w)&&w.referenceTo.some(b=>l(b)))||(t.set(d.objectApiName,"smallParent"),f+=m)}return t}function ei(n){let e=new Map(n.objects.map(u=>[u.objectApiName,u])),t=Xc(n),r=[...t.values()].includes("catalog"),o=new Map;for(let u of e.keys()){let f=t.get(u);o.set(u,f!==void 0?{kind:"whole",why:f}:{kind:"drawn",rooted:!(Pt.has(u)&&!r)})}let s=n.order?[...n.order]:Qc(n.objects),i=new Map(s.map((u,f)=>[u,f])),a=(u,f)=>(i.get(u)??1/0)<(i.get(f)??1/0),c=u=>{let f=o.get(u);return f?.kind==="drawn"&&f.rooted},l=new Map,p=new Map;for(let u of[...e.values()].sort((f,d)=>f.objectApiName<d.objectApiName?-1:1)){let f=u.objectApiName,d=[];for(let m of[...u.fields].sort((h,w)=>h.name<w.name?-1:1)){if(m.referenceTo.length===0||!Se(m))continue;let h=Wn(f,m),w=m.referenceTo.length>1;for(let b of[...m.referenceTo].sort()){let O=o.get(b),A=Mt(f,m,e.get(b)?.childRelationships),g=n.excluded?.get(b),y=x=>w?{prefix:x??null}:{};if(!O){h&&n.excluded?.has(b)&&d.push({objectApiName:f,field:m.name,parent:b,target:"excluded",carries:!1,owed:!1,required:h,masterDetail:A,...y(g)});continue}let S=b===f,E=S||!a(b,f),T={objectApiName:f,field:m.name,parent:b,target:O.kind==="whole"?"whole":"drawn",carries:!S&&c(b)&&c(f)&&(h||!E),owed:E,required:h,masterDetail:A,...y(e.get(b)?.keyPrefix)};if(d.push(T),T.carries){let x=p.get(b)??[];x.push(T),p.set(b,x)}}}l.set(f,d)}return{classes:o,whole:[...t.entries()].map(([u,f])=>({objectApiName:u,why:f})).sort((u,f)=>u.objectApiName<f.objectApiName?-1:1),linksOf:l,carriersInto:p,order:s}}function Qp(n,e){return[...new Set((n.linksOf.get(e)??[]).map(t=>t.field))].sort()}function Xp(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 eg(n,e,t,r){return(n.linksOf.get(e)??[]).find(o=>o.field===t&&Zc(r,o))}var Fe=2e3,td=500,Hn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,nd=Pe;function Wt(n){return n.length===0?"":` WHERE ${n.join(" AND ")}`}function Ke(n){return to(n)+2*(n.match(/'/g)?.length??0)}function ti(n,e,t){let r=Ke(n)+Ke(t),o=Ke(", "),s=[],i=[],a=r;for(let c of e){let l=Ke(`'${c}'`);i.length>0&&(a+o+l>14e3||i.length>=td)&&(s.push(i),i=[],a=r),a+=(i.length>0?o:0)+l,i.push(c)}return i.length>0&&s.push(i),s}function wt(n){let e=new Set,t=[];for(let r of n){if(!Hn.test(r))continue;let o=ce(r);e.has(o)||(e.add(o),t.push(r))}return t}function Gn(n){return tt(U(n))==="QUERY_TIMEOUT"}var rd=new Set(["MALFORMED_QUERY","INVALID_FIELD"]);function ni(n){let e=tt(U(n));return e!==void 0&&rd.has(e)}var he="CreatedDate";function od(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function sd(n){return/\(\s*SELECT\b/i.test(od(n))}function id(n){return n==null||n===""}var ri=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;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 c=a.toLowerCase();i.has(c)||!o.has(c)||(i.add(c),s.push(V(a)))}return s}readOptionsOf(e){return Pe.has(e)?{all:!0}:void 0}termsOf(e){let t=this.options.filterOf?.(e);return[...t!==void 0&&t.trim()!==""?[`(${t})`]:[],...Pe.has(e)?["IsDeleted = false"]:[]]}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 V(t)}rootShapeOf(e){let t=V(e.objectApiName),r=this.slow.has(t),o=e.carriers.map(c=>({field:this.fieldOf(t,c.field),prefixes:c.drawnPrefixes===void 0?void 0:[...c.drawnPrefixes]})),s=r?[]:o.filter(c=>c.prefixes===void 0),i=o.filter(c=>!s.includes(c)),a=(c,l)=>!id(c)&&(l===void 0||l.some(p=>String(c).startsWith(p)));return{object:t,select:this.columnsOf(t,i.map(c=>c.field)),terms:[...this.termsOf(t),...s.map(c=>`${c.field} = null`)],held:s.length>0,tested:i.length>0,isRoot:c=>!i.some(l=>a(c[l.field],l.prefixes))}}async countRoots(e){let t=new Array(e.length),r=0;return await Ae(e,async(o,s)=>{let i=await this.countRootsOf(o);t[s]=i,this.counted.set(o.objectApiName,i.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),o=this.rootShapeOf(e),s=a=>this.count(`SELECT COUNT() FROM ${a.object}${Wt(a.terms)}`,r);if(!this.slow.has(t))try{let a=await s(o);return{objectApiName:t,rows:a,exact:!o.tested}}catch(a){if(!o.held||!Gn(a))throw a;this.slow.add(t)}let i=await s(this.rootShapeOf(e));return{objectApiName:t,rows:i,exact:!1,timedOut:!0}}async drawUniform(e,t){let r=0;await Ae(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);for(;;){let o=this.rootShapeOf(e),s=`SELECT ${o.select.join(", ")} FROM ${o.object}${Wt(o.terms)}`,i=!1;try{for await(let a of this.pages(s,r)){i=!0;let c=a.filter(o.isRoot).map(l=>String(l.Id));c.length>0&&await t(e.objectApiName,c)}return}catch(a){if(i||!o.held||!Gn(a))throw a;this.slow.add(e.objectApiName)}}}async drawRecent(e,t){let r=e.map(s=>({objectApiName:s.objectApiName,by:this.newestBy(s.objectApiName)})),o=0;return await Ae(e,async(s,i)=>{s.take>0&&this.counted.get(s.objectApiName)!==0&&await this.newestRoots(s,r[i].by,t),o++,this.progress("drawing",{objectApiName:s.objectApiName,done:o,total:e.length})}),r}newestBy(e){return(this.options.fieldsOf(e)??[]).some(o=>o.toLowerCase()===he.toLowerCase())&&this.options.sorts?.(e,he)!==!1?"created":"id"}readsNewestApart(e){let t=this.options.filterOf?.(e);return this.newestBy(e)==="created"&&t!==void 0&&sd(t)}async newestRoots(e,t,r){let o=e.objectApiName,s=this.readOptionsOf(o),i=this.readsNewestApart(o),a=0,c,l=!1;for(;a<e.take;){let p=this.rootShapeOf(e),u=p.tested?Fe:Math.min(Fe,e.take-a),f=t==="created"?this.columnsOf(o,[...p.select,he]):p.select,{after:d,order:m}=ad(t,c,i,l),h=`SELECT ${f.join(", ")} FROM ${p.object}${Wt([...p.terms,...d])} ORDER BY ${m} LIMIT ${u}`,w;try{w=await this.gather(h,s)}catch(A){if(!p.held||!Gn(A))throw A;this.slow.add(o);continue}let b=w.filter(p.isRoot).map(A=>String(A.Id)).slice(0,e.take-a);if(a+=b.length,b.length>0&&await r(o,b),w.length<u){if(!(i&&l))return;l=!1;continue}let O=w[w.length-1];c=cd(o,O,t),l=i}}async readParents(e){let t=new Array(e.length);return await Ae(e,async(r,o)=>{t[o]=await this.parentsOf(r)}),t}async parentsOf(e){let t=V(e.objectApiName),r=this.columnsOf(t,e.columns),o=wt(e.ids),s=this.readOptionsOf(t),i=await this.byList(t,r,"Id",o,this.termsOf(t),s),a=new Set(i.map(f=>ce(String(f.Id)))),c=o.filter(f=>!a.has(ce(f))),l=this.options.filterOf?.(t),p=[];if(c.length>0&&l!==void 0&&l.trim()!==""){let f=Pe.has(t)?["IsDeleted = false"]:[];p=await this.byList(t,r,"Id",c,f,s)}let u=new Set(p.map(f=>ce(String(f.Id))));return{objectApiName:e.objectApiName,rows:i,columns:r,absent:c.filter(f=>!u.has(ce(f))),outsideFilter:p}}async readStandardPrices(e,t){let r=wt(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"&&Hn.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=wt(t),i=wt(r);if(s.length===0||i.length===0)return[];let a=this.columnsOf("PricebookEntry",["Product2Id","Pricebook2Id",...o]),c=[...this.termsOf("PricebookEntry"),`Pricebook2Id IN (${i.map(l=>`'${l}'`).join(", ")})`,`CurrencyIsoCode = '${e}'`];return this.byList("PricebookEntry",a,"Product2Id",s,c,void 0)}async byList(e,t,r,o,s,i){let a=[...s,`${r} IN (`].join(" AND "),c=`SELECT ${un(t).join(", ")} FROM ${e} WHERE ${a}`,l=[];for(let p of ti(c,o,")")){let u=`SELECT ${t.join(", ")} FROM ${e} WHERE ${a}${p.map(f=>`'${f}'`).join(", ")})`;for(let f of await fn(u,d=>this.gather(d,i)))l.push(f)}return l}async readChildren(e){let t=new Array(e.length);return await Ae(e,async(r,o)=>{t[o]=await this.childrenOf(r)}),t}async childrenOf(e){let t=V(e.objectApiName),r=this.fieldOf(t,e.field),o=e.cap,s=this.newestBy(t),i=o!=="all"&&s==="created",a=this.columnsOf(t,[r,...e.columns,...i?[he]:[]]),c=wt(e.parentIds),l=this.readOptionsOf(t),p=this.termsOf(t),u=new Map,f={objectApiName:t,field:r,rows:[],columns:a,cut:[],counts:new Map,newestBy:s},d=()=>{for(let y of c)f.counts.set(y,u.get(ce(y))??0);return f};if(c.length===0)return f;if(o==="all"){let y=Vn(await this.byList(t,a,r,c,p,l),r,1/0,s);f.rows=y.rows;for(let[S,E]of y.counts)u.set(S,E);return d()}let m=[...p,`${r} IN (`].join(" AND "),h={head:`SELECT ${r}, COUNT(Id) n FROM ${t} WHERE ${m}`,tail:`) GROUP BY ${r}`},w={head:`SELECT ${un(a).join(", ")} FROM ${t} WHERE ${m}`,tail:")"},b=Ke(h.head+h.tail)>Ke(w.head+w.tail)?h:w,O=[],A=[];for(let y of ti(b.head,c,b.tail)){let S=e.sourceRows<=o*y.length||this.ungrouped.has(t)||this.options.countsBy?.(t,r)===!1?void 0:await this.countedByParent(t,h,r,y,l);if(S===void 0){O.push(...y);continue}for(let E of S)E.rows>o?A.push(E):O.push(E.parentId)}let g=Vn(await this.byList(t,a,r,O,p,l),r,o,s);f.rows.push(...g.rows),f.cut.push(...g.cut);for(let[y,S]of g.counts)u.set(y,S);for(let y of A){let S=`SELECT ${a.join(", ")} FROM ${t} WHERE ${[...p,`${r} = '${y.parentId}'`].join(" AND ")} ORDER BY ${Jn(s)} LIMIT ${o}`,E;try{E=await fn(S,T=>this.gather(T,l))}catch(T){if(!ni(T))throw T;let x=Vn(await this.byList(t,a,r,[y.parentId],p,l),r,o,s);f.rows.push(...x.rows),f.cut.push(...x.cut);for(let[N,C]of x.counts)u.set(N,C);continue}f.rows.push(...E),f.cut.push({parentId:y.parentId,rows:Math.max(0,y.rows-E.length)}),u.set(ce(y.parentId),y.rows)}return d()}async countedByParent(e,t,r,o,s){let i=`${t.head}${o.map(l=>`'${l}'`).join(", ")}${t.tail}`,a;try{a=await this.gather(i,s)}catch(l){if(!ni(l))throw l;this.ungrouped.add(e);return}let c=[];for(let l of a){let p=l[r],u=Number(l.n);typeof p=="string"&&Number.isFinite(u)&&c.push({parentId:p,rows:u})}return c}async readWhole(e,t){await Ae(e,async r=>{let o=V(r.objectApiName),s=this.columnsOf(o,r.columns),i=this.readOptionsOf(o),a=`SELECT ${s.join(", ")} FROM ${o}${Wt(this.termsOf(o))}`;for await(let c of io(a,l=>this.pages(l,i),l=>this.gather(l,i)))await t(r.objectApiName,c)})}};function Jn(n){return n==="created"?`${he} DESC, Id DESC`:"Id DESC"}function ad(n,e,t,r){let o=Jn("created");return n==="id"?{after:e?[`Id < '${e.id}'`]:[],order:Jn("id")}:e?t?r?{after:[`${he} = ${e.at}`,`Id < '${e.id}'`],order:"Id DESC"}:{after:[`${he} < ${e.at}`],order:o}:{after:[`(${he} < ${e.at} OR (${he} = ${e.at} AND Id < '${e.id}'))`],order:o}:{after:[],order:o}}function cd(n,e,t){let r=e.Id;if(typeof r!="string"||!Hn.test(r))throw new Error(`A record of ${n} came back without its id.`);if(t==="id")return{at:"",id:r};let o=e[he];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:Mo(o),id:r}}function oi(n){let e=n[he],t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function dd(n,e){let t=oi(n),r=oi(e);return t!==r?t===void 0?1:r===void 0?-1:r-t:Be(String(e.Id),String(n.Id))}function Vn(n,e,t,r){let o=new Map;for(let c of n){let l=c[e];if(typeof l!="string")continue;let p=ce(l),u=o.get(p);u?u.rows.push(c):o.set(p,{parentId:l,rows:[c]})}let s=[],i=[],a=new Map;for(let[c,{parentId:l,rows:p}]of o)p.sort(r==="created"?dd:(u,f)=>Be(String(f.Id),String(u.Id))),s.push(...p.slice(0,t)),p.length>t&&i.push({parentId:l,rows:p.length-t}),a.set(c,p.length);return{rows:s,cut:i,counts:a}}function si(n,e,t=0,r=!1){if(n.rows<=0)return 0;if(e==="uniform")return Math.ceil(n.rows/Fe);let o=Math.ceil(Math.min(Math.max(0,t),n.rows)/Fe);return r?o+Math.max(0,o-1):o}function dg(n){let e=V(n.objectApiName),t=n.columns.some(f=>f.toLowerCase()==="systemmodstamp"),r=no(n.columns,t?["Id","SystemModstamp"]:["Id"]),o=Math.max(0,n.planRows),s=Math.max(0,n.sourceRows),i=r.map(f=>oo(e,f)),a=i.reduce((f,d)=>f+Math.ceil(o/d),0),c=Math.max(1,Math.ceil(s/Fe)),l=Math.floor(s/Fe),p=s%Fe,u=c+i.slice(1).reduce((f,d)=>f+l*Math.ceil(Fe/d)+(p>0?Math.ceil(p/d):0),0);return nd.has(e)?{by:"cursor",requests:u,byIds:a,byCursor:u,cursorAlone:!0}:a<=u?{by:"ids",requests:a,byIds:a,byCursor:u}:{by:"cursor",requests:u,byIds:a,byCursor:u}}var ld=new Set(["BusinessHours","OperatingHours"]);function ud(n){let{storage:e,withinMB:t}=n,r=new Map;for(let a of n.automation??[])r.set(a.objectApiName,(r.get(a.objectApiName)??0)+a.bytes);let o=r.size>0?{automationBytes:a=>r.get(a)??0}:{};if("unread"in e){if(t===void 0)return;let a=Math.floor(Math.max(0,t)*1048576);return{budget:{bytes:a,withinMB:t,limitedBy:"within"},bytesLimit:"within",roomBytes:a,...o}}let s=ss({storage:e,...t!==void 0?{withinMB:t}:{}});if("unread"in s)return;let i=s.terms.limitedBy==="within"?"within":"storage";return{budget:{bytes:s.bytes,remainingMB:e.remainingMB,maxMB:e.maxMB,share:We,roundingMB:it,...t!==void 0?{withinMB:t}:{},limitedBy:i},bytesLimit:i,roomBytes:Math.floor(We*Math.max(0,e.remainingMB-it)*1048576),...o}}function fd(n,e){let t=n.nodes.filter(o=>o.included&&!Fr(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 bg(n){let e=n.options??{},t=fd(n.graph,new Set(n.excludedObjects??[])),r=t.reduce((u,f)=>u+st(f.objectApiName,{rows:f.rows??0}),0),o=Zo({storageBytes:r},n.storage),s=ud({storage:n.storage,...e.withinMB!==void 0?{withinMB:e.withinMB}:{}}),i=ei({objects:t,referenceData:ld,...e.whole?{whole:e.whole}:{},roomBytes:s?.roomBytes??0,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(u,f)=>st(u,{rows:f})}),a=e.draw??Ee.draw,c=s?As(s.budget.bytes,e.maxTotal):0,p=t.filter(u=>{let f=i.classes.get(u.objectApiName);return f?.kind==="drawn"&&f.rooted}).reduce((u,f)=>{let m=(i.linksOf.get(f.objectApiName)??[]).some(h=>h.carries&&h.required)?0:f.rows??0;return u+1+si({objectApiName:f.objectApiName,rows:m,exact:!1},a,Math.min(m,c))},0);return{wholeOrg:o,...s?{budget:s.budget}:{},whole:i.whole.filter(u=>u.why!=="asked"),planReads:{source:pd(p,n.source),seconds:p*Ko}}}function pd(n,e){if("unread"in e)return{verdict:"unread",estimate:n,unread:e.unread};let t=Yo(n,e);if(t.verdict==="unread")return t;let r=n>Math.floor(xt*e.remaining);return{...t,verdict:r?"exceeds":t.verdict}}var ii=q({value:z(),validFor:H(J().int().nonnegative()).optional()}).loose(),ai=q({controllerValues:Xe(z(),J().int().nonnegative()).optional(),defaultValue:ii.nullable().optional(),values:H(ii)}).loose(),gd=q({picklistFieldValues:Xe(z(),Re())}).loose(),md=/^[A-Za-z][A-Za-z0-9_]*$/,hd=/^012[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/;function wd(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 bd(n){let e=gd.parse(n),t=new Map;for(let[r,o]of Object.entries(e.picklistFieldValues)){let s=ai.safeParse(o);s.success&&t.set(r,wd(s.data))}return t}function yd(n){return ai.parse(n).values.map(e=>e.value)}function ci(n,e,t,r){for(let s of r===void 0?[e]:[e,r])if(!md.test(s))throw new Error(`Not an API name: "${s}"`);if(!hd.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 Rg(n,e,t){return bd(await n.request(ci(n,e,t)))}async function Sg(n,e,t,r){return yd(await n.request(ci(n,e,t,r)))}var Rd=q({FileStorageMB:q({Remaining:J()}).loose()}).loose(),Sd=H(q({errorCode:z().optional(),message:z().optional()}).loose());function Od(n){if(!(n instanceof Error))return new Error(String(n));try{let e=Sd.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 Eg(n,e,t){if(!mo(t))throw new Error(`Not a record id: ${t}`);try{let r=await n.request({method:"GET",url:`/sobjects/${e}/${t}/${Rs[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 Od(r)}}async function jg(n,e,t){try{let r=await n.request({method:"POST",url:`/sobjects/${e}`,body:JSON.stringify(t),headers:{"content-type":"application/json"}}),o=jt(r,e);return{id:o.id,success:o.success,errors:o.errors}}catch(r){return{id:"",success:!1,errors:[wo(r)]}}}async function Ng(n){return Rd.parse(await n.request({method:"GET",url:"/limits"})).FileStorageMB.Remaining}var Ed=["Task","Event","FeedItem","FeedComment","EmailMessage","ContentDocumentLink","Note","CaseComment"],ui=["Account","Contact","Lead","Opportunity","Case","Campaign","Contract","Order","Asset","Product2"],Yn=["User","Group","GroupMember","PermissionSet","PermissionSetAssignment","PermissionSetGroup","RecordType","Profile","UserRole"],jd=1e3,Nd=6e4,Kn=1e4,Cd=300,di=2e3,Pd=50,Td=3,fi=3,Fd=5,vd=new Set(["flows","processes","triggers","conditions","definitions"]),pi=new Set(["OwnerId","CreatedById","LastModifiedById","RecordTypeId"]),bt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function W(n){return n.slice(0,15)}function oe(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Ye(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function xd(n){let e=oe(n?.first),t=oe(n?.last);if(!(!Number.isFinite(e)||!Number.isFinite(t)))return{from:Math.floor((e-jd)/1e3)*1e3,to:Math.ceil((Math.max(e,t)+Nd)/1e3)*1e3}}function qg(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(c=>c.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=>vd.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 zg(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:U(o)}}finally{r.close()}}))}async function Md(n,e,t){let r=new Map,o=0,s;for(let{objectApiName:i,ids:a}of e){if(o>=Td||r.size>1||t())break;let c=a.slice(0,Pd);if(c.length!==0)try{let[l]=te(c,c.length),p=await n.queryDeleted(`SELECT CreatedById FROM ${V(i)} WHERE Id IN (${l})`),u=!1;for(let f of p.records){let d=f?.CreatedById;typeof d=="string"&&bt.test(d)&&(r.has(W(d))||r.set(W(d),d),u=!0)}u&&o++}catch(l){s??=U(l)}}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 _d(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 Dd(n){return n.queryable!==!1&&n.deletable!==!1&&n.createable!==!1&&n.layoutable!==!1&&!Yn.some(e=>e.toLowerCase()===n.name.toLowerCase())}async function gi(n,e){let t;try{t=await e(n)}catch(i){return{reason:U(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:Ld(t)}}function Ld(n){return n.fields.filter(e=>e.type==="reference"&&!pi.has(e.name)&&!((e.referenceTo??[]).length>0&&(e.referenceTo??[]).every(t=>Yn.includes(t)))).map(e=>e.name)}function Bd(n,e){return`CreatedById = '${n}' AND CreatedDate >= ${Ye(e.from)} AND CreatedDate <= ${Ye(e.to)}`}function mi(n,e){return n.length===1?Bd(n[0],e):`CreatedById IN (${n.map(t=>`'${t}'`).join(", ")}) AND CreatedDate >= ${Ye(e.from)} AND CreatedDate <= ${Ye(e.to)}`}async function hi(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=xd(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(oe(e.writtenBetween?.first),oe(e.writtenBetween?.last)),o.window={from:Ye(i.from),to:Ye(i.to)};let a=e.runUserId!==void 0&&bt.test(e.runUserId)?e.runUserId:void 0,c=e.user!==void 0&&bt.test(e.user)?e.user:void 0,l=e.created.some(u=>u.ids.length>0),p=a?{user:a}:l?await Md(n,e.created,r):c!==void 0?{user:c}:{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 p?(o.refusal=p.refusal,s.stopped=r(),s):Kd(n,e,e.ties,p.user,s,i,t)}function $d(n){return n.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}async function qd(n,e,t){if(e.length===0)return[];if(n.counts)try{return await n.counts(e)}catch(o){let s=U(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:U(s)})}}return r}async function zd(n){try{return(await n.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t?.Id).filter(t=>typeof t=="string"&&bt.test(t))}catch{return[]}}async function Ud(n,e,t,r,o,s){let i=V(e.name),a=[...new Set(["Id","CreatedById","CreatedDate",e.modified,e.modifiedBy,e.nameField,...e.references].filter(u=>u!==void 0).map(V))],c=async u=>(await n.query(u)).records.filter(f=>typeof f=="object"&&f!==null),l=[],p;for(;;){if(s())return{rows:l,overBound:!1,stopped:!0};let u=`SELECT ${a.join(", ")} FROM ${i} WHERE ${mi([...t.values()],r)}${p?` AND Id > '${p}'`:""} ORDER BY Id LIMIT ${di}`,f;try{let d=ro(u);f=d?await so(await c(d.first),d,c):await c(u)}catch(d){return{reason:U(d)}}for(let d of f){if(typeof d.Id!="string")continue;p=d.Id;let m=typeof d.CreatedById=="string"?W(d.CreatedById):"",h=oe(d.CreatedDate);if(!t.has(m)||!(h>=r.from&&h<=r.to)||o(W(d.Id)))continue;let w=e.modifiedBy?d[e.modifiedBy]:void 0,b=e.nameField?d[e.nameField]:void 0,O=[];for(let A of e.references){let g=d[A];typeof g=="string"&&bt.test(g)&&O.push({field:A,key:W(g)})}if(l.push({id:d.Id,modified:oe(d[e.modified]),created:h,creator:m,references:O,...typeof w=="string"?{modifiedBy:W(w)}:{},...typeof b=="string"&&b.trim()!==""?{name:b.trim().slice(0,80)}:{}}),l.length>Kn)return{rows:l.slice(0,Kn),overBound:!0,stopped:!1}}if(f.length<di)return{rows:l,overBound:!1,stopped:!1}}}function Wd(n){let e=new Map,t=o=>{let s=o.toLowerCase(),i=e.get(s);return i||(i=(async()=>kt.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(c=>c.childSObject.toLowerCase()===s.toLowerCase()&&c.field===i);return{cascade:a?.cascadeDelete===!0,restricted:a?.restrictedDelete===!0}}}}async function Gd(n,e,t,r,o,s){let i=await _d(n),a=d=>i?i.get(d.toLowerCase()):{name:d},c=[],l=[],p=d=>c.some(m=>m.toLowerCase()===d.toLowerCase()),u=d=>Yn.some(m=>m.toLowerCase()===d.toLowerCase()),f=(d,m)=>{if(p(d)||u(d))return;let h=a(d)?.name;if(!h){m&&o.unread.push({objectApiName:d,reason:"The org has no such object."});return}if(c.length>=Cd){l.includes(h)||l.push(h);return}c.push(h)};for(let d of e)f(d,!0);for(let d of Ed)f(d,!1);for(let d of t)f(d,!0);for(let d of ui)f(d,!1);for(let d of e){if(s())return;for(let m of(await r.now(d))?.childRelationships??[]){let h=a(m.childSObject);h&&Dd(h)&&!p(h.name)&&f(h.name,!1)}}return{looked:c,notLooked:l}}async function Vd(n,e,t,r,o,s,i){let a=[],c=new Map([...r.keys()].map(l=>[l.toLowerCase(),l]));for(let l of e){let p=((await o.now(l))?.fields??[]).filter(u=>u.type==="reference"&&!pi.has(u.name));for(let u of p)for(let f of u.referenceTo??[]){let d=c.get(f.toLowerCase());if(!d)continue;let m=(r.get(d)??[]).map(b=>b.id),{restricted:h}=await o.relation(d,l,u.name),w=V(u.name);for(let b of te(m)){if(i())return;let O;try{O=(await n.query(`SELECT Id, ${w} FROM ${V(l)} WHERE ${w} IN (${b})`)).records}catch(A){s.unread.push({objectApiName:l,reason:`What its ${u.name} points at among the records found could not be read (${U(A)}): what only it ties is left as tied to nothing.`});continue}for(let A of O){let{Id:g,[u.name]:y}=A??{};typeof g!="string"||typeof y!="string"||t.has(W(g))&&a.push({from:W(g),to:W(y),restricted:h})}}}}return a}async function Jd(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 te(i)){if(r())return!1;try{let c=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${V(s)} WHERE Id IN (${a})`);for(let l of c.records){let{Id:p,CreatedDate:u}=l??{},f=typeof p=="string"?e.get(W(p)):void 0,d=oe(u);f&&Number.isFinite(d)&&(f.from=d,f.to=d)}}catch{}}return!0}function Hd(n,e,t,r,o,s){let{listing:i}=r,a=new Set(ui.map(d=>d.toLowerCase())),c=[],l=[],p=["made","madeOver","late","untied"];for(let[d,m]of n){let h=[],w=0;for(let y of m){let S=e.get(W(y.id));if(S){if(S.class==="untied"&&a.has(d.toLowerCase())){w++;continue}h.push({id:y.id,modified:y.modified,created:y.created,class:S.class,sameSave:S.sameSave,turn:S.turn,...y.modifiedBy!==void 0?{modifiedBy:y.modifiedBy}:{},...y.name!==void 0?{name:y.name}:{}})}}if(w>0&&i.handWork.push({objectApiName:d,count:w}),h.length===0)continue;let b={made:0,madeOver:0,late:0,untied:0},O=0,A=0,g={};for(let y of h)b[y.class]++,y.sameSave&&O++,Gt(y,o,s)&&(A++,g[y.class]=(g[y.class]??0)+1);i.found.push({objectApiName:d,count:h.length,names:p.flatMap(y=>h.filter(S=>S.class===y)).flatMap(y=>y.name?[y.name]:[]).slice(0,fi),classes:{...b,...O>0?{sameSave:O}:{},...A>0?{changed:A,changedIn:g}:{}}}),b.untied>0&&c.push({objectApiName:d,count:b.untied}),b.late>0&&l.push({objectApiName:d,count:b.late}),r.rows.set(d,h)}let u=[];i.handWork.length>0&&u.push(`The run's user created records in the run's window tied to nothing of the run, on objects people make by hand (${$d(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 f=(t.otherRuns??[]).filter(d=>d.ids.length>0||d.idsUntold===!0).length;f>0&&u.push(`${f===1?"Another run":`${f} 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.`),u.length>0&&u.push("The runs of another machine, or of a CI, in the same window are not seen."),i.untied={objects:c,...u.length>0?{refusal:u.join(" ")}:{}},i.late=l}async function Kd(n,e,t,r,o,s,i){let{listing:a}=o,c=()=>e.signal?.aborted===!0,l=()=>(o.stopped=!0,o),p=oe(e.writtenBetween?.first),u=Math.max(p,oe(e.writtenBetween?.last)),f=Math.min(Number.POSITIVE_INFINITY,...[t.removalBegan,...i.map(P=>P.first)].map(oe).filter(Number.isFinite)),d=Math.ceil((u+9e5)/1e3)*1e3,m={from:s.from,to:Math.max(s.to,Math.min(d,Math.floor(f/1e3)*1e3))},h=new Map,w={from:p,to:u};for(let{objectApiName:P,ids:v}of e.created)for(let M of v)h.set(W(M),{kind:"created",objectApiName:P,id:M,from:Number.NaN,to:Number.NaN});for(let{objectApiName:P,ids:v,between:M}of t.writtenOver??[]){let $=oe(M?.first),G=oe(M?.last);for(let ee of v)h.has(W(ee))||h.set(W(ee),{kind:"overwritten",objectApiName:P,id:ee,from:$,to:G})}let b=[...new Set([...e.created,...t.writtenOver??[]].filter(P=>P.ids.length>0).map(P=>P.objectApiName))],O=new Set([...(t.otherRuns??[]).flatMap(P=>P.ids.map(W)),...(t.leased??[]).map(W)]),A=P=>e.remap.has(P)||h.has(P)||O.has(P),g=await zd(n),y=new Map([[W(r),r]]);for(let P of g)y.has(W(P))||y.set(W(P),P);let S=new Set(g.map(W).filter(P=>P!==W(r))),E=Wd(n),T=await Gd(n,b,e.automation.creates,E,a,c);if(!T)return l();let{looked:x,notLooked:N}=T;a.looked=x,N.length>0&&(a.notLooked=N);let C=await qd(n,x.map(P=>`SELECT COUNT() FROM ${V(P)} WHERE ${mi([...y.values()],m)}`),c);if(c())return l();let F=new Map,_=[];for(let[P,v]of x.entries()){let M=C[P];if(M===void 0)return l();if(M===0)continue;if(c())return l();let $=await gi(v,E.of);if("reason"in $){a.unread.push({objectApiName:v,reason:$.reason});continue}if(typeof M=="object"){a.unread.push({objectApiName:v,reason:M.reason});continue}let G=await Ud(n,$,y,m,A,c);if("reason"in G){a.unread.push({objectApiName:v,reason:G.reason});continue}if(G.stopped)return l();G.overBound?_.push({objectApiName:v,count:G.rows.length,names:G.rows.flatMap(ee=>ee.name?[ee.name]:[]).slice(0,fi),overBound:!0}):G.rows.length>0&&F.set(v,G.rows)}let D=new Map;for(let{part:P,created:v}of e.otherParts??[])for(let{objectApiName:M,ids:$}of v)for(let G of $)D.set(W(G),{part:P,objectApiName:M});let R=new Map;for(let[P,v]of D.size>0?[...F]:[]){let M=[];for(let $ of v){let G,ee=!1;for(let we of $.references){let ve=h.get(we.key)??D.get(we.key);if(!ve)continue;let{cascade:sn}=await E.relation(ve.objectApiName,P,we.field);sn&&(h.has(we.key)?ee=!0:G??=D.get(we.key)?.part)}if(G===void 0||ee){M.push($);continue}let se=R.get(G)??[],K=se.find(we=>we.objectApiName===P);K?K.count++:se.push({objectApiName:P,count:1}),R.set(G,se)}M.length>0?F.set(P,M):F.delete(P)}R.size>0&&(a.otherParts=[...R].map(([P,v])=>({part:P,objects:v})));let k=new Map;for(let[P,v]of h)k.set(P,v.objectApiName);for(let[P,v]of F)for(let M of v)k.set(W(M.id),P);let I=[],j=new Set;for(let[P,v]of F)for(let M of v){let $=[];for(let G of M.references){let ee=k.get(G.key);if(!ee)continue;h.has(G.key)&&j.add(G.key);let{cascade:se}=await E.relation(ee,P,G.field);$.push({key:G.key,cascade:se})}I.push({key:W(M.id),created:M.created,automatedProcess:S.has(M.creator),references:$})}let L=await Vd(n,b,h,F,E,a,c);if(!L)return l();for(let P of L)j.add(P.from);if(!await Jd(n,h,j,c))return l();let B=Eo({anchors:h,candidates:I,pointers:L,runSpan:w,window:s,removalBegan:f,madeEarlier:new Set((t.madeEarlier??[]).map(W)),lateEarlier:new Set((t.lateEarlier??[]).map(W))});return Hd(F,B,t,o,u,i),c()?l():(await Yd(n,E,o,{user:r,span:m,lastWrite:u,removalSpans:i,isRun:P=>h.has(P)||e.remap.has(P)}),a.found.push(..._),t.muted&&(a.muted=t.muted),o.ordering={query:P=>n.query(P),queryDeleted:P=>n.queryDeleted(P),describe:async P=>await E.now(P)??n.describe(P),describeGlobal:()=>n.describeGlobal(),destroy:(P,v)=>n.destroy(P,v),update:(P,v)=>n.update(P,v),serverTime:()=>n.serverTime(),userId:()=>n.userId()},o)}var li={untied:0,late:1,madeOver:2,made:3};async function Yd(n,e,t,r){let o=new Map;for(let d of t.rows.values())for(let m of d)o.set(W(m.id),m);if(o.size===0||t.rows.has(pe))return;let s=(await jo(n,{has:d=>o.has(d)||r.isRun(d),start:r.span.from,end:r.span.to,user:r.user})).filter(d=>!r.isRun(W(d.id))&&d.names.some(m=>o.has(m)));if(s.length===0)return;let i=await gi(pe,e.of);if("reason"in i){t.listing.unread.push({objectApiName:pe,reason:i.reason});return}let a=new Map,c=s.map(d=>{let m=d.names.flatMap(O=>{let A=o.get(O);return A?[A]:[]});a.set(d.id,m.map(O=>W(O.id)));let h=m.reduce((O,A)=>li[A.class]<li[O]?A.class:O,"made"),w=Math.max(...m.map(O=>O.created)),b=d.modifiedBy!==void 0&&W(d.modifiedBy)===W(r.user)&&d.modified<=w+6e4;return{id:d.id,created:d.created,modified:b?Math.min(d.modified,d.created):d.modified,...d.modifiedBy!==void 0?{modifiedBy:W(d.modifiedBy)}:{},class:h,turn:"before"}});t.rows.set(pe,c),t.reports=a;let l={made:0,madeOver:0,late:0,untied:0},p=0,u={};for(let d of c)l[d.class]++,Gt(d,r.lastWrite,r.removalSpans)&&(p++,u[d.class]=(u[d.class]??0)+1);let{listing:f}=t;f.found.push({objectApiName:pe,count:c.length,names:[],classes:{...l,...p>0?{changed:p,changedIn:u}:{}}}),l.late>0&&(f.late=[...f.late??[],{objectApiName:pe,count:l.late}]),l.untied>0&&f.untied&&(f.untied={...f.untied,objects:[...f.untied.objects,{objectApiName:pe,count:l.untied}]})}function Gt(n,e,t){let r=Math.max(e,n.created)+2e3;return!(n.modified<=r)&&!Zd(n,t)}function Zd(n,e){return n.modifiedBy!==void 0&&e.some(t=>n.modifiedBy===W(t.userId)&&n.modified>=oe(t.first)&&n.modified<=oe(t.last))}async function Ug(n,e,t=[]){return(await hi(n,e,t)).listing}function Qd(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 Wg(n,e,t){let r=()=>e.signal?.aborted===!0,o=ho(),s=new Set,i=new Set,a=new Set,c=new Set,l=[],p="new",u,f,d,m=new Map,h={unread:[],handWork:[]},w=new Map,b=new Map,O=async(N,C)=>{let F=N.lastWrite??Number.NaN,_=new Set,D=new Map;for(let[L,B]of C){let P=B.filter(v=>t.includeChanged||!Gt(v,F,t.removalSpans)).map(v=>v.id);for(let v of P)_.add(v);D.set(L,P)}if(_.size===0||!N.window)return;let R=new Set(e.created.flatMap(({ids:L})=>L.map(W))),k=N.ordering??n,I=No(k,{runStart:N.window.from,runEnd:F,runRecords:{has:L=>R.has(L)},taken:_,removalSpans:t.removalSpans,includeChanged:t.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{}}),j=await mn(k,[...C.keys()].map(L=>({objectApiName:L})));for(let{objectApiName:L}of j){if(L===pe)continue;let B=D.get(L)??[];if(B.length===0)continue;if(r())return;let P=await I(L,B);P.reason!==void 0&&b.set(L,P.reason);for(let v of B)P.held.has(W(v))&&(_.delete(v),w.set(v,P.holders))}A(N,C,_)},A=(N,C,F)=>{let _=N.reports;if(!_)return;let D=new Set([...C].filter(([R])=>R!==pe).flatMap(([,R])=>R.filter(k=>F.has(k.id)).map(k=>W(k.id))));for(let R of C.get(pe)??[])w.has(R.id)||(_.get(R.id)??[]).every(k=>D.has(k))||(F.delete(R.id),w.set(R.id,["DuplicateRecordItem"]))},g=(N,C)=>{N.result.alreadyGone++,N.along.has(C)&&(N.result.withRemoval=(N.result.withRemoval??0)+1)},y=(N,C,F)=>{C.forEach((_,D)=>{let R=F[D];if((R.lockResends!==void 0||N.lockResent.has(_))&&N.lockResent.set(_,R.kind),R.kind==="refused"){N.refused.set(_,R.reason),R.limit&&N.limited.add(_);return}N.refused.delete(_),N.limited.delete(_),c.add(_),R.kind==="deleted"?N.result.deleted++:g(N,_)})},S=async(N,C,F)=>{for(let _=0;_<C.length;_+=Ue){if(r())return!1;let D=C.slice(_,_+Ue),R=N.result.deleted,k=await Ao(n,N.result.objectApiName,D,o,{stopped:r,settle:(I,j)=>y(N,I,[...j])});if(F&&N.result.deleted>R){let I=N.result.deleted-R;N.result.afterRemoval=(N.result.afterRemoval??0)+I,F==="under"&&(N.result.afterRemovalUnder=(N.result.afterRemovalUnder??0)+I)}if(k)return!1}return!0},E=()=>l.reduce((N,C)=>N+C.result.deleted,0),T=async()=>{let N=h.left??[];if(N.length===0||!d)return;let C=d.rows,F=[],_=[];for(let R of N){let k=[],I=[];for(let j of R.objects){let L=(C.get(j.objectApiName)??[]).filter(v=>v.class===R.class).map(v=>v.id),B=r()?[]:(await hn(L,v=>be(n,j.objectApiName,[],v),()=>!0)).gone;for(let v of B)c.add(v);let P=Math.min(B.length,j.count);j.count>P&&k.push({...j,count:j.count-P}),P>0&&I.push({objectApiName:j.objectApiName,count:P})}k.length>0&&F.push({...R,objects:k}),I.length>0&&_.push({class:R.class,objects:I})}if(_.length===0)return;let D={...h};delete D.left,h={...D,...F.length>0?{left:F}:{},goneAlong:_}},x=()=>(f??=(async()=>{let N=await hi(n,e,t.removalSpans);d=N;let{listing:C}=N;if(h={...C.window?{window:C.window}:{},unread:[...C.unread,...C.found.filter(R=>R.overBound).map(R=>({objectApiName:R.objectApiName,reason:`More than ${Kn} 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.`}))],...C.automationGaps?{automationGaps:C.automationGaps}:{},handWork:C.handWork},N.stopped){p="cancelled";return}for(let R of N.rows.values())for(let k of R)k.class==="made"||k.class==="madeOver"?i.add(k.id):k.class==="late"&&a.add(k.id);if(C.refusal!==void 0){p="refused",u=C.refusal;return}let F=t.sweepUntied===!0&&C.untied?.refusal===void 0,_=R=>R.class==="made"||R.class==="madeOver"||R.class==="late"&&t.sweepLate===!0||R.class==="untied"&&F;if(m=new Map([...N.rows].map(([R,k])=>[R,k.filter(_)]).filter(([,R])=>R.length>0)),await O(N,m),r()){p="cancelled";return}if(t.approve&&m.size>0){let R=await t.approve(C);if(R!==void 0){p="refused",u=R;return}}let D=Qd(C,t);D.length>0&&(h={...h,left:D}),p="asked"})(),f);return{automationMade:s,made:i,late:a,gone:c,get listing(){return d&&!d.stopped?d.listing:void 0},get takes(){return p==="asked"?[...m.keys()]:[]},ask:x,async first(N){if(N&&(o=N),await x(),p!=="asked"||!d)return!1;let C=d,F=m,_=C.lastWrite??Number.NaN,D=await mn(C.ordering??n,[...F.keys()].map(k=>({objectApiName:k}))),R=[];for(let{objectApiName:k}of D){let I=F.get(k)??[],j={result:{objectApiName:k,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};l.push(j);let L=[];for(let B of I){if(Gt(B,_,t.removalSpans)&&!t.includeChanged){j.result.keptChanged++;continue}let P=w.get(B.id);if(P){j.result.keptDependents=(j.result.keptDependents??0)+1,j.result.heldBy=[...new Set([...j.result.heldBy??[],...P])];continue}s.add(B.id),B.turn==="before"?L.push(B.id):j.later.push(B.id),B.turn==="with"&&j.along.add(B.id)}R.push([j,L])}for(let[k,I]of R)if(!await S(k,I))return p="cancelled",E()>0;return p="first",E()>0},async afterRemoval(N){if(N&&(o=N),p!=="first")return!1;let C=E();for(let F of l){let _=F.later.splice(0),D=_.filter(k=>F.along.has(k)),R=_.filter(k=>!F.along.has(k));if(!await S(F,R,"pointedAt")||!await S(F,D,"under"))return p="cancelled",E()>C}if(E()>0)for(let F of l){let _=[...F.refused.keys()].filter(D=>!F.limited.has(D));if(!await S(F,_))return p="cancelled",E()>C}for(let F of l){if(r())break;let{gone:_}=await hn([...F.refused.keys()],D=>be(n,F.result.objectApiName,[],D),()=>!0);for(let D of _)F.refused.delete(D),F.lockResent.has(D)&&F.lockResent.set(D,"gone"),g(F,D),c.add(D)}return await T(),p="done",E()>C},result(){if(p==="refused")return{status:"refused",refusal:u??"",objects:[],...h};if(p==="new"||p==="asked")return{status:"cancelled",objects:[],...h};let N=l.map(({result:F,refused:_,lockResent:D})=>{F.refused=_.size;let R=b.get(F.objectApiName);return F.reasons=[...new Set([...R!==void 0&&(F.keptDependents??0)>0?[`What hangs from them could not be read, and they were kept: ${R}`]:[],...Io(F.objectApiName,o),...ko(D.values()),..._.values()])].slice(0,Fd),F}),C=l.some(F=>F.later.length>0);return{status:Xd(N,p==="cancelled",C,el(h,t)),objects:N,...h}}}}function Xd(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 el(n,e){return(n.left??[]).some(t=>t.class==="late"&&e.sweepLate===!0||t.class==="untied"&&e.sweepUntied===!0)}function Gg(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 Vg(n){return n.objects.filter(e=>e.deleted+e.refused>0).map(e=>({...eo(e.objectApiName),deleted:e.deleted,failed:e.refused}))}function Jg(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 Hg(n){return n.found.reduce((e,t)=>e+t.count,0)}function Kg(n){return n.found.map(e=>e.objectApiName)}var tl=15e3,Qg=2,nl=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function rl(n,e){try{let{user_id:t}=await new Ct(tl).withTimeout(`${e} run user`,async()=>n());return typeof t=="string"&&nl.test(t)?t:void 0}catch{return}}function Xg(n,e,t){n?.runUser&&rl(e,t).then(r=>{r!==void 0&&n.runUser?.(r)})}var ol=30*6e4,sl=16,il=["map_value","leave_empty","set_default","truncate","map_record_type","exclude_object","skip_rows","ignore"];function nm(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()])}var wi=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<=sl)break;this.tried.delete(s)}}before(e,t=Date.now()){let r=this.tried.get(e),o=a=>a===void 0||t-a>ol||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 al(n){let e={flow:0,trigger:0,process:0,workflowRule:0,unread:[]};if(!("automation"in n))return{...e,unread:["automation"]};for(let t of es(n.automation))e[t.kind]++;return e.unread=ns(n.automation).map(t=>t.part),e}function cl(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 ts(n.automation,r))t[o.kind]++;return t}function dl(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 il.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 ll(n){let e=n.objects.reduce((t,r)=>t+r.sourceRows,0)+n.noRecordDrawn.reduce((t,r)=>t+r.sourceRows,0);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,kept:n.rows,inSource:e}}var bi=class{constructor(e,t){this.config=e;this.before=t}config;before;confirmed=[];fired;firedOnUpdate;deliverability;sampleFit;automationRead(e,t=[]){this.fired=al(e),this.firedOnUpdate=cl(e,t)}emailsRead(e){this.deliverability=e}confirm(e){this.confirmed.includes(e)||this.confirmed.push(e)}sampled(e){this.sampleFit=ll(e)}fit(){return this.sampleFit?{...this.sampleFit}:void 0}context(e){let t=dl(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 ul="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",fl="RHZ",pl=/[A-Za-z0-9]{3}RHZ[A-Za-z0-9]{12}/g,Zn="000",yi=62**8;function Vt(n,e){let t=n!==null&&/^[A-Za-z0-9]{3}$/.test(n)?n:Zn,r="";for(let s=e;r.length===0||s>0;s=Math.floor(s/62))r=ul[s%62]+r;let o=Et(`${t}${fl}${r.padStart(9,"0")}`);if(o===void 0)throw new Error(`No placeholder id for record ${e}`);return o}var Jt=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:Vt(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,c]of Object.entries(o))a!=="Id"&&a!=="attributes"&&(i[a]=c);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=_r(r);if(s)return this.personContactsOf(s,l=>e(t,Mr(l),o));let i=Vr(r);if(i)return this.ownersOf(i,l=>e(t,Gr(l),o));let a=Hr(r);if(a)return this.teamOf(a,l=>e(t,Jr(a.objectApiName,a.fields,l)),()=>e(t,Wr));let c=qr(r);return c?this.rolesOf(c,l=>e(t,$r(l,c.fields),o)):this.namesAPlaceholder(r)?[]:e(t,r,o)}}async rolesOf(e,t){let r=e.opportunities.filter(c=>!this.rowOf(c)),o=r.length>0?await t(r):[],s=e.opportunities.flatMap(c=>{let l=this.rowOf(c),p=l?.objectApiName==="Opportunity"?l.fields[ln]:void 0;return l&&typeof p=="string"&&p!==""?[{id:c,row:l,contact:p}]:[]});if(s.length===0)return o;let i=await this.prefixOf(Br),a=new Date().toISOString();return[...o,...s.map(({id:c,row:l,contact:p})=>{let u=Vt(i,yi+this.platformTeam.size+this.platformRoles.size);return this.platformRoles.set(u.slice(0,15),l),zr({...Object.fromEntries(e.fields.map(f=>[f,null])),Id:u,OpportunityId:c,[ln]:p,...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(w=>!this.rowOf(w)),c=a.length>0?await t(a):[],l=i.filter(w=>this.rowOf(w)?.objectApiName==="Opportunity");if(l.length===0)return c;let p=Lr[o],u=o===dn,f=u?(await r()).flatMap(w=>typeof w.Id=="string"&&(w.IsTotalValidated===!0||w.IsTotalValidated==="true")?[w.Id]:[]):[void 0],d=await this.prefixOf(u?dn:Dr),m=Ur[o]??{},h=[];for(let w of l){let b=await this.ownerOf(w);if(b!==void 0)for(let O of f){let A=Vt(d,yi+this.platformTeam.size+this.platformRoles.size);this.platformTeam.set(A.slice(0,15),this.rowOf(w)),h.push({Id:A,OpportunityId:w,[p]:b,...O!==void 0?{SplitTypeId:O}:{},...Object.fromEntries(s.map(g=>[g,m[g]??null]))})}}return[...c,...h]}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===At?[a]:[]);if(s.length===0)return o;let i=await this.prefixOf(xr);return[...o,...s.map(a=>{let c=this.rowOf(a);if("Name"in c.fields)return{Id:a,[ze]:null};let l=Vt(i,c.seq);return this.personContacts.set(l.slice(0,15),c),{Id:a,[ze]:l}})]}namesAPlaceholder(e){for(let[t]of e.matchAll(pl))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 im(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 Oi="UNKNOWN_ERROR",Ai="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",gl=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"]),Ri=new Set(["FIELD_CUSTOM_VALIDATION_EXCEPTION","INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST","FIELD_FILTER_VALIDATION_EXCEPTION"]),ml=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"]}]]),Qn="FIELD_CUSTOM_VALIDATION_EXCEPTION";function dm(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 hl(n,e,t){if(e.statusCode!==Qn||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 Ht(n,e){let t=n.detail?.[e];return typeof t=="number"?t:0}function Si(n){let e=n.detail?.fields;return Array.isArray(e)?e:[]}function wl(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 bl(n,e){if(gl.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 yl(n,e){let t=n.fields.RecordTypeId;return typeof t=="string"?e.get(t.slice(0,15)):void 0}function Rl(n,e,t,r){let{row:o}=n,s=e.fields[0],i=t===Nr?"unique_value_collision":"rehearsal_refusal";return{id:et(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||Oi,a=bl(s,e),c=n.onUpdate?void 0:hl(s.objectApiName,e,o),l=d=>{let m=d===void 0?void 0:s.fields[d];return{statusCode:i,fields:[...e.fields],...a!==void 0?{message:a}:{},...c!==void 0?{rule:c}:{},rowsOfTheRun:n.standsFor,...i==="STRING_TOO_LONG"&&typeof m=="string"?{valueLength:m.length}:{},...Ri.has(i)&&d!==void 0&&!n.onUpdate?{writtenWithoutTheField:!0}:{}}};if(n.onUpdate){let d=e.fields[0];return[{id:et("rehearsal_update_refusal",s.objectApiName,d,void 0,i),kind:"rehearsal_update_refusal",severity:"warning",source:"rehearsal",objectApiName:s.objectApiName,...d!==void 0?{field:d}:{},value:i,rows:1,detail:l(d),decisions:["exclude_object","ignore"]}]}if(n.linked)return[Rl(n,e,i,l)];let p=ml.get(i);if(p&&e.fields.length>0)return(p.kind==="required_field_missing"?e.fields:e.fields.slice(0,1)).map(m=>{let h=s.fields[m],w=p.kind==="picklist_value_refused",b=w?yl(s,t):void 0,O=w&&typeof h=="string"?h:void 0,A=O!==void 0?wl(r.get(s.objectApiName)?.get(m),O,b):void 0;return{id:et(p.kind,s.objectApiName,m,b,O),kind:p.kind,severity:p.severity,source:"rehearsal",objectApiName:s.objectApiName,field:m,...b!==void 0?{recordType:b}:{},...O!==void 0?{value:O}:{},rows:1,detail:{...l(m),...A!==void 0?{reason:A}:{}},decisions:[...p.decisions],...p.severity==="warning"?{defaultDecision:"leave_empty"}:{}}});let u=e.fields[0],f=u!==void 0&&Ri.has(i);return[{id:et("rehearsal_refusal",s.objectApiName,u,void 0,i),kind:"rehearsal_refusal",severity:f?"warning":"blocking",source:"rehearsal",objectApiName:s.objectApiName,...u!==void 0?{field:u}:{},value:i,rows:1,detail:l(u),decisions:u!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],...f?{defaultDecision:"leave_empty"}:{}}]}function Ii(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:Oi,message:"",fields:[]}],a=an(...i.map(c=>Sl(s,c,e,t,r)));for(let c of a){let l=o.get(c.id);if(!l){o.set(c.id,c);continue}let p=Math.max(Ht(l,"valueLength"),Ht(c,"valueLength"));o.set(c.id,{...l,rows:l.rows+1,detail:{...c.detail,...l.detail,rowsOfTheRun:Ht(l,"rowsOfTheRun")+Ht(c,"rowsOfTheRun"),fields:[...new Set([...Si(l),...Si(c)])],...p>0?{valueLength:p}:{}}})}}return an([...o.values()])}function Ol(n){return n!=null&&n!==""}function Al(n){let e=n.fields.RecordTypeId,t=Object.keys(n.fields).filter(r=>r!=="attributes"&&Ol(n.fields[r])).sort();return[n.objectApiName,typeof e=="string"?e:"",t.join(",")].join("|")}function ki(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 Il(n){let e=n.fields.Status;return[n.objectApiName,Object.keys(n.fields).sort().join(","),typeof e=="string"?e:""].join("|")}function Ei(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=Il(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 ji(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((c,l)=>c.seq-l.seq)){let c=new Set,l=new Set;for(let u of Object.values(a.fields)){let f=e(u);f&&f.seq!==a.seq&&c.add(f.seq);let d=f?void 0:t(u);d&&d.seq!==a.seq&&r.has(d.seq)&&(c.add(d.seq),l.add(d.seq))}let p=[...c].sort((u,f)=>u-f);o.set(a.seq,p),l.size>0&&i.set(a.seq,[...l].sort((u,f)=>u-f)),s.set(a.seq,p.reduce((u,f)=>Math.max(u,(s.get(f)??0)+1),0))}return{bySeq:r,parents:o,levels:s,...i.size>0?{personContactsNamed:i}:{}}}function Ni(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 c=e.get(a);c===void 0?i.add(a):"seq"in c&&c.seq!==o&&i.add(c.seq)}t.set(o,[...i].sort((a,c)=>a-c))}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 Ze(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 Xn(n,e){let t=new Set;for(let r of n){t.add(r.seq);for(let o of Ze(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 tr=5,nr=25,kl=200,El=10,jl="PROCESSING_HALTED",Nl="SandForge_Rehearsal_Rollback__c";function rr(n,e=0){return Math.max(0,nr-n-e-1)}function Xt(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 Ci(n,e,t=[],r=new Map){let o=new Map;n.collections.forEach((a,c)=>a.seqs.forEach(l=>o.set(l,c)));let s=new Set([...Xt(n.collections.flatMap(a=>a.seqs),e),...t.flatMap(a=>a.contacts??[])]),i=[];for(let a of s){let c=o.get(a),l=r.get(a),p=c??(l===void 0?void 0:"id"in l?-1:o.get(l.seq));p!==void 0&&i.push({account:a,after:p})}return i.sort((a,c)=>a.after-c.after||a.account-c.account)}function Cl(n,e,t){let r=[...e].flatMap(a=>{let c=t.get(a);return c?[c]:[]}).sort((a,c)=>a.objectApiName.localeCompare(c.objectApiName)||a.seq-c.seq),o=[],s,i=new Set;for(let a of r){let c=!i.has(a.objectApiName);(!s||s.seqs.length>=kl||c&&i.size>=El)&&(s={level:n,seqs:[]},i=new Set,o.push(s)),s.seqs.push(a.seq),i.add(a.objectApiName)}return o}function er(n,e){return[...n.keys()].sort((t,r)=>t-r).flatMap(t=>Cl(t,n.get(t)??[],e))}function en(n,e){let t=p=>e.levels.get(p)??0,r=[...n].sort((p,u)=>t(u.seq)-t(p.seq)||p.seq-u.seq),o=[],s=[],i=new Set,a=new Map,c=(p,u)=>{let f=new Map([...p].map(([d,m])=>[d,new Set(m)]));for(let d of u){let m=f.get(t(d))??new Set;m.add(d),f.set(t(d),m)}return f},l=p=>{let u=er(p,e.bySeq).length,f=Xt([...p.values()].flatMap(d=>[...d]),e).length;return u<=tr&&u+f<nr};for(let p of r){if(i.has(p.seq))continue;let u=[p.seq,...Ze(p.seq,e)],f=c(new Map,u);if(!l(f)){s.push(p.seq);continue}let d=c(a,u);l(d)?a=d:(o.push({collections:er(a,e.bySeq)}),a=f);for(let m of u)i.add(m)}return a.size>0&&o.push({collections:er(a,e.bySeq)}),{calls:o,beyond:s.sort((p,u)=>p-u)}}function Zt(n){return`rows${n}`}function or(n){return`update${n}`}var Pi="rollback";function Qt(n){return`contact${n}`}function Pl(n,e,t){let r=o=>t.filter(s=>s.after===o).map(s=>Qt(s.account));return[...r(-1),...n.collections.flatMap((o,s)=>[Zt(s),...r(s)]),...Array.from({length:e},(o,s)=>or(s)),Pi]}function Ti(n,e,t,r,o,s=[],i=new Map,a={of:()=>{},reads:[]}){let{reads:c}=a;if(s.length>rr(n.collections.length,c.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 ${nr} subrequests`);let l=new Map;n.collections.forEach((g,y)=>g.seqs.forEach((S,E)=>l.set(S,`@{${Zt(y)}[${E}].id}`)));let p=g=>{let y=l.get(g.seq);if(y!==void 0)return y;let S=i.get(g.seq);if(S!==void 0)return"id"in S?S.id:l.get(S.seq)},u=new Set(c.map(g=>g.account)),f=g=>{let y=t(g);if(y){let E=p(y);return E===void 0?void 0:{sent:E}}let S=a.of(g);return S?u.has(S.seq)?{sent:`@{${Qt(S.seq)}.${ze}}`}:void 0:{sent:g}},d=g=>g.seqs.map(y=>{let S=e.bySeq.get(y);if(!S)throw new Error(`Row ${y} is not among the rows the run creates`);return S}),m=(g,y)=>({method:"POST",url:`${r}/composite/sobjects`,referenceId:Zt(y),body:{allOrNone:!1,records:d(g).map(S=>{let E={attributes:{type:S.objectApiName}};for(let[T,x]of Object.entries(S.fields)){if(T==="attributes"||T==="Id")continue;let N=f(x);if(N===void 0)throw new Error(`${S.objectApiName} row ${S.seq} names a record the run creates that its call does not hold`);E[T]=N.sent}return E})},httpHeaders:{...o}}),h=({account:g})=>{let y=e.bySeq.get(g),S=y?p(y):void 0;if(S===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/${At}/${S}?fields=${ze}`,referenceId:Qt(g)}},w=g=>c.filter(y=>y.after===g).map(h),b=[...w(-1),...n.collections.flatMap((g,y)=>[m(g,y),...w(y)])];s.forEach((g,y)=>{let S=l.get(g.rowSeq);if(S===void 0)throw new Error(`An update of ${g.objectApiName} names a record its call does not create`);let E={};for(let[T,x]of Object.entries(g.fields)){if(T==="attributes"||T==="Id")continue;let N=f(x);if(N===void 0)throw new Error(`An update of ${g.objectApiName} names a record the run creates that its call does not hold`);E[T]=N.sent}b.push({method:"PATCH",url:`${r}/sobjects/${g.objectApiName}/${S}`,referenceId:or(y),body:E,httpHeaders:{...o}})});let O=n.collections[0]?.seqs[0],A=O===void 0?void 0:e.bySeq.get(O);if(!A)throw new Error("A rehearsal call holds no row");return b.push({method:"PATCH",url:`${r}/sobjects/${A.objectApiName}/${Tl(A.placeholderId)}`,referenceId:Pi,body:{[Nl]:!0}}),{allOrNone:!0,collateSubrequests:!1,compositeRequest:b}}function Tl(n){return Et(`${n.slice(0,3)}000000000000`)??"000000000000000AAA"}var Fl=q({body:Re(),httpStatusCode:J(),referenceId:z().optional()}).loose(),vl=q({compositeResponse:H(Fl)}).loose(),Yt=H(q({errorCode:z().optional(),statusCode:z().optional()}).loose()),xl=H(q({success:hr()}).loose());function Kt(n){let e=Yt.safeParse(n.body);return n.httpStatusCode>=400&&e.success&&e.data.length>0&&e.data.every(t=>(t.errorCode??t.statusCode)===jl)}function Fi(n,e,t=0,r=()=>{},o=[]){let s=vl.safeParse(n);if(!s.success)throw new Error("The target answered the rehearsal with no composite answer");let i=s.data.compositeResponse,a=Pl(e,t,o),c=a.length,l=i[c-1];if(i.length!==c||!l)throw new Error(`The target answered ${i.length} subrequests of the ${c} the rehearsal sent`);let p=i.findIndex((m,h)=>m.referenceId!==void 0&&m.referenceId!==a[h]);if(p!==-1)throw new Error(`The target ran the rehearsal's subrequests out of the order sent (${String(i[p]?.referenceId)} in place of ${a[p]}): no verdict can be read from it`);let u=m=>i[a.indexOf(m)];for(let{account:m}of o){let h=u(Qt(m));if(h.httpStatusCode<400||Kt(h))continue;let w=Yt.safeParse(h.body),b=w.success?w.data[0]?.errorCode??w.data[0]?.statusCode:"";throw new Error(`The target refused to read back the contact the platform wrote with a person account (status ${h.httpStatusCode}${b?`, ${b}`:""}): no verdict can be read past it`)}let f=e.collections.map((m,h)=>{let w=u(Zt(h));if(Kt(w))return{kind:"halted"};let b=xl.safeParse(w.body);if(w.httpStatusCode<400&&b.success){if(b.data.length!==m.seqs.length)throw new Error(`The target answered ${b.data.length} rows of the ${m.seqs.length} a request sent`);return{kind:"rows",outcomes:b.data.map((A,g)=>jt(A,r(m.seqs[g])??""))}}let O=Yt.safeParse(w.body);if(w.httpStatusCode>=400&&O.success&&O.data.length>0)return{kind:"refused",errors:O.data.map(pn)};throw new Error(`The target answered a request of the rehearsal with status ${w.httpStatusCode}`)}),d=Array.from({length:t},(m,h)=>{let w=u(or(h));if(Kt(w))return{kind:"halted"};if(w.httpStatusCode<400)return{kind:"saved"};let b=Yt.safeParse(w.body);if(b.success&&b.data.length>0)return{kind:"refused",errors:b.data.map(pn)};throw new Error(`The target answered an update of the rehearsal with status ${w.httpStatusCode}`)});if(l.httpStatusCode<400)return{kind:"not_rolled_back",ids:f.flatMap(m=>m.kind==="rows"?m.outcomes.filter(h=>h.success).map(h=>h.id):[])};if(Kt(l)&&sr(f)===-1&&!d.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:f,updates:d}}function sr(n){return n.findIndex(e=>e.kind==="refused"||e.kind==="rows"&&e.outcomes.some(t=>!t.success))}function vi(n,e,t=()=>{}){let r=new Map,o=sr(e);return n.collections.forEach((s,i)=>{if(o!==-1&&i>o)return;let a=e[i];s.seqs.forEach((c,l)=>{if(a.kind==="refused"){r.set(c,{passed:!1,errors:a.errors});return}let p=a.kind==="rows"?a.outcomes[l]:void 0;if(!p||p.success){r.set(c,{passed:!0});return}let u=bo(p,t(c));r.set(c,{passed:!1,errors:p.errorDetails??[],...u.kind==="linked"?{linkedTo:u.id}:{}})})}),r}function xi(n,e){let t=new Map;if(sr(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 Ml(n,e){let t=e.targetRecordTypes;if(!t)return n;let r=new Set(n.flatMap(s=>s.recordType!==void 0&&lo(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?uo(i):void 0)}return n.map(s=>fo(s,o.get(s.objectApiName)))}async function _l(n,e){let t=[...new Set(n.filter(({errors:r})=>r.some(o=>o.statusCode===Qn)).map(({row:r})=>r.objectApiName))];if(t.length===0||!e.validationRules)return[];try{return await e.validationRules(t)}catch{return[]}}async function Dl(n,e){let t=new Map;for(let{row:s,errors:i,onUpdate:a}of n)if(!a)for(let c of i){let l=c.fields[0];c.statusCode!==Ai||l===void 0||t.set(s.objectApiName,(t.get(s.objectApiName)??new Set).add(l))}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 c=new Map;for(let l of a)!i.has(l.name)||!l.picklistValues||c.set(l.name,{values:l.picklistValues,...l.controllerName?{controllerName:l.controllerName}:{}});r.set(s,c)}return r}var ir=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},tn=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 Ll(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 Mi(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 Bl(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,c]of i.outcomes.entries()){let l=s.seqs[a];if(c.success&&c.id.slice(0,15)===r&&l!==void 0)return{seq:l}}}return{id:n}}function $l(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 c=a?void 0:t(i);c&&(o.add(c.seq),s.add(c.seq))}return{seq:n.seq,objectApiName:n.objectApiName,rowSeq:r.seq,fields:n.fields,needs:[...o],...s.size>0?{contacts:[...s]}:{}}}function ar(n,e,t){let r=new Set(n.collections.flatMap(i=>i.seqs)),o=new Set(Xt(r,t)),s=[];for(let i of e){if(!i.needs.every(c=>r.has(c)))continue;let a=(i.contacts??[]).filter(c=>!o.has(c));if(s.length+1>rr(n.collections.length,o.size+a.length))break;for(let c of a)o.add(c);s.push(i)}return s}function _i(n,e){let t=o=>{let s=Xn(o.flatMap(c=>c.needs.flatMap(l=>{let p=e.bySeq.get(l);return p?[p]:[]})),e),i=en(s,e),[a]=i.calls;return i.calls.length===1&&i.beyond.length===0&&a&&ar(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 c of n.slice(o+1)){let l=t([...i,c]);l&&(i=[...i,c],a=l)}return{call:a,beyond:r}}return{beyond:r}}function ql(n,e,t){let r=[...e],o=i=>{let a=new Set(ar(i,r,t));return r=r.filter(c=>!a.has(c)),a.size};for(let i of n)o(i);let s=0;for(;r.length>0;){let{call:i,beyond:a}=_i(r,t),c=new Set(a);if(r=r.filter(l=>!c.has(l)),!i||o(i)===0)break;s++}return n.length+s}async function Om(n){let e=new Jt(n.keyPrefixOf,n.runningUser);await n.prepare(e);let t=e.rows,r=R=>e.rowOf(R),o=R=>e.personContactOf(R),s=ji(t,r,o),i=ki(t),a=Ei(e.updated.flatMap(R=>{let k=$l(R,r,o);return k?[k]:[]})),c=a.updates,l=Xn([...i.rows,...c.flatMap(R=>R.needs.flatMap(k=>{let I=s.bySeq.get(k);return I?[I]:[]}))],s),p=R=>i.standsFor.get(R)??1,u=R=>{let k=s.bySeq.get(R)?.placeholderId.slice(0,3);return k===void 0||k===Zn?null:k},f=new Map,d=new Map,m=new Map,h=new Map,w=new Map,b=s,O=en(l,s);for(let R of O.beyond)d.set(R,"beyond_a_call");let A=ql(O.calls,c,s),g=A*tr,y=0;if(A>0){if(n.signal?.aborted)throw new tn(0);n.onProgress?.({phase:"confirming",calls:A}),await n.confirm({rows:t.length,sampled:l.length,updates:Mi(c).map(({objectApiName:R,count:k})=>({objectApiName:R,updates:k})),calls:A,maxCalls:g,objects:Mi(l).map(({objectApiName:R,count:k})=>({objectApiName:R,rows:k}))})}let S=R=>{let k=f.get(R);return k?.passed===!1&&k.linkedTo===void 0},E=R=>[R,...Ze(R,b)].some(S),T=R=>{if(w.has(R.rowSeq))return"record_linked";for(let k of R.needs){if(E(k))return"parent_refused";let I=d.get(k);if(I)return I}};for(;;){if(n.signal?.aborted)throw new tn(y);let R=l.filter(M=>f.has(M.seq)||d.has(M.seq)?!1:Ze(M.seq,b).some(S)?(d.set(M.seq,"parent_refused"),!1):!0),k=c.filter(M=>{if(m.has(M.seq)||h.has(M.seq))return!1;let $=T(M);return $?(h.set(M.seq,$),!1):!0});if(R.length===0&&k.length===0)break;if(y>=g){for(let M of R)d.set(M.seq,"call_budget");for(let M of k)h.set(M.seq,"call_budget");break}let I;if(R.length>0){let M=en(R,b);for(let $ of M.beyond)d.set($,"beyond_a_call");I=M.calls[0]}else{let M=_i(k,b);for(let $ of M.beyond)h.set($.seq,"beyond_a_call");I=M.call}if(!I)continue;let j=ar(I,k.filter(M=>!h.has(M.seq)),b);y++,n.onProgress?.({phase:"rehearsing",call:y,calls:Math.max(A,y)});let L=Ci(I,b,j,w),B=Ti(I,s,r,n.apiPath,n.writeHeaders,j,w,{of:o,reads:L}),P=Fi(await n.composite(B),I,j.length,M=>s.bySeq.get(M)?.objectApiName,L);if(P.kind==="not_rolled_back")throw new ir(P.ids,Ll(P.ids,t));let v=new Map;for(let[M,$]of vi(I,P.collections,u))f.set(M,$),!$.passed&&$.linkedTo!==void 0&&v.set(M,Bl($.linkedTo,I,P.collections));for(let[M,$]of xi(j,P))m.set(M,$);if(v.size>0){for(let[M,$]of v)w.set(M,$);b=Ni(s,w),c=c.map(M=>({...M,needs:M.needs.flatMap($=>{let G=w.get($);return G===void 0?[$]:"seq"in G?[G.seq]:[]})}))}}let x=[],N=0,C=0;for(let R of l){let k=f.get(R.seq);if(!k)continue;if(k.passed){N++;continue}let I=k.linkedTo!==void 0;I&&C++,x.push({row:R,errors:k.errors,standsFor:p(R.seq),...I?{linked:!0}:{}})}let F=0,_=0;for(let R of c){let k=m.get(R.seq),I=s.bySeq.get(R.rowSeq);if(!k||!I)continue;let j=a.standsFor.get(R.seq)??1;if(_+=j,k.passed){F++;continue}x.push({row:{...I,fields:{...I.fields,...R.fields}},errors:k.errors,standsFor:j,onUpdate:!0})}let D=new Map;for(let[R,k]of d){let j=`${s.bySeq.get(R)?.objectApiName??""}|${k}`;D.set(j,(D.get(j)??0)+1)}return{gaps:await Ml(Ii(x,n.recordTypeNames,await Dl(x,n),await _l(x,n)),n),rows:t.length,sampled:l.length,judged:f.size,passed:N,linked:C,notJudged:d.size,notJudgedWhy:[...D].map(([R,k])=>{let[I,j]=R.split("|");return{objectApiName:I,rows:k,reason:j}}),updates:e.updates,updatesJudged:m.size,updatesPassed:F,updatesNotRehearsed:e.updates-_,calls:y,plannedCalls:A}}var zl="QuoteLineItem",cr="Quote",nn="Opportunity",dr="OpportunityLineItem",fr="SyncedQuoteId",pr="QuoteId",gr="OpportunityLineItemId",ur=new Set(["Id",pr,gr]);function yt(n){return n.slice(0,15)}function lr(n,e){let t=n[e];return typeof t=="string"&&t!==""?yt(t):void 0}function km(n,e){return!n.has(nn)||!n.has(cr)||!n.has(dr)?[]:e.get(nn)?.some(r=>r.name===fr)!==!0?[]:[{sourceObject:cr,targetObject:dr,relationshipName:`${cr}Before${dr}`,type:"lookup",required:!0}]}function Ul(n,e,t){let r=[...ur,...t.filter(s=>!ur.has(s))].map(V).join(", "),o=s=>s.map(i=>`'${Ot(i)}'`).join(", ");return`SELECT ${r} FROM ${zl} WHERE ${pr} IN (${o(n)}) AND ${gr} IN (${o(e)})`}var Wl=200;function Gl(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function Em(n,e,t){let r=[],o=[...new Set(e.map(s=>s.product))];for(let s of Gl(o,Wl)){let i=new Set(s.map(yt)),a=[...new Set(e.filter(c=>i.has(yt(c.product))).map(c=>c.quote))];r.push(...await n(Ul(a,s,t)))}return r}function jm(n,e,t){let r=new Map;for(let s of e){let i=lr(s,"Id"),a=lr(s,pr),c=lr(s,gr);if(!i||!a||!c||t.has(i))continue;let l=`${a}:${c}`;r.set(l,[...r.get(l)??[],s])}let o=new Map;for(let s of n){let i=r.get(`${yt(s.quote)}:${yt(s.product)}`)?.shift();i&&o.set(s.index,i)}return o}var Di=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Vl(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(Di.test(n)&&Di.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 Nm(n,e,t,r=new Set){let o={};for(let[s,i]of Object.entries(n))ur.has(s)||r.has(s)||!t(s)||Vl(i,e[s])||(o[s]=i??null);return o}function Cm(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 Jl=2e3,Hl=3,Kl=20,Rt=20;function Lm(n,e){let t=go(n,e);return{query:r=>t.query(r),describe:r=>t.describe(r),queryAll:async r=>{let o=await n.query(r,{scanAll:!0});return po(n.limitInfo,e),{totalSize:o.totalSize,records:o.records}},serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp}}function Li(n,e,t){return`${n}:${e.slice(0,15)}:${t}`}function Bi(n,e){return`${n}.${e}`}var Yl=[{modified:"LastModifiedDate",by:"LastModifiedById"},{modified:"SystemModstamp"},{}],ke="CreatedById",rn="CreatedDate",Zl=n=>new Promise(e=>setTimeout(e,n));function Y(n){return n.slice(0,15)}function on(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Qe(n){return typeof n.Id=="string"?n.Id:void 0}function mr(n){return Array.isArray(n)?`[${n.map(mr).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${mr(r)}`).join(",")}}`:JSON.stringify(n)}var $i=class{constructor(e){this.deps=e}deps;describes=new Map;async verify(e,t={}){let r=t.now??(()=>new Date),o=t.sleep??Zl,s=t.intervalMs??Jl,i=Math.max(1,t.maxAttempts??Hl),a=t.linkSample??Kl,c=await this.runEnd(e),l=this.deps.source,p="unavailable"in l?l.unavailable:void 0,u=new Map;if(!("unavailable"in l))for(let A of e.records)u.set(A.objectApiName,await this.linkPlan(l,e,A,a));let f=null,d=null,m=[],h=0,w=this.explaining(e,c),b=w.window?await this.runUser(e):void 0;for(let A=1;A<=i;A++){h=A,await o(s),m=[];for(let y of e.records)m.push(await this.read(e,y,c,u.get(y.objectApiName),w,b));let g=mr(m);if(f!==null&&g===f){d=m;break}f=g}let O=(d??m).map(Ql);return{verdict:Xl(d!==null,O,p),verifiedAt:r().toISOString(),attempts:h,objects:O,...p!==void 0?{linksUnchecked:p}:{}}}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=on(await r.call(this.deps.target));Number.isFinite(s)&&(t=s-(o+Date.now())/2)}catch{}}return e.runRecordedAt.getTime()+t+Nt}explaining(e,t){let r=new Set;for(let{objectApiName:l,field:p,recordIds:u}of e.leftEmptyByFilter??[])for(let f of u)r.add(Li(l,f,p));let o=new Set(Object.entries(e.leftEmptyByTheRun??{}).flatMap(([l,p])=>p.map(u=>Bi(l,u)))),s=[...new Set((e.withTheirRecord??[]).flatMap(l=>{let p=e.remapTable[l];return p===void 0?[]:[p]}))],i=e.runStartedAt?.getTime()??Number.NaN,a=Number.isFinite(i)&&Number.isFinite(t),c={from:i-Nt,to:t+Nt};return{emptiedByFilter:r,emptiedByTheRun:o,withTheirRecord:s,createdByRun:new Set(Object.values(e.remapTable).map(Y)),...a?{window:c,counted:e.runEndedAt?{from:c.from,to:t}:c}:{}}}async setByAutomation(e,t,r){let o=r.window,s=e.filter(({link:p,createdBy:u})=>o!==void 0&&typeof u=="string"&&p.found!==null&&!r.createdByRun.has(Y(p.found)));if(!o||s.length===0)return{explained:[],broken:e.map(({link:p})=>p)};let i=new Map,a=new Map;for(let{link:p}of s){let u=await this.objectOfId(t.referenceTo?.get(p.field)??[],p.found);u!==void 0&&a.set(u,[...a.get(u)??[],p.found])}for(let[p,u]of a)try{let f=await be(this.deps.target,p,[ke,rn],[...new Set(u)]);for(let d of f){let m=Qe(d);m&&i.set(Y(m),d)}}catch{}let c=[],l=[];for(let p of e){let{link:u,createdBy:f}=p,d=u.found===null?void 0:i.get(Y(u.found)),m=on(d?.[rn]);s.includes(p)&&typeof f=="string"&&typeof d?.[ke]=="string"&&Y(d[ke])===Y(f)&&m>=o.from&&m<=o.to?c.push({...u,cause:"automation"}):l.push(u)}return{explained:c,broken:l}}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=>kt.parse(i))}async linkPlan(e,t,r,o){let s=r.objectApiName,i={fields:[],expected:new Map,sample:[]};try{let[a,c]=await Promise.all([this.describe(this.deps.target,"target",s),this.describe(e,"source",s)]),l=new Set(a.fields.filter(g=>g.type==="reference"&&(g.createable===!0||g.updateable===!0)).map(g=>g.name)),p=new Set(t.fieldExclusions?.[s]??[]),u=t.fieldMappings?.[s]??{},f=c.fields.filter(g=>g.type==="reference"&&!p.has(g.name)).map(g=>({from:g.name,to:u[g.name]??g.name})).filter(({to:g})=>l.has(g)&&!p.has(g));if(f.length===0)return i;let d=new Map,m=new Map;for(let[g,y]of Object.entries(t.remapTable))d.set(Y(y),g),m.set(Y(g),y);let h=r.ids.slice(0,o).filter(g=>d.has(Y(g)));if(h.length===0)return i;let w=await be(e,s,f.map(g=>g.from),h.map(g=>d.get(Y(g)))),b=new Map;for(let g of w){let y=Qe(g),S=y?m.get(Y(y)):void 0;if(!S)continue;let E=[];for(let{from:T,to:x}of f){let N=g[T],C=typeof N=="string"?m.get(Y(N)):void 0;C&&E.push({field:x,expected:C})}E.length>0&&b.set(Y(S),E)}let O=[...new Set([...b.values()].flat().map(g=>g.field))],A=new Map(a.fields.filter(g=>O.includes(g.name)).map(g=>[g.name,g.referenceTo??[]]));return{fields:O,expected:b,sample:O.length>0?h:[],referenceTo:A,createdBy:a.fields.some(g=>g.name===ke)}}catch(a){return{...i,unchecked:U(a)}}}async runUser(e){for(let t of e.records){let r=t.ids[0];if(r!==void 0)try{let[o]=await be(this.deps.target,t.objectApiName,[ke],[r]),s=o?.[ke];if(typeof s=="string"&&/^[A-Za-z0-9]{15,18}$/.test(s))return s}catch{}}}async countInTheWindow(e,t,r){let o=s=>new Date(s).toISOString().replace(/\.\d{3}Z$/,"Z");try{return(await this.deps.target.query(`SELECT COUNT() FROM ${V(e)} WHERE ${ke} = '${t}' AND ${rn} >= ${o(r.from)} AND ${rn} <= ${o(r.to)}`)).totalSize}catch{return}}async withTheirRecordThere(e,t){let r=e.ids[0]?.slice(0,3);if(r===void 0)return 0;let o=new Set(e.ids.map(Y)),s=t.withTheirRecord.filter(i=>i.slice(0,3)===r&&!o.has(Y(i)));if(s.length===0)return 0;try{let i=await be(this.deps.target,e.objectApiName,[],s);return new Set(i.map(Qe).filter(a=>a!==void 0).map(Y)).size}catch{return 0}}async read(e,t,r,o,s,i){let a=t.objectApiName,c={objectApiName:a,expected:t.ids.length,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:0,...o?.unchecked!==void 0?{linksUnchecked:o.unchecked}:{}},l,p={},u;for(let w of Yl)try{let b=[w.modified,w.by].filter(O=>!!O);l=await be(this.deps.target,a,b,t.ids),p=w;break}catch(b){u??=U(b)}if(!l)return{...c,error:u??"The org gave no reason."};let f=new Map;for(let w of l){let b=Qe(w);b&&f.set(Y(b),w)}let d=t.ids.filter(w=>!f.has(Y(w))),m=0;if(d.length>0){let w=await this.recycleBin(a,d);if("unread"in w)c.notVisibleIds=d,c.recycleBinUnread=w.unread;else for(let b of d){let O=w.found.get(Y(b));O==="deleted"?c.deletedIds.push(b):O==="there"?m++:c.notVisibleIds.push(b)}}if(c.present=f.size+m,c.withTheirRecord=await this.withTheirRecordThere(t,s),i!==void 0&&s.counted){let w=await this.countInTheWindow(a,i,s.counted);w!==void 0&&(c.createdInTheWindow=w)}let h=new Map(Object.entries(e.removalStamps??{}).map(([w,b])=>[Y(w),on(b)]));if(p.modified&&Number.isFinite(r))for(let w of t.ids){let b=f.get(Y(w));if(!b)continue;let O=on(b[p.modified]);if(!Number.isFinite(O)||O<=r||O<=(h.get(Y(w))??Number.NaN))continue;let A=p.by?b[p.by]:void 0;c.changed.push({recordId:w,modifiedAt:String(b[p.modified]),...typeof A=="string"?{modifiedById:A}:{}})}if(o&&o.sample.length>0)try{let w=await be(this.deps.target,a,o.createdBy?[...o.fields,ke]:o.fields,o.sample),b=new Set(e.writtenWithout?.[a]??[]),O=[];for(let A of w){let g=Qe(A);if(g)for(let{field:y,expected:S}of o.expected.get(Y(g))??[]){let E=A[y],T=typeof E=="string"&&E!==""?E:null;if(T!==null&&Y(T)===Y(S)){c.linksChecked++;continue}if(T===null&&s.emptiedByFilter.has(Li(a,g,y))){c.linksChecked++,c.explained.push({recordId:g,field:y,expected:S,found:T,cause:"lookup-filter"});continue}if(T===null&&s.emptiedByTheRun.has(Bi(a,y))){c.linksChecked++,c.explained.push({recordId:g,field:y,expected:S,found:T,cause:"run"});continue}if(T===null&&b.has(y))continue;c.linksChecked++;let x={recordId:g,field:y,expected:S,found:T};T===null?c.broken.push(x):O.push({link:x,createdBy:A[ke]})}}if(O.length>0){let{explained:A,broken:g}=await this.setByAutomation(O,o,s);c.explained.push(...A),c.broken.push(...g)}}catch(w){c.linksUnchecked=U(w)}return c}async recycleBin(e,t){let r=new Map;try{let o=V(e);for(let s of te(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 c=a,l=Qe(c);if(!l)continue;let p=c.IsDeleted===!0||c.IsDeleted==="true";r.set(Y(l),p?"deleted":"there")}}}catch(o){return{unread:U(o)}}return{found:r}}};function Ql(n){let e=n.explained.filter(r=>r.cause==="run").length,t=n.present+n.withTheirRecord;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,Rt),deletedIds:n.deletedIds.slice(0,Rt),notVisibleIds:n.notVisibleIds.slice(0,Rt),linksChecked:n.linksChecked,linksBroken:n.broken.length,brokenLinks:n.broken.slice(0,Rt),...n.explained.length>0?{linksLeftEmptyByFilter:n.explained.filter(r=>r.cause==="lookup-filter").length,linksSetByAutomation:n.explained.filter(r=>r.cause==="automation").length,...e>0?{linksLeftEmptyByTheRun:e}:{},explainedLinks:n.explained.slice(0,Rt)}:{},...n.error!==void 0?{error:n.error}:{},...n.linksUnchecked!==void 0?{linksUnchecked:n.linksUnchecked}:{},...n.recycleBinUnread!==void 0?{recycleBinUnread:n.recycleBinUnread}:{},...n.withTheirRecord>0?{withTheirRecord:n.withTheirRecord}:{},...n.createdInTheWindow!==void 0&&n.createdInTheWindow>t?{moreInTheWindow:n.createdInTheWindow-t}:{}}}function Xl(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 Bm(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 $m(n){return n?{[nn]:[fr]}:{}}function qm(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 qi=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 zi=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{zn as a,Un as b,Vc as c,Jc as d,Vp as e,nu as f,ss as g,ru as h,ou as i,su as j,iu as k,au as l,Pe as m,Hi as n,mu as o,ta as p,wa as q,Sa as r,Oa as s,Aa as t,ka as u,Ea as v,ps as w,Ju as x,qi as y,zl as z,nn as A,dr as B,fr as C,pr as D,gr as E,km as F,Em as G,jm as H,Nm as I,Cm as J,Qu as K,Xu as L,ef as M,of as N,sf as O,bs as P,gf as Q,mf as R,hf as S,wf as T,bf as U,yf as V,Rf as W,Sf as X,Of as Y,Af as Z,kf as _,Ef as $,ce as aa,Be as ba,Cf as ca,Pf as da,Ua as ea,As as fa,Os as ga,vs as ha,ue as ia,Ya as ja,ut as ka,Ge as la,$f as ma,qf as na,zf as oa,Uf as pa,Wf as qa,Gf as ra,Vf as sa,Zc as ta,ei as ua,Qp as va,Xp as wa,eg as xa,ri as ya,si as za,dg as Aa,op as Ba,Pn as Ca,sp as Da,Bs as Ea,ip as Fa,ap as Ga,Rc as Ha,cp as Ia,jc as Ja,yp as Ka,Rp as La,Sp as Ma,xc as Na,_n as Oa,zi as Pa,_c as Qa,Dc as Ra,kp as Sa,Pp as Ta,qn as Ua,Tp as Va,Fp as Wa,vp as Xa,xp as Ya,Qs as Za,Lp as _a,$p as $a,qp as ab,zp as bb,Xs as cb,ud as db,bg as eb,Rg as fb,Sg as gb,Eg as hb,jg as ib,Ng as jb,jd as kb,Nd as lb,Cd as mb,qg as nb,zg as ob,Ug as pb,Wg as qb,Gg as rb,Vg as sb,Jg as tb,Hg as ub,Kg as vb,Qg as wb,rl as xb,Xg as yb,nm as zb,wi as Ab,bi as Bb,im as Cb,dm as Db,ir as Eb,tn as Fb,Om as Gb,Lm as Hb,$i as Ib,Bm as Jb,$m as Kb,qm as Lb};
|
package/lib/chunk-3F5YMM2F.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
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 a}from"./chunk-SIOZXPFG.mjs";var c="FIELD_CUSTOM_VALIDATION_EXCEPTION",g="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",R="FIELD_FILTER_VALIDATION_EXCEPTION",F="INACTIVE_OWNER_OR_USER",w=/\[(005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?)\]/,E="005",h=["CreatedById","LastModifiedById"];function L(e,n){if(e.statusCode!==F)return;let r=f(n,"OwnerId"),t=r===void 0?void 0:n[r],o=w.exec(e.message)?.[1];if(!(typeof t!="string"||o===void 0))return t.slice(0,15)===o.slice(0,15)?o.slice(0,15):void 0}function O(e,n,r){let t=f(n,"OwnerId");if(t===void 0||t.toLowerCase()===r?.toLowerCase())return;let o=n[t];if(!(typeof o!="string"||!o.startsWith(E)||e.fields.some(u=>u.toLowerCase()!=="ownerid")||!(w.test(e.message)?L(e,n)!==void 0:h.every(u=>f(n,u)===void 0))))return{field:t,refusedBy:"inactive-owner",reason:a(e)}}var I=new Map([[c,"validation-rule"],[g,"restricted-picklist"],[R,"lookup-filter"]]);function _(e){return e!=null&&e!==""}function f(e,n){let r=n.toLowerCase();return Object.keys(e).find(t=>t.toLowerCase()===r&&_(e[t]))}function m(e,n,r,t,o){if(!e||e.length===0)return;let d=new Map;for(let s of e){let u=I.get(s.statusCode);if(!u){let i=o?.inactiveOwner===!0&&s.statusCode===F?O(s,n,r):void 0;if(!i)return;d.has(i.field)||d.set(i.field,i);continue}let l=s.fields.map(i=>f(n,i)).filter(i=>i!==void 0&&i.toLowerCase()!==r?.toLowerCase());if(l.length===0||u==="lookup-filter"&&!l.every(i=>t?.(i)===!0))return;for(let i of l)d.has(i)||d.set(i,{field:i,refusedBy:u,reason:a(s)})}return[...d.values()]}function A(e){return(e??[]).some(n=>n.statusCode===c&&n.fields.length===0)}function C(e,n){let r=new Set(n.map(t=>t.field));return Object.fromEntries(Object.entries(e).filter(([t])=>!r.has(t)))}function S(e,n){let r=e??{rows:0,fields:[]};r.rows+=n.rows;for(let t of n.fields){let o=r.fields.find(d=>d.field===t.field&&d.reason===t.reason);o?o.rows+=t.rows:r.fields.push({...t})}return r}var p={"validation-rule":"a validation rule of the target refused it","restricted-picklist":"a restricted picklist of the target refused its value","lookup-filter":"a lookup filter of the target refused the record it names","inactive-owner":"the target holds the owner it names inactive"};function v(e){return(e?.fields??[]).map(({field:n,refusedBy:r="validation-rule",reason:t,rows:o,replacedWith:d})=>{let s=d===void 0?`written without ${n}`:`written with ${n} set to "${d}"`;return`, ${o} ${s}: ${p[r]}, ${t}`}).join("")}function W(e){let n=`${e.rows} record(s) written again without the fields the target refused them on${v(e)}`;return n.endsWith(".")?n:`${n}.`}export{g as a,R as b,F as c,L as d,f as e,m as f,A as g,C as h,S as i,v as j,W as k};
|
package/lib/chunk-3RYLICRX.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{c as I}from"./chunk-UNDIBZWG.mjs";import{a as w,b as O}from"./chunk-CA5NAXSU.mjs";import{b as l,n as u}from"./chunk-7EANH5PY.mjs";var V="tooling",T={GenAiPlannerDefinition:["Id","DeveloperName","MasterLabel"],GenAiPlannerFunctionDef:["PlannerId","Plugin"],GenAiPluginDefinition:["Id","DeveloperName","LocalDeveloperName","MasterLabel","Description"],GenAiPluginFunctionDef:["PluginId","Function"],GenAiFunctionDefinition:["Id","DeveloperName","LocalDeveloperName","MasterLabel","Description"],GenAiPlannerAttrDefinition:["ParentId","DeveloperName","ParameterName"]},_="DeveloperName",y=200,j="This org has no Agentforce agent: create one, then write the test file from this run.",v="This org has no Agentforce: it has no GenAiPlannerDefinition, the object that lists its agents.",g=l().nullish().transform(n=>n==null||n===""?void 0:n),z={GenAiPlannerDefinition:u({Id:l().min(1),DeveloperName:l().min(1),MasterLabel:g}),GenAiPlannerFunctionDef:u({PlannerId:l().min(1),Plugin:g}),GenAiPluginDefinition:u({Id:l().min(1),DeveloperName:l().min(1),LocalDeveloperName:g,MasterLabel:g,Description:g}),GenAiPluginFunctionDef:u({PluginId:l().min(1),Function:g}),GenAiFunctionDefinition:u({Id:l().min(1),DeveloperName:l().min(1),LocalDeveloperName:g,MasterLabel:g,Description:g}),GenAiPlannerAttrDefinition:u({ParentId:l().min(1),DeveloperName:l().min(1),ParameterName:g})},D=class extends Error{constructor(t,d,s){super(s);this.object=t;this.code=d;this.name="CatalogRefusal"}object;code};async function W(n){try{let e=await h(n,"GenAiPlannerDefinition");if(e.length===0)return{kind:"no-agent",reason:"none",message:j};let t=e.map(a=>a.Id),d=await A(n,"GenAiPlannerFunctionDef","PlannerId",t),s=await A(n,"GenAiPlannerAttrDefinition","ParentId",t),o=await A(n,"GenAiPluginDefinition","Id",d.map(a=>a.Plugin)),i=await A(n,"GenAiPluginFunctionDef","PluginId",o.map(a=>a.Id)),r=await A(n,"GenAiFunctionDefinition","Id",i.map(a=>a.Function)),f=R(o),L=R(r),x=a=>{let m=E(i.filter(p=>N(p.PluginId,a)).map(p=>p.Function),L);return{actions:m.items,unnamedActions:m.unnamed}};return{kind:"agents",catalog:{agents:e.map(a=>{let m=E(d.filter(c=>N(c.PlannerId,a.Id)).map(c=>c.Plugin),f),p=m.items.map((c,M)=>{let b=m.rows[M];return b?{...c,...x(b.Id)}:{...c,actions:[],unnamedActions:0}});return{id:a.Id,name:a.DeveloperName,...a.MasterLabel!==void 0?{label:a.MasterLabel}:{},topics:p,unnamedTopics:m.unnamed,variables:s.filter(c=>N(c.ParentId,a.Id)).map(c=>({name:c.DeveloperName,...c.ParameterName!==void 0?{parameterName:c.ParameterName}:{}}))}}).sort((a,m)=>C(a.name,m.name))}}}catch(e){if(!(e instanceof D))throw e;return e.object==="GenAiPlannerDefinition"&&e.code==="INVALID_TYPE"?{kind:"no-agent",reason:"no-agentforce",message:v}:{kind:"unreadable",object:e.object,message:`The org would not read ${e.object}: ${e.message}`}}}function H(n,e){return n.agents.find(t=>t.name===e)}function Z(n,e){return n.topics.find(t=>t.name===e)?.actions.map(t=>t.name)??[]}var G=["Off_Topic"];function B(n){return n.topics.find(e=>G.includes(e.name)||G.includes(e.localName??""))?.name}function U(n,e){return n.variables.some(t=>t.name===e||t.parameterName===e)}async function h(n,e,t){let d=`SELECT ${T[e].join(", ")} FROM ${e}${t?` WHERE ${t}`:""}`,s;try{s=await n(d)}catch(i){let r=O(i);throw new D(e,F(i)??w(r),r)}let o=z[e];return s.map(i=>{let r=o.safeParse(i);if(!r.success){let f=r.error.issues[0];throw new D(e,void 0,`a row has no ${f.path.join(".")} the catalog can read (${f.message})`)}return r.data})}async function A(n,e,t,d){let s=[...new Set(d.filter(i=>i!==void 0&&I(i)))],o=[];for(let i=0;i<s.length;i+=y){let r=s.slice(i,i+y).map(f=>`'${f}'`);o.push(...await h(n,e,`${t} IN (${r.join(", ")})`))}return o}function F(n){if(typeof n!="object"||n===null)return;let{errorCode:e,name:t}=n;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(t))return t}function P(n){return n.slice(0,15)}function N(n,e){return P(n)===P(e)}function R(n){return new Map(n.map(e=>[P(e.Id),e]))}function E(n,e){let t=new Map,d=0;for(let o of n){if(o===void 0)continue;if(!I(o)){t.has(o)||t.set(o,{item:{name:o,described:!1}});continue}let i=e.get(P(o));if(!i){d++;continue}let r=i[_];t.has(r)||t.set(r,{row:i,item:{name:r,...i.LocalDeveloperName!==void 0?{localName:i.LocalDeveloperName}:{},...i.MasterLabel!==void 0?{label:i.MasterLabel}:{},...i.Description!==void 0?{description:i.Description}:{},described:!0}})}let s=[...t.values()].sort((o,i)=>C(o.item.name,i.item.name));return{items:s.map(o=>o.item),rows:s.map(o=>o.row),unnamed:d}}function C(n,e){return n<e?-1:n>e?1:0}export{V as a,T as b,_ as c,j as d,v as e,W as f,H as g,Z as h,G as i,B as j,U as k};
|
package/lib/chunk-42RER7V4.mjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
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{f as ce}from"./chunk-CGWXQX75.mjs";import{tc as de}from"./chunk-B45CNPUX.mjs";import{b as u,e as f,i as ie,k as w,l as m,r as se,s as N,u as ae,v as D}from"./chunk-7EANH5PY.mjs";import{createHash as fe}from"node:crypto";import*as C from"node:fs/promises";import*as M from"node:path";import*as I from"node:fs/promises";import*as O from"node:path";import*as U from"node:fs";import*as b from"node:path";function Oe(t){let e=b.resolve(t);for(;;){if(U.existsSync(b.join(e,".git"))||U.existsSync(b.join(e,"pnpm-workspace.yaml")))return e;let r=b.dirname(e);if(r===e)throw new Error(`No repository root found above ${t}`);e=r}}function le(t){let e=b.resolve(t);return process.platform==="win32"?e.toLowerCase():e}function _(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t))throw new Error(`Not an org id a file of the sas can be named after: "${t}"`);return t}var q=class extends Error{constructor(r,n){super(`Refusing output path inside the repository: ${r} (repo root: ${n}). Frozen-dataset exports, retained-ID lists and working manifests must live in a sas directory OUTSIDE the repo \u2014 versioning them would create a real\u2194anonymized correspondence table.`);this.resolvedPath=r;this.repoRoot=n;this.name="InsideRepoPathError"}resolvedPath;repoRoot},k=class{repoRoot;constructor(e){this.repoRoot=e?b.resolve(e):Oe(process.cwd())}isInsideRepo(e){let r=le(this.repoRoot),n=le(e);if(n===r)return!0;let i=b.relative(r,n);return i!==""&&!i.startsWith("..")&&!b.isAbsolute(i)}assertOutsideRepo(e){if(this.isInsideRepo(e))throw new q(b.resolve(e),this.repoRoot);return b.resolve(e)}};function ot(t){return t.map(({objectApiName:e,why:r,count:n})=>({objectApiName:e,count:n,note:ce(n,r)}))}var ue=/^\d+\.\d+\.\d+$/,Se=/^[0-9a-f]{12}$/,P=class extends Error{constructor(e){super(e),this.name="ManifestError"}};function it(t){let e=(t.now?.()??new Date).toISOString(),r={version:t.version,status:"frozen",frozenAt:e,source:t.source,saltFingerprint:t.saltFingerprint,rulesVersion:t.rulesVersion,volumetry:t.volumetry,controls:{nonReidentification:t.nonReidentification,dryRunLoad:null,author:t.author,date:e},...t.coverage?{coverage:t.coverage}:{}};return W(r),r}function W(t){if(!ue.test(t.version))throw new P(`version must be semver, got ${JSON.stringify(t.version)}`);if(t.status!=="frozen")throw new P(`status must be "frozen", got ${JSON.stringify(t.status)}`);if(!t.frozenAt)throw new P("frozenAt is required");if(!t.source?.orgId||!t.source.decisionDate)throw new P("source.orgId and source.decisionDate are required");if(!Se.test(t.saltFingerprint))throw new P("saltFingerprint must be 12 lowercase hex chars of the salt SHA-256");if(!ue.test(t.rulesVersion))throw new P(`rulesVersion must be semver, got ${JSON.stringify(t.rulesVersion)}`);if(typeof t.volumetry?.budgetMax!="number"||!t.volumetry.measured)throw new P("volumetry.budgetMax and volumetry.measured are required");if(!t.controls?.nonReidentification)throw new P("controls.nonReidentification is required");if(!t.controls.author||!t.controls.date)throw new P("controls.author and controls.date are required");let e=t.coverage;if(e!==void 0&&(typeof e.objects!="number"||typeof e.truncated!="boolean"||typeof e.maxNodes!="number"||!Array.isArray(e.unboundedObjects)||!Array.isArray(e.filesLeftOut)||e.leftToThePlatform!==void 0&&!Array.isArray(e.leftToThePlatform)||e.exclusionCosts!==void 0&&!Array.isArray(e.exclusionCosts)||e.requiredLeftEmpty!==void 0&&!Array.isArray(e.requiredLeftEmpty)||e.keptWithoutARule!==void 0&&!Array.isArray(e.keptWithoutARule)||e.encryptedNotKept!==void 0&&!Array.isArray(e.encryptedNotKept)))throw new P("coverage, when present, needs objects, truncated, maxNodes, unboundedObjects and filesLeftOut, and a list of what it left to the platform, of what its exclusions cost, of the required fields the rules leave empty, of the fields kept without a rule, or of the encrypted fields not kept, if it names any")}function pe(t){return W(t),`${JSON.stringify(t,null,2)}
|
|
8
|
-
`}function st(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new P("Manifest must be a JSON object");let e=t;return W(e),e}var V="platform-records.json",G=class extends Error{constructor(e){let r=e.checks.filter(n=>!n.passed).map(n=>`${n.name} (${n.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${r}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},ge=class{guard;constructor(e){this.guard=e??new k}async write(e,r,n,i){if(!i.passed)throw new G(i);let o=this.guard.assertOutsideRepo(e),s=this.guard.assertOutsideRepo(O.join(o,"data"));await I.mkdir(s,{recursive:!0});for(let l of await I.readdir(s))l.endsWith(".json")&&await I.rm(this.guard.assertOutsideRepo(O.join(s,l)));let a=[],d=async(l,p)=>{let g=this.guard.assertOutsideRepo(l);await I.writeFile(g,`${JSON.stringify(p)}
|
|
9
|
-
`,"utf8"),a.push(g)},c=this.guard.assertOutsideRepo(O.join(o,"manifest.json"));await I.writeFile(c,pe(n),"utf8"),a.push(c);for(let l of r.objects)await d(O.join(s,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await d(O.join(o,"record-types.json"),r.recordTypes),await d(O.join(o,"personcontact-sidecar.json"),r.personContactSidecar),await d(O.join(o,V),{...r.standardPricebook?{standardPricebook:r.standardPricebook}:{}}),{dir:o,files:a}}};var K="manifest.json",Fe=["record-types.json","personcontact-sidecar.json",V],Z="data",Ee="sha256:";async function gt(t){let e=await H(M.join(t,K));if(e===void 0)throw new Error(`No frozen dataset at ${t}: it holds no ${K}.`);let r=[{name:K,content:ke(e)}];for(let i of Fe){let o=await H(M.join(t,i));o!==void 0&&r.push({name:i,content:o})}for(let i of await xe(M.join(t,Z))){let o=await H(M.join(t,Z,i));o!==void 0&&r.push({name:`${Z}/${i}`,content:o})}let n=fe("sha256");for(let{name:i,content:o}of r.sort((s,a)=>me(s.name,a.name)))n.update(`${i}\0${fe("sha256").update(o).digest("hex")}
|
|
10
|
-
`);return`${Ee}${n.digest("hex")}`}async function xe(t){let e;try{e=await C.readdir(t)}catch(r){if(r.code==="ENOENT")return[];throw r}return e.filter(r=>r.endsWith(".json"))}async function H(t){try{return await C.readFile(t)}catch(e){if(e.code==="ENOENT")return;throw e}}function ke(t){let e;try{e=JSON.parse(t.toString("utf8"))}catch{return t}if(Y(e)&&Y(e.controls)){let r={...e.controls};delete r.dryRunLoad,e={...e,controls:r}}return Buffer.from(X(e),"utf8")}function X(t){return Array.isArray(t)?`[${t.map(X).join(",")}]`:Y(t)?`{${Object.keys(t).sort(me).map(r=>`${JSON.stringify(r)}:${X(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function me(t,e){return t===e?0:t<e?-1:1}import*as h from"node:fs/promises";import*as z from"node:path";var yt=4*1024*1024,wt=64*1024*1024;var he=1e4,L=u().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),S=u().min(1).max(40),bt=m({forgeId:u().min(1).max(200),targetOrgId:u().min(1).max(128),timestamp:S,duration:f().nonnegative(),status:ae(["success","partial","failure"]),cancelled:D(!0).optional(),writtenBetween:m({first:S,last:S}).optional(),retryOf:u().min(1).max(200).optional(),objects:w(m({objectApiName:u().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:w(L)})),linked:f().int().nonnegative(),mayHaveBeenWritten:f().int().nonnegative().optional(),undo:m({removedAt:S,deleted:f().int().nonnegative(),alreadyGone:f().int().nonnegative(),kept:f().int().nonnegative(),refused:f().int().nonnegative(),notReached:f().int().nonnegative().optional(),notVisible:f().int().nonnegative().optional()}).optional(),removalStamps:N(L,S).optional(),removalSpans:w(m({first:S,last:S,userId:L})).optional(),removalLeft:w(L).optional(),sweep:m({sweptAt:S,deleted:f().int().nonnegative(),keptChanged:f().int().nonnegative(),refused:f().int().nonnegative()}).optional(),inJournal:m({journalId:u().min(1).max(200),part:f().int().nonnegative(),left:w(m({objectApiName:u().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:f().int().nonnegative()}))}).optional()}),Rt=m({version:D(1),plans:w(ie())}),Pt=m({version:D(1),runs:w(m({forgeId:u().min(1).max(300),ids:w(L),late:w(L).optional()}))});var J="referenceid-mapping.json",Ne=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,Me=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,T=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=new Set;function De(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var _e=m({at:u().min(1).max(40),object:u().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:w(se([u().min(1).max(400),u().regex(T)])).max(1e4)}),Ce=m({journal:m({startedAt:u().min(1).max(40),pid:f().int().positive(),runUserId:u().regex(T).optional()})});function Be(t){let e,r={},n=new Map,i;for(let o of t.split(`
|
|
11
|
-
`)){if(o.trim()==="")continue;let s;try{s=JSON.parse(o)}catch{continue}if(!e){let c=Ce.safeParse(s);c.success&&(e=c.data.journal);continue}let a=_e.safeParse(s);if(!a.success)continue;let d=n.get(a.data.object)??[];for(let[c,l]of a.data.created)Object.prototype.hasOwnProperty.call(r,c)||d.push(c),r[c]=l;n.set(a.data.object,d),i=a.data.at}if(!(!e||i===void 0||Object.keys(r).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:i,mapping:r,created:[...n].filter(([,o])=>o.length>0).map(([o,s])=>({objectApiName:o,referenceIds:s})),load:{startedAt:e.startedAt,endedAt:i},...e.runUserId?{runUserId:e.runUserId}:{}}}}function Je(t){return`referenceid-mapping.${_(t)}.json`}async function B(t){let e;try{e=await h.readFile(t,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}return JSON.parse(e)}async function At(t,e){let r=e.assertOutsideRepo(t),n;try{n=await h.readdir(r)}catch(o){if(o.code==="ENOENT")return[];throw o}let i=new Set(n.flatMap(o=>Ne.exec(o)?.[1]??Me.exec(o)?.[1]??[]));if(n.includes(J)){let s=(await B(e.assertOutsideRepo(z.join(r,J))))?.orgId;typeof s=="string"&&$e(s)&&i.add(s)}return[...i].sort()}function $e(t){try{return _(t),!0}catch{return!1}}var Ue=w(m({objectApiName:u(),referenceIds:w(u())})),qe=m({startedAt:u(),endedAt:u()}),We=m({first:u(),last:u()}),Ge=m({removedAt:u(),deleted:f(),alreadyGone:f(),kept:f(),refused:f(),notReached:f().optional()}),Ve=N(u(),u()),Ke=w(m({first:u(),last:u(),userId:u()})),ye=N(u(),u()),ee=u().regex(T);function v(t,e){let r=t.safeParse(e);return r.success?r.data:void 0}function A(t){if(typeof t!="object"||t===null)return;let e=t,r=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(y=>typeof y[1]=="string")):{},n=v(Ue,e.created),i=v(qe,e.load),o=v(We,e.writtenBetween),s=v(Ge,e.removal),a=v(Ve,e.removalStamps),d=v(Ke,e.removalSpans),c=v(ye,e.personContacts),l=v(ye,e.withTheirRecord),p=v(ee,e.runUserId),g=v(w(ee),e.madeEarlier),R=v(w(ee),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:r,...n?{created:n}:{},...i?{load:i}:{},...o?{writtenBetween:o}:{},...s?{removal:s}:{},...a?{removalStamps:a}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...l?{withTheirRecord:l}:{},...p?{runUserId:p}:{},...g?{madeEarlier:g}:{},...R?{lateEarlier:R}:{}}}function F(t){return Array.isArray(t.earlier)?t.earlier.flatMap(e=>A(e)??[]):[]}function E(t){return t.load?.endedAt??t.updatedAt}function Ze(t,e){return t.slice(0,15)===e.slice(0,15)}function j(t){return t.slice(0,15)}function we(t,e){let r={};for(let[n,i]of Object.entries(t??{}))Object.prototype.hasOwnProperty.call(e,i)?Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=i):delete e[n];return r}function be(t,e){if(e.size===0)return t;let r=Object.fromEntries(Object.entries(t.mapping).filter(([,d])=>!e.has(j(d)))),n=we(t.personContacts,r),i=we(t.withTheirRecord,r),o=t.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(l=>Object.prototype.hasOwnProperty.call(r,l))})).filter(d=>d.referenceIds.length>0),s=Object.fromEntries(Object.entries(t.removalStamps??{}).filter(([d])=>!e.has(j(d)))),a={...t,mapping:r};return delete a.removalStamps,delete a.personContacts,delete a.withTheirRecord,{...a,...o?{created:o}:{},...Object.keys(s).length>0?{removalStamps:s}:{},...Object.keys(n).length>0?{personContacts:n}:{},...Object.keys(i).length>0?{withTheirRecord:i}:{}}}function Re(t){return t.created?t.created.some(e=>e.referenceIds.length>0):Object.keys(t.mapping).length>0}var Pe=class{constructor(e,r){this.sasDir=e;this.guard=r?.guard??new k,this.orgId=r?.orgId??"";let n=r?.organizationId;this.askOrganizationId=typeof n=="function"?n:async()=>n,this.now=r?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(z.join(this.sasDir,this.orgId===""?J:Je(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(z.join(this.sasDir,J))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${_(this.orgId)}`}journalPath(e){let r=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(z.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(r))}.ndjson`))}retiring=new Map;journal(e){let r=this.journalPath(e),n=!1,i=!1,o=!1,s,a=Promise.resolve(),d;Q.add(r);let c=p=>{a=a.then(async()=>{if(!(d!==void 0||i))try{if(!n){n=!0,await h.mkdir(z.dirname(r),{recursive:!0});let g={journal:{startedAt:e.toISOString(),pid:process.pid,...s?{runUserId:s}:{}}};await h.appendFile(r,`${JSON.stringify(g)}
|
|
12
|
-
`,"utf8")}await h.appendFile(r,`${JSON.stringify(p)}
|
|
13
|
-
`,"utf8")}catch(g){d=g instanceof Error?g.message:String(g)}})},l=async()=>{await a,i=!0,await h.rm(r,{force:!0})};return this.retiring.set(r,l),{writtenAs:p=>{T.test(p)&&(s=p)},created:(p,g)=>{let R=g.filter(([y,x])=>y!==""&&T.test(x));if(R.length!==0){o=!0;for(let y=0;y<R.length;y+=1e4)c({at:this.now().toISOString(),object:p,created:R.slice(y,y+1e4)})}},flush:async()=>(await a,d),close:async()=>{await a,this.retiring.delete(r),(i||!o)&&await h.rm(r,{force:!0}),i=!0,Q.delete(r)}}}async stoppedLoads(e){let r;try{r=await h.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(s){if(s.code==="ENOENT")return[];throw s}let n=`${this.journalStem}.load-`,i=new Set(e.flatMap(s=>s.load?[s.load.startedAt]:[])),o=[];for(let s of r){if(!s.startsWith(n)||!/^\d{1,16}\.ndjson$/.test(s.slice(n.length)))continue;let a=this.guard.assertOutsideRepo(z.join(this.sasDir,s));if(Q.has(a))continue;let d;try{d=await h.readFile(a,"utf8")}catch{continue}let c=Be(d);!c||i.has(c.startedAt)||c.pid!==process.pid&&De(c.pid)||o.push({file:a,load:c.load})}return o}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let r=A(e);return[...r?[r]:[],...F(e)].map(n=>({mapping:new Map(Object.entries(n.mapping)),...n.created?{created:n.created}:{},...n.writtenBetween?{writtenBetween:n.writtenBetween}:{},endedAt:E(n),...n.removalStamps?{removalStamps:n.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let r=typeof e.orgId=="string"?e.orgId:"",n=A(e);return[...n?[this.recordedOf(n,r)]:[],...F(e).map(i=>({...this.recordedOf(i,r),earlier:!0}))]}recordedOf(e,r){return{orgId:r,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:E(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let r=e.organizationId;if(r===void 0)return!1;let n=await this.currentOrganizationId();return n!==void 0&&!Ze(r,n)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await B(this.filePath);if(e!==void 0)return e;let r=this.singleFilePath;if(r===void 0)return;let n=await B(r);return n?.orgId===this.orgId?n:void 0}async readWithJournals(){let e=await this.readFile(),r=e?[A(e),...F(e)]:[],n=await this.stoppedLoads(r.filter(a=>a!==void 0));if(n.length===0)return{payload:e,journals:[]};let i=[...r.filter(a=>a!==void 0),...n.map(({load:a})=>a)].sort((a,d)=>Date.parse(E(d))-Date.parse(E(a))),[o,...s]=i;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...o,...s.length>0?{earlier:s}:{}},journals:n.map(({file:a})=>a)}}async dropJournals(e){for(let r of e)await h.rm(r,{force:!0}).catch(()=>{})}async write(e){let r=this.filePath;await h.mkdir(z.dirname(r),{recursive:!0}),await h.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
14
|
-
`,"utf8");let n=this.singleFilePath;if(n!==void 0)try{(await B(n))?.orgId===this.orgId&&await h.rm(n)}catch{}}async keptLoads(e,r,n=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let i=new Set(r.map(j)),o=new Set(n),s=A(e);return[...s?[s]:[],...F(e)].map(a=>be(a,i)).filter(a=>Re(a)||o.has(E(a)))}async persist(e,r){let{payload:n,journals:i}=await this.readWithJournals(),o=r?.earlier?await this.keptLoads(n,r.earlier.settled,r.earlier.stillToSweep):[],s=await this.currentOrganizationId(),a=this.now().toISOString(),d=p=>Object.fromEntries(Object.entries(p??{}).filter(([g,R])=>e.has(g)&&e.has(R))),c=d(r?.personContacts),l=d(r?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...s!==void 0?{organizationId:s}:{},updatedAt:a,mapping:Object.fromEntries([...e.entries()].sort(([p],[g])=>p.localeCompare(g))),...r?{created:r.created.map(({objectApiName:p,referenceIds:g})=>({objectApiName:p,referenceIds:g.filter(R=>e.has(R))})).filter(p=>p.referenceIds.length>0),load:{startedAt:r.startedAt.toISOString(),endedAt:a},...r.writtenBetween?{writtenBetween:{...r.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(l).length>0?{withTheirRecord:l}:{},...r.runUserId?{runUserId:r.runUserId}:{}}:{},...o.length>0?{earlier:o}:{}}),r?.earlier&&await this.dropJournals(i),r){let p=this.journalPath(r.startedAt),g=this.retiring.get(p);g?await g():await h.rm(p,{force:!0}).catch(()=>{})}}async recordRemoval(e,r){let{payload:n,journals:i}=await this.readWithJournals(),o=A(n);if(n===void 0||o===void 0)return!1;let s=[o,...F(n)],a=s.findIndex(p=>E(p)===e);if(a<0)return!1;let d=new Set(r.gone.map(j)),[c,...l]=s.map((p,g)=>be(g===a?Xe(p,r):p,d));return await this.write({version:1,orgId:typeof n.orgId=="string"?n.orgId:"",...n.organizationId!==void 0?{organizationId:n.organizationId}:{},...c,updatedAt:this.now().toISOString(),...l.length>0?{earlier:l}:{}}),await this.dropJournals(i),!0}async recordMade(e,r,n=[],i=[]){let{payload:o,journals:s}=await this.readWithJournals(),a=A(o);if(o===void 0||a===void 0)return!1;let d=[a,...F(o)],c=d.findIndex(y=>E(y)===e);if(c<0)return!1;let l=[...i],p=y=>{let x=ve(y.madeEarlier,r,l),oe=ve(y.lateEarlier,n,l),$={...y};return delete $.madeEarlier,delete $.lateEarlier,{...$,...x.length>0?{madeEarlier:x}:{},...oe.length>0?{lateEarlier:oe}:{}}},[g,...R]=d.map((y,x)=>x===c?p(y):y);return await this.write({version:1,orgId:typeof o.orgId=="string"?o.orgId:"",...o.organizationId!==void 0?{organizationId:o.organizationId}:{},...g,...R.length>0?{earlier:R}:{}}),await this.dropJournals(s),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:r,journals:n}=await this.readWithJournals(),i=A(r);if(r===void 0||i===void 0)return!1;let o=new Set(e),s=F(r),a=s.filter(d=>Re(d)||!o.has(E(d)));return a.length===s.length?!1:(await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...i,...a.length>0?{earlier:a}:{}}),await this.dropJournals(n),!0)}async recordStamps(e){let{payload:r,journals:n}=await this.readWithJournals(),i=A(r);if(r===void 0||i===void 0)return!1;let o=[i,...F(r)],s=o.map(c=>He(c,e));if(s.every((c,l)=>c===o[l]))return!1;let[a,...d]=s;return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...a,...d.length>0?{earlier:d}:{}}),await this.dropJournals(n),!0}};function ve(t,e,r=[]){let n=new Map,i=new Set(r.map(j)),o=[];for(let s of[...t??[],...e]){let a=j(s),d=a.slice(0,3),c=n.get(d)??0;!T.test(s)||i.has(a)||c>=he||(i.add(a),n.set(d,c+1),o.push(s))}return o}function He(t,e){let r=new Set(Object.values(t.mapping).map(j)),n=Object.entries(e).filter(([o])=>r.has(j(o)));if(n.length===0)return t;let i=new Set(n.map(([o])=>j(o)));return{...t,removalStamps:{...Object.fromEntries(Object.entries(t.removalStamps??{}).filter(([o])=>!i.has(j(o)))),...Object.fromEntries(n)}}}function Xe(t,e){let r={...t.removalStamps,...e.stamps},n=[...t.removalSpans??[],...e.span?[e.span]:[]],i=e.mark??t.removal;return{...t,...i?{removal:i}:{},...Object.keys(r).length>0?{removalStamps:r}:{},...n.length>0?{removalSpans:n}:{}}}var je={BusinessHours:["Name"]},Ot=["DUPLICATE_VALUE","DUPLICATES_DETECTED","duplicate value found"];var Ye=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Qe=/^[A-Za-z][A-Za-z0-9_]*$/;function te(t){return t.slice(0,15)}function re(t,e){let r=t.mapping.get(e);return typeof r=="string"&&Ye.test(r)?r:void 0}function Ie(t){let e=new Set((t.created??[]).flatMap(n=>n.referenceIds)),r=new Set;for(let n of t.mapping.keys()){if(e.has(n))continue;let i=re(t,n);i&&r.add(te(i))}return r}function et(t){let e=new Set((t.created??[]).flatMap(i=>i.referenceIds)),r=[...Object.entries(t.personContacts??{}),...Object.entries(t.withTheirRecord??{})];for(let i=!0;i;){i=!1;for(let[o,s]of r)e.has(o)||!e.has(s)||(e.add(o),i=!0)}let n=new Set;for(let[i]of r){let o=e.has(i)?re(t,i):void 0;o&&n.add(te(o))}return n}function Ae(t){let e=Ie(t),r=new Map;for(let{objectApiName:o,referenceIds:s}of t.created??[])Qe.test(o)&&r.set(o,[...r.get(o)??[],...s]);let n=new Set,i=[];for(let[o,s]of[...r].reverse()){let a=[];for(let d of[...s].reverse()){let c=re(t,d);if(!c)continue;let l=te(c);e.has(l)||n.has(l)||(n.add(l),a.push(c))}a.length>0&&i.push({objectApiName:o,ids:a})}return i}function ne(t){return de(t.removal)?[]:Ae(t).filter(e=>!ze(e.objectApiName))}function ze(t){return Object.prototype.hasOwnProperty.call(je,t)}function tt(t){return Ae(t).filter(e=>ze(e.objectApiName)).map(({objectApiName:e,ids:r})=>({objectApiName:e,count:r.length}))}function xt(t){return t.find(e=>ne(e).length>0)??t[0]}function kt(t,e){return t.filter(r=>r.endedAt!==e.endedAt&&r.created!==void 0&&ne(r).length===0)}function Lt(t){let e=t.created!==void 0,r=et(t),n=[...Ie(t)].filter(o=>!r.has(o)),i=tt(t);return{orgId:t.orgId,loadedAt:t.endedAt,created:ne(t).map(({objectApiName:o,ids:s})=>({objectApiName:o,count:s.length})),linked:e?n.length:0,recorded:e,...t.removal?{removed:t.removal}:{},...t.earlier?{earlier:!0}:{},...i.length>0?{keptByThePlatform:i}:{}}}export{Oe as a,_ as b,q as c,k as d,ot as e,it as f,pe as g,st as h,V as i,ge as j,gt as k,je as l,Ot as m,Je as n,At as o,Pe as p,Ae as q,ne as r,tt as s,xt as t,kt as u,Lt as v};
|