sandforge 1.82.0 → 1.84.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/chunk-23SEDORH.mjs +11 -0
- package/lib/{chunk-7WSLT5VX.mjs → chunk-24RFOFYT.mjs} +1 -1
- package/lib/chunk-26POJDIT.mjs +7 -0
- package/lib/{chunk-SFGZFB4F.mjs → chunk-2AZQHBEF.mjs} +1 -1
- package/lib/{chunk-6VSZNZHH.mjs → chunk-2HVOZUM4.mjs} +1 -1
- package/lib/{chunk-XFU3HRUV.mjs → chunk-2JDAOWUW.mjs} +1 -1
- package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
- package/lib/chunk-2WFIVO4F.mjs +13 -0
- package/lib/chunk-2YHZBUZE.mjs +7 -0
- package/lib/{chunk-SZGGFST2.mjs → chunk-326AJTIU.mjs} +14 -14
- package/lib/{chunk-Q6SXNKV2.mjs → chunk-36JOHEJL.mjs} +1 -1
- package/lib/chunk-3PVRGTVK.mjs +7 -0
- package/lib/{chunk-VZVICK7Q.mjs → chunk-3Q353S2R.mjs} +1 -1
- package/lib/chunk-3TZSBHEY.mjs +7 -0
- package/lib/{chunk-UHFLKP26.mjs → chunk-43TOMFV4.mjs} +1 -1
- package/lib/{chunk-XK5W7BVE.mjs → chunk-4CVUUVGJ.mjs} +1 -1
- package/lib/{chunk-VYOYXTCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
- package/lib/{chunk-EOFO3PHS.mjs → chunk-4JE4BYXK.mjs} +1 -1
- package/lib/{chunk-7EYQYZJP.mjs → chunk-54WZUS7J.mjs} +1 -1
- package/lib/chunk-5CRLRHOJ.mjs +7 -0
- package/lib/{chunk-FA4ZKDCU.mjs → chunk-5IZTFMJM.mjs} +1 -1
- package/lib/chunk-5M5FQ7RP.mjs +7 -0
- package/lib/{chunk-3HROD5RE.mjs → chunk-5SMWFNE7.mjs} +1 -1
- package/lib/{chunk-YAIIRFKJ.mjs → chunk-5XTUSN72.mjs} +1 -1
- package/lib/chunk-6I6TWNV5.mjs +7 -0
- package/lib/{chunk-PYRZFUVU.mjs → chunk-6JWWSDM6.mjs} +1 -1
- package/lib/chunk-6O222PW6.mjs +7 -0
- package/lib/{chunk-2UU42PTD.mjs → chunk-6PD6K7LP.mjs} +1 -1
- package/lib/{chunk-GGUOIDWP.mjs → chunk-6QE6R6RL.mjs} +1 -1
- package/lib/{chunk-DJCGURW7.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
- package/lib/{chunk-DT3T7FRD.mjs → chunk-6YL7BNYD.mjs} +1 -1
- package/lib/chunk-6ZLKIT3H.mjs +7 -0
- package/lib/{chunk-CBL42DUU.mjs → chunk-7QYHEHMA.mjs} +1 -1
- package/lib/chunk-7SQSWVAU.mjs +9 -0
- package/lib/{chunk-ZUBBEP75.mjs → chunk-7UVKIWKV.mjs} +1 -1
- package/lib/{chunk-TWV4A5RK.mjs → chunk-7WATA4SB.mjs} +1 -1
- package/lib/chunk-7YNM6KFZ.mjs +7 -0
- package/lib/chunk-A3MYSOOC.mjs +7 -0
- package/lib/chunk-AL4C3GFT.mjs +7 -0
- package/lib/chunk-B3FBHVNN.mjs +21 -0
- package/lib/{chunk-27Z76O2O.mjs → chunk-B63POIPQ.mjs} +1 -1
- package/lib/{chunk-RTWYLOCA.mjs → chunk-BAWCOKRW.mjs} +1 -1
- package/lib/{chunk-NWOI25WY.mjs → chunk-BBRWFKS5.mjs} +1 -1
- package/lib/chunk-BEA27DLS.mjs +7 -0
- package/lib/chunk-BRY3PLIZ.mjs +7 -0
- package/lib/chunk-CBH3TOWK.mjs +341 -0
- package/lib/chunk-CPQIZGG5.mjs +7 -0
- package/lib/chunk-CVHNXJH3.mjs +7 -0
- package/lib/{chunk-HFUDCNU5.mjs → chunk-D4GF4FAB.mjs} +1 -1
- package/lib/chunk-DGDRQRCW.mjs +7 -0
- package/lib/{chunk-YAJQS3OL.mjs → chunk-DPMRIMUC.mjs} +1 -1
- package/lib/chunk-DUN2EPRC.mjs +7 -0
- package/lib/chunk-E3A3LOCY.mjs +7 -0
- package/lib/{chunk-TMA34QMA.mjs → chunk-EAC5QCE3.mjs} +1 -1
- package/lib/{chunk-VQJMP3DC.mjs → chunk-EC72TIEG.mjs} +1 -1
- package/lib/chunk-EPFCERGL.mjs +7 -0
- package/lib/{chunk-3MGMNK3Q.mjs → chunk-ETDCBLGU.mjs} +1 -1
- package/lib/{chunk-LXDSRP2W.mjs → chunk-F3AQW6IU.mjs} +1 -1
- package/lib/{chunk-A65ADTCR.mjs → chunk-FITPY3L4.mjs} +1 -1
- package/lib/chunk-FNJ4SGWO.mjs +7 -0
- package/lib/{chunk-SAMWHL22.mjs → chunk-FP7CYB2F.mjs} +1 -1
- package/lib/{chunk-JLZRZL5E.mjs → chunk-GKY2JMHY.mjs} +1 -1
- package/lib/chunk-GMIGWR6U.mjs +7 -0
- package/lib/{chunk-AUS6NFLZ.mjs → chunk-GNRSF65U.mjs} +1 -1
- package/lib/chunk-GOOVPVWX.mjs +7 -0
- package/lib/{chunk-PPHVWUFY.mjs → chunk-GWZRR3MM.mjs} +1 -1
- package/lib/{chunk-JH27IKCO.mjs → chunk-H2BHESDA.mjs} +2 -2
- package/lib/chunk-H33DVU3D.mjs +7 -0
- package/lib/chunk-H4CGM6YO.mjs +7 -0
- package/lib/{chunk-WOOUISSO.mjs → chunk-HCGXK7G7.mjs} +1 -1
- package/lib/{chunk-VZT4E2OJ.mjs → chunk-HIDW7FNV.mjs} +1 -1
- package/lib/chunk-HSBXRQTI.mjs +7 -0
- package/lib/chunk-HUZPBE47.mjs +7 -0
- package/lib/chunk-HV7VPEXP.mjs +7 -0
- package/lib/chunk-I6E6T6YY.mjs +7 -0
- package/lib/chunk-IUM4NFKI.mjs +10 -0
- package/lib/chunk-IVFVNNGB.mjs +37 -0
- package/lib/{chunk-5K2I2DMP.mjs → chunk-IZGCEOYO.mjs} +1 -1
- package/lib/{chunk-ZHIZY3ZC.mjs → chunk-J3DND3BC.mjs} +1 -1
- package/lib/{chunk-VPDEJGPS.mjs → chunk-JAEDM4SI.mjs} +1 -1
- package/lib/chunk-JCFBFF4Y.mjs +7 -0
- package/lib/{chunk-GBGHJTPC.mjs → chunk-JE6SCT6R.mjs} +1 -1
- package/lib/chunk-JGZPD4IM.mjs +7 -0
- package/lib/{chunk-C3LNYAVJ.mjs → chunk-JKJ74BX5.mjs} +1 -1
- package/lib/{chunk-EEFUE2ES.mjs → chunk-JLSIWO4Z.mjs} +1 -1
- package/lib/{chunk-3CX7GPCR.mjs → chunk-JSAJS3MY.mjs} +1 -1
- package/lib/chunk-JTJK2D36.mjs +7 -0
- package/lib/{chunk-V3R45ZWT.mjs → chunk-KAZS5Z6W.mjs} +1 -1
- package/lib/chunk-KB4ZHM4Q.mjs +10 -0
- package/lib/{chunk-J24TIGSI.mjs → chunk-KGU4SVIT.mjs} +1 -1
- package/lib/chunk-KJWFYBMU.mjs +15 -0
- package/lib/{chunk-H4JUYUSL.mjs → chunk-KZTZDC7H.mjs} +1 -1
- package/lib/chunk-L2E5WBGD.mjs +8 -0
- package/lib/{chunk-XU25YA46.mjs → chunk-L53JWJ3S.mjs} +1 -1
- package/lib/{chunk-Y4TDVDP2.mjs → chunk-LA4KIATH.mjs} +6 -6
- package/lib/chunk-LC3NDW4N.mjs +7 -0
- package/lib/{chunk-GCGHHN4K.mjs → chunk-LKTNQEBS.mjs} +1 -1
- package/lib/chunk-M2ABR4JM.mjs +7 -0
- package/lib/{chunk-3C2ZZIFN.mjs → chunk-M4BLK6HJ.mjs} +1 -1
- package/lib/{chunk-L4INJ5TZ.mjs → chunk-M6K34KGF.mjs} +1 -1
- package/lib/chunk-MDMPJEV3.mjs +7 -0
- package/lib/{chunk-32EUNQT6.mjs → chunk-MJZU3U5O.mjs} +68 -63
- package/lib/{chunk-PBE44M2Y.mjs → chunk-MSIEU5MR.mjs} +1 -1
- package/lib/{chunk-NLB3RGIY.mjs → chunk-N4WPCWJO.mjs} +1 -1
- package/lib/{chunk-SNEOKYV7.mjs → chunk-NCZKWSC7.mjs} +1 -1
- package/lib/{chunk-6KP6WETK.mjs → chunk-NED4MBIM.mjs} +1 -1
- package/lib/chunk-NOBQTEQD.mjs +7 -0
- package/lib/{chunk-RCYEBY42.mjs → chunk-NSQWI7ZY.mjs} +1 -1
- package/lib/{chunk-DBBPDSFN.mjs → chunk-O677VOGO.mjs} +1 -1
- package/lib/chunk-OFTT7J2M.mjs +7 -0
- package/lib/{chunk-C2N2TNEU.mjs → chunk-OLCVHL7I.mjs} +1 -1
- package/lib/chunk-OM5NORJG.mjs +7 -0
- package/lib/chunk-OMNMLKDT.mjs +7 -0
- package/lib/{chunk-CELEBWEZ.mjs → chunk-OPMO6I45.mjs} +1 -1
- package/lib/{chunk-LHU6CPGE.mjs → chunk-OUZQPYT3.mjs} +1 -1
- package/lib/chunk-OVNMB6Q2.mjs +7 -0
- package/lib/{chunk-6GQUZ4IP.mjs → chunk-PAXNWTYK.mjs} +1 -1
- package/lib/{chunk-XSKPYGMT.mjs → chunk-PBY2O6OF.mjs} +1 -1
- package/lib/chunk-PEDQPM2P.mjs +926 -0
- package/lib/chunk-PH7SP4YK.mjs +21 -0
- package/lib/{chunk-3SKLBRPL.mjs → chunk-PMN4PAC3.mjs} +1 -1
- package/lib/chunk-PMWAFDUB.mjs +48 -0
- package/lib/chunk-PPLVFX6N.mjs +7 -0
- package/lib/{chunk-STRMWSIQ.mjs → chunk-PR3XCSPO.mjs} +1 -1
- package/lib/{chunk-GJ6SZVHT.mjs → chunk-PR42EZSR.mjs} +1 -1
- package/lib/{chunk-YMDFF657.mjs → chunk-PWRJRL5U.mjs} +1 -1
- package/lib/{chunk-Q3DY7TO2.mjs → chunk-Q7GIJBCD.mjs} +1 -1
- package/lib/chunk-Q7TLC3I2.mjs +7 -0
- package/lib/{chunk-ZXFL2MSN.mjs → chunk-QAFPQ3YB.mjs} +1 -1
- package/lib/{chunk-T7WREYA5.mjs → chunk-QKEKG2LD.mjs} +1 -1
- package/lib/chunk-QO53K5W2.mjs +9 -0
- package/lib/{chunk-MUEQRIK7.mjs → chunk-QTG6LUZT.mjs} +1 -1
- package/lib/{chunk-KP5G6FUC.mjs → chunk-RE7RYF3B.mjs} +1 -1
- package/lib/{chunk-FOIWWK7G.mjs → chunk-RGBGUCJA.mjs} +1 -1
- package/lib/{chunk-DWMRIWV5.mjs → chunk-RGUQOSBU.mjs} +1 -1
- package/lib/{chunk-7PY3VQP3.mjs → chunk-RHNTHGNU.mjs} +1 -1
- package/lib/chunk-RKTFFCNS.mjs +7 -0
- package/lib/chunk-RMFU4BAL.mjs +28 -0
- package/lib/{chunk-KKOA62S4.mjs → chunk-ROV3QXEF.mjs} +14 -13
- package/lib/chunk-RT47RKLY.mjs +7 -0
- package/lib/{chunk-ZUTUYBNW.mjs → chunk-S42RBRH2.mjs} +1 -1
- package/lib/{chunk-Z42PHCVZ.mjs → chunk-SI267LYR.mjs} +1 -1
- package/lib/chunk-T3G6VZNS.mjs +7 -0
- package/lib/chunk-TNT27RBG.mjs +7 -0
- package/lib/chunk-UBIKR5VO.mjs +7 -0
- package/lib/chunk-UI3JQVRU.mjs +8 -0
- package/lib/{chunk-YT22LMF7.mjs → chunk-UIOMAX56.mjs} +1 -1
- package/lib/chunk-UX3BVH2Y.mjs +7 -0
- package/lib/chunk-VCUXCK36.mjs +7 -0
- package/lib/chunk-VINGECAJ.mjs +10 -0
- package/lib/chunk-VOXJHJIE.mjs +7 -0
- package/lib/chunk-W6PN6TJG.mjs +7 -0
- package/lib/{chunk-FKK5YBGZ.mjs → chunk-WAPSSYMT.mjs} +1 -1
- package/lib/{chunk-PR74GYVI.mjs → chunk-WUUKFE2U.mjs} +1 -1
- package/lib/chunk-WWTCWWZI.mjs +7 -0
- package/lib/chunk-WXDLQT2O.mjs +10 -0
- package/lib/chunk-WY5V5PR3.mjs +7 -0
- package/lib/chunk-X4BXESMQ.mjs +7 -0
- package/lib/chunk-XBQGZGWR.mjs +7 -0
- package/lib/chunk-XGGOUNPP.mjs +7 -0
- package/lib/chunk-XKWW3GKF.mjs +7 -0
- package/lib/{chunk-JJITOWZK.mjs → chunk-Y2DRK37K.mjs} +1 -1
- package/lib/{chunk-XZISAZA6.mjs → chunk-YA6ATMTB.mjs} +1 -1
- package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
- package/lib/chunk-YHR4WQPR.mjs +7 -0
- package/lib/{chunk-KJYEQHYP.mjs → chunk-YTLUYSMF.mjs} +1 -1
- package/lib/chunk-YWEQQL3C.mjs +8 -0
- package/lib/{chunk-PWVDNN2C.mjs → chunk-Z4LKKOFY.mjs} +1 -1
- package/lib/chunk-ZBAWJUG2.mjs +7 -0
- package/lib/{chunk-XO5FBOQF.mjs → chunk-ZJW6YOMV.mjs} +1 -1
- package/lib/chunk-ZQQXSCVI.mjs +7 -0
- package/lib/{chunk-47UHTN3Q.mjs → chunk-ZQWIVYVM.mjs} +1 -1
- package/lib/chunk-ZV7ZFQQC.mjs +9 -0
- package/lib/sandforge-autopilot.mjs +25 -25
- package/lib/sandforge-backup.mjs +1 -1
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +52 -21
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +4 -4
- package/lib/sandforge-env.mjs +106 -107
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +21 -23
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/compare.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-2JZGCCPG.mjs +0 -9
- package/lib/chunk-3HEMJTAP.mjs +0 -925
- package/lib/chunk-3XG25GTF.mjs +0 -7
- package/lib/chunk-42BFLWHR.mjs +0 -7
- package/lib/chunk-466F37VD.mjs +0 -7
- package/lib/chunk-4JKR4PTZ.mjs +0 -8
- package/lib/chunk-52EXDVPN.mjs +0 -7
- package/lib/chunk-7CVDVBEE.mjs +0 -7
- package/lib/chunk-7LKI7OAS.mjs +0 -7
- package/lib/chunk-7SDZR6SR.mjs +0 -7
- package/lib/chunk-A32ISQ6M.mjs +0 -28
- package/lib/chunk-A7JJWOLT.mjs +0 -7
- package/lib/chunk-BMTNTBBM.mjs +0 -7
- package/lib/chunk-BN33LVPQ.mjs +0 -7
- package/lib/chunk-BZ24IAP5.mjs +0 -7
- package/lib/chunk-CCEH7L53.mjs +0 -7
- package/lib/chunk-CV47FDQW.mjs +0 -7
- package/lib/chunk-CZLJZQCS.mjs +0 -7
- package/lib/chunk-DIL62SUN.mjs +0 -7
- package/lib/chunk-DIS254AN.mjs +0 -7
- package/lib/chunk-FZF23M6R.mjs +0 -7
- package/lib/chunk-G2JR3F63.mjs +0 -7
- package/lib/chunk-GGNUACTY.mjs +0 -7
- package/lib/chunk-GHPR5UVV.mjs +0 -7
- package/lib/chunk-HIHCYMSL.mjs +0 -7
- package/lib/chunk-HKUWHVI7.mjs +0 -9
- package/lib/chunk-HQQVANWQ.mjs +0 -20
- package/lib/chunk-IRZJU2PG.mjs +0 -22
- package/lib/chunk-ISSP2FZ5.mjs +0 -7
- package/lib/chunk-IVZJSDJD.mjs +0 -7
- package/lib/chunk-JESRFE2Z.mjs +0 -11
- package/lib/chunk-JFNLKHY6.mjs +0 -8
- package/lib/chunk-JKT5YAQ2.mjs +0 -7
- package/lib/chunk-JQZTMFO7.mjs +0 -7
- package/lib/chunk-KIMQQ6JQ.mjs +0 -7
- package/lib/chunk-LAUOSXMN.mjs +0 -341
- package/lib/chunk-MKTXJCXN.mjs +0 -10
- package/lib/chunk-O2PUGRNW.mjs +0 -10
- package/lib/chunk-O4BROUGM.mjs +0 -7
- package/lib/chunk-P55MKIZX.mjs +0 -37
- package/lib/chunk-P63WJMXQ.mjs +0 -7
- package/lib/chunk-PE435FVH.mjs +0 -15
- package/lib/chunk-PPGDAUEQ.mjs +0 -7
- package/lib/chunk-QAPVKPEC.mjs +0 -7
- package/lib/chunk-RLWB7F26.mjs +0 -7
- package/lib/chunk-RYRMUPMY.mjs +0 -7
- package/lib/chunk-SCKUIE3R.mjs +0 -7
- package/lib/chunk-SU65Z2BA.mjs +0 -7
- package/lib/chunk-TCBAE65A.mjs +0 -7
- package/lib/chunk-WEMLDUQA.mjs +0 -7
- package/lib/chunk-WSUKC2U3.mjs +0 -7
- package/lib/chunk-WT3SCUHS.mjs +0 -7
- package/lib/chunk-YGJF55VJ.mjs +0 -7
- package/lib/chunk-YH4DYI6D.mjs +0 -7
- package/lib/chunk-ZQO5PDX5.mjs +0 -48
- package/lib/chunk-ZUOPC4W2.mjs +0 -7
|
@@ -0,0 +1,10 @@
|
|
|
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 Jn,d as Kn,j as Yn}from"./chunk-23SEDORH.mjs";import{a as zn,b as Vn}from"./chunk-W6PN6TJG.mjs";import{p as Nt,q as wr}from"./chunk-3Q353S2R.mjs";import{d as gr,h as pr,m as mr}from"./chunk-RHNTHGNU.mjs";import{c as qn}from"./chunk-Q7TLC3I2.mjs";import{a as hr,b as yr}from"./chunk-HF6LAK3G.mjs";import{j as tr,k as nr,l as rr,m as or,n as sr}from"./chunk-D4GF4FAB.mjs";import{b as ir}from"./chunk-CVHNXJH3.mjs";import{a as lr,b as fr}from"./chunk-TQ2TQHTT.mjs";import{d as Ft}from"./chunk-HFSBDM7B.mjs";import{c as Zn,g as Xe,h as Mt,j as er}from"./chunk-OHEOJISY.mjs";import{a as Xn}from"./chunk-EADHKH3A.mjs";import{E as ke,_ as Hn,b as Oe,da as Qn,q as Ke,r as Ye,t as Pt}from"./chunk-TNT27RBG.mjs";import{h as $t}from"./chunk-TZE3Y7IQ.mjs";import{b as F}from"./chunk-CA5NAXSU.mjs";import{a as ur,b as cr}from"./chunk-PC247GKX.mjs";import{a as vt,b as ar,c as dr}from"./chunk-TUACWKIH.mjs";import{$ as Sn,$d as Je,Cc as Fn,Ec as vn,Fc as Nn,Kd as ze,Ld as Cn,Md as Ve,Nc as Bn,Nd as _n,Oc as xn,Od as Et,P as wn,Pd as In,Sd as jn,Td as Tt,Vd as He,X as Rn,Z as bn,_ as Ge,_d as Qe,aa as An,ba as En,be as Dn,ca as Tn,ce as Ot,da as On,de as Ln,fa as qe,ga as kn,ge as kt,ha as $n,he as Wn,ia as Pn,ie as Un,je as Gn,m as yn,vc as Mn}from"./chunk-PMWAFDUB.mjs";import{b as Q,e as G,i as We,k as X,l as B,s as At,v as hn,z as Ue}from"./chunk-WZQEK4WT.mjs";import{randomUUID as bs}from"node:crypto";import{hostname as Ss,homedir as As,uptime as Es}from"node:os";import{mkdir as Ts,readFile as $r,readdir as Os,rename as Pr,writeFile as ks}from"node:fs/promises";import{dirname as Bt,join as Ct}from"node:path";function Rr(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:F(e)}]}}function br(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function Cu(e){return{typeOrg:()=>zn(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:Mn()}).then(br,Rr),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(br,Rr)}}var he=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function $s(e){return e instanceof he||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var Ps=60,Ms=5*6e4,Fs=3e4,vs=6e4,Ns=200,Bs=448,xs=384,nt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ye=Q().regex(nt),Cs=B({id:ye,permissionSetId:ye,permissionSet:Q().min(1).max(255)}),_s=B({runId:Q().min(1).max(255),host:Q().min(1).max(255),pid:G().int().nonnegative(),hostStartedAt:Ue.datetime({offset:!0}),acquiredAt:Ue.datetime({offset:!0}),endsAt:Ue.datetime({offset:!0}),needs:X(ye),assigning:X(ye),created:X(Cs)}),Mr=B({version:hn(1),organizationId:ye,userId:ye,leases:X(_s)}),Is=B(ur),js=cr(e=>{let t=Is.safeParse(e);return t.success?t.data:void 0});function Fr(e=process.env,t=As()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Ct(t,".sandforge","mute-leases")}function Ds(e,t,n){if(!nt.test(t)||!nt.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Ct(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var vr={host:Ss(),pid:vt.pid,startedAt:vt.startedAt},Ls=6e4,ce=new Set;function Nr(e,t,n){return`${e}
|
|
8
|
+
${t}
|
|
9
|
+
${n}`}function Ws(e,t,n,r={}){let o=r.now?.()??Date.now();if(!(Date.parse(e.endsAt)>o)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return ce.has(Nr(t,e.runId,e.acquiredAt));let s=r.bootedAt?.()??Date.now()-Es()*1e3,i=Date.parse(e.hostStartedAt);return Number.isFinite(i)&&i<s-Ls?!1:(r.isAlive??dr)(e.pid)}var Us=e=>new Promise(t=>setTimeout(t,e));function Ze(e,t,n){let r=n?.code;return new Error(`The journal of the mute leases in ${Bt(e)} could not be ${t}${typeof r=="string"?` (${r})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function Gs(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+ar).toISOString()}}function Br(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function qs(e){return`nothing was assigned. ${Br(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function et(e,t,n,r,o=qs,s=vs){let i=n.self??vr,a={self:i,...n.checks?{checks:n.checks}:{}},d=Date.now()+s;for(await Ts(Bt(e),{recursive:!0,mode:Bs}).catch(c=>{throw Ze(e,"made",c)});;){let c;try{c=js.acquire(`${e}.lock`,u=>u,a)}catch(u){throw Ze(e,"locked",u)}if("lock"in c)try{let u=await zs(e,t).catch(g=>{throw Ze(e,"read",g)});return await r(u,async g=>{let p=`${e}.${process.pid}-${bs()}.tmp`;try{await ks(p,JSON.stringify(g,null,2),{encoding:"utf8",mode:xs}),await Pr(p,e)}catch(m){throw Ze(e,"written",m)}})}finally{c.lock.release()}if(Date.now()>d){let u=Gs(c.busy,i);throw new he({code:"MUTE_FAILED",message:`The journal of the mute leases in ${Bt(e)} stayed locked for a minute by process ${u.pid} on ${u.host}: ${o(u)}`})}await Us(Ns)}}async function zs(e,t){let n={version:1,...t,leases:[]},r;try{r=await $r(e,"utf8")}catch(o){if(o.code==="ENOENT")return n;throw o}try{let o=Mr.safeParse(JSON.parse(r));if(o.success)return o.data}catch{}return await Pr(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var Vs=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function tt(e,t,n,r){let o=t.leases.filter(u=>u!==n&&r(u)),s=[...n.created],i=new Set,a=n.assigning[0];if(a!==void 0){let u=new Set(t.leases.flatMap(g=>g===n?[]:g.created.map(p=>p.id))),f=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${a}')`).then(g=>g.records).catch(()=>[]);for(let g of f){let p=typeof g.Id=="string"?g.Id:void 0,m=typeof g.PermissionSetId=="string"?g.PermissionSetId:void 0;if(!p||!m||u.has(p)||s.some(R=>R.id===p))continue;let w=g.PermissionSet;s.push({id:p,permissionSetId:m,permissionSet:typeof w?.Name=="string"?w.Name:m}),i.add(p)}}let d={removed:[],passed:[],left:[],found:[]};for(let u of s){let f=o.find(m=>m.needs.includes(u.permissionSetId));if(f){f.created.some(m=>m.id===u.id)||f.created.push(u),d.passed.push(u);continue}let g=await e.deleteAssignment(u.id),p=g.errors?.[0]?.statusCode??g.errors?.[0]?.errorCode;g.success||p!==void 0&&Vs.has(p)?(d.removed.push(u),i.has(u.id)&&d.found.push(u)):d.left.push({...u,why:g.errors?.[0]?.message??p??"the org refused the delete"})}let c=t.leases.indexOf(n);return d.left.length===0?t.leases.splice(c,1):t.leases[c]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:d.left.map(({id:u,permissionSetId:f,permissionSet:g})=>({id:u,permissionSetId:f,permissionSet:g}))},d}function le(e){return e.map(t=>t.permissionSet)}function Sr(e,t){let n=o=>le(o).join(", "),r=[];return e.removed.length>0&&r.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&r.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&r.push(`${e.left.map(o=>`${o.permissionSet} (${o.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),r}function Ar(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function xr(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function Hs(e,t,n){let r=[];for(let o of[...t.leases])n(o)||r.push(...(await tt(e,t,o,n)).found);return r}var _t="SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess",$e="the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)";function It(e){return e?.PermissionsAssignPermissionSets===!0||e?.PermissionsManageUsers===!0}async function Qs(e){let t;try{t=(await e.query(_t)).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${F(n)})`}return It(t)?void 0:$e}function Er(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var Tr=/^[A-Za-z][A-Za-z0-9_]*$/;async function Js(e,t){let r=t.map(Er).filter(i=>Tr.test(i.developerName)&&(!i.namespace||Tr.test(i.namespace)));if(r.length===0)return new Map;let o=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(r.map(i=>`'${i.developerName}'`))].join(", ")+")"),s=new Map;for(let i of t){let{namespace:a,developerName:d}=Er(i),c=o.records.find(u=>String(u.Name??"").toLowerCase()===d.toLowerCase()&&String(u.NamespacePrefix??"").toLowerCase()===a.toLowerCase());typeof c?.Id=="string"&&s.set(i,c.Id)}return s}async function Or(e,t,n){if(n.length===0)return new Map;let r=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(s=>`'${s}'`).join(", ")})`),o=new Map;for(let s of r.records){let i=s.PermissionSetId,a=s.Id;typeof i=="string"&&typeof a=="string"&&o.set(i,a)}return o}function xt(e,t,n){return{state:t,assigned:[],held:[],permissions:Ot(e),silenced:e.silenced.map(r=>({...r})),stillRan:e.stillRuns.map(r=>({...r})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(r=>({...r}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(r=>({...r}))}:{},...n?{reason:n}:{}}}var Cr="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function Ks(e,t,n={}){let r,o;try{let c=await e.typeOrg();r=Vn(c),o=c.id}catch(c){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${F(c)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(r)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:s,automation:i,planned:a}=Zs(t,n.writes);if(s.assign.length===0)return{plan:s,automation:t,planned:a,acquire:async()=>({outcome:a,release:async()=>a})};let d=await Qs(e);return d!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${d}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}}:(_r.set(s,await Xs(n.dir??Fr(),o)),{plan:s,automation:i,planned:a,acquire:c=>ei(e,s,c,n)})}var _r=new WeakMap,Ys=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function Xs(e,t){if(!nt.test(t))return 0;let n=`${t.slice(0,15)}-`,r;try{r=await Os(e)}catch{return 0}let o=0;for(let s of r)if(!(!s.startsWith(n)||!Ys.test(s)))try{let i=Mr.safeParse(JSON.parse(await $r(Ct(e,s),"utf8")));if(!i.success)continue;for(let a of i.data.leases)o+=(a.assigning.length>0?1:0)+a.created.length}catch{}return o}function Zs(e,t){let n=Dn(e,t);return n.assign.length===0?{plan:n,automation:e,planned:xt(n,"nothing",Cr)}:{plan:n,automation:Ln(e,Ot(n)),planned:xt(n,"planned")}}async function ei(e,t,n,r={}){let o=r.self??vr,s=()=>r.checks?.now?.()??Date.now(),i=r.minutes??Ps,a=S=>{throw new he({code:"MUTE_FAILED",message:S})},d=await e.identity().catch(S=>a(`The target would not say who the run writes as (${F(S)}).`)),c={organizationId:d.organization_id,userId:d.user_id},u=Ds(r.dir??Fr(),c.organizationId,c.userId),f=t.assign.map(S=>S.permissionSet),g=await Js(e,f).catch(S=>a(`The permission sets to assign could not be read (${F(S)}).`)),p=f.filter(S=>!g.has(S));p.length>0&&a(`The target holds no permission set ${p.join(", ")}: nothing was assigned.`);let m=f.map(S=>g.get(S)),w=new Map(f.map(S=>[g.get(S),S])),R=S=>Ws(S,u,o,r.checks),b=new Date(s()).toISOString(),P=Nr(u,n,b),M=!1,z=m.map(S=>w.get(S)),E=r.retryEveryMs??Fs,j,C=(S,N)=>{if(j!==void 0)return;let O=new Set(S.map(k=>k.id)),v=!1,_=()=>clearInterval(j);j=setInterval(()=>{v||(v=!0,et(u,c,r,async(k,re)=>{let W=k.leases.find(V=>V.runId===n&&V.acquiredAt===b);if(W){W.assigning=[],W.created=[...W.created,...N.filter(K=>!W.created.some(oe=>oe.id===K.id))].filter(K=>!O.has(K.id));let V=await tt(e,k,W,R);for(let K of V.removed)O.add(K.id);await re(k)}_()},void 0,0).catch(()=>{}).finally(()=>{v=!1}))},E),j.unref?.()},ue=await et(u,c,r,async(S,N)=>{let O=le(await Hs(e,S,R)),v=await Or(e,c.userId,m),_=m.filter($=>!v.has($)),k={runId:n,host:o.host,pid:o.pid,hostStartedAt:o.startedAt,acquiredAt:b,endsAt:new Date(s()+i*6e4).toISOString(),needs:m,assigning:[..._],created:[]};S.leases.push(k),ce.add(P),await N(S),M=!0;let re=[...k.assigning],W=()=>N(S).then(()=>{re=[...k.assigning]},$=>F($)),V=async $=>{k.assigning=[];let D=await tt(e,S,k,R);ce.delete(P);let I=await W();I!==void 0&&C(D.removed,[...D.passed,...D.left]);let U=I!==void 0&&re.length===0?{sets:z,until:k.endsAt}:void 0,Te=Sr(D,I===void 0);return a([$,...I!==void 0&&I!==$?[I]:[],...Te.length>0?Te:["Nothing was assigned."],...I!==void 0&&(D.passed.length>0||D.left.length>0||U)?[Ar(o.pid,U)]:[],...O.length>0?[`Taking its lease, the run took back ${O.join(", ")}, ${xr(O)}.`]:[]].join(" "))};for(let $ of _){let D=await e.createAssignment({AssigneeId:c.userId,PermissionSetId:$});if(k.assigning=k.assigning.filter(U=>U!==$),D.success&&D.id){k.created.push({id:D.id,permissionSetId:$,permissionSet:w.get($)});let U=await W();if(U!==void 0)return V(U);continue}let I=D.errors?.[0];if((I?.statusCode??I?.errorCode)==="DUPLICATE_VALUE"){let U=await W();if(U!==void 0)return V(U);continue}return V(`${w.get($)} could not be assigned to the user the run writes as: ${I?.message??I?.statusCode??"the org refused it"}.`)}let K=await Or(e,c.userId,m).catch(()=>new Map),oe=m.filter($=>!K.has($));if(oe.length>0)return V(`Read back, the user the run writes as does not hold ${oe.map($=>w.get($)).join(", ")}.`);let je=new Set(k.created.map($=>$.permissionSetId));return{endsAt:k.endsAt,assigned:k.created.map($=>$.permissionSet),held:m.filter($=>!je.has($)).map($=>w.get($)),found:O}}).catch(S=>{if(ce.delete(P),$s(S))throw S;return a(`${F(S)}${M?"":" Nothing was assigned."}`)}),J={...xt(t,"muted"),assigned:ue.assigned,held:ue.held,leaseEndsAt:ue.endsAt,...ue.found.length>0?{tookBackOfEnded:ue.found}:{}},_e=r.renewEveryMs??Ms,Ee=_e>0?setInterval(()=>{et(u,c,r,async(S,N)=>{let O=S.leases.find(_=>_.runId===n&&_.acquiredAt===b);if(!O||!ce.has(P))return;let v=new Date(s()+i*6e4).toISOString();O.endsAt=v,await N(S),J.leaseEndsAt=v}).catch(()=>{})},_e):void 0;Ee?.unref?.();let Ie;return{outcome:J,release:()=>(Ie??=(async()=>{Ee&&clearInterval(Ee);let S={};try{await et(u,c,r,async(O,v)=>{let _=O.leases.find(k=>k.runId===n&&k.acquiredAt===b);ce.delete(P),_&&(S.done=await tt(e,O,_,R),await v(O))},O=>`nothing was taken back. ${Br(O)} Should none of its runs be muting this org, end process ${O.pid}`);let N=S.done?.left??[];return{...J,released:N.length===0,takenBack:le(S.done?.removed??[]),...S.done&&S.done.passed.length>0?{passed:le(S.done.passed)}:{},...N.length>0?{notTakenBack:le(N),reason:`${N.map(O=>`${O.permissionSet} (${O.why})`).join(", ")} could not be taken back: the lease ends at ${J.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(N){ce.delete(P);let O=S.done;if(C(O?.removed??[],O?[...O.passed,...O.left]:[]),O!==void 0){let v=J.leaseEndsAt,_=v!==void 0&&Date.parse(v)>s()?{sets:z,until:v}:void 0;return{...J,released:!1,takenBack:le(O.removed),notTakenBack:le([...O.passed,...O.left]),reason:[F(N),...Sr({...O,removed:[]},!1),Ar(o.pid,_)].join(" ")}}return{...J,released:!1,takenBack:[],reason:`the assignments could not be taken back (${F(N)}): this process tries again while it runs, and takes them back once it can use the journal; past ${J.leaseEndsAt}, or once process ${o.pid} has ended, the next run that mutes this org releases the lease`}}})(),Ie)}}var ti=2,ni=3;function ri(e){return!e||e.assign.length===0?0:ti+ni+2*e.assign.length+(_r.get(e)??0)}function _u(e){let t=ri(e);return t>0?{mute:t}:{}}function oi(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function Iu(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function ju(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:oi(`the target's automation could not be read (${t.unread})`)};let r=await Ks(await e(),t,n);if("refused"in r)throw new he(r.refused);return{automation:r.automation,...r.plan.assign.length>0?{prepared:r}:{},muted:r.planned,plan:r.plan}}function Du(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function Lu(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??Cr}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+xr(e.tookBackOfEnded));for(let o of e.silenced)n.push(` silenced: ${kt(o)} (bypass ${o.permission})`);for(let o of e.stillRan)n.push(` still runs: ${kt(o)} (${Wn(o.why)})`);for(let o of e.alsoLifted??[])n.push(` also lifts: ${Un(o)}`);for(let o of e.liftsUnread??[])n.push(` ${Gn(o)}`);let r=e.takenBack??(e.released===!0?e.assigned:[]);if(r.length>0&&n.push(` taken back: ${r.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let o=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${o?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}var si=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function Ir(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}function jr(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t):[]}function Dr(e){return typeof e=="string"&&si.test(e)?e:void 0}function Lr(e){let t=new Map;for(let r of jr(Ir(e,"variables"))){let o=r.name,s=Dr(r.objectType);typeof o=="string"&&s&&t.set(o.toLowerCase(),s)}let n=[];for(let r of jr(Ir(e,"recordCreates"))){let o=r.inputReference,s=Dr(r.object)??(typeof o=="string"?t.get(o.toLowerCase()):void 0);s&&!n.some(i=>i.toLowerCase()===s.toLowerCase())&&n.push(s)}return n}var Wr={AccountPartner:["Role"],CampaignMember:["Status"],Case:["Status"],Contract:["Status"],Lead:["Status"],Opportunity:["StageName"],OpportunityPartner:["Role"],Order:["Status"],Partner:["Role"],ServiceAppointment:["Status"],Solution:["Status"],Task:["Priority","Status"],WorkOrder:["Status"],WorkOrderLineItem:["Status"]};function qu(e,t){let n=new Map,r=t!==void 0&&Object.prototype.hasOwnProperty.call(Wr,t)?Wr[t]:[];for(let o of e){let s=o.type==="multipicklist";if(o.type!=="picklist"&&!s&&!o.picklistValues?.length)continue;let i=(o.type==="combobox"||o.restrictedPicklist===!1)&&!r.includes(o.name);n.set(o.name,{multi:s,restricted:o.restrictedPicklist===!0,required:o.nillable===!1&&o.defaultedOnCreate!==!0,...o.controllerName?{controllerName:o.controllerName}:{},...i?{anyValue:i}:{}})}return n}var ii=new Set;function ai(e,t){let n=new Set(e),r=[],o=new Set,s=(i,a)=>{if(o.has(i))return;let d=t.get(i)?.controllerName;d&&n.has(d)&&a<e.length&&s(d,a+1),!o.has(i)&&(o.add(i),r.push(i))};for(let i of e)s(i,0);return r}function di(e){return typeof e=="boolean"?String(e):typeof e=="string"&&e!==""?e:void 0}function ui(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o)??[];s.includes(r)||s.push(r),n.set(o,s)}return[...n]}function ci(e,t,n,r,o,s,i){let a=new Set(o.values),d=a,c,u=r.controllerName?di(e[r.controllerName]):void 0,f=u===void 0?void 0:o.allowedByControllingValue?.get(u);f&&(d=new Set(o.values.filter(b=>f.has(b))),c=r.controllerName);let g=n.filter(b=>!d.has(b));if(g.length===0)return[];let p=b=>i&&!i.has(b)?"not-in-target":a.has(b)?"controlling-value":"record-type",m,w,R=n.filter(b=>d.has(b));return r.multi&&R.length>0?e[t]=R.join(";"):(o.defaultValue!==null&&d.has(o.defaultValue)?(m=o.defaultValue,w="default"):r.required&&(m=o.values.find(b=>d.has(b)),w=m===void 0?void 0:"first"),m===void 0?delete e[t]:e[t]=m),ui(g,p).map(([b,P])=>({field:t,reason:b,values:P,recordType:s,...b==="controlling-value"&&c?{controllingField:c}:{},...m!==void 0&&w?{replacedBy:m,replacement:w}:{}}))}function zu(e,t,n,r,o=ii){let s=[];for(let i of ai(Object.keys(e),n)){let a=e[i];if(typeof a!="string"||o.has(i))continue;let d=n.get(i),c=t?.get(i),u=d?.restricted?r?.picklists.get(i):void 0;if(!c&&!u)continue;if(a===""){delete e[i];continue}let f=d?.multi?a.split(";"):[a];if(d&&u&&r){s.push(...ci(e,i,f,d,u,r.recordType,c));continue}if(!c||d?.anyValue)continue;let g=f.filter(m=>!c.has(m));if(g.length===0)continue;let p=f.filter(m=>c.has(m));d?.multi&&p.length>0?e[i]=p.join(";"):delete e[i],s.push({field:i,reason:"not-in-target",values:[...new Set(g)]})}return s}var li="012000000000000AAA",rt="Master",qr="";function Vu(e,t){return e?.get(typeof t=="string"?t:qr)}async function fi(e,t,n){try{return{picklists:await e(t,n)}}catch(r){return{error:F(r)}}}var Ur=class{constructor(t){this.read=t}read;reads=new Map;said=new Set;async forRows(t){let n=new Map,r=[],{read:o}=this;if(!o)return{byRecordType:n,notes:r};if(t.withoutRecordTypes){let c=[...t.fields].filter(([f,g])=>g.restricted&&g.controllerName&&t.written(f)).map(([f])=>f),u=new Set(c.filter(f=>t.rows.some(g=>typeof g[f]=="string"&&g[f]!=="")));if(u.size>0){let f={targetId:li,developerName:rt},g=await this.readFor(o,t.objectApiName,f.targetId);this.keep(n,r,t.objectApiName,qr,u,f,g)}return{byRecordType:n,notes:r}}if(!t.recordTypeMappings||!t.written("RecordTypeId"))return{byRecordType:n,notes:r};let s=[...t.fields].filter(([c,u])=>u.restricted&&t.written(c)).map(([c])=>c);if(s.length===0)return{byRecordType:n,notes:r};let i=new Map(t.recordTypeMappings.map(c=>[c.sourceId,c])),a=new Map;for(let c of t.rows){let u=c.RecordTypeId;if(!(typeof u!="string"||!i.has(u)))for(let f of s){let g=c[f];if(typeof g!="string"||g==="")continue;let p=a.get(u)??new Set;p.add(f),a.set(u,p)}}let d=await Promise.all([...a].map(async([c,u])=>{let f=i.get(c);return{sourceId:c,fields:u,target:f,answer:await this.readFor(o,t.objectApiName,f.targetId)}}));for(let{sourceId:c,fields:u,target:f,answer:g}of d)this.keep(n,r,t.objectApiName,c,u,f,g);return{byRecordType:n,notes:r}}readFor(t,n,r){let o=`${n}|${r}`,s=this.reads.get(o);return s||(s=fi(t,n,r),this.reads.set(o,s)),s}keep(t,n,r,o,s,i,a){let d=`${r}|${i.targetId}`;if("error"in a){this.said.has(d)||(this.said.add(d),n.push({recordType:i.developerName,error:a.error}));return}t.set(o,{recordType:i.developerName,picklists:a.picklists});let c=[...s].filter(u=>!a.picklists.has(u)&&!this.said.has(`${d}|${u}`));if(c.length!==0){for(let u of c)this.said.add(`${d}|${u}`);n.push({recordType:i.developerName,leftOut:c})}}};function Hu(e){return e.error!==void 0?{recordSummary:`(picklist values of record type ${e.recordType} could not be read \u2014 checked against each field's values)`,messages:[e.error]}:{recordSummary:`(picklist values of record type ${e.recordType} not given for ${(e.leftOut??[]).join(", ")} \u2014 checked against each field's values)`,messages:[`The target's answer for record type ${e.recordType} leaves out ${(e.leftOut??[]).join(", ")}.`]}}var Gr=class{entries=new Map;get size(){return this.entries.size}add(t,n){for(let r of n){let o=[t,r.field,r.reason,r.recordType??"",r.controllingField??"",r.replacement??"",r.replacedBy??""].join("\0"),s=this.entries.get(o);if(s){s.entry.rows++;for(let i of r.values)s.values.add(i);continue}this.entries.set(o,{entry:{objectApiName:t,field:r.field,reason:r.reason,values:[],rows:1,...r.recordType!==void 0?{recordType:r.recordType}:{},...r.controllingField!==void 0?{controllingField:r.controllingField}:{},...r.replacedBy!==void 0?{replacedBy:r.replacedBy}:{},...r.replacement!==void 0?{replacement:r.replacement}:{}},values:new Set(r.values)})}}list(){return[...this.entries.values()].map(({entry:t,values:n})=>({...t,values:[...n].sort()}))}};function gi(e){let t=`${e.rows} row${e.rows===1?"":"s"}`,n=e.values.map(s=>`"${s}"`).join(", "),r=e.reason==="not-in-target"?"not a value of the field in the target":e.reason==="record-type"?`not allowed for record type ${e.recordType??""}`:`not allowed with the value of ${e.controllingField??"its controlling field"}`,o=e.replacedBy===void 0?"left out":e.replacement==="first"?`replaced by "${e.replacedBy}", the first value record type ${e.recordType??""} allows: the field is required and has no default there`:`replaced by "${e.replacedBy}", the default of record type ${e.recordType??""}`;return`${e.field} on ${t}: ${n} ${r}, ${o}`}function Qu(e){return e.length===0?"":`, picklist values not written as read: ${e.map(gi).join("; ")}`}function ec(e){let t={...e.picklistValueMappings?.length?{picklistValueMappings:e.picklistValueMappings}:{},...e.recordTypeMappings?.length?{recordTypeMappings:e.recordTypeMappings}:{},...e.defaultValues?.length?{defaultValues:e.defaultValues}:{},...e.truncateFields?.length?{truncateFields:e.truncateFields}:{},...e.ignoredGaps?.length?{ignoredGaps:e.ignoredGaps}:{},...e.skippedRows?.length?{skippedRows:e.skippedRows}:{}};return Object.keys(t).length>0?t:void 0}var pi=new Set(["picklist_value_refused","picklist_value_absent","currency_inactive"]);function Qr(e){let t=wn(e.gapId);return t?t.objectApiName!==e.object?{ignored:`the gap is of ${t.objectApiName}, not of ${e.object}`}:t.field===void 0||t.value===void 0?{ignored:"the gap names no field and value whose rows to hold back"}:pi.has(t.kind)?{held:{field:t.field,...t.recordType!==void 0?{recordType:t.recordType}:{},value:t.value}}:{ignored:`a ${t.kind} gap does not offer it: its rows are not exactly those holding its value`}:{ignored:"not the id of a gap"}}function tc(e){let t=Qr(e);return"ignored"in t?t.ignored:void 0}function zr(e,t,n){if(e===void 0)return!0;let r=t??rt;if(e===r)return!0;let o=Xe(e),s=Xe(r);if(o.namespacePrefix!==void 0||s.namespacePrefix===void 0||s.developerName!==e)return!1;if(n===void 0)return!0;let i=Mt(e,n,a=>a);return"found"in i&&i.found.namespacePrefix===s.namespacePrefix}function mi(e){return e==null||e===""}var Vr=class{entries=new Map;get size(){return this.entries.size}add(t,n=1){let r=[t.kind,t.objectApiName,t.field??"",t.recordType??"",t.from??"",t.to??""].join("\0"),o=this.entries.get(r);if(o){o.rows+=n;return}this.entries.set(r,{...t,rows:n})}list(){return[...this.entries.values()].map(t=>({...t}))}},ot=class{picklists=new Map;defaults=new Map;truncated=new Map;skipped=new Map;ignoredGaps;constructor(t){for(let n of t?.picklistValueMappings??[]){let r=this.picklists.get(n.object)??[];r.push(n),this.picklists.set(n.object,r)}for(let n of t?.defaultValues??[]){let r=this.defaults.get(n.object)??[];r.push(n),this.defaults.set(n.object,r)}for(let{object:n,field:r}of t?.truncateFields??[]){let o=this.truncated.get(n)??new Set;o.add(r),this.truncated.set(n,o)}this.ignoredGaps=new Set(t?.ignoredGaps??[]);for(let n of t?.skippedRows??[]){let r=Qr(n);if(!("held"in r))continue;let o=this.skipped.get(n.object)??[];o.push(r.held),this.skipped.set(n.object,o)}}skipsRowsOf(t){return this.skipped.has(t)}namesARecordTypeBare(t){return[...(this.picklists.get(t)??[]).map(r=>r.recordType),...(this.skipped.get(t)??[]).map(r=>r.recordType)].some(r=>r!==void 0&&r!==rt&&Xe(r).namespacePrefix===void 0)}holdsBack(t,n,r,o,s){for(let i of this.skipped.get(t)??[]){if(!zr(i.recordType,r,s))continue;let a=n(i.field);if(!(typeof a!="string"||!a.split(";").includes(i.value)))return o.add({kind:"skip_rows",objectApiName:t,field:i.field,...i.recordType!==void 0?{recordType:i.recordType}:{},from:i.value}),!0}return!1}changesRowsOf(t){return this.picklists.has(t)||this.defaults.has(t)}defaultOf(t,n){let r=this.defaults.get(t)?.find(o=>o.field===n);return r===void 0?void 0:String(r.value)}applyToRow(t,n,r,o,s){for(let i of this.picklists.get(t)??[]){if(!zr(i.recordType,r,s))continue;let a=n[i.field];if(typeof a!="string"||a==="")continue;let d=a.split(";");if(!d.includes(i.from))continue;let c=d.flatMap(u=>u!==i.from?[u]:i.to===null?[]:[i.to]);c.length===0?delete n[i.field]:n[i.field]=[...new Set(c)].join(";"),o.add({kind:i.to===null?"leave_empty":"map_value",objectApiName:t,field:i.field,...i.recordType!==void 0?{recordType:i.recordType}:{},from:i.from,...i.to!==null?{to:i.to}:{}})}for(let{field:i,value:a}of this.defaults.get(t)??[])mi(n[i])&&(n[i]=a,o.add({kind:"set_default",objectApiName:t,field:i,to:String(a)}))}truncate(t,n,r,o){for(let s of this.truncated.get(t)??[]){let i=n[s],a=r.get(s);typeof i!="string"||a===void 0||a<=0||i.length<=a||(n[s]=i.slice(0,a),o.add({kind:"truncate",objectApiName:t,field:s}))}}truncatedFieldsOf(t){return this.truncated.get(t)??new Set}};function nc(e,t){let n=new Map(t.map(i=>[i.objectApiName,i])),r=[],o=new Map,s=[];for(let i of e){let a=n.get(i.object),d=Hr(i.object,i.from,a?.source??[],"the source");if("reason"in d){s.push({decision:i,reason:d.reason});continue}if(i.to===null){o.set(d.type.recordTypeId,i);continue}let c=Hr(i.object,i.to,a?.target??[],"the target");if("reason"in c){s.push({decision:i,reason:c.reason});continue}o.set(d.type.recordTypeId,i),r.push({sourceId:d.type.recordTypeId,targetId:c.type.recordTypeId,developerName:c.type.developerName})}return{mappings:r,bySource:o,unresolved:s}}function Hr(e,t,n,r){let o=Mt(t,n.filter(s=>!s.master),Ft);if("found"in o)return{type:o.found};if("ambiguous"in o){let s=o.ambiguous.map(Ft),i=s.find(a=>a.namespacePrefix);return{reason:er(e,t,r,s)+(i?"; a package's is named with its namespace: "+Zn(i.namespacePrefix,i.developerName):"")}}return{reason:`${r} has no ${e} record type named ${t}`}}function rc(e,t){return t.bySource.size===0?e?[...e]:void 0:[...(e??[]).filter(n=>!t.bySource.has(n.sourceId)),...t.mappings]}import{createHash as ed}from"node:crypto";var hi="__pass2__";function Jr(e){let t=e.errors??[],n=t.some(s=>s.skipped===!0),r=t.some(s=>s.objectApiName===hi&&s.failedCount>0);return e.failedCount===0&&e.failedReads.length===0&&!n&&!r?"success":e.successCount+e.updatedCount+e.linkedCount+(e.wouldInsertCount??0)>0?"partial":"failure"}function sc(e,t,n){return{forgeId:`forge-${Date.now()}`,status:n.status,graph:t,duration:Date.now()-n.startedAt,timestamp:new Date().toISOString(),idRemapCount:e.remapCount,idRemapTable:e.remapTable,idRemapExisting:e.existingSourceIds,...e.withTheirRecordSourceIds?{idRemapWithTheirRecord:e.withTheirRecordSourceIds}:{},...e.withTheirRecordCount!==void 0&&e.withTheirRecordCount>0?{withTheirRecordCount:e.withTheirRecordCount}:{},...e.linkedToCreatedCount!==void 0&&e.linkedToCreatedCount>0?{linkedToCreatedCount:e.linkedToCreatedCount}:{},createdCount:e.successCount,...e.updatedCount>0?{updatedCount:e.updatedCount}:{},linkedExistingCount:e.linkedCount,existingRecords:e.existingRecords,idRemapByObject:e.remapByObject,idRemapCreated:e.createdByObject,readByObject:e.readByObject,failedReads:e.failedReads,errors:e.errors,truncatedObjects:e.truncatedObjects,...e.cappedObjects?{cappedObjects:e.cappedObjects}:{},...e.fieldExclusionsUnmatched?{fieldExclusionsUnmatched:e.fieldExclusionsUnmatched}:{},...e.orphanParentsCapped?{orphanParentsCapped:e.orphanParentsCapped}:{},...e.files?{files:e.files}:{},...e.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:e.fileContentFieldsLeftOut}:{},...e.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:e.encryptedFieldsLeftOut}:{},...e.picklistValuesChanged?{picklistValuesChanged:e.picklistValuesChanged}:{},...e.currenciesReplaced?{currenciesReplaced:e.currenciesReplaced}:{},...e.recordTypesGiven?{recordTypesGiven:e.recordTypesGiven}:{},...e.writtenWithoutFields?{writtenWithoutFields:e.writtenWithoutFields}:{},...e.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:e.lookupsLeftEmptyByFilter}:{},...e.contactPoints?{contactPoints:e.contactPoints}:{},...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.apiCalls!==void 0?{apiCalls:e.apiCalls}:{},...e.dryRun?{dryRun:!0,wouldInsertCount:e.wouldInsertCount}:{},...e.gaps?{gaps:e.gaps}:{},...e.decisionsApplied?{decisionsApplied:e.decisionsApplied}:{},...e.mayHaveBeenWritten?{mayHaveBeenWritten:e.mayHaveBeenWritten}:{},...e.remapInJournal?{remapInJournal:!0}:{},...e.sample?{sample:e.sample}:{},...e.roots?{roots:e.roots}:{},...e.reads?{reads:e.reads}:{}}}var Kr="RUN_CANCELLED";function uc(e){return{idRemapByObject:e.remapByObject,errors:e.errors,notSentByObject:e.notSentByObject,writtenWithoutFields:e.writtenWithoutFields,mayHaveBeenWritten:e.mayHaveBeenWritten}}function cc(e){let t=new Map,n=r=>{let o=t.get(r)??Yn(r);return t.set(r,o),o};for(let r of e.idRemapByObject??[]){let o=n(r.objectApiName);o.created+=r.created,o.updated+=r.updated??0}for(let r of e.errors??[]){if(r.objectApiName.startsWith("__")||r.referenceData===!0||r.stage==="scope"&&r.failedCount===0&&r.skipped!==!0)continue;let o=n(r.objectApiName);o.failed+=r.failedCount,r.skipped===!0&&(o.skipped=r.failedCount>0?"counted":"uncounted")}for(let r of e.notSentByObject??[]){let o=n(r.objectApiName);o.notSent=(o.notSent??0)+r.notSent}for(let r of e.writtenWithoutFields??[]){let o=n(r.objectApiName);o.writtenWithoutFields=(o.writtenWithoutFields??0)+r.rows}for(let{objectApiName:r,sourceIds:o}of e.mayHaveBeenWritten??[]){let s=n(r);s.mayHaveBeenWritten=(s.mayHaveBeenWritten??0)+o.length}return[...t.values()]}function lc(e,t){return t.some(r=>r.created+r.updated>0)?"cancelled":(e?Jr(e):"success")==="success"?"stopped":"cancelled"}function fc(e){return e?{details:{contactPoints:e.neutralized?"neutralized":"kept",contactPointFields:e.fields.length,contactPointValues:e.values}}:{}}function gc(e){return Object.fromEntries((e.idRemapByObject??[]).map(t=>[t.objectApiName,t.created+t.linked+(t.updated??0)]))}var $c=2e3,Pc=1e4,yi=Rn;function Mc(e,t,n=yi){let r=t!==void 0&&t>0?Math.floor(t):void 0;return r!==void 0&&r<=n?[]:e.nodes.filter(o=>o.included&&o.recordCountUnknown!==!0).map(o=>({objectApiName:o.objectApiName,rows:r===void 0?o.recordCount:Math.min(o.recordCount,r)})).filter(o=>o.rows>n).sort((o,s)=>s.rows-o.rows)}var ao=.8,uo=.5;function qt(e){return Math.max(0,e.remainingMB-uo-(e.uncountedWrites?.mb??0))}var ve=1024,it=2*ve,co=4*ve,wi=8*ve,Ri=1*ve,bi=4*ve,Si=255,Ai=/__kav$/i,Ei=new Map([Oe,Ke,Ye,"Campaign","CampaignMember"].map(e=>[e.toLowerCase(),e]));function at(e){return Ei.get(e.toLowerCase())??e}function Yr(e,t=0){let n=0;for(let r of Object.values(e))typeof r=="string"&&r.length>t&&(n+=Buffer.byteLength(r,"utf8"));return n}function Dt(e,t){let n=at(e);return n===Oe?Yr(t):n===Ke?Pt(t)?co:it:n===Ye&&Pt(t)?0:n==="Campaign"?wi:n==="CampaignMember"?Ri:Ai.test(e)?bi+Yr(t,Si):it}function lo(e,t){let n=Math.min(t.personAccounts??0,t.rows),r=t.rows-n,o=at(e);return o===Ke?r*it+n*co:o===Ye?r*it:r*Dt(e,{})}function Ti(e){let t=e.map(({objectApiName:m,rows:w,counted:R,mayAdd:b=0,mayBeByThePlatform:P})=>{let M={rows:b,storageBytes:b*Dt(m,{}),...b>0?{mayAdd:b}:{},...P&&P.rows>0?{mayBeByThePlatform:P}:{}};return R?{objectApiName:m,...M,rows:R.rows+M.rows,storageBytes:lo(m,R)+M.storageBytes}:{objectApiName:m,...M,rows:w.length+M.rows,storageBytes:w.reduce((z,E)=>z+Dt(m,E),0)+M.storageBytes}}).filter(({rows:m})=>m>0).sort((m,w)=>w.rows-m.rows||m.objectApiName.localeCompare(w.objectApiName)),n=e.reduce((m,w)=>m+(w.leftOut?.writtenBefore??0),0),r=e.filter(m=>(m.leftOut?.heldBack??0)>0).map(({objectApiName:m,leftOut:w})=>({objectApiName:m,rows:w?.heldBack??0})),o=e.filter(m=>(m.leftOut?.byThePlatform??0)>0).map(({objectApiName:m,leftOut:w})=>({objectApiName:m,rows:w?.byThePlatform??0})),s=e.flatMap(({objectApiName:m,leftOut:w})=>w?.linkedByValue&&w.linkedByValue.rows>0?[{objectApiName:m,...w.linkedByValue}]:[]),i=m=>e.filter(w=>(w.leftOut?.[m]??0)>0).map(({objectApiName:w,leftOut:R})=>({objectApiName:w,rows:R?.[m]??0})),a=i("recordTypeNotInTarget"),d=i("withoutParent"),c=i("noParentInSource"),u=i("outsideFilter"),f=i("linkedToTarget"),g=i("currencyReplaced"),p=e.flatMap(({objectApiName:m,leftEmpty:w=[]})=>w.filter(({rows:R})=>R>0).map(({field:R,rows:b})=>({objectApiName:m,field:R,rows:b})));return{objects:t,...p.length>0?{leftEmpty:p}:{},totalRows:t.reduce((m,w)=>m+w.rows,0),storageBytes:t.reduce((m,w)=>m+w.storageBytes,0),...n>0||r.length>0||a.length>0||o.length>0||s.length>0||d.length>0||c.length>0||u.length>0||f.length>0||g.length>0?{leftOut:{writtenBefore:n,heldBack:r,...a.length>0?{recordTypeNotInTarget:a}:{},...o.length>0?{byThePlatform:o}:{},...s.length>0?{linkedByValue:s}:{},...d.length>0?{withoutParent:d}:{},...c.length>0?{noParentInSource:c}:{},...u.length>0?{outsideFilter:u}:{},...f.length>0?{linkedToTarget:f}:{},...g.length>0?{currencyReplaced:g}:{}}}:{}}}function Fc(e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null,...e.queryScope==="records"?["records"]:[]])}var Oi=16,Xr=class{kept=new Map;note(t,n,r=Date.now()){this.kept.delete(t),this.kept.set(t,{at:r,total:n.totalRows,objects:n.objects.map(({objectApiName:o,rows:s})=>({objectApiName:o,rows:s}))});for(let o of this.kept.keys()){if(this.kept.size<=Oi)break;this.kept.delete(o)}}of(t){return this.kept.get(t)}},ki=500;function $i(e,t){return e>2*t||e-t>ki}function vc(e,t,n=Date.now()){return{minutesBefore:Math.max(1,Math.ceil((n-e.at)/6e4)),total:e.total,objects:e.objects.map(({objectApiName:r,rows:o})=>({objectApiName:r,rows:o})),...$i(t,e.total)?{farAbove:!0}:{}}}function Nc(e){let t=e.objects.reduce((n,r)=>n+(r.mayAdd??0),0);return t>0?{pricesForLines:t}:{}}function Bc(e){let t=e.objects.find(n=>n.mayBeByThePlatform)?.mayBeByThePlatform;return!t||t.rows<=0?{}:{rolesMayBeByThePlatform:{rows:t.rows,...t.before===!0?{before:!0}:{}}}}function xc(e,t){return t===void 0?e:{request:n=>e.request(n),writtenTo:t}}var st=B({Max:G(),Remaining:G()}).loose(),Pi=B({DataStorageMB:st,DailyApiRequests:st.optional(),DailyBulkApiBatches:st.optional(),FileStorageMB:st.optional()}).loose(),Mi=B({DailyApiRequests:B({Max:G(),Remaining:G()}).loose()}).loose(),Fi="the org does not tell this user its daily API requests";function fo(e,t,n){if(e!==null&&typeof e=="object"&&!(t in e))throw new Error(n)}async function vi(e){let t=await e.request({method:"GET",url:"/limits"});fo(t,"DataStorageMB",yn);let n=Pi.parse(t),r=n.DataStorageMB.Remaining,o=e.writtenTo,s=o!==void 0?Kn(o,r,(i,a)=>lo(i,{rows:a})):void 0;return o!==void 0&&Jn(o,r),{maxMB:n.DataStorageMB.Max,remainingMB:r,...s?{uncountedWrites:s}:{},...n.DailyApiRequests?{dailyApiRequests:{max:n.DailyApiRequests.Max,remaining:n.DailyApiRequests.Remaining}}:{},...n.DailyBulkApiBatches?{dailyBulkApiBatches:{max:n.DailyBulkApiBatches.Max,remaining:n.DailyBulkApiBatches.Remaining}}:{},...n.FileStorageMB?{fileStorage:{maxMB:n.FileStorageMB.Max,remainingMB:n.FileStorageMB.Remaining}}:{}}}async function Zr(e){let t=await e.request({method:"GET",url:"/limits"});fo(t,"DailyApiRequests",Fi);let n=Mi.parse(t);return{max:n.DailyApiRequests.Max,remaining:n.DailyApiRequests.Remaining}}var Lt=200,go=2e3,Ni=.1;function Bi(e){return e.reduce((t,{rows:n,bulk:r,readRows:o,perCall:s})=>{let i=Math.min(Lt,Math.max(1,s??Lt)),a=n<=0?0:r?sr(n):Math.ceil(n/i),d=o&&o>0?Math.ceil(o/go):0;return t+a+d},0)}var zt=["checkpoint","mute","readBack","deliverability","fit"],xi={checkpoint:"for the checkpoint taken first",mute:"to assign and take back the permission sets that mute the target's automation",readBack:"to read back the record types the target gave",deliverability:"to read whether the target delivers its emails",fit:"to fit the run to the storage"};function Ci(e){return zt.reduce((t,n)=>t+Math.max(0,e[n]??0),e.run)}function _i(e){return zt.some(t=>(e[t]??0)>0)?{...e}:void 0}function jt(e,t){let n=typeof e=="number"?void 0:_i(e),r=typeof e=="number"?e:Ci(e),o=n?{parts:n}:{};if(!t)return{verdict:"unread",estimate:r,unread:"the limits the org answered list no DailyApiRequests",...o};if("unread"in t)return{verdict:"unread",estimate:r,unread:t.unread,...o};let{max:s,remaining:i}=t;return{verdict:r>i?"exceeds":i-r<Ni*s?"near":"fits",estimate:r,max:s,remaining:i,...o}}function Ii(e){if(!e)return"";let t=zt.filter(n=>(e[n]??0)>0).map((n,r)=>`${e[n]}${r===0?" of them":""} ${xi[n]}`);return t.length>0?` (${t.join(", ")})`:""}var Pe="API_BUDGET_EXCEEDED";function ji(e,t,n){if(e.verdict==="exceeds")return`The run takes about ${e.estimate} API requests${Ii(e.parts)}, and ${t} has ${e.remaining} of its ${e.max} daily requests left: it would stop part way through, its records refused with REQUEST_LIMIT_EXCEEDED. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records. `+(n?`${n} `:"")+"Nothing was written."}function Di(e){return e.verdict==="near"?{apiRequests:{estimate:e.estimate,remaining:e.remaining,max:e.max,...e.parts?{parts:{...e.parts}}:{}}}:{}}var dt="CHECKPOINT_REFUSED";function Li(e){return e?{checkpoint:e.estimate.apiRequests}:{}}function Wi(e){let t=e?.refusal;if(t!==void 0)return{code:dt,message:Nt(t),refusal:t}}var Ui="The run was stopped while it took the checkpoint first: nothing of it was kept, and nothing was written.";async function Cc(e){let t;try{t=await e()}catch(n){return{stop:{code:dt,message:wr(n)}}}return t.taken?{checkpoint:t.checkpoint}:"stopped"in t?{stop:{code:Kr,message:Ui}}:{stop:{code:dt,message:Nt(t.refusal),refusal:t.refusal}}}var eo=1e4,Gi=1e4,qi=.01;function zi(e,t,n){return t<2e3||hr.has(e)||(n??yr).has(e)}function ut(e,t,n){if(t<=0)return{jobs:[],rest:0};if(zi(e,t,n.restOnly))return{jobs:[],rest:t};let r=[];for(let o=t;o>0;o-=eo){let s=Math.min(o,eo);if(s<2e3)return{jobs:r,rest:s};r.push(s)}return{jobs:r,rest:0}}function Vi(e){return nr({stateReads:or(e,tr,"save")})}function Hi(e,t,n){let{jobs:r,rest:o}=ut(e,t,n);return r.reduce((s,i)=>s+Vi(i),0)+Math.ceil(o/Lt)}var Qi=4,Ji=3;function Ki(e){let t=new Set(e.updatedAfterInsert??[]),n=new Map((e.plan.leftOut?.linkedByValue??[]).map(({objectApiName:d,rows:c})=>[d,c])),r=[...e.plan.objects.map(({objectApiName:d,rows:c})=>({objectApiName:d,rows:c+(n.get(d)??0)})),...[...n].filter(([d])=>!e.plan.objects.some(c=>c.objectApiName===d)).map(([d,c])=>({objectApiName:d,rows:c}))],o=e.plan.objects.filter(({objectApiName:d})=>t.has(d)).map(({objectApiName:d,rows:c})=>({objectApiName:d,rows:c})),{bulk:s}=e,i=e.files!==void 0&&e.files>0?e.files:0,a=s?Qi*r.filter(({rows:d})=>d>0).length:0;return{run:(s?[...r,...o].reduce((d,{objectApiName:c,rows:u})=>d+Hi(c,u,s),0):Bi([...r,...o]))+i+a+Math.max(0,e.sentBefore??0),...Li(e.checkpoint),...e.mute!==void 0&&e.mute>0?{mute:e.mute}:{},...e.readBack!==void 0&&e.readBack>0?{readBack:e.readBack}:{},...e.deliverability!==void 0&&e.deliverability>0?{deliverability:e.deliverability}:{}}}var Yi=200;function Xi(e){let t={...e.measures.restOnly?{restOnly:e.measures.restOnly}:{}},n=new Set(e.updatedAfterInsert??[]),r=e.plan.objects.map(({objectApiName:a,rows:d})=>({objectApiName:a,rows:d,writes:ut(a,d,t),updates:n.has(a)?ut(a,d,t):void 0})),o=r.flatMap(({writes:a,updates:d})=>d?[a,d]:[a]),s=e.measures.files,i=s&&"count"in s&&s.count>0?s.count:0;return{objects:r.map(({objectApiName:a,rows:d,writes:c})=>({objectApiName:a,rows:d,jobs:c.jobs.length})),sourceRequests:(e.measures.sourceReads??r.reduce((a,{rows:d})=>a+Math.ceil(Math.max(0,d)/go),0)+i+Math.ceil(i/Yi))+Ji*r.filter(({rows:a})=>a>0).length+(e.sourceSentBefore===void 0?Math.max(0,e.measures.heldReads??0):Math.max(0,e.sourceSentBefore)),bulkBatches:o.reduce((a,{jobs:d})=>a+d.reduce((c,u)=>c+Math.ceil(u/Gi),0),0),durationSeconds:o.reduce((a,{jobs:d,rest:c})=>a+d.reduce((u,f)=>u+rr(f,"save"),0)+c*qi,0),restObjects:r.filter(({rows:a,writes:d})=>a>0&&d.jobs.length===0).map(({objectApiName:a})=>a)}}var Zi="the limits the org answered list no DailyBulkApiBatches";function ea(e,t){if(e.verdict==="exceeds")return`The run writes through Bulk API jobs that take about ${e.estimate} of the daily Bulk API batches, and ${t} has ${e.remaining} of its ${e.max} left: its jobs would be refused part way through. Run it once the org has batches to spare \u2014 the limit is counted over the last 24 hours, and Bulk API 1.0 shares it \u2014 or leave objects out. Nothing was written.`}function ta(e,t){if(e.verdict==="exceeds")return`The run reads the source records in about ${e.estimate} API requests, and ${t} has ${e.remaining} of its ${e.max} daily requests left: the reads would stop part way through, and the org's own integrations with them. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or leave objects out. Nothing was written.`}function na(e,t){if(e.verdict==="exceeds")return`The files to copy take about ${Z(e.estimateMB)} MB of file storage, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB${be(ge(e),t)}: leave out the objects whose files take it, turn the copy of files off on Review, or free file storage in ${t}. Nothing was written.`}function ra(e,t){return`A clone of the whole org reads a few objects whole, and ${e.map(({objectApiName:r,rows:o})=>`${r} (${o} rows)`).join(", ")} ${e.length===1?"holds":"hold"} more than the ${t} rows of one object the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting or leave the object out on Review. Nothing was written.`}var oa=200;function sa(e){if(!e||e.length===0)return;let t=Math.min(...e.map(r=>r.bound)),n=e.map(({objectApiName:r,rows:o})=>({objectApiName:r,rows:o}));return{code:"READ_BOUND_EXCEEDED",message:ra(n,t),readBound:{bound:t,objects:n.slice(0,oa)}}}var po="FILES_UNREAD",mo="FILE_STORAGE_UNREAD";function ia(e,t,n){if(!e)return{};if("unmeasured"in e)return{files:{unmeasured:!0},stop:{code:po,message:`The source would neither sum nor list its files, so what they take of the file storage ${n} has left is not known: turn the copy of files off on Review, or run it again once the source answers. Nothing was written.`}};if(e.count<=0)return{};let r=ho({storageBytes:e.bytes},"unread"in t?t:t.fileStorage??{unread:"the limits the org answered list no FileStorageMB"});if(r.verdict==="unread")return{files:{count:e.count,check:r},stop:{code:mo,message:`The file storage ${n} has left could not be read (${r.unread}), so the ${e.count} files to copy could not be checked against it: turn the copy of files off on Review, or run it again once the org answers. Nothing was written.`}};let o=na(r,n);return{files:{count:e.count,check:r},...o!==void 0&&r.verdict==="exceeds"?{stop:{code:"STORAGE_EXCEEDED",message:o,storage:{estimateMB:Number(Z(r.estimateMB)),remainingMB:r.remainingMB,kind:"files",...ge(r)}}}:{}}}function aa(e){let t=e.wholeOrg,n=t?.measures.files,r=jt(Ki({...e,...t?{bulk:t.measures.restOnly?{restOnly:t.measures.restOnly}:{},...n&&"count"in n?{files:n.count}:{}}:{}}),e.budget),o=ji(r,e.target,ir),s=[],i=Wi(e.checkpoint);i&&s.push(i),o!==void 0&&s.push({code:Pe,message:o,...t&&r.verdict==="exceeds"?{api:{kind:"requests",org:"target",estimate:r.estimate,remaining:r.remaining}}:{}});let a;if(t){let f=Xi({...e,measures:t.measures,...t.sourceSentBefore!==void 0?{sourceSentBefore:t.sourceSentBefore}:{}}),g=f.bulkBatches>0?jt(f.bulkBatches,t.bulkBatches??{unread:Zi}):void 0,p=g&&ea(g,e.target);p!==void 0&&g?.verdict==="exceeds"&&s.push({code:Pe,message:p,api:{kind:"bulkBatches",org:"target",estimate:g.estimate,remaining:g.remaining}});let m=jt(f.sourceRequests,t.sourceBudget),w=ta(m,t.source);w!==void 0&&m.verdict==="exceeds"&&s.push({code:Pe,message:w,api:{kind:"requests",org:"source",estimate:m.estimate,remaining:m.remaining}}),a={source:m,...g?{bulkBatches:g}:{},cost:f}}let[d,...c]=s,u=c.filter(f=>f.code===Pe);return{api:r,...d?{stop:d}:{},...t&&u.length>0?{alsoRefused:u}:{},...a?{wholeOrg:a}:{},asks:e.checkpoint!==void 0||t!==void 0,confirmation:{...Di(r),...e.checkpoint?{checkpoint:e.checkpoint}:{}}}}function ho(e,t,n=0){let r=Math.max(0,n),o=e.storageBytes+r,s=o/1048576,i=r>0?{automationMB:r/1048576}:{};if("unread"in t)return{verdict:"unread",estimateMB:s,unread:t.unread,...i};let{maxMB:a,remainingMB:d,uncountedWrites:c}=t,u=qt(t)*1048576;return{verdict:o>u?"exceeds":o>ao*u?"near":"fits",estimateMB:s,maxMB:a,remainingMB:d,...i,...c?{uncountedWrites:c}:{}}}function ge(e){if(e.verdict==="unread")return{};let t=e.uncountedWrites?.mb??0,n=e.verdict==="exceeds"&&e.estimateMB<=e.remainingMB-t;return{...e.uncountedWrites?{uncountedWrites:e.uncountedWrites}:{},...n?{roundingMB:uo}:{}}}function be(e,t){let{uncountedWrites:n,roundingMB:r}=e,o=[...n?[`about ${Z(n.mb)} MB of it taken by what ${n.runs===1?"a run":`${n.runs} runs`} from this machine wrote to ${t} in the last ${n.minutes} minute(s), which Salesforce has not counted yet`]:[],...r!==void 0?[`up to ${r} MB of it may be taken already: Salesforce says it to the MB`]:[]];return o.length>0?` (${o.join("; ")})`:""}function da(e,t){if(!t||t.length===0)return 0;let n=new Map;for(let{objectApiName:r,bytes:o}of t)n.set(r,(n.get(r)??0)+Math.max(0,o));return e.objects.reduce((r,{objectApiName:o,rows:s})=>r+s*(n.get(o)??0),0)}function lt(e){return`about ${Z(e.estimateMB)} MB of data storage`+(e.automationMB!==void 0&&e.automationMB>0?`, about ${Z(e.automationMB)} MB of it for what the target's automation creates under them`:"")}function ua(e,t){let n=Ti(e),r=t.emailTextBytes,o=e.some(i=>at(i.objectApiName)===Oe&&i.counted);if(r===void 0||!Number.isFinite(r)||!o)return n;let s=n.objects.map(i=>at(i.objectApiName)===Oe?{...i,storageBytes:i.storageBytes+Math.max(0,r)}:i);return{...n,objects:s,storageBytes:s.reduce((i,a)=>i+a.storageBytes,0)}}function ca(e,t,n){return e.flatMap(({objectApiName:r,included:o,piiFields:s,anonymizeFields:i})=>{if(!o||!t.has(r))return[];let a=new Set(n?i:[]),d=s.filter(c=>!a.has(c));return d.length>0?[{objectApiName:r,fields:d}]:[]})}function la(e){let t=e.leftOut??[],n=new Set(t.map(({objectApiName:s})=>s)),r=[...t,...e.nodes.filter(s=>s.leftOutByUser===!0&&!n.has(s.objectApiName)).map(({objectApiName:s})=>({objectApiName:s,reason:"excludedByUser"}))],o=new Map;for(let{reason:s}of r)o.set(s,(o.get(s)??0)+1);return{objects:r,counts:[...o].map(([s,i])=>({reason:s,count:i})).sort((s,i)=>i.count-s.count||s.reason.localeCompare(i.reason))}}var fa=2;async function _c(e){let t=R=>({unread:F(R)}),n=ua(e.objects,e.measures),r=await vi(e.target.limits).catch(t),o="unread"in r?await Zr(e.target.limits).catch(t):r.dailyApiRequests,s=await Zr(e.source.limits).catch(t),i=ho(n,r,da(n,e.automation)),a=Va(i,e.target.org),d=e.sample?wa({sample:e.sample,storage:r,target:e.target.org,...e.sampleAsked?{asked:e.sampleAsked}:{}}):void 0,c=ia(e.measures.files,r,e.target.org),u=e.sentBefore?.(),f=aa({plan:n,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...e.readBack!==void 0?{readBack:e.readBack}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{},...e.mute!==void 0?{mute:e.mute}:{},deliverability:e.deliverability??fa,...u?{sentBefore:u.target}:{},budget:o,target:e.target.org,wholeOrg:{measures:e.measures,bulkBatches:"unread"in r?r:r.dailyBulkApiBatches,sourceBudget:s,source:e.source.org,...u?.source!==void 0?{sourceSentBefore:u.source}:{}}}),g=[sa(e.measures.readWholeOver),d,d===void 0&&a!==void 0&&i.verdict==="exceeds"?{code:"STORAGE_EXCEEDED",message:`${a} Nothing was written.`,storage:{estimateMB:Number(Z(i.estimateMB)),remainingMB:i.remainingMB,...ge(i)}}:void 0,c.stop,f.stop,...f.alsoRefused??[]].filter(R=>R!==void 0),p=e.measures.restOnly?{restOnly:e.measures.restOnly}:{},m=new Set(n.objects.map(({objectApiName:R})=>R)),{wholeOrg:w}=f;return{wouldInsert:n.objects.map(({objectApiName:R,rows:b})=>{let{jobs:P,rest:M}=ut(R,b,p);return{objectApiName:R,rows:b,jobs:P.length,byRest:M}}),totalRows:n.totalRows,targetRequests:f.api,sourceRequests:w.source,...w.bulkBatches?{bulkBatches:w.bulkBatches}:{},storage:i,...c.files?{files:c.files}:{},durationSeconds:w.cost.durationSeconds,leftOut:{...la(e.graph),...n.leftOut?{rows:n.leftOut}:{}},personalAsIs:ca(e.graph.nodes,m,e.anonymizePII),wouldBeRefused:g,...e.measures.personAccountsAsBusiness?{personAccountsAsBusiness:e.measures.personAccountsAsBusiness}:{},...e.sample?{sample:e.sample}:{}}}var ga="SAMPLE_STORAGE_UNREAD",yo="SAMPLE_CANNOT_FIT",pa="SAMPLE_TOO_LARGE",wo="SAMPLE_PLAN_MISMATCH",Wt="SAMPLE_PLAN_GONE";function ma(e){let{storage:t,bounds:n,target:r}=e;if("unread"in t&&!(n.withinMB!==void 0||n.maxTotal!==void 0))return{code:ga,message:`The data storage ${r} has left could not be read (${t.unread}), and a sample is fitted to it: there is nothing to hold it to. Give the most it may take (--fit-within <MB>) or the most records (--max-total <n>), or run it again once the org answers. Nothing was written.`}}function ha(e,t){if(e.remainingMB===void 0||e.share===void 0)return;let n=Math.max(0,t.remainingMB-(e.roundingMB??0)-(t.uncountedWrites?.mb??0));return Math.floor(e.share*n*1048576)}function ya(e){let{sample:t,storage:n,target:r}=e,o=ha(t.budget,n);if(o===void 0||t.storageBytes<=o)return;let s=$o(t.storageBytes/1048576,o/1048576),i=Z(t.budget.bytes/1048576),a=n.uncountedWrites;return{code:"STORAGE_EXCEEDED",message:`The sample was fitted to ${i} MB of the data storage ${r} had left (${t.budget.remainingMB} MB), and ${r} now says ${n.remainingMB} MB left${be(a?{uncountedWrites:a}:{},r)}, which holds ${s.bound} MB of a sample: the sample takes about ${s.over} MB. Simulate again \u2014 run the dry run again \u2014 to draw a sample that fits: a run never cuts its sample short. Nothing was written.`,storage:{estimateMB:Number(s.over),remainingMB:n.remainingMB,...a?{uncountedWrites:a}:{}},sample:{fittedMB:Number(i),holdsMB:Number(s.bound)}}}function wa(e){let{sample:t,storage:n,target:r}=e;return"unread"in n?ma({storage:n,bounds:e.asked??t.budget,target:r}):ya({sample:t,storage:n,target:r})}var Ra=new Set(["gone","changed","otherOrg","otherSetup","otherSha"]),ba={changed:"is no longer as its dry run wrote it: its ids changed since",otherOrg:"was drawn of another org than the source",otherSetup:"was drawn for another setup of the run \u2014 other flags, filters, objects or options of the sample",otherSha:"is not the plan its dry run printed"};function Sa(e,t){return t==="resume"?{code:Wt,message:`The plan of the sample this run resumes ${e==="gone"?"is no longer on this machine":"is no longer as it was written"}: the records it was to write cannot be taken up after where it stopped (--resume). Remove what it wrote (--remove), or run the clone again without --resume to draw a new sample. Nothing was written.`,sample:{plan:e}}:e==="gone"?{code:Wt,message:'No plan of a sample is at the path given to --fit-plan: give the folder its dry run printed ("sample plan: \u2026"), within a day of it, or leave --fit-plan out to draw a new sample. Nothing was written.',sample:{plan:e}}:{code:wo,message:`The plan given to --fit-plan ${ba[e]}: run the dry run again with the flags of this run, and replay the plan it prints. Nothing was written.`,sample:{plan:e}}}var Aa=new Set([pa,yo,Wt,wo]),Ea=20;function Ic(e,t){if(e instanceof Error){if(e.name==="SampleRefusedError"){let{code:n,heaviest:r,sample:o}=e;if(typeof n!="string"||!Aa.has(n))return;let s=Array.isArray(r)?r.flatMap(d=>{let c=d?.objectApiName;return typeof c=="string"?[c]:[]}):[],i=En({code:n,sample:o})?.sample??{},a={...i,...n===yo&&i.heaviest===void 0&&s.length>0?{heaviest:s.slice(0,Ea)}:{}};return fe.of({code:n,message:e.message,...Object.keys(a).length>0?{sample:a}:{}})}if(e.name==="SamplePlanError"&&t!=="draw"){let{refusal:n}=e;return typeof n!="string"||!Ra.has(n)?void 0:fe.of(Sa(n,t))}}}var Ta=B({SingleEmail:B({Max:G(),Remaining:G()}).loose().optional(),DailyWorkflowEmails:B({Max:G(),Remaining:G()}).loose().optional()}).loose();async function jc(e){let t=Ta.parse(await e.request({method:"GET",url:"/limits"})),n={};for(let r of["SingleEmail","DailyWorkflowEmails"]){let o=t[r];o&&(n[r]={max:o.Max,remaining:o.Remaining})}return n}var Oa=15;function Ro(e){let t=e.SingleEmail;return t!==void 0&&t.max<=Oa}function ka(e){return Ro(e)&&e.DailyWorkflowEmails!==void 0}function $a(e,t,n=!1){let r=e.map(a=>({...a,sentBy:[...a.sentBy]})),o=(a,d)=>{let c=r.find(u=>u.objectApiName===a.objectApiName&&u.limit===d);if(!c){let u={...a,limit:d,sentBy:[...a.sentBy]};return r.push(u),u}c.perRecord+=a.perRecord;for(let u of a.sentBy)c.sentBy.includes(u)||c.sentBy.push(u);return c},s=e.filter(a=>a.limit==="SingleEmail"),i=e.filter(a=>a.limit==="DailyWorkflowEmails");if(n)for(let a of s)o(a,"DailyWorkflowEmails");if(t)for(let a of i)o(a,"SingleEmail").alertsAmong=!0;return r}function bo(e){let t=new Map(e.objects.map(n=>[n.objectApiName,{rows:n.rows,byThePlatform:0}]));for(let{objectApiName:n,rows:r}of e.leftOut?.byThePlatform??[]){let o=t.get(n)??{rows:0,byThePlatform:0};t.set(n,{rows:o.rows+r,byThePlatform:o.byThePlatform+r})}return t}function Vt(e){return new Set([...bo(e)].flatMap(([t,{rows:n}])=>n>0?[t]:[]))}function Pa(e,t,n){let r=bo(e),o=new Map;for(let i of t){let{rows:a,byThePlatform:d}=r.get(i.objectApiName)??{rows:0,byThePlatform:0};if(a===0)continue;let c=o.get(i.limit)??{limit:i.limit,objects:[],emails:0,verdict:"fits"};c.objects.push({objectApiName:i.objectApiName,rows:a,perRecord:i.perRecord,sentBy:i.sentBy,...d>0?{byThePlatform:d}:{}}),c.emails+=a*i.perRecord,o.set(i.limit,c)}let s=ct(n)?n.unread:void 0;return[...o.values()].map(i=>{if(s!==void 0||ct(n))return{...i,verdict:"unread",unread:s};let a=n[i.limit];return a?{...i,verdict:i.emails>a.remaining?"exceeds":"fits",remaining:a.remaining,max:a.max}:{...i,verdict:"unread",unread:`the org's limits list no ${i.limit}`}})}function ct(e){return typeof e.unread=="string"}function Ma(e,t,n){let r=!ct(n)&&Ro(n),o=!ct(n)&&ka(n),s=Pa(e,$a(t,r,o),n);if(!r)return s;let i=Vt(e);return t.some(d=>d.limit==="DailyWorkflowEmails"&&i.has(d.objectApiName))?s.map(d=>d.limit==="SingleEmail"?{...d,alertsCounted:!0}:d):s}async function Dc(e){if(e.plan.totalRows===0||e.objects.length===0)return{checks:[]};let t;try{t=await e.readAutomation(e.objects)}catch(i){return{checks:[],unread:`the target's automation: ${F(i)}`}}let n=va(t,Fa(e.plan)),r=n!==void 0?{unread:n}:{},o=In(t);if(o.length===0)return{checks:[],...r};let s=await e.readLimits().catch(i=>({unread:F(i)}));return{checks:Ma(e.plan,o,s),...r}}function Fa(e){let t=Vt(e);return(n,r)=>r==="insert"&&t.has(n)}function va(e,t,n="the target's"){let r=[So(e.unread,n),xa(e,t)].filter(o=>o!==void 0).join("; ");return r!==""?r:void 0}var Na={flows:"flows",processes:"processes",workflowRules:"workflow rules"};function So(e,t){let n=e.flatMap(({part:r,reason:o})=>{let s=Na[r];return s!==void 0?[`${t} ${s}: ${o}`]:[]});return n.length>0?n.join("; "):void 0}var we=10;function Ba(e){if(e.condition!=="unreadable")return;let t=e.apiName.indexOf("__");return t>0?e.apiName.slice(0,t):void 0}function xa(e,t){let n=e.objects.flatMap(o=>{let i=[...new Set(ze(o).filter(d=>t(o.objectApiName,d.write)).flatMap(d=>d.fired).flatMap(({flow:d,keptQuiet:c})=>d!==void 0&&c!==!0&&d.condition!=="read"&&d.timing!=="beforeSave"?[d]:[]))].map(d=>{let c=Ba(d);return c!==void 0?`${d.label} (package ${c}, whose flows the org lets no one read)`:d.label});if(i.length===0)return[];let a=i.length>we?` and ${i.length-we} more`:"";return[{count:i.length,words:`${i.slice(0,we).join(", ")}${a} on ${o.objectApiName}`}]});return n.length===0?void 0:`the definition${n.reduce((o,{count:s})=>o+s,0)===1?"":"s"} of ${n.map(({words:o})=>o).join("; ")}`}function Lc(e){return{limit:e.limit,emails:e.emails,remaining:e.remaining??0,max:e.max??0,objects:e.objects.map(({objectApiName:t,perRecord:n})=>({objectApiName:t,perRecord:n})),...e.alertsCounted?{alertsCounted:!0}:{}}}function Wc(e){return{limit:e.limit,emails:e.emails,unread:e.unread??""}}var Ca={SingleEmail:{one:"single email",more:"single emails"},DailyWorkflowEmails:{one:"workflow email",more:"workflow emails"}};function Ao(e,t){let n=Ca[t];return`${e} ${e===1?n.one:n.more}`}function _a(e,t){return e.alertsCounted?`, its email alerts among them: ${t} counts them against its single emails, as a Developer Edition does`:""}function Uc(e,t){let n=e.filter(o=>o.verdict==="exceeds");if(n.length===0)return;let r=n.map(o=>`about ${Ao(o.emails,o.limit)}`+(o.alertsCounted?" (its email alerts among them, as a Developer Edition counts them)":"")+`, ${o.remaining??0} of ${o.max??0} left today`).join("; ");return`The target's automation would make ${t} send ${r}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. Assign the user a bypass that keeps what sends quiet \u2014 muting the target's automation for the run (--mute-automation on the command line, the Mute box on a page) assigns, for the run alone, those the target's flows test \u2014 or write fewer records.`}function Gc(e,t){return e.map(n=>{let r=n.objects.map(s=>`${s.perRecord} per ${s.objectApiName}, by ${s.sentBy.join(", ")}`+(s.byThePlatform?`; ${s.byThePlatform} ${s.objectApiName} written by the platform with ${ke(s.objectApiName)}, whose flows run all the same`:"")).join("; "),o=` emails: these records make ${t} send about ${Ao(n.emails,n.limit)} (${r})`+_a(n,t);return n.verdict==="unread"?`${o}; what it has left today could not be read (${n.unread??""})`:n.verdict==="fits"?`${o}; it has ${n.remaining??"?"} of ${n.max??"?"} left today`:`${o}, more than the ${n.remaining??"?"} of ${n.max??"?"} it has left today: past them the action fails, and a record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER). A bypass that keeps the flow quiet, or a smaller run, avoids it`})}var Eo="EMAILS_NOT_ACCEPTED";function qc(e,t={}){let n=[So(e,"the target's"),...t.applyAssignmentRules===!0?e.filter(({part:r})=>r==="assignmentRules").map(({reason:r})=>`the target's assignment rules: ${r}`):[]].filter(r=>r!==void 0);return n.length>0?n.join("; "):void 0}function zc(e){return"requests"in e&&typeof e.requests=="number"?Math.max(0,e.requests):io}function Vc(e){let t=e?.read?.requests??0;return t>0?{deliverability:t}:{}}var To={clone:{run:"this clone",allTheSame:"to clone all the same"},sync:{run:"this sync",allTheSame:"to sync all the same"},seed:{run:"this seed",allTheSame:"to seed all the same"},autopilot:{run:"this Autopilot run",allTheSame:"to run it all the same"},rewind:{run:"this rewind",allTheSame:"to rewind all the same"},undo:{run:"this undo",allTheSame:"to undo all the same"},masking:{run:"this masking",allTheSame:"to mask all the same"},restore:{run:"this restore",allTheSame:"to restore all the same"},cleanup:{run:"this cleanup",allTheSame:"to delete all the same"},empty:{run:"this emptying",allTheSame:"to empty all the same"},load:{run:"this load",allTheSame:"to load all the same"}},Ia={flow:"flow",process:"process",workflowRule:"workflow rule",assignmentRule:"assignment rule"},ja={email:"",notRead:" (its definition was not read)",assignment:" (applied: it can mail the owner it assigns)"};function Oo(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function Me(e){let t=new Map;for(let n of e){let r=t.get(n.objectApiName)??[];r.push(`${Ia[n.kind]} "${n.name}"${ja[n.why]}`),t.set(n.objectApiName,r)}return[...t].map(([n,r])=>{let o=r.length>we?[...r.slice(0,we),`${r.length-we} more`]:r;return`${Oo(o)} on ${n}`}).join("; ")}var to="read with one line of anonymous Apex that sends nothing";function ko(e){return"level"in e&&e.level==="withheld"}function Da(e){return"unread"in e?`deliverability: not read (${e.unread}) \u2014 the run is refused without --accept-emails, as on All email`:e.level==="all"?`deliverability: All email \u2014 the emails of what still runs go out (${to})`:`deliverability: System email only or No access \u2014 none of the emails its flows, processes, workflow rules and Apex send goes out, and the org still counts them against its daily email limits (${to})`}function La(e,t){let{run:n,allTheSame:r}=To[e.run],{target:o}=e,s=Me(e.senders),i=e.sendersUnread,a=s!==""?`what still runs as ${n} writes its records sends some: ${s}`+(i!==void 0?`; what could not be read may send more (${i})`:""):`what runs as ${n} writes its records could not all be read (${i??""}), so it may send some`,d=[];"unread"in t?d.push(`Whether ${o} delivers the emails its automation sends could not be read (${t.unread}), and ${a}.`,`Nothing was written. Add --accept-emails ${r}, or check Setup > Deliverability: on System email only or No access, none of them goes out.`):d.push(`${o} delivers every email its automation sends (Setup > Deliverability: All email), and ${a}.`,e.keepsAddresses===!0?`They go to the addresses the records and the alerts name: those of the records ${n} writes, as they hold them, the records' owners, the records already in ${o}, and an address an alert names.`:`They go to the addresses the records and the alerts name: those ${n} writes are under .invalid, but not the records' owners, the records already in ${o}, nor an address an alert names.`,`Nothing was written. Add --accept-emails ${r}, set the org's deliverability to System email only, or turn off what sends them.`);let c=e.muteQuiets??[];if(c.length>0){let u=new Set(c.map(g=>`${g.objectApiName}\0${g.kind}\0${g.name}`)),f=e.senders.filter(g=>!u.has(`${g.objectApiName}\0${g.kind}\0${g.name}`));d.push(`--mute-automation keeps quiet ${Me(c)}, which ${c.length===1?"tests":"test"} a bypass a permission set of ${o} holds`+(f.length>0?`; it cannot quiet ${Me(f)}.`:"."))}return d.join(" ")}function Hc(e){if(e.senders.length===0&&e.sendersUnread===void 0)return{verdict:"nothingSends",confirmation:{}};let t=e.reading??{unread:"the run did not read it"},n={reading:t,senders:[...e.senders],...e.sendersUnread!==void 0?{sendersUnread:e.sendersUnread}:{}},r=Da(t);return ko(t)?{verdict:"withheld",deliverability:n,confirmation:{},line:r,audit:"withheld"}:{verdict:"asks",deliverability:n,confirmation:{deliverability:e.keepsAddresses===!0?{...n,keepsAddresses:!0}:n},...e.accepted?{}:{stop:{code:Eo,message:La(e,t)}},line:r,audit:"unread"in t?"unread":"all"}}function Qc(e,t){let n=Vt(t);return e.filter(r=>!n.has(r.objectApiName))}function Jc(e){if(e.length===0)return;let t=[...new Set(e.map(n=>n.objectApiName))];return` emails: ${Me(e)} send nothing: the run writes no ${Oo(t)} record. A real run is refused all the same, and names them: it asks before it reads which records it writes`}function Kc(e){let t=d=>`${d.objectApiName}\0${d.kind}\0${d.name}`,n=new Set(e.planned.map(t)),r=e.held.filter(d=>!n.has(t(d)));if(r.length===0||e.accepted)return;let o=e.reading;if(o!==void 0&&ko(o))return;let{run:s,allTheSame:i}=To[e.run],a=o===void 0?`whether ${e.target} delivers them was not read, as nothing that sends one was to run`:"unread"in o?`whether ${e.target} delivers them could not be read (${o.unread})`:`${e.target} delivers every one of them (All email)`;return{code:Eo,relit:r,message:`The mute's lease does not hold every permission set it was to assign, and what they were to keep quiet still runs for ${s}: ${Me(r)} may send emails, and ${a}. The run's question did not ask about them. Nothing was written. Add --accept-emails ${i}, or run it again once the lease can assign them.`}}function Yc(e){return e.verdict==="unread"?{estimateMB:e.estimateMB,unread:e.unread}:{estimateMB:e.estimateMB,maxMB:e.maxMB,remainingMB:e.remainingMB,near:e.verdict==="near"}}function Z(e){return Ut(e,e<10?2:1)}function Ut(e,t){if(e<=0)return"0";let n=10**t;return(Math.ceil(e*n-1e-9)/n).toString()}function $o(e,t){let n={over:e<10?2:1,bound:t<10?2:1};for(;;){let r={over:Ut(e,n.over),bound:Ut(t,n.bound)},o=Math.max(n.over,n.bound);if(Number(r.over)>Number(r.bound)||o>=6)return r;n={over:o+1,bound:o+1}}}function Po(e){return e.map(({objectApiName:t,kind:n,name:r})=>({objectApiName:t,kind:n,name:r}))}function Wa(e){return Po(Et(e,"insert"))}function Ua(e,t){let n=new Set(t);return Po(Et(e,"update",r=>n.has(r)))}var Mo=["lookups","statuses","invitees","retry","upsert"];function Xc(e,t={}){let n=Gt(e,t.leftOut),r=new Set(n),o=new Map,s=(u,f)=>{if(!r.has(u))return;let g=o.get(u)??new Set;g.add(f),o.set(u,g)},i=e.edges.filter(u=>mr(u)&&r.has(u.sourceObject)&&r.has(u.targetObject)),a=new Map;for(let{sourceObject:u,targetObject:f}of i)u!==f&&a.set(u,[...a.get(u)??[],f]);let d=(u,f)=>{let g=new Set([u]),p=[u];for(let m=p.shift();m!==void 0;m=p.shift())for(let w of a.get(m)??[]){if(w===f)return!0;g.has(w)||(g.add(w),p.push(w))}return!1},c=i.filter(u=>u.required!==!0&&u.insertOnly!==!0);for(let{sourceObject:u,targetObject:f}of c)(u===f||d(f,u))&&s(f,"lookups");for(let u of Object.keys(Qn))s(u,"statuses");for(let u of Object.keys(Hn))s(u,"invitees");if(t.retry===!0)for(let{sourceObject:u,targetObject:f}of c)u!==f&&s(f,"retry");if(t.upsert===!0)for(let u of n)s(u,"upsert");return n.flatMap(u=>{let f=o.get(u);return f?[{objectApiName:u,steps:Mo.filter(g=>f.has(g))}]:[]})}function Ga(e){let t=new Set(e.flatMap(n=>n.steps));return Mo.filter(n=>t.has(n))}function Zc(e,t=[]){let n=new Set(t);return jn(e,(r,o)=>o==="insert"||o==="update"&&n.has(r))}function el(e,t,n){let r=new Set(Ve(e).map(i=>i.toLowerCase())),o=t.filter(i=>!r.has(i.toLowerCase())),s=Qe(e,o);return o.map(i=>{let a=s.find(c=>c.permission.toLowerCase()===i.toLowerCase()),d=a?.permissionSet?.name;return{permission:i,...d?{permissionSet:d}:{},others:a?.others.map(c=>c.name)??[],...a&&!d?{noneHolds:!0}:{},...d&&n?.alias&&n.username?{command:Je(d,n.alias,n.username)}:{}}})}function qa(e){return e==="flows"||e==="triggers"||e==="processes"||e==="workflowRules"||e==="automation"}function Ne(e){return e.unread.flatMap(({part:t,reason:n})=>qa(t)?[{part:t,reason:n}]:[])}var tl="OWNER_MAP_INACTIVE",nl="OWNER_MAP_UNKNOWN",fe=class e extends Error{code;storage;ceiling;reason;api;readBound;sample;roots;constructor(t,n,r,o,s,i){super(n),this.name="ForgeRunGateError",this.code=t,r&&(this.storage=r),o!==void 0&&(this.ceiling=o),s!==void 0&&(this.reason=s),i?.api&&(this.api=i.api),i?.readBound&&(this.readBound=i.readBound),i?.sample&&(this.sample=i.sample),i?.roots&&(this.roots=i.roots)}static of(t){return new e(t.code,t.message,t.storage,void 0,t.refusal?.code,{...t.api?{api:t.api}:{},...t.readBound?{readBound:t.readBound}:{},...t.sample?{sample:t.sample}:{},...t.roots?{roots:t.roots}:{}})}get stop(){if(An(this.code))return{code:this.code,...this.storage?{storage:this.storage}:{},...this.ceiling!==void 0?{ceiling:this.ceiling}:{},...this.reason!==void 0&&this.code===dt?{reason:this.reason}:{},...this.api&&this.code===Pe?{api:this.api}:{},...this.readBound&&this.code==="READ_BOUND_EXCEEDED"?{readBound:this.readBound}:{},...this.sample?{sample:this.sample}:{},...this.roots&&(za.has(this.code)||this.code==="STORAGE_EXCEEDED")?{roots:this.roots}:{}}}},za=new Set(["ROOTS_QUERY_REFUSED","NO_ROOTS","ROOTS_EXCEEDED","ROOTS_PLAN_MISMATCH","ROOTS_PLAN_GONE"]);function rl(e){return e instanceof fe||e instanceof Error&&e.name==="ForgeRunGateError"&&typeof e.code=="string"}var no="FILE_STORAGE_EXCEEDED";function ol(e){if(!(e instanceof Error)||e.name!=="ForgeFilesRefusedError")return;let{code:t,storage:n}=e;if(t===po||t===mo)return new fe(t,e.message);let r=n?.neededBytes,o=n?.remainingBytes;if(t!==no||typeof r!="number"||typeof o!="number"||!Number.isFinite(r)||!Number.isFinite(o))return;let s=o/1048576;return new fe(no,e.message,{estimateMB:Number($o(r/1048576,s).over),remainingMB:s,kind:"files"})}function Va(e,t){if(e.verdict==="exceeds")return`The records to write take ${lt(e)}, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB${be(ge(e),t)}: leave objects out, lower the records per object, or free data storage in ${t}.`}var ro=10;function sl(e,t,n){let r=[`write gate: ${e.totalRows} record(s) to write to ${n}, ${lt(t)}`];for(let s of e.objects.slice(0,ro))r.push(` ${s.objectApiName.padEnd(42)}${String(s.rows).padStart(8)}`);let o=e.objects.slice(ro);if(o.length>0){let s=o.reduce((i,a)=>i+a.rows,0);r.push(` and ${o.length} more object(s), ${s} record(s)`)}for(let{objectApiName:s,mayAdd:i}of e.objects)i!==void 0&&r.push(` counted in: up to ${i} ${s} record(s) the run may read as it writes them, a price in the currency of the record its lines belong to, the source's own beside the one read`);for(let{objectApiName:s,mayBeByThePlatform:i}of e.objects)i!==void 0&&r.push(` counted in: up to ${i.rows} ${s} record(s) the platform `+(i.before===!0?`may have written with ${ke(s)}, in the run this one takes up`:`may write itself with ${ke(s)}`)+", which the run then links to and does not send");r.push(...Ha(e.leftOut));for(let{objectApiName:s,field:i,rows:a}of e.leftEmpty??[])r.push(` written empty: ${s}.${i} on ${a} record(s), the record it names held back by the run, never written`);return t.verdict==="unread"?(r.push(` the data storage ${n} has left could not be read (${t.unread}): whether the records fit is not known`),r):(r.push(` data storage of ${n}: ${t.remainingMB} MB left of ${t.maxMB} MB`+be(ge(t),n)),t.verdict==="near"&&r.push(` that is more than ${Math.round(ao*100)} % of what ${n} has left: Salesforce counts storage a while after a load, so less may be left than it says`),r)}function Ha(e){if(!e)return[];let t=[];e.writtenBefore>0&&t.push(` not counted: ${e.writtenBefore} record(s) the run it retries or resumes wrote, which it links to and does not write again`);for(let{objectApiName:n,rows:r}of e.heldBack)t.push(` not counted: ${n}, ${r} record(s), held back for a record type closed to the user the run writes as`);for(let{objectApiName:n,rows:r}of e.recordTypeNotInTarget??[])t.push(` not counted: ${n}, ${r} record(s), held back for a record type the target has none of, which it would refuse`);for(let{objectApiName:n,rows:r}of e.withoutParent??[])t.push(` not counted: ${n}, ${r} record(s) held back with a record they cannot be written without, held back itself`);for(let{objectApiName:n,rows:r}of e.noParentInSource??[])t.push(` not counted: ${n}, ${r} record(s) left aside: a lookup they may not leave empty names a record the source does not hold, which no copy can write`);for(let{objectApiName:n,rows:r}of e.outsideFilter??[])t.push(` not counted: ${n}, ${r} record(s) left aside: a lookup they may not leave empty names a record outside its object's filter, which the run does not copy`);for(let{objectApiName:n,rows:r}of e.byThePlatform??[])t.push(` not counted: ${n}, ${r} record(s) written by the platform with ${ke(n)}, which the run links to and does not send`);for(let{objectApiName:n,rows:r,fields:o}of e.linkedByValue??[])t.push(` not counted: ${n}, ${r} record(s) the target holds under the same ${o.join(", ")}, which the run links to and does not create`);for(let{objectApiName:n,rows:r}of e.linkedToTarget??[])t.push(` not counted: ${n}, ${r} record(s), the standard price book: linked to the target's own, never written`);for(let{objectApiName:n,rows:r}of e.currencyReplaced??[])t.push(` not counted: ${n}, ${r} record(s) in a currency the target lacks, replaced by the source's own price in the currency written, for the same product and price book`);return t}var Qa={flow:e=>`flow "${e}" runs before a record is deleted, and can refuse the delete`,trigger:e=>`Apex trigger ${e} runs on a delete, and can refuse it`,packageTrigger:e=>`Apex trigger ${e}, installed by a managed package, runs on a delete and can refuse it; no one in the org can change it`,lock:()=>"once activated, a record locks the records under it, which a removal then takes only with it, or once it is back in Draft"},Ja=["flows","triggers"];function il(e,t,n=[],r="--remove"){let o=Ja.filter(i=>n.some(a=>a.part===i)),s=o.length===0?[]:[` ${o.map(i=>ee[i]).join(" and ")} could not be read: whether one refuses the removal is not known`];if(e.length===0&&o.length===0)return[`reversibility: nothing found in ${t} that refuses a removal of this run's records (no flow before a delete, no Apex trigger on one, no record that locks past Draft)`];if(e.length===0){let i=[...o.includes("flows")?[]:["no flow before a delete"],...o.includes("triggers")?[]:["no Apex trigger on a delete"],"no record that locks past Draft"];return[`reversibility: nothing found in ${t} that refuses a removal of this run's records in what could be read (${i.join(", ")})`,...s]}return[`reversibility: a removal of this run's records (${r}) may be refused in ${t}:`,...e.map(({objectApiName:i,kind:a,name:d})=>` ${i}: ${Qa[a](d??"")}`),...s]}var ee={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function se({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}var Ka={lookups:"a lookup filled in once its record exists",statuses:"an order or a contract given back its status after it went in as a draft",invitees:"an event's invitee given its answer",retry:"a lookup the run it retries left empty filled in",upsert:"a record the target holds written over by --upsert"};function Re(e){return e.map(t=>`${t.objectApiName}: ${se(t)}`).join("; ")}function Ht(e,t,n){return e.flatMap(r=>{if(r.command){let o=r.others.length>0?`; ${r.others.join(", ")} hold${r.others.length===1?"s":""} it too`:"";return[`${r.permissionSet} is the smallest permission set of ${t} that holds ${r.permission}${o}. Assigned to the user ${n} writes as, it keeps quiet what ${r.permission} excludes: ${r.command}`]}return r.noneHolds?[`No permission set of ${t} holds ${r.permission}: an admin creates one that includes it, and assigns it to the user ${n} writes as.`]:[]})}function Qt(e,t,n,r){let o=[...new Set(e.flatMap(s=>s.permissionSet??[]))];return!n||o.length===0?[]:r?[`--mute-automation would be refused: ${$e}.`]:[`With --mute-automation, the ${t} assigns ${o.join(", ")} to the user it writes as for the ${t} alone, under a lease, and what ${o.length===1?"it keeps":"they keep"} quiet does not fire.`]}function al(e,t,n={}){let r=n.updated??[],o=Wa(e),s=Ua(e,r.map(c=>c.objectApiName)),i=Ne(e);if(o.length===0&&s.length===0&&i.length===0)return;let a=[];if(o.length>0&&a.push(`${t} runs automation on the records this clone inserts: ${Re(o)}.`),s.length>0){let c=Ga(r.filter(u=>s.some(f=>f.objectApiName===u.objectApiName))).map(u=>Ka[u]);a.push(`${t} runs automation as this clone updates records it inserted (${c.join("; ")}): ${Re(s)}.`)}let d=r.length>0?"inserts and updates":"inserts";for(let{part:c,reason:u}of i)a.push(`${ee[c][0].toUpperCase()}${ee[c].slice(1)} of ${t} could not be read (${u}), so what fires as the clone ${d} is not known.`);return a.push(...Ht(n.assign??[],t,"the clone")),a.push(...Qt(n.assign??[],"clone",n.mayMute===!0,e.cannotAssign===!0)),a.push(`Nothing was written. Add --accept-automation to clone all the same, or turn that automation off in ${t} first.`),a.join(" ")}function dl(e,t,n={}){let r=Tt(e,n.drafted??[]),o=Ne(e);if(r.length===0&&o.length===0)return;let s=[],i=r.filter(d=>d.write==="update"),a=r.filter(d=>d.write==="delete");if(a.length>0){let d=a.map(c=>`${c.objectApiName}: ${se(c)} (${Fe[c.when]})`);s.push(`${t} runs automation on the records this removal deletes: ${d.join("; ")}.`)}i.length>0&&s.push(`${t} runs automation as this removal sets activated records back to Draft, the only way the platform deletes them: ${Re(i)}.`);for(let{part:d,reason:c}of o)s.push(`${ee[d][0].toUpperCase()}${ee[d].slice(1)} of ${t} could not be read (${c}), so what fires as the removal deletes is not known.`);return s.push(...Ht(n.assign??[],t,"the removal")),s.push(...Qt(n.assign??[],"removal",n.mayMute===!0,e.cannotAssign===!0)),s.push(`Nothing was deleted. Add --accept-automation to remove all the same, or turn that automation off in ${t} first.`),s.join(" ")}var Fe={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"};function ul(e,t,n,r){let o=[`removal automation: what ${t} runs as the removal takes the records back`];for(let i of Tt(e,r))o.push(i.write==="delete"?` ${i.objectApiName}: ${Fe[i.when]}: ${se(i)}`:` ${i.objectApiName}: set back to Draft before its delete: ${se(i)}`);let s=Ne(e);o.length===1&&s.length===0&&o.push(` nothing fires on the ${n} object(s) it deletes records of`);for(let{part:i,reason:a}of s)o.push(` ${ee[i]} could not be read: ${a}`);return o}var Ya={bringBack:"brought back from the recycle bin",recreate:"made again with a new Id",giveBack:"given back its values from before the run",setToDraft:"set back to Draft before its delete"};function cl(e,t,n,r="removal",o){let s=Ne(e),i=(a,d)=>{let c=[Xa[d](t)];for(let u of He(e,a))c.push(u.step==="delete"?` ${u.objectApiName}: ${Fe[u.when]}: ${se(u)}`:` ${u.objectApiName}: ${Ya[u.step]}: ${se(u)}`);if(c.length===1&&s.length===0){let u=new Set(Object.values(a).flat()).size,f=Za.has(d)?"deletes":"writes";c.push(` nothing fires on the ${u} object(s) it ${f} records of`)}return c};return[...i(n,r),...o?i(o,Fo(r)):[],...s.map(({part:a,reason:d})=>` ${ee[a]} could not be read: ${d}`)]}var Xa={removal:e=>`removal automation: what ${e} runs as the removal takes the run back`,reload:e=>`reload automation: what ${e} runs as the reload purges what earlier loads created`,reloadSweep:e=>`reload automation: what ${e} runs as the reload's sweep deletes what the target's automation made for the loads it replaces`,replayAgain:e=>`replay automation: what ${e} runs as the replay purges what earlier replays created`,replayAgainSweep:e=>`replay automation: what ${e} runs as the replay's sweep deletes what the target's automation made for the replays it replaces`};function ll(e,t,n){let r=He(e,n.steps),o=n.sweep?He(e,n.sweep):[],s=Ne(e);if(r.length===0&&o.length===0&&s.length===0)return;let i=c=>r.filter(u=>u.step===c),a=oo[n.subject??"removal"],d=[];if(i("bringBack").length>0&&d.push(`${t} runs automation as ${a.this} brings back from the recycle bin what the run deleted: ${Re(i("bringBack"))}.`),i("giveBack").length>0&&d.push(`${t} runs automation as ${a.this} gives the records the run wrote over their values from before it: ${Re(i("giveBack"))}.`),i("setToDraft").length>0&&d.push(`${t} runs automation as ${a.this} sets activated records back to Draft, the only way the platform deletes them: ${Re(i("setToDraft"))}.`),i("delete").length>0){let c=i("delete").map(u=>`${u.objectApiName}: ${se(u)} (${Fe[u.when]})`);d.push(`${t} runs automation on the records ${a.this} deletes: ${c.join("; ")}.`)}if(o.length>0){let c=o.map(u=>`${u.objectApiName}: ${se(u)} (${Fe[u.when]})`);d.push(`${t} runs automation on the records ${oo[Fo(n.subject??"removal")].this} deletes: ${c.join("; ")}.`)}for(let{part:c,reason:u}of s)d.push(`${ee[c][0].toUpperCase()}${ee[c].slice(1)} of ${t} could not be read (${u}), so what fires as ${a.the} writes is not known.`);return d.push(...Ht(n.assign??[],t,a.who)),d.push(...Qt(n.assign??[],a.run,n.mayMute===!0,e.cannotAssign===!0)),d.push(`Nothing was written or deleted. Add --accept-automation to ${a.verb} all the same, or turn that automation off in ${t} first.`),d.join(" ")}var Za=new Set(["reloadSweep","replayAgainSweep"]);function Fo(e){return e==="replayAgain"||e==="replayAgainSweep"?"replayAgainSweep":"reloadSweep"}var oo={removal:{this:"this removal",the:"the removal",who:"the removal",run:"removal",verb:"remove"},reload:{this:"this reload's purge",the:"the reload's purge",who:"the reload",run:"reload",verb:"reload"},reloadSweep:{this:"this reload's sweep",the:"the reload's sweep",who:"the reload",run:"reload",verb:"reload"},replayAgain:{this:"this replay's purge",the:"the replay's purge",who:"the replay",run:"replay",verb:"replay again"},replayAgainSweep:{this:"this replay's sweep",the:"the replay's sweep",who:"the replay",run:"replay",verb:"replay again"}};var td=2e3,nd=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function No(e,t){let n=e!==void 0&&Number.isFinite(e)?Math.floor(e):t;return Math.min(Ge,Math.max(1,n))}function wl(e){return e===void 0||!Number.isFinite(e)?td:Math.max(1,Math.floor(e/10))}function Bo(e){return e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):Sn}function Rl(e){let t=$n(e);if(t!==void 0)return{issue:t};let n=Tn(e);return n?{objectApiName:n.objectApiName,query:{...n.where!==null?{where:n.where}:{},...n.orderBy!==null?{orderBy:n.orderBy}:{},...n.limit!==null?{limit:n.limit}:{}}}:{issue:{kind:"noObject"}}}function bl(e){if(e.where!==void 0&&!On.safeParse(e.where).success)return{kind:"where"};if(e.orderBy!==void 0&&!kn.safeParse(e.orderBy).success)return{kind:"orderBy"};if(e.limit!==void 0&&!(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=Ge))return{kind:"limit"}}function Sl(e,t,n,r){let o=$t(e),s=[...t.where!==void 0?[`(${t.where})`]:[],...n!==void 0&&n!==""?[`(${n})`]:[]],i=s.length>0?` WHERE ${s.join(" AND ")}`:"",a=t.limit!==void 0&&t.limit<=r?t.limit:r+1;return`SELECT Id FROM ${o}${i} ORDER BY ${t.orderBy??"Id"} LIMIT ${a}`}function rd(e,t,n){return!Number.isFinite(e)||e<1||!Number.isFinite(t)||t<=0||!Number.isFinite(n)||n<=0?0:Math.max(0,Math.min(Math.floor(e)-1,Math.floor(n*e/t)))}function Al(e,t,n){let r=t.where!==void 0?` WHERE ${t.where}`:"";return`SELECT Id FROM ${$t(e)}${r} ORDER BY ${t.orderBy??qe} LIMIT ${Math.max(1,Math.floor(n))}`}function El(e,t,n){if(e.verdict!=="exceeds")return;let r=rd(n.count,e.estimateMB,qt(e)),o=ge(e),s=`the ${n.count} ${n.objectApiName} records the query chooses`,i=r>=1?`about ${r} of ${s} fit, each with what its clone copies: a LIMIT of ${r} in the query clones that many \u2014 after ORDER BY ${qe}, the newest \u2014, or narrow its WHERE; or leave objects out, or free data storage in ${t}.`:`one of ${s} takes more than that by itself, with what its clone copies: leave objects out, clone less deep, or free data storage in ${t}.`;return{code:"STORAGE_EXCEEDED",message:`The records to write take ${lt(e)}, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB${be(o,t)}: ${i} ${ie}`,storage:{estimateMB:Number(Z(e.estimateMB)),remainingMB:e.remainingMB,...o},...Se(n.objectApiName).roots?{roots:{objectApiName:n.objectApiName,...r>=1?{fits:r}:{}}}:{}}}function od(e){let t=new Set,n=[];for(let r of e){let o=lr(r);t.has(o)||(t.add(o),n.push(r))}return n.sort(fr)}function vo(e){return ed("sha256").update(od(e).join(`
|
|
10
|
+
`)).digest("hex")}function Tl(e){return nd.test(e)}function sd(e,t){let n=r=>r===void 0?void 0:r.replace(/\s+/g," ").trim();return n(e?.where)===n(t?.where)&&n(e?.orderBy??"Id")===n(t?.orderBy??"Id")&&e?.limit===t?.limit}function Ol(e,t){if(e.sourceOrgId!==t.sourceOrgId)return"otherOrg";if(e.objectApiName.toLowerCase()!==t.objectApiName.toLowerCase()||t.query!==void 0&&!sd(e.query,t.query)||t.ids!==void 0&&vo(t.ids)!==e.sha256)return"otherQuery";if(vo(e.ids)!==e.sha256)return"changed"}var ie="Nothing was written.";function Se(e,t={}){return e!==void 0&&/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(e)?{roots:{objectApiName:e,...t}}:{}}function kl(e,t){return{code:"ROOTS_QUERY_REFUSED",message:`${Pn(e)}. Nothing was read or written.`,...Se(t)}}function $l(e,t,n){let r=t?.where!==void 0?` WHERE ${t.where}`:"";return{code:"NO_ROOTS",message:t===void 0?`None of the ${e} records named is in the source org: there is nothing to clone. ${ie}`:`The query chooses no ${e} record of the source org: there is nothing to clone. Count what it chooses there with sf data query -q "SELECT COUNT() FROM ${e}${r}", and check its WHERE. ${ie}`,...Se(e,{cap:n})}}function Pl(e,t,n,r){let o=Ge.toLocaleString("en-US"),s=n==="query"&&r?.orderBy!==void 0,i=`${s?"":`ORDER BY ${qe} `}LIMIT ${t}`,a=n==="query"?`Give the query ${i}`+(r?.limit!==void 0?` in place of its LIMIT ${r.limit}`:"")+` to clone the first ${t} of its order, narrow its WHERE, or raise --max-roots (the sandforge.forge.maxRoots setting) up to ${o}; past that, copy a sample of the whole org with a filter on its roots.`:`Name ${t} at most, or raise --max-roots up to ${o}.`;return{code:"ROOTS_EXCEEDED",message:`The ${n==="query"?"query chooses":"records named are"} more than the ${t} ${e} records a run clones, and nothing holds ${n==="query"?"it":"them"} to that: refused before anything else was read, rather than cut at an order nobody chose. ${a} ${ie}`,...Se(e,{cap:t,...s?{ordered:!0}:{}})}}var id={otherOrg:"were read of another org than this run reads",otherQuery:"were chosen by another query, of another object, or are other records",changed:"are no longer the ids it was kept with"};function Ml(e,t){return{code:"ROOTS_PLAN_MISMATCH",message:`The records the dry run chose ${id[t]}: run the dry run again with this query, and give the run the plan it keeps. ${ie}`,...Se(e).roots?{roots:{objectApiName:e,plan:t}}:{}}}function Fl(e){return{code:"ROOTS_PLAN_GONE",message:`The run this one resumes cloned the records a query chose, and its journal does not name them: reading the query again could choose others. Remove what it wrote, then run the clone again. ${ie}`,...Se(e).roots?{roots:{objectApiName:e,plan:"gone"}}:{}}}function vl(e,t,n){let r=n[n.length-1],o=r?` (${r.objectApiName} came to ${r.rows.toLocaleString("en-US")} after ${n.length} object${n.length===1?"":"s"})`:"";return{code:"READ_BOUND_EXCEEDED",message:`The ${e} roots reach more than ${t.toLocaleString("en-US")} records${o}, and a clone from records holds all it reads before it writes. Take fewer records (a LIMIT), clone less deep (--depth direct), leave objects out, or raise --max-read-total. `+ie,readBound:{bound:t,objects:n.slice(0,200).map(s=>({...s})),of:"roots"}}}function Nl(e){let{bound:t,sent:n,next:r,objectApiName:o,sourceRequestsLeft:s}=e,i=s===void 0?"the source would not say what it has left today":`a tenth of the ${s.toLocaleString("en-US")} it has left today`;return{code:"API_BUDGET_EXCEEDED",message:`Reading what the ${e.roots} roots reach would send the source more than ${t.toLocaleString("en-US")} requests (${i}): ${n} sent, ${r} more for ${o}. Take fewer records, clone less deep (--depth direct), or leave objects out. ${ie}`,api:{kind:"requests",org:"source",estimate:n+r,remaining:s??t,reading:{bound:t}}}}var Jt=class{constructor(t,n){this.given=t;this.store=n}given;store;has(t){return this.given.has(t)||this.store?.mapping(t)?.earlier===!0}retried(t){return this.given.has(t)}get(t){let n=this.given.get(t);if(n!==void 0)return n;let r=this.store?.mapping(t);return r?.earlier?r.targetId:void 0}get from(){return this.given.size===0&&(this.store?.earlierMapped??0)>0?"resume":"retry"}get size(){return this.given.size+(this.store?.earlierMapped??0)}keys(){return this.given.keys()}[Symbol.iterator](){return this.given.entries()}};function ae(e){return e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function xo(e){let t=e?.roots,n=e?.rootObjectApiName??t?.objectApiName,r=!!(n&&(e?.rootRecordId||t));return{isScoped:r,dryRun:e?.dryRun??!1,referenceFallback:e?.referenceFallback??(r?"nullify":"keep"),rootRecordId:e?.rootRecordId,rootObjectApiName:n,...t&&n?{roots:{...t,objectApiName:n,cap:No(t.cap,bn),readTotal:Bo(t.readTotal)}}:{},recordTypeMappings:e?.recordTypeMappings,maxRecordsPerObject:e?.maxRecordsPerObject,referenceDataObjects:new Set(e?.referenceDataObjects??["BusinessHours","OperatingHours"]),expandOrphanParents:e?.expandOrphanParents??!1,maxOrphanParentExpansions:e?.maxOrphanParentExpansions??20,upsertMode:e?.upsertMode==="auto"?"auto":"off",writeApi:e?.writeApi==="auto"?"auto":"rest",fieldExclusions:e?.fieldExclusions??{},excludedObjects:new Set(e?.excludedObjects??[]),ownerMappings:e?.ownerMappings??{},objectSoqlFilters:e?.objectSoqlFilters,fieldMappings:e?.fieldMappings??{},anonymization:e?.anonymization,keepContactPoints:e?.keepContactPoints===!0,files:e?.files?{maxFileBytes:Math.min(e.files.maxFileBytes>0?e.files.maxFileBytes:10*1048576,35*1048576),acceptedAsIs:e.files.acceptedAsIs===!0}:void 0,writtenBefore:new Jt(new Map(Object.entries(e?.writtenBefore??{})),e?.stream?.store),beforeWrite:e?.beforeWrite,stream:e?.stream?{pageSize:ae(e.stream.pageSize),ceiling:ae(e.stream.ceiling),resumeAfter:e.stream.resumeAfter?new Map(Object.entries(e.stream.resumeAfter)):e.stream.store?.checkpoints()??new Map,onPage:e.stream.onPage,...e.stream.store?{store:e.stream.store}:{},...e.stream.summaryBound!==void 0?{summaryBound:Math.max(0,Math.floor(e.stream.summaryBound))}:{},...ae(e.stream.secondPassPageSize)!==void 0?{secondPassPageSize:ae(e.stream.secondPassPageSize)}:{},...ae(e.stream.writeWindow)!==void 0?{writeWindow:ae(e.stream.writeWindow)}:{},...e.stream.everything===!0?{everything:!0}:{},...ae(e.stream.wholeReadBound)!==void 0?{wholeReadBound:ae(e.stream.wholeReadBound)}:{},...e.stream.sample&&e.stream.everything===!0?{sample:e.stream.sample}:{}}:void 0,decisions:new ot(e?.decisions),recordTypeDecisions:new Map}}async function Co(e,t){let{records:n,pages:r}=await Xn(e,t);return{records:n,requests:r}}var ud=25,qo=15,pt=5,mt=25,Yt=60,Xt=20,io=6+Yt+Xt+1+6+1+20,Be=4,cd="SELECT ApiName, Label, TriggerType, RecordTriggerType, TriggerObjectOrEvent.QualifiedApiName, ActiveVersionId, HasAsyncAfterCommitPath FROM FlowDefinitionView WHERE IsActive = true AND TriggerType IN ('RecordBeforeSave', 'RecordAfterSave', 'RecordBeforeDelete')",ld="SELECT Name, NamespacePrefix, TableEnumOrId, EntityDefinition.QualifiedApiName, UsageBeforeInsert, UsageAfterInsert, UsageBeforeUpdate, UsageAfterUpdate, UsageBeforeDelete, UsageAfterDelete, UsageAfterUndelete FROM ApexTrigger WHERE Status = 'Active'",fd="SELECT ApiName, Label, TriggerObjectOrEvent.QualifiedApiName, ActiveVersionId FROM FlowDefinitionView WHERE IsActive = true AND ProcessType = 'Workflow'",gd="SELECT Id, Name, NamespacePrefix, TableEnumOrId FROM WorkflowRule",pd="SELECT Name, SobjectType FROM AssignmentRule WHERE Active = true",md="SELECT DeveloperName, MasterLabel, SobjectType FROM DuplicateRule WHERE IsActive = true",hd="SELECT DeveloperName, NamespacePrefix FROM UserSetupEntityAccess WHERE KeyPrefix = '0CP'";function _o(e){return`SELECT Metadata FROM Flow WHERE Id = '${e}'`}function yd(e,t){if(t.length>pt)throw new Error(`A Tooling composite holds ${pt} queries, not ${t.length}`);return{allOrNone:!1,compositeRequest:t.map((n,r)=>({method:"GET",url:`${e}/tooling/query?q=${encodeURIComponent(n)}`,referenceId:`q${r}`}))}}function wd(e,t){if(t.length>mt)throw new Error(`A Tooling composite retrieves ${mt} records, not ${t.length}`);return{allOrNone:!1,compositeRequest:t.map(({sobject:n,id:r},o)=>{if(!ne.test(r))throw new Error(`Not a record id: ${r}`);return{method:"GET",url:`${e}/tooling/sobjects/${n}/${r}`,referenceId:`r${o}`}})}}var gt="PROCESSING_HALTED",Rd=B({compositeResponse:X(B({body:We(),httpStatusCode:G(),referenceId:Q()}).loose())}),bd=B({records:X(At(Q(),We()))}).loose(),Sd=At(Q(),We()),Ad=X(B({errorCode:Q().optional(),message:Q().optional()}).loose());function zo(e,t,n,r,o){let s=Rd.safeParse(e);if(!s.success)throw new Error("The org answered the Tooling composite with no composite answer");let i=new Map(s.data.compositeResponse.map(a=>[a.referenceId,a]));return Array.from({length:t},(a,d)=>{let c=i.get(`${n}${d}`);if(!c)return{refused:`The org gave no answer to this ${r} of the composite`};if(c.httpStatusCode<400){let g=o(c.body);return g?{records:g}:{refused:`The org answered with status ${c.httpStatusCode} and no rows`}}let u=Ad.safeParse(c.body),f=u.success?u.data[0]:void 0;return{refused:f?[f.errorCode,f.message].filter(Boolean).join(": "):`status ${c.httpStatusCode}`,...f?.errorCode===gt?{halted:!0}:{}}})}function Ed(e,t){return zo(e,t,"q","query",n=>{let r=bd.safeParse(n);return r.success?r.data.records:void 0})}function Td(e,t){return zo(e,t,"r","retrieve",n=>{let r=Sd.safeParse(n);return r.success?[r.data]:void 0})}function Od(e){return async t=>Td(await e.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(wd(`/services/data/v${e.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length)}function Vl(e){return{query:async(t,n)=>{let r=await e(t);return Co({query:async o=>r.query(o),queryMore:async o=>r.queryMore(o)},n)},toolingQuery:async(t,n)=>{let r=await e(t);return Co({query:async o=>r.tooling.query(o),queryMore:async o=>r.tooling.queryMore(o)},n)},toolingQueries:async(t,n)=>{let r=await e(t),o=await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(yd(`/services/data/v${r.version}`,n)),headers:{"Content-Type":"application/json"}});return Ed(o,n.length)},toolingRetrieves:async(t,n)=>Od(await e(t))(n)}}async function kd(e,t,n,r){let o=t.map(u=>({retrieving:r?u.queries.filter(f=>f.retrieve!==void 0):[],waiting:r?u.queries.filter(f=>f.retrieve===void 0):[...u.queries],left:u.requests})),s={retrieving:mt,waiting:pt},i=(u,f)=>{for(let g of o){let p=f.filter(m=>m.queue===g).map(m=>m.query);p.length>0&&g[u].unshift(...p)}},a=(u,f)=>{for(let g of o){let p=f.filter(m=>m.queue===g).map(m=>m.query);p.length===0&&g.retrieving.length===0||(g.reason??=u,g.waiting.unshift(...p,...g.retrieving.splice(0)))}},d=0,c=async()=>{for(;;){let u=o.find(E=>E.left>0&&(E.retrieving.length>0||E.waiting.length>0));if(!u)return;let f=u.retrieving.length>0?"retrieving":"waiting";u.left--,d++;let g=[];for(let E of o){if(E!==u&&E.left<=0)continue;let j=s[f]-g.length;if(j<=0)break;for(let C of E[f].splice(0,j))g.push({query:C,queue:E})}let p;try{p=r&&f==="retrieving"?await r(g.map(({query:E})=>E.retrieve)):await e(g.map(({query:E})=>E.soql))}catch(E){let j=F(E);if(f==="retrieving")a(j,g);else for(let{query:C}of g)C.refused(j);continue}let m=f==="retrieving"?"retrieve":"query",w=[],R=[],b=0,P,M;if(g.forEach((E,j)=>{let C=p[j]??{refused:`The org gave no answer to this ${m} of the composite`};"records"in C?(E.query.take(C.records),b++):C.halted?(w.push(E),P??=C.refused):f==="retrieving"?(R.push(E),M??=C.refused):E.query.refused(C.refused)}),f==="retrieving"&&b===0){a(M??P??gt,g);continue}if(R.length>0){for(let{queue:E}of R)E.reason??=M;i("waiting",R)}if(w.length===0)continue;let z=g.length-w.length;if(z===0){for(let{query:E}of w)E.refused(P??gt);continue}s[f]=Math.min(s[f],z);for(let{queue:E}of w)E.reason=P;i(f,w)}};await Promise.all(Array.from({length:Math.max(1,n)},c));for(let u of o)for(let f of[...u.retrieving,...u.waiting])f.refused(u.reason??gt);return d}function $d(e){return`SELECT Metadata FROM WorkflowRule WHERE Id = '${e}'`}function Pd(e){return`SELECT FlowVersionViewId, ApiName, ObjectType FROM FlowVariableView WHERE FlowVersionViewId IN (${e.map(n=>`'${n}'`).join(", ")})`}function Md(e){return`SELECT DurableId, QualifiedApiName FROM EntityDefinition WHERE QualifiedApiName IN (${e.map(n=>`'${n}'`).join(", ")})`}function Fd(e){return`SELECT Id, DeveloperName, NamespacePrefix FROM CustomPermission WHERE DeveloperName IN (${e.map(n=>`'${n}'`).join(", ")})`}function vd(e){return`SELECT SetupEntityId, ParentId, Parent.Name, Parent.Label, Parent.NamespacePrefix FROM SetupEntityAccess WHERE SetupEntityType = 'CustomPermission' AND SetupEntityId IN (${e.map(n=>`'${n}'`).join(", ")}) AND Parent.IsOwnedByProfile = false AND Parent.PermissionSetGroupId = null`}function Nd(e,t){let n=t.map(r=>`'${r}'`).join(", ");return`SELECT ParentId, COUNT(Id) n FROM ${e} WHERE ParentId IN (${n}) GROUP BY ParentId`}var ne=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,Zt=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,Bd="myvariable_current",xd={RecordBeforeSave:"beforeSave",RecordAfterSave:"afterSave",RecordBeforeDelete:"beforeDelete"},Cd={Create:"create",Update:"update",CreateAndUpdate:"createAndUpdate",Delete:"delete"},Vo={onCreateOnly:"create",onAllChanges:"createAndUpdate",onCreateOrTriggeringUpdate:"createAndUpdate"},_d=[["UsageBeforeInsert","beforeInsert"],["UsageAfterInsert","afterInsert"],["UsageBeforeUpdate","beforeUpdate"],["UsageAfterUpdate","afterUpdate"],["UsageBeforeDelete","beforeDelete"],["UsageAfterDelete","afterDelete"],["UsageAfterUndelete","afterUndelete"]],Id={emailAlert:"email",emailSimple:"email",customNotificationAction:"notification",outboundMessage:"outbound"},jd={emailSimple:"SingleEmail",emailAlert:"DailyWorkflowEmails"},Dd={Alert:"email",OutboundMessage:"outbound"},Ld=new Set(["sms","mms","twilio","whatsapp","vonage","nexmo","messagebird","plivo","sinch"]);function nn(e){if(typeof e!="object"||e===null)return;let t=e.QualifiedApiName;return typeof t=="string"&&t!==""?t:void 0}var y=e=>typeof e=="string"?e:"";function A(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}function q(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t):[]}function rn(e,t,n,r){return{apiName:e,label:t||e,timing:n,startsOn:r,condition:"notRead",permissions:[],paths:[],messages:[],switches:[]}}function Wd(e){let t=nn(e.TriggerObjectOrEvent),n=xd[y(e.TriggerType)];if(!t||!n)return;let r=n==="beforeDelete"?"delete":Cd[y(e.RecordTriggerType)]??"createAndUpdate",o=y(e.ActiveVersionId),s=rn(y(e.ApiName),y(e.Label),n,r);return e.HasAsyncAfterCommitPath===!0&&(s.paths=[{kind:"async"}]),{objectApiName:t,id:ne.test(o)?o:null,flow:s}}function Ud(e){let t=y(e.ActiveVersionId);return{objectApiName:nn(e.TriggerObjectOrEvent),id:ne.test(t)?t:null,flow:rn(y(e.ApiName),y(e.Label),"afterSave","createAndUpdate")}}function Gd(e){let t=nn(e.EntityDefinition)??(y(e.TableEnumOrId)||void 0),n=y(e.Name);if(!t||!n)return;let r=y(e.NamespacePrefix);return{objectApiName:t,trigger:{name:r?`${r}.${n}`:n,events:_d.filter(([o])=>e[o]===!0).map(([,o])=>o)}}}function Io(e){return e.startsOn==="create"||e.startsOn==="createAndUpdate"?e.timing==="afterSave"?0:1:e.startsOn==="update"?2:3}function Ho(e){let t=new Set(es(JSON.stringify(e??null)).filter(o=>xe(o)==="Permission").map(en));if(t.size===0)return[];let n=A(e,"filterFormula"),r=new Set((typeof n=="string"?Ce(n):[]).filter(o=>xe(o.reference)==="Permission"&&o.value===void 0).map(o=>en(o.reference)));return[...t].sort((o,s)=>o.localeCompare(s)).map(o=>({name:o,bypass:r.has(o)}))}function Qo(e){return typeof e!="string"?[]:rs(Ce(e)).filter(t=>xe(t.reference)!=="Permission").map(t=>({...t,where:"start",bypass:!0}))}function qd(e){let t=A(e,"filterFormula");if(typeof t=="string"&&t.trim()!=="")return[...new Set(yt(t).flatMap(r=>{let o=Hd(r);return o?[o]:[]}))];let n=q(A(e,"filters"));return n.length===0||!Qd(y(A(e,"filterLogic")),n.length)?[]:[...new Set(n.filter(r=>y(r.operator)==="IsNull"&&A(r.value,"booleanValue")===!1).map(r=>y(r.field)).filter(r=>zd.test(r)))]}var zd=/^[A-Za-z][A-Za-z0-9_]*$/,Vd=/^(?:\{!\s*)?\$Record\.([A-Za-z][A-Za-z0-9_]*)\s*\}?$/i;function Hd(e){let t=pe(e,"NOT");if(t===void 0)return;let n=sn(t),r=pe(n,"ISBLANK")??pe(n,"ISNULL");return r===void 0?void 0:Vd.exec(r.trim())?.[1]}function Qd(e,t){let n=e.trim().toLowerCase();if(n==="and"||t===1&&n!=="or")return!0;if(!/^\d+(\s+and\s+\d+)*$/.test(n))return!1;let r=new Set(n.split(/\s+and\s+/).map(Number));return Array.from({length:t},(o,s)=>s+1).every(o=>r.has(o))}var Jo={permission:"Permission",setup:"Setup",user:"User",profile:"Profile",custommetadata:"CustomMetadata"},Ko=String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`,Yo=new RegExp(String.raw`\$(?:Permission|Setup|User|Profile|CustomMetadata)\.${Ko}`,"gi"),Ae=String.raw`(?:\{!\s*)?(\$(?:Permission|Setup|User|Profile|CustomMetadata)\.${Ko})\s*\}?`,Jd=new RegExp(`^${Ae}$`,"i"),Kd=new RegExp(`^NOT\\s+${Ae}$`,"i"),Xo=new RegExp(`^(?:${Ae}\\s*(==?|<>|!=)\\s*(TRUE|FALSE)|(TRUE|FALSE)\\s*(==?|<>|!=)\\s*${Ae})$`,"i"),jo=String.raw`("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')`,Zo=new RegExp(`^(?:${Ae}\\s*(==?|<>|!=)\\s*${jo}|${jo}\\s*(==?|<>|!=)\\s*${Ae})$`,"i");function de(e){let t=e.indexOf("."),n=Jo[e.slice(1,t).toLowerCase()];return n?`$${n}${e.slice(t)}`:e}function xe(e){return Jo[e.slice(1,e.indexOf(".")).toLowerCase()]}function en(e){return e.slice(e.indexOf(".")+1)}function es(e){return[...new Set([...e.matchAll(Yo)].map(t=>de(t[0])))]}var Yd=new RegExp(`^${Yo.source}$`,"i");function ts(e){return typeof e=="string"&&Yd.test(e)}function ht(e,t){return e.toLowerCase()===t.toLowerCase()}function ns(e){return e.slice(1,-1).replace(/\\(.)/g,"$1")}function rs(e){let t=new Map;for(let n of e)t.set(`${n.reference.toLowerCase()}=${n.value??""}`,n);return[...t.values()]}function Do(e,t){return e.some(n=>ht(n.reference,t.reference)&&n.value===t.value)}function Ce(e){return yt(e).flatMap(Xd)}function on(e){return tn(e).flatMap(Zd)}function Xd(e){let t=Xo.exec(e);if(t){let[,o,s,i,a,d,c]=t,u=s??d,f=(i??a).toUpperCase();return(u.startsWith("=")?f==="FALSE":f==="TRUE")?[{reference:de(o??c)}]:[]}let n=Zo.exec(e);if(n){let[,o,s,i,a,d,c]=n;return(s??d).startsWith("=")?[]:[{reference:de(o??c),value:ns(i??a)}]}let r=pe(e,"NOT");if(r===void 0){let o=Kd.exec(e);return o?[{reference:de(o[1])}]:[]}return on(r)}function Zd(e){let t=Jd.exec(e);if(t)return[{reference:de(t[1])}];let n=Xo.exec(e);if(n){let[,s,i,a,d,c,u]=n,f=i??c,g=(a??d).toUpperCase();return(f.startsWith("=")?g==="TRUE":g==="FALSE")?[{reference:de(s??u)}]:[]}let r=Zo.exec(e);if(r){let[,s,i,a,d,c,u]=r;return(i??c).startsWith("=")?[{reference:de(s??u),value:ns(a??d)}]:[]}let o=pe(e,"NOT");return o===void 0?[]:Ce(o)}function yt(e){let t=sn(e),n=pe(t,"AND");if(n)return wt(n,",").flatMap(yt);let r=wt(t,"&&");return r.length>1?r.flatMap(yt):[t]}function tn(e){let t=sn(e),n=pe(t,"OR");if(n)return wt(n,",").flatMap(tn);let r=wt(t,"||");return r.length>1?r.flatMap(tn):[t]}function pe(e,t){let n=new RegExp(`^${t}\\s*\\(([\\s\\S]*)\\)$`,"i").exec(e);return n&&os(n[1])?n[1]:void 0}function sn(e){let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")")&&os(t.slice(1,-1));)t=t.slice(1,-1).trim();return t}function os(e){let t=0;for(let{char:n,quoted:r}of ss(e))if(!r){if(n==="(")t++;else if(n===")"&&--t<0)return!1}return t===0}function wt(e,t){let n=[],r=0,o=0;for(let{char:s,index:i,quoted:a}of ss(e))a||(s==="("?r++:s===")"?r--:r===0&&e.startsWith(t,i)&&(n.push(e.slice(o,i).trim()),o=i+t.length));return n.push(e.slice(o).trim()),n.filter(s=>s!=="")}function*ss(e){let t=null;for(let n=0;n<e.length;n++){let r=e[n];if(t){r==="\\"?n++:r===t&&(t=null),yield{char:r,index:n,quoted:!0};continue}if(r==='"'||r==="'"){t=r,yield{char:r,index:n,quoted:!0};continue}yield{char:r,index:n,quoted:!1}}}function eu(e){let t=A(e,"start");if(typeof t=="object"&&t!==null){let n=y(A(A(t,"connector"),"targetReference"))||void 0,r=q(A(t,"scheduledPaths")).map(o=>y(A(A(o,"connector"),"targetReference"))||void 0);return{name:n,everyPath:r.every(o=>o===n)}}return{name:y(A(e,"startElementReference"))||void 0,everyPath:!0}}function tu(e,t){let n=e.leftValueReference,r=e.rightValue;if(ts(n)){let s=de(n);if(typeof A(r,"booleanValue")=="boolean")return[{reference:s}];let i=A(r,"stringValue");return typeof i=="string"?[{reference:s,value:i}]:[]}let o=typeof n=="string"?t.get(n):void 0;return o===void 0?[]:[...on(o),...Ce(o)]}function nu(e,t){let n=e.leftValueReference,r=typeof n=="string"?t.get(n):void 0;return es([typeof n=="string"?n:"",y(A(e.rightValue,"elementReference")),r??""].join(" "))}function ru(e,t,n){let{leftValueReference:r,operator:o,rightValue:s}=e;if(o!=="EqualTo"&&o!=="NotEqualTo")return"unknown";let i=o==="EqualTo",a=A(s,"booleanValue");if(ts(r)){if(!ht(r,t.reference))return"unknown";if(typeof a=="boolean"&&t.value===void 0)return a===i?"true":"false";let u=A(s,"stringValue");return typeof u=="string"&&t.value!==void 0?u===t.value===i?"true":"false":"unknown"}let d=typeof r=="string"?n.get(r):void 0;if(d===void 0||typeof a!="boolean")return"unknown";let c=a===i;return Do(on(d),t)?c?"true":"false":Do(Ce(d),t)?c?"false":"true":"unknown"}function ou(e,t,n){let r=q(e.conditions);if(r.length===0)return"unknown";let o=r.map(i=>ru(i,t,n)),s=y(e.conditionLogic).toLowerCase()||"and";return s==="and"?o.includes("false")?"false":o.every(i=>i==="true")?"true":"unknown":s==="or"?o.includes("true")?"true":o.every(i=>i==="false")?"false":"unknown":"unknown"}function su(e,t,n){for(let r of q(e.rules)){let o=ou(r,t,n),s=!y(A(r.connector,"targetReference"));if(o!=="false"){if(o==="true")return s;if(!s)return!1}}return!y(A(e.defaultConnector,"targetReference"))}function is(e){let t=q(A(e,"decisions")),n=new Map(q(A(e,"formulas")).filter(f=>typeof f.expression=="string").map(f=>[y(f.name),y(f.expression)])),r=f=>q(f.rules).flatMap(g=>q(g.conditions)),o=[...new Set(t.flatMap(f=>r(f).flatMap(g=>nu(g,n))))];if(o.length===0)return{permissions:[],switches:[]};let{name:s,everyPath:i}=eu(e),a=i?t.find(f=>y(f.name)===s):void 0,d=a?rs(r(a).flatMap(f=>tu(f,n))).filter(f=>su(a,f,n)):[],c=o.filter(f=>xe(f)==="Permission").map(f=>({name:en(f),bypass:d.some(g=>ht(g.reference,f)&&g.value===void 0),where:"decision"})).sort((f,g)=>f.name.localeCompare(g.name)),u=o.filter(f=>xe(f)!=="Permission").flatMap(f=>{let g=d.filter(p=>ht(p.reference,f));return g.length>0?g.map(p=>({...p,where:"decision",bypass:!0})):[{reference:f,where:"decision",bypass:!1}]}).sort((f,g)=>f.reference.localeCompare(g.reference));return{permissions:c,switches:u}}function iu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(t=>t!=="").map(t=>t.toLowerCase())}function au(...e){return e.some(t=>{let n=iu(t);return n.some(r=>Ld.has(r))||n.some((r,o)=>r==="text"&&/^messages?$/.test(n[o+1]??""))})}function as(e){return q(A(e,"actionCalls")).flatMap(t=>{let n=y(t.actionType),r=y(t.label)||y(t.name)||y(t.actionName),o=Id[n],s=jd[n];return o?[{kind:o,name:r,...s?{limit:s}:{}}]:n==="apex"&&au(y(t.actionName),y(t.name),r)?[{kind:"sms",name:r,guessed:!0}]:[]})}function du(e){return q(A(A(e,"start"),"scheduledPaths")).map(t=>{let n=y(t.label)||y(t.name)||void 0;if(y(t.pathType)==="AsyncAfterCommit")return{kind:"async",label:n};let r=Number(t.offsetNumber),o=y(t.timeSource)==="RecordField"?y(t.recordField):"";return{kind:"scheduled",label:n,...Number.isFinite(r)?{offset:r}:{},...y(t.offsetUnit)?{unit:y(t.offsetUnit)}:{},...o?{field:o}:{}}})}function ds(e,t){let n=Lr(t);n.length>0&&(e.creates=n)}function uu(e,t){if(typeof t!="object"||t===null)return;let n=A(t,"start"),r=is(t);e.permissions=[...Ho(n),...r.permissions],e.switches=[...Qo(A(n,"filterFormula")),...r.switches];let o=qd(n);o.length>0&&(e.requiresFilled=o),e.paths=du(t),e.messages=as(t),ds(e,t)}function cu(e,t){let n=new Map(q(A(t,"processMetadataValues")).map(o=>[y(o.name),y(A(o.value,"stringValue"))]));e.startsOn=Vo[n.get("TriggerType")??""]??"createAndUpdate";let r=is(t);return e.permissions=r.permissions,e.switches=r.switches,e.messages=as(t),ds(e,t),n.get("ObjectType")||void 0}function lu(e,t){e.startsOn=Vo[y(A(t,"triggerType"))]??"createAndUpdate";let n=A(t,"formula");e.permissions=typeof n=="string"?Ho({filterFormula:n}):[],e.switches=Qo(n);let r=q(A(t,"workflowTimeTriggers"));return e.paths=r.map(o=>{let s=Number(o.timeLength);return{kind:"scheduled",...Number.isFinite(s)?{offset:s}:{},...y(o.workflowTimeTriggerUnit)?{unit:y(o.workflowTimeTriggerUnit)}:{},...y(o.offsetFromField)?{field:y(o.offsetFromField)}:{}}}),e.messages=[A(t,"actions"),...r.map(o=>o.actions)].flatMap(q).flatMap(o=>{let s=Dd[y(o.type)];return s?[{kind:s,name:y(o.name),...s==="email"?{limit:"DailyWorkflowEmails"}:{}}]:[]}),A(t,"active")===!0}function us(e,t){return(e?`${e}__${t}`:t).toLowerCase()}function Kt(e,t){let n=qn(t);return n===void 0?{part:e,reason:F(t)}:{part:e,reason:`the org could not be reached (${n})`,unreachable:n}}var Lo={flows:0,triggers:1,conditions:2,processes:3,workflowRules:4,definitions:5,assignmentRules:6,duplicateRules:7,userPermissions:8,permissionSets:9};function fu(e){return[...e].sort((t,n)=>Lo[t.part]-Lo[n.part]||(t.reason<n.reason?-1:t.reason>n.reason?1:0))}async function ft(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let s=r++;n[s]=await e[s]()}};return await Promise.all(Array.from({length:Math.min(t,e.length)},o)),n}var Wo=[vn,gr,Bn,xn,Nn],Uo=["ProductCategory","ProductCatalog"];function Gt(e,t=new Set){let{referenceDataObjects:n}=xo(void 0),r=e.nodes.filter(u=>u.included&&!t.has(u.objectApiName)&&!n.has(u.objectApiName)).map(u=>u.objectApiName),o=new Set(r),s=new Set(e.nodes.map(u=>u.objectApiName)),i=Object.entries(Fn).filter(([u,{object:f}])=>o.has(u)&&!s.has(f)&&!t.has(f)).map(([,{object:u}])=>u),a=pr(e,t),d=u=>e.edges.some(f=>f.required===!0&&u.includes(f.sourceObject)&&a.has(f.sourceObject)&&o.has(f.targetObject)),c=i.length>0||d(Wo);return[...new Set([...r,...i,...c?Wo.filter(u=>a.has(u)):[],...d(Uo)?Uo.filter(u=>a.has(u)):[]])]}var Go=class{deps;constructor(t){this.deps=t}async readForGraph(t,n,r=new Set){return this.read(t,Gt(n,r))}async read(t,n,r={}){let o=[],s=0,i=new Map(n.map(l=>[l.toLowerCase(),l])),a=l=>l===void 0?void 0:i.get(l.toLowerCase()),d=(l,h)=>async()=>{try{let T=await h();return s+=T.requests,T.records}catch(T){return s++,o.push(Kt(l,T)),[]}},c=l=>()=>this.deps.query(t,l),u=l=>()=>this.deps.toolingQuery(t,l),f=async()=>[],g=n.some(l=>/^(case|lead)$/i.test(l)),[p,m,w,R,b,P]=await ft([d("flows",c(cd)),d("triggers",u(ld)),d("processes",c(fd)),d("workflowRules",u(gd)),g?d("assignmentRules",c(pd)):f,d("duplicateRules",c(md))],Be),M=p.map(Wd).filter(l=>l!==void 0).flatMap(l=>{let h=a(l.objectApiName);return h?[{...l,objectApiName:h}]:[]}),z=m.map(Gd).filter(l=>l!==void 0).flatMap(l=>{let h=a(l.objectApiName),T=l.trigger.events.some(x=>x!=="afterUndelete"||r.undeletes===!0);return h&&T?[{...l,objectApiName:h}]:[]}),E=w.map(Ud),j=E.filter(l=>l.objectApiName===void 0&&l.id!==null).map(l=>l.id),C=n.filter(l=>l.includes("__")&&Zt.test(l)),ue=R.some(l=>/^01I/.test(y(l.TableEnumOrId))),[J,_e]=await ft([j.length>0?d("processes",c(Pd(j))):f,ue&&C.length>0?d("workflowRules",c(Md(C))):f],Be),Ee=new Map(J.filter(l=>y(l.ApiName).toLowerCase()===Bd).map(l=>[y(l.FlowVersionViewId),y(l.ObjectType)]));for(let l of E)l.objectApiName===void 0&&l.id!==null&&(l.objectApiName=Ee.get(l.id)||void 0);let Ie=new Map(_e.map(l=>[y(l.DurableId),y(l.QualifiedApiName)])),S=R.flatMap(l=>{let h=y(l.TableEnumOrId),T=a(Ie.get(h)??h),x=y(l.Name),L=y(l.Id);if(!T||!x)return[];let Y=y(l.NamespacePrefix),me=Y?`${Y}.${x}`:x;return[{objectApiName:T,id:ne.test(L)?L:null,flow:rn(me,me,"afterSave","createAndUpdate")}]}),N=E.filter(l=>l.objectApiName===void 0||a(l.objectApiName)!==void 0),O=new Map(n.map((l,h)=>[l,h])),v=l=>O.get(a(l.objectApiName)??"")??n.length,_=M.filter(l=>l.id!==null).sort((l,h)=>Io(l.flow)-Io(h.flow)||v(l)-v(h)||l.flow.label.localeCompare(h.flow.label)),k=this.deps.toolingQueries,re=k?this.deps.toolingRetrieves:void 0,W=re?mt:pt,V=k?Yt*W:ud,K=k?Xt*W:qo,oe=_.slice(0,V),je=[...N.map(l=>({read:l,kind:"process"})),...S.map(l=>({read:l,kind:"rule"}))].filter(({read:l})=>l.id!==null).sort((l,h)=>v(l.read)-v(h.read)||(l.kind===h.kind?0:l.kind==="process"?-1:1)||l.read.flow.label.localeCompare(h.read.flow.label)),$=je.slice(0,K),D,I,U=new Set,Te=l=>l[0]?.Metadata,ls=(l,h)=>{l.flow.condition="read",uu(l.flow,Te(h))},fs=(l,h)=>{l.flow.condition="unreadable",D??=h},gs=({read:l,kind:h})=>h==="process"?_o(l.id):$d(l.id),ps=({read:l,kind:h},T)=>{let x=Te(T);if(typeof x!="object"||x===null){l.flow.condition="unreadable";return}if(l.flow.condition="read",h==="process"){let L=cu(l.flow,x);l.objectApiName??=L}else lu(l.flow,x)||U.add(l.flow)},ms=({read:l},h)=>{l.flow.condition="unreadable",I??=h},an=(l,h,T,x,L)=>l.map(Y=>({soql:h(Y),retrieve:T(Y),take:me=>x(Y,me),refused:me=>L(Y,me)})),dn=an(oe,l=>_o(l.id),l=>({sobject:"Flow",id:l.id}),ls,fs),un=an($,gs,({read:l,kind:h})=>({sobject:h==="process"?"Flow":"WorkflowRule",id:l.id}),ps,ms);k?s+=await kd(l=>k(t,l),[{queries:dn,requests:Yt},{queries:un,requests:Xt}],Be,re&&(l=>re(t,l))):await ft([...dn,...un].map(l=>async()=>{try{let h=await this.deps.toolingQuery(t,l.soql);s+=h.requests,l.take(h.records)}catch(h){s++,l.refused(F(h))}}),Be),D!==void 0&&o.push(Kt("conditions",D)),I!==void 0&&o.push(Kt("definitions",I));for(let l of[...M,...N,...S])l.id===null&&(l.flow.condition="unreadable");let cn=N.flatMap(l=>{let h=a(l.objectApiName);return h?[{...l,objectApiName:h}]:[]}),ln=S.filter(l=>!U.has(l.flow)),Rt=[...M,...cn,...ln].flatMap(l=>l.flow.permissions),fn;if(Rt.length>0){let[l]=await ft([d("userPermissions",c(hd))],Be);if(!o.some(h=>h.part==="userPermissions")){let h=new Set(l.map(T=>us(y(T.NamespacePrefix),y(T.DeveloperName))));fn=h;for(let T of Rt)T.held=h.has(T.name.toLowerCase())}}let gn=[...new Set(Rt.filter(l=>l.bypass&&l.held!==!0).map(l=>l.name))],De=gn.length>0?await gu(gn,l=>d("permissionSets",c(l))(),()=>o.some(l=>l.part==="permissionSets"),async l=>{try{let h=await this.deps.query(t,l);return s+=h.requests,h.records}catch(h){throw s++,h}}):void 0,Le={};if(De?.some(l=>l.permissionSets.length>0)){let{toolingQueries:l,toolingRetrieves:h}=this.deps;try{let{readValidationRuleBypasses:T}=await import("./chunk-6O222PW6.mjs"),x=await T(L=>this.deps.toolingQuery(t,L),n,l&&(L=>l(t,L)),h&&(L=>h(t,L)));s+=x.requests,Le.validationRuleBypasses=x.rules.flatMap(L=>L.permissions.some(Y=>fn?.has(Y.toLowerCase()))?[]:[L]),x.notRead>0&&(Le.validationRulesNotRead=x.notRead)}catch(T){s++,Le.validationRulesUnread=F(T)}}let pn=!1;if(De?.some(l=>l.permissionSets.length>0))try{let l=await this.deps.query(t,_t);s+=l.requests;let[h]=l.records;pn=h!==void 0&&!It(h)}catch{s++}let hs=l=>b.filter(h=>y(h.SobjectType).toLowerCase()===l.toLowerCase()).map(h=>({name:y(h.Name)})).sort((h,T)=>h.name.localeCompare(T.name)),ys=l=>P.filter(h=>y(h.SobjectType).toLowerCase()===l.toLowerCase()).map(h=>({name:y(h.MasterLabel)||y(h.DeveloperName),developerName:y(h.DeveloperName)})).sort((h,T)=>h.name.localeCompare(T.name)),ws=(l,h)=>l.label.localeCompare(h.label),bt=(l,h)=>l.filter(T=>T.objectApiName===h).map(T=>T.flow).sort(ws),St=new Map;for(let l of _.slice(oe.length))St.set(l.objectApiName,(St.get(l.objectApiName)??0)+1);let mn=n.flatMap(l=>{let h=St.get(l);return h?[{objectApiName:l,flows:h}]:[]}),Rs=n.map(l=>({objectApiName:l,flows:bt(M,l),triggers:z.filter(h=>h.objectApiName===l).map(h=>h.trigger).sort((h,T)=>h.name.localeCompare(T.name)),processes:bt(cn,l),workflowRules:bt(ln,l),assignmentRules:hs(l),duplicateRules:ys(l)})).filter(l=>l.flows.length>0||l.triggers.length>0||l.processes.length>0||l.workflowRules.length>0||l.assignmentRules.length>0||l.duplicateRules.length>0);return{objectsRead:[...n],objects:Rs,unread:fu(o),conditionsNotRead:_.length-oe.length,conditionsBound:V,...mn.length>0?{conditionsNotReadOn:mn}:{},definitionsNotRead:je.length-$.length,definitionsBound:K,...De?{bypassGrants:De}:{},...pn?{cannotAssign:!0}:{},...Le,requests:s}}};function te(e){return e.slice(0,15)}async function gu(e,t,n,r){let o=e.flatMap(p=>{let m=p.indexOf("__"),w=m>0?p.slice(0,m):"",R=m>0?p.slice(m+2):p;return Zt.test(R)&&(!w||Zt.test(w))?[{name:p,developerName:R}]:[]});if(o.length===0)return;let s=await t(Fd([...new Set(o.map(p=>p.developerName))]));if(n())return;let i=new Map;for(let p of s){let m=y(p.Id);ne.test(m)&&i.set(us(y(p.NamespacePrefix),y(p.DeveloperName)),m)}let a=o.flatMap(p=>{let m=i.get(p.name.toLowerCase());return m?[m]:[]}),d=a.length>0?await t(vd(a)):[];if(n())return;let c=[...new Set(d.map(p=>y(p.ParentId)).filter(p=>ne.test(p)))],u=new Map;for(let p of["SetupEntityAccess","ObjectPermissions"]){if(c.length===0)break;let m=await t(Nd(p,c));if(n())return;for(let w of m){let R=te(y(w.ParentId)),b=typeof w.n=="number"?w.n:Number(w.n);u.set(R,(u.get(R)??0)+(Number.isFinite(b)?b:0))}}let f=new Map;for(let p of s){let m=y(p.Id);ne.test(m)&&f.set(te(m),cs(y(p.NamespacePrefix),y(p.DeveloperName)))}let g=r&&c.length>0?await hu(c,f,r):void 0;return o.map(({name:p})=>{let m=i.get(p.toLowerCase()),w=new Map;for(let R of d){if(!m||te(y(R.SetupEntityId))!==te(m))continue;let b=te(y(R.ParentId)),P=R.Parent,M=y(A(P,"Name"));if(!M||w.has(b))continue;let z=y(A(P,"NamespacePrefix"));w.set(b,{name:z?`${z}__${M}`:M,label:y(A(P,"Label"))||M,grants:u.get(b)??0,...g===void 0?{}:"refused"in g?{customPermissionsUnread:g.refused}:{customPermissions:g.bySet.get(b)??[]}})}return{permission:p,permissionSets:[...w.values()].sort((R,b)=>R.grants-b.grants||R.name.localeCompare(b.name))}})}function cs(e,t){return e?`${e}__${t}`:t}function pu(e){return`SELECT ParentId, SetupEntityId FROM SetupEntityAccess WHERE SetupEntityType = 'CustomPermission' AND ParentId IN (${e.map(n=>`'${n}'`).join(", ")})`}function mu(e){return`SELECT Id, DeveloperName, NamespacePrefix FROM CustomPermission WHERE Id IN (${e.map(n=>`'${n}'`).join(", ")})`}async function hu(e,t,n){try{let r=await n(pu(e)),o=new Map(t),s=[...new Set(r.map(a=>y(a.SetupEntityId)).filter(a=>ne.test(a)&&!o.has(te(a))))];if(s.length>0)for(let a of await n(mu(s))){let d=y(a.Id);ne.test(d)&&o.set(te(d),cs(y(a.NamespacePrefix),y(a.DeveloperName)))}let i=new Map;for(let a of r){let d=te(y(a.ParentId)),c=o.get(te(y(a.SetupEntityId)));if(!c)continue;let u=i.get(d)??[];u.includes(c)||u.push(c),i.set(d,u)}for(let a of i.values())a.sort((d,c)=>d.localeCompare(c));return{bySet:i}}catch(r){return{refused:F(r)}}}var yu={insert:"on insert",update:"on update",delete:"on delete"},wu={insert:{before:"before save",after:"after save",beforeAndAfter:"before and after save"},update:{before:"before save",after:"after save",beforeAndAfter:"before and after save"},delete:{before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"}},Ru={flow:e=>`flow "${e}"`,trigger:e=>`Apex trigger ${e}`,process:e=>`process "${e}"`,workflowRule:e=>`workflow rule "${e}"`},bu={flows:"the flows",triggers:"the Apex triggers",conditions:"the start conditions of some flows",processes:"the Process Builder processes",workflowRules:"the workflow rules",definitions:"the definitions of some processes or workflow rules",assignmentRules:"the assignment rules",duplicateRules:"the duplicate rules",userPermissions:"the custom permissions of the user the run writes as",permissionSets:"the permission sets that hold a bypass the user the run writes as does not"},Su={email:"email",notification:"custom notification",outbound:"outbound message",sms:"text message"};function Au(e){let t=e.guessed?" (guessed from the name of an Apex action)":"";return`${Su[e.kind]} "${e.name}"${t}`}function Eu(e){let t=e.label?` "${e.label}"`:"";if(e.kind==="async")return`asynchronous path${t}`;if(e.offset===void 0||e.unit===void 0)return`scheduled path${t}`;let n=Math.abs(e.offset),r=n===1?e.unit.replace(/s$/,""):e.unit,o=e.offset<0?"before":"after";return`scheduled path${t} (${n} ${r} ${o} ${e.field??"the save"})`}function Tu(e){let t=e.value===void 0?"true":`'${e.value}'`;return e.where==="decision"?`its first decision ends it when ${e.reference} is ${t}`:`not when ${e.reference} is ${t}`}function Ou(e,t){let n=e.flow,r=n?.permissions??[],o=n?.switches??[],s=n?.messages??[],i=n?.paths??[],a=p=>p.held===!0?" (held)":p.held===!1?" (not held)":"",d=r.filter(p=>p.bypass&&p.where!=="decision"),c=r.filter(p=>p.bypass&&p.where==="decision"),u=r.filter(p=>!p.bypass&&p.where!=="decision"),f=[...r.filter(p=>!p.bypass&&p.where==="decision").map(p=>p.name),...o.filter(p=>!p.bypass).map(p=>p.reference)],g=e.kind==="flow"?"start condition":"definition";return[wu[t][e.when],...s.length>0?[`SENDS MESSAGES: ${s.map(Au).join(", ")}`]:[],...i.length>0?[`then after commit: ${i.map(Eu).join(", ")}`]:[],...d.length>0?[`not for a user with ${d.map(p=>p.name+a(p)).join(", ")}`]:[],...c.length>0?[`its first decision ends it for a user with ${c.map(p=>p.name+a(p)).join(", ")}`]:[],...o.filter(p=>p.bypass).map(Tu),...e.keptQuiet?["quiet for this run"]:[],...u.length>0?[`its start condition names ${u.map(p=>p.name).join(", ")}`]:[],...f.length>0?[`its decisions test ${f.join(", ")}`]:[],...n?.condition==="notRead"?[`${g} not read`]:[],...n?.condition==="unreadable"?[`${g} unreadable`]:[]]}function Hl(e,t,n={}){let r=[`target automation: what ${t} runs on the ${e.objectsRead.length} object(s) the run writes`];for(let i of e.objects){r.push(` ${i.objectApiName}`);for(let{write:c,fired:u}of ze(i)){let f=u.map(g=>`${Ru[g.kind](g.name)} (${Ou(g,c).join("; ")})`);r.push(` ${yu[c]}: ${f.join(", ")}`)}let a=n.mayApplyAssignmentRules!==!1;for(let c of i.assignmentRules??[])r.push(n.applyAssignmentRules?` assignment rule "${c.name}": applied${a?" (--apply-assignment-rules)":""}: it can give the records it routes another owner, and mail that owner`:` assignment rule "${c.name}": not applied: the run sends Sforce-Auto-Assign: FALSE and keeps the owner it sets${a?" (--apply-assignment-rules applies it)":""}`);let d=i.duplicateRules??[];d.length>0&&r.push(` duplicate rules: ${d.map(c=>`"${c.name}"`).join(", ")}: the run saves a record a rule only alerts on; a rule that blocks still refuses it`)}e.objects.length===0&&r.push(_n(e.unread)?" nothing found in what could be read":" no active flow, process, workflow rule, Apex trigger, assignment rule or duplicate rule runs on them");let o=Ve(e),s=Cn(e).filter(i=>!o.includes(i));if(s.length>0){r.push(` bypass: assign ${s.join(", ")} to the user the run writes as, and the flows whose start condition excludes them stay quiet`+(n.mayMute===!1?"":e.cannotAssign===!0?`; --mute-automation would be refused: ${$e}`:"; --mute-automation assigns them for the run alone, and takes them back as it ends"));for(let{permission:i,permissionSet:a,others:d}of Qe(e,s)){if(!a){r.push(` ${i}: no permission set of ${t} holds it: an admin creates one that includes it`);continue}let c=d.length>0?`; also held by ${d.map(f=>f.name).join(", ")}`:"",u=n.username?`: ${Je(a.name,t,n.username)}`:"";r.push(` ${i}: held by permission set ${a.name}, the smallest${c}${u}`)}}if(o.length>0&&r.push(` bypass held: the user the run writes as holds ${o.join(", ")}, and what excludes them stays quiet for this run`),e.conditionsNotRead>0){let i=(e.conditionsNotReadOn??[]).map(({objectApiName:a,flows:d})=>`${a} (${d})`).join(", ");r.push(` ${e.conditionsNotRead} start condition(s) not read: the read takes ${e.conditionsBound} at most`+(i?`; left unread on ${i}`:""))}(e.definitionsNotRead??0)>0&&r.push(` ${e.definitionsNotRead} process or workflow rule definition(s) not read: the read takes ${e.definitionsBound??qo} at most`);for(let{part:i,reason:a}of e.unread)r.push(` ${bu[i]} could not be read: ${a}`);return r.push(` read in ${e.requests} request(s) to ${t}`),r}export{Jr as a,sc as b,Kr as c,uc as d,cc as e,lc as f,fc as g,gc as h,Cu as i,$s as j,$e as k,Ks as l,Zs as m,ri as n,_u as o,Iu as p,ju as q,Du as r,Lu as s,qu as t,zu as u,Vu as v,Ur as w,Hu as x,Gr as y,gi as z,Qu as A,ec as B,tc as C,Vr as D,nc as E,rc as F,No as G,wl as H,Rl as I,bl as J,Sl as K,rd as L,Al as M,El as N,od as O,vo as P,Tl as Q,Ol as R,kl as S,$l as T,Pl as U,Ml as V,Fl as W,vl as X,Nl as Y,xo as Z,Co as _,ud as $,qo as aa,pt as ba,mt as ca,Yt as da,Xt as ea,io as fa,cd as ga,ld as ha,fd as ia,gd as ja,pd as ka,md as la,hd as ma,_o as na,yd as oa,wd as pa,Ed as qa,Td as ra,Od as sa,Vl as ta,kd as ua,$d as va,Pd as wa,Md as xa,Fd as ya,vd as za,Nd as Aa,Ho as Ba,Qo as Ca,qd as Da,is as Ea,as as Fa,du as Ga,us as Ha,Kt as Ia,ft as Ja,Gt as Ka,Go as La,gu as Ma,pu as Na,mu as Oa,Hl as Pa,$c as Qa,Pc as Ra,yi as Sa,Mc as Ta,ao as Ua,uo as Va,qt as Wa,Dt as Xa,lo as Ya,Ti as Za,Fc as _a,Xr as $a,$i as ab,vc as bb,Nc as cb,Bc as db,xc as eb,Fi as fb,vi as gb,Zr as hb,Ni as ib,Bi as jb,Ci as kb,jt as lb,Pe as mb,ji as nb,Di as ob,dt as pb,Li as qb,Wi as rb,Ui as sb,Cc as tb,ut as ub,Qi as vb,Ji as wb,Ki as xb,Xi as yb,Zi as zb,ea as Ab,ta as Bb,na as Cb,ra as Db,sa as Eb,ia as Fb,aa as Gb,ho as Hb,ge as Ib,be as Jb,da as Kb,lt as Lb,ua as Mb,ca as Nb,la as Ob,fa as Pb,_c as Qb,ga as Rb,yo as Sb,pa as Tb,wo as Ub,Wt as Vb,ma as Wb,wa as Xb,Ic as Yb,jc as Zb,Oa as _b,Ro as $b,ka as ac,$a as bc,Pa as cc,Ma as dc,Dc as ec,Fa as fc,va as gc,Lc as hc,Wc as ic,Ao as jc,Uc as kc,Gc as lc,Eo as mc,qc as nc,zc as oc,Vc as pc,Da as qc,Hc as rc,Qc as sc,Jc as tc,Kc as uc,Yc as vc,Z as wc,$o as xc,Wa as yc,Ua as zc,Xc as Ac,Ga as Bc,Zc as Cc,el as Dc,Ne as Ec,tl as Fc,nl as Gc,fe as Hc,rl as Ic,ol as Jc,Va as Kc,sl as Lc,Ha as Mc,il as Nc,Ht as Oc,al as Pc,dl as Qc,ul as Rc,cl as Sc,ll as Tc};
|
|
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as B,b as J}from"./chunk-PC247GKX.mjs";import{a as S}from"./chunk-
|
|
7
|
+
import{a as B,b as J}from"./chunk-PC247GKX.mjs";import{a as S}from"./chunk-S42RBRH2.mjs";import{$a as b,Ra as h,Sa as E,Ta as U,Ua as D}from"./chunk-PMWAFDUB.mjs";import{b as l,l as m,s as C,u as M,v as K}from"./chunk-WZQEK4WT.mjs";import{randomBytes as L}from"node:crypto";import{mkdirSync as ye,statSync as Z}from"node:fs";import{mkdir as w,open as Oe,readFile as R,readdir as _,rename as Fe,rm as f,rmdir as xe,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as Ie}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Ce,gzip as be}from"node:zlib";import{createHash as me}from"node:crypto";var G=16,Y=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:C(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return me("sha256").update(n).digest("hex")}function we(n){return JSON.stringify([n.name.toLowerCase(),n.type,n.createable===!0,n.updateable===!0,n.nillable===!0,[...n.referenceTo??[]].sort(),n.encrypted===!0])}function dn(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:we(t)})).sort((t,r)=>t.key<r.key?-1:t.key>r.key?1:0);return{digest:W(e.map(({line:t})=>t).join(`
|
|
8
8
|
`)),fields:Object.fromEntries(e.map(({name:t,line:r})=>[t,W(r).slice(0,G)]))}}function pn(n,e){let t={added:[],removed:[],changed:[]};if(n.digest===e.digest)return t;let r=new Map(Object.entries(n.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}])),i=new Map(Object.entries(e.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}]));for(let[o,{name:s,print:a}]of i){let p=r.get(o);p===void 0?t.added.push(s):p.print!==a&&t.changed.push(s)}for(let[o,{name:s}]of r)i.has(o)||t.removed.push(s);return t.added.sort(),t.removed.sort(),t.changed.sort(),t}var g=448,Pe=384,Ee=30,ee=3,De=15,ne=1440*6e4,I=1440*6e4,Se=Q(be),ve=Q(Ce),T="checkpoint.json",ze="fingerprints.json.gz",Ae="fingerprints.json",Le="snapshots.json",te="replay.json.gz",re=/^[A-Za-z][A-Za-z0-9_]*$/;function In(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?Ie(e):c(V(),".sandforge");return c(t,"checkpoints")}function Re(n=V()){return c(n,".sandforge","locks")}function k(n){let e=D.safeParse(n).success?S(n.slice(0,15)):void 0;if(e===void 0)throw new d("invalid","Not an Organization Id");return e}function Ne(n){return n.length===18&&D.safeParse(n).success&&S(n.slice(0,15))===n}function v(n,e,t){return ie(c(n,e,t),e,t)}function ie(n,e,t){return{organizationId:e,checkpointId:t,dir:n,checkpointFile:c(n,T),fingerprintsFile:c(n,ze),plainFingerprintsFile:c(n,Ae),snapshotsFile:c(n,Le),indexDir:c(n,"index"),binDir:c(n,"bin"),filesDir:c(n,"files"),previewsDir:c(n,"previews"),rewindsDir:c(n,"rewinds")}}function oe(n){if(!re.test(n)||n.length>80)throw new d("invalid","Not a Salesforce API name");return n}function Cn(n,e){return c(n.indexDir,`${oe(e)}.idx`)}function bn(n){return c(n.indexDir,"recreated.ndjson")}function Pn(n){return c(n.indexDir,"notInBin.ndjson")}function En(n,e){return c(n.binDir,`${oe(e)}.ids`)}function Dn(n){return c(n.filesDir,"documents.ndjson")}function Sn(n){return c(n.filesDir,"links.ndjson")}function vn(n){return c(n.dir,te)}var $e=[/^checkpoint\.json$/,/^fingerprints\.json(?:\.gz)?$/,/^snapshots\.json$/,/^backups\/[A-Za-z0-9_-]{1,200}__[A-Za-z][A-Za-z0-9_]{0,79}\.ndjson(?:\.gz)?$/,/^bin\/[A-Za-z][A-Za-z0-9_]{0,79}\.ids$/,/^files\/(?:links|documents)\.ndjson(?:\.gz)?$/,/^index\/(?:recreated|notInBin)\.ndjson$/,/^replay\.json\.gz$/],zn=te,je=["","backups","bin","files","index"],An=T;function se(n){return $e.some(e=>e.test(n))}async function Ln(n){let e=[];for(let t of je){let r;try{r=await _(c(n.dir,t),{withFileTypes:!0})}catch(i){if(F(i)==="ENOENT"||F(i)==="ENOTDIR")continue;throw i}for(let i of r){let o=t===""?i.name:`${t}/${i.name}`;if(!i.isFile()||!se(o))continue;let s=c(n.dir,t,i.name);e.push({path:o,file:s,bytes:(await x(s)).size})}}return e.sort((t,r)=>ge(t.path,r.path))}function Rn(n,e){if(!se(e))throw new d("invalid","Not a file a checkpoint holds");return c(n,...e.split("/"))}function Nn(n,e){return c(n.previewsDir,O(E,e))}function H(n,e){return c(n.rewindsDir,O(U,e))}function O(n,e){let t=n.safeParse(e);if(!t.success)throw new d("invalid","Not an id of this store");return t.data}async function X(n){await w(n,{recursive:!0,mode:g})}var q="abcdefghijklmnopqrstuvwxyz0123456789";function $n(n,e=new Date){let t=e.toISOString(),r=`${t.slice(0,4)}${t.slice(5,7)}${t.slice(8,10)}`,i=`${t.slice(11,13)}${t.slice(14,16)}${t.slice(17,19)}`,o=Array.from(L(4),s=>q[s%q.length]).join("");return`${n}-${r}-${i}-${o}`}function _e(n,e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Not a number of days: ${e}`);return e===0?null:new Date(n.getTime()+e*I).toISOString()}function ce(n,e){return n.expiresAt!==null&&Date.parse(n.expiresAt)<=e}function Te(n,e){if(n.expiresAt===null)return!1;let t=Date.parse(n.expiresAt);return t>e&&t-e<=ee*I}function He(n,e){let t=e-De*I;return Date.parse(n.readFrom)<t?new Date(t).toISOString():void 0}function Me(n,e){let t=ae(n);return t!==void 0&&t<=e}function ae(n){let e=n.scratchExpiresAt;if(e===void 0)return;let t=Date.parse(e);if(Number.isFinite(t))return/^\d{4}-\d{2}-\d{2}$/.test(e)?t+I:t}function Ke(n,e){let t=ae(n);return t!==void 0&&t>e&&t-e<=ee*I}var d=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointStoreError"}code};function jn(n,e,t){let r=n.detail!==void 0?` (${n.detail})`:"";if(n.path===e)switch(n.reason){case"otherOwner":return`another user of this machine owns it, and could read and replace the checkpoints in it. ${t} names a folder of your own.`;case"notAFolder":return`it is a file, not a folder. ${t} names a folder for them, or move the file away.`;case"cannotMake":return`it could not be made${r}. ${t} names a folder this user can write.`}let i="the folder of every org\u2019s lock, whatever the store";switch(n.reason){case"otherOwner":return`${i}, is owned by another user of this machine: run as its owner, or remove it.`;case"notAFolder":return`${i}, is a file, not a folder: move the file away.`;case"cannotMake":return`${i}, could not be made${r}: make it a folder this user can write.`}}var de=m({version:K(1),objects:C(l().regex(re).max(80),Y)});async function Ue(n,e){let t;try{t=JSON.parse(await Je(n))}catch{throw new d("damaged","The checkpoint\u2019s field prints cannot be read")}let r=de.safeParse(t);if(!r.success)throw new d("damaged","The checkpoint\u2019s field prints do not parse");let i=new Map(Object.entries(r.data.objects));for(let o of e)if(i.get(o.objectApiName)?.digest!==o.fingerprint)throw new d("damaged",`The field prints of ${o.objectApiName} are not the checkpoint\u2019s`);return i}async function Be(n){let e=de.safeParse({version:1,objects:n});if(!e.success)throw new d("invalid",`Not field prints: ${e.error.message}`);return Se(`${JSON.stringify(e.data)}
|
|
9
9
|
`)}async function Je(n){let e;try{e=await R(n.fingerprintsFile)}catch(t){if(t.code!=="ENOENT")throw t;return R(n.plainFingerprintsFile,"utf8")}return(await ve(e)).toString("utf8")}function _n(n){let e=n.uid??(()=>process.getuid?.()),t=n.locksDir??Re();for(let r of[n.root,t]){let i=We(r,e);if(i!==void 0)return{refusal:i}}return{store:new N({...n,locksDir:t})}}function We(n,e){try{let t=Z(n,{throwIfNoEntry:!1});if(t!==void 0&&!t.isDirectory())return{reason:"notAFolder",path:n};ye(n,{recursive:!0,mode:g});let r=e();return r!==void 0&&Z(n).uid!==r?{reason:"otherOwner",path:n}:void 0}catch(t){return{reason:"cannotMake",path:n,detail:cn(t)}}}var N=class{root;locksDir;renameFile;lockOptions;changes=new Map;constructor(e){this.root=e.root,this.locksDir=e.locksDir,this.renameFile=e.rename??((t,r)=>Fe(t,r)),this.lockOptions={...e.lockSelf?{self:e.lockSelf}:{},...e.lockChecks?{checks:e.lockChecks}:{}}}folderOf(e,t){return v(this.root,k(e),O(h,t))}async create(e,t){let r=this.folderOf(e,t);await X(c(this.root,r.organizationId));try{await w(r.dir,{mode:g})}catch(i){throw F(i)==="EEXIST"?new d("exists",`A checkpoint ${t} is kept already`):i}return await w(r.indexDir,{mode:g}),await w(r.binDir,{mode:g}),r}async write(e){let t=z(e),r=this.folderOf(t.org.organizationId,t.checkpointId);await this.writeWhole(r.checkpointFile,$(t))}async writeFingerprints(e,t){await this.writeWhole(e.fingerprintsFile,await Be(t))}async readFingerprints(e,t){return Ue(e,t.objects)}async checkpointsOf(e){return this.readsOf(k(e))}async read(e){let t=O(h,e);for(let r of await this.organizationKeys()){let i=v(this.root,r,t);if(await y(i.dir))return A(i)}}async update(e,t){let r=async()=>{let a=await this.read(e);if(a===void 0)throw new d("notFound",`No checkpoint ${e} is kept`);if(a.checkpoint===void 0)throw new d("damaged",`The checkpoint ${e} is damaged`);let p=t(structuredClone(a.checkpoint));if(p.checkpointId!==a.folder.checkpointId||j(p.org.organizationId)!==a.folder.organizationId)throw new d("invalid","A change never moves a checkpoint");return await this.write(p),b.parse(p)},o=(this.changes.get(e)??Promise.resolve()).then(r,r),s=o.catch(()=>{});return this.changes.set(e,s),s.then(()=>{this.changes.get(e)===s&&this.changes.delete(e)}),o}keep(e,t,r=new Date){return this.update(e,i=>({...i,expiresAt:t?null:_e(r,Ee)}))}async list(e={}){let t=(e.now??new Date).getTime(),r=e.organizationId!==void 0?k(e.organizationId):void 0,i=[];for(let o of await this.organizationKeys(r)){let s=await this.readsOf(o),a=qe(s);for(let p of s)i.push(await Qe(p,t,a,e.refreshedAt))}return i.sort((o,s)=>ge(s.checkpointId,o.checkpointId))}async delete(e){let t=await this.read(e);if(t===void 0)return{outcome:"notFound"};let r=this.lock(t.folder.organizationId,"delete",t.folder.checkpointId);if("busy"in r)return{outcome:"busy",holder:r.busy};try{await f(t.folder.dir,{recursive:!0,force:!0})}finally{r.lock.release()}return t.checkpoint?{outcome:"deleted",checkpoint:t.checkpoint}:{outcome:"deleted"}}async importInto(e,t,r){let i=this.folderOf(e,t),o=c(this.root,i.organizationId);await X(o);let s=ie(c(o,`${Ge}${L(6).toString("hex")}`),i.organizationId,i.checkpointId);await w(s.dir,{mode:g});try{let a=z(await r(s));if(a.checkpointId!==i.checkpointId||j(a.org.organizationId)!==i.organizationId)throw new d("invalid","An import keeps the checkpoint it was asked to");let p=z({...a,bytes:await Xe(s.dir,a)});if(await this.writeWhole(s.checkpointFile,$(p)),await y(i.dir))return{outcome:"exists"};try{await this.renameFile(s.dir,i.dir)}catch(u){if(await y(i.dir))return{outcome:"exists"};throw u}return{outcome:"imported",checkpoint:p}}finally{await f(s.dir,{recursive:!0,force:!0}),await xe(o).catch(()=>{})}}async sweep(e=new Date){let t=e.getTime(),r={checkpoints:[],journals:[],previews:0,skipped:[]};for(let i of await this.organizationKeys()){await Ze(c(this.root,i),t);let o=await en(await this.readsOf(i),t);if(o.length===0)continue;let s=this.lock(i,"sweep");if("busy"in s){r.skipped.push(i);continue}try{for(let a of o)await nn(await A(a),t,r)}finally{s.lock.release()}}return r}lock(e,t,r){return on(this.locksDir,e,{operation:t,...r!==void 0?{checkpointId:r}:{}},this.lockOptions)}heldBy(e){return sn(this.locksDir,e,this.lockOptions)}async organizationKeys(e){return(await P(this.root)).filter(r=>Ne(r)&&(e===void 0||r===e))}async readsOf(e){let t=(await P(c(this.root,e))).filter(i=>h.safeParse(i).success),r=[];for(let i of t)r.push(await A(v(this.root,e,i)));return r}async writeWhole(e,t){let r=`${e}.${process.pid}-${L(4).toString("hex")}.tmp`,i=await Oe(r,"wx",Pe);try{try{await i.writeFile(t,typeof t=="string"?"utf8":void 0),await i.sync()}finally{await i.close()}await this.renameFile(r,e)}catch(o){throw await f(r,{force:!0}),o}}},Ge=".importing-",Ye=/^\.importing-[0-9a-f]{12}$/;async function Ze(n,e){for(let t of await P(n)){if(!Ye.test(t))continue;let r=c(n,t),i=await x(r).catch(()=>{});i!==void 0&&i.mtimeMs+ne<=e&&await f(r,{recursive:!0,force:!0})}}function z(n){let e=b.safeParse(n);if(!e.success)throw new d("invalid",`Not a checkpoint: ${e.error.message}`);return e.data}function $(n){return`${JSON.stringify(n,null,2)}
|
|
10
10
|
`}async function pe(n,e){let t=0;for(let r of await _(n,{withFileTypes:!0})){let i=c(n,r.name);r.isDirectory()?t+=await pe(i,e):r.isFile()&&i!==e&&(t+=(await x(i)).size)}return t}async function Xe(n,e){let t=await pe(n,c(n,T)),r=o=>Buffer.byteLength($({...e,bytes:o}),"utf8"),i=t+r(t);return i=t+r(i),i}async function A(n){let e;try{e=JSON.parse(await R(n.checkpointFile,"utf8"))}catch{return{folder:n}}let t=b.safeParse(e);return t.success?t.data.checkpointId!==n.checkpointId||j(t.data.org.organizationId)!==n.organizationId?{folder:n}:{folder:n,checkpoint:t.data}:{folder:n}}function qe(n){let e;for(let{folder:t,checkpoint:r}of n){let i=r?.lastRewind?.rewindId;i!==void 0&&(e===void 0||i>e.rewindId)&&(e={checkpointId:t.checkpointId,rewindId:i})}return e}function Ve(n,e,t,r){if(n.status==="taking")return{why:"taking"};if(n.status==="failed")return{why:"failed"};let i=r?.(e);if(i!==void 0)return{why:"refreshed",refreshedAt:i};if(Me(n.org,t))return{why:"scratchExpired"}}async function Qe({folder:n,checkpoint:e},t,r,i){let o={checkpointId:n.checkpointId,organizationId:n.organizationId};if(e===void 0)return{...o,valid:!1,why:"damaged"};let s=Ve(e,n.organizationId,t,i);if(s!==void 0)return{...o,checkpoint:e,valid:!1,why:s.why,...s.refreshedAt!==void 0?{refreshedAt:s.refreshedAt}:{}};let a={...o,checkpoint:e,valid:!0};Te(e,t)&&(a.expiresSoon=!0),Ke(e.org,t)&&(a.scratchExpiresSoon=!0);let p=He(e,t);p!==void 0&&(a.binReachSince=p);let u=e.lastRewind;return u!==void 0&&r?.checkpointId===n.checkpointId&&u.undoUntil!==void 0&&u.undoneAt===void 0&&Date.parse(u.undoUntil)>t&&await y(H(n,u.rewindId))&&(a.undo={rewindId:u.rewindId,until:u.undoUntil}),a}async function en(n,e){let t=[];for(let{folder:r,checkpoint:i}of n)i!==void 0&&(ce(i,e)||await ue(r,i,e)||(await fe(r,e)).length>0)&&t.push(r);return t}async function ue(n,e,t){let r=e.lastRewind?.undoUntil;return e.lastRewind!==void 0&&r!==void 0&&Date.parse(r)<=t&&await y(H(n,e.lastRewind.rewindId))}async function fe(n,e){let t=[];for(let r of await P(n.previewsDir)){if(!E.safeParse(r).success)continue;let i=c(n.previewsDir,r),o=await x(i).catch(()=>{});o!==void 0&&o.mtimeMs+ne<=e&&t.push(i)}return t}async function nn(n,e,t){let{folder:r,checkpoint:i}=n;if(i===void 0)return;if(i.expiresAt!==null&&ce(i,e)){await f(r.dir,{recursive:!0,force:!0});let s=i.lastRewind?.undoUntil,a=s!==void 0&&i.lastRewind?.undoneAt===void 0&&Date.parse(s)>e;t.checkpoints.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,expiresAt:i.expiresAt,...a?{undoUntil:s}:{}});return}let o=i.lastRewind;o?.undoUntil!==void 0&&await ue(r,i,e)&&(await f(H(r,o.rewindId),{recursive:!0,force:!0}),t.journals.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,rewindId:o.rewindId,undoUntil:o.undoUntil}));for(let s of await fe(r,e))await f(s,{recursive:!0,force:!0}),t.previews+=1}var tn=m({...B,operation:M(["take","rewind","undo","delete","sweep","empty"]),checkpointId:h.optional()}),le=J(n=>{let e=tn.safeParse(n);return e.success?e.data:void 0});function rn(n,e){return c(n,`${k(e)}.lock`)}function on(n,e,t,r={}){let i=k(e),o=t.checkpointId!==void 0?O(h,t.checkpointId):void 0,s=le.acquire(c(n,`${i}.lock`),a=>({...a,operation:t.operation,...o!==void 0?{checkpointId:o}:{}}),r);return"busy"in s?{busy:he(s.busy)}:{lock:{organizationId:i,release:s.lock.release}}}function sn(n,e,t={}){let r=le.holder(rn(n,e),t);return r!==void 0?he(r):void 0}function he({version:n,token:e,...t}){return t}async function P(n){try{return(await _(n,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch(e){if(F(e)==="ENOENT"||F(e)==="ENOTDIR")return[];throw e}}async function y(n){return(await x(n).catch(()=>{}))?.isDirectory()===!0}function j(n){try{return k(n)}catch{return}}function ge(n,e){return n<e?-1:n>e?1:0}function F(n){return n?.code}function cn(n){return n instanceof Error?n.message:String(n)}export{dn as a,pn as b,g as c,Pe as d,Ee as e,ee as f,De as g,ne as h,In as i,Re as j,k,Cn as l,bn as m,Pn as n,En as o,Dn as p,Sn as q,vn as r,zn as s,An as t,se as u,Ln as v,Rn as w,Nn as x,H as y,X as z,$n as A,_e as B,ce as C,Te as D,He as E,Me as F,Ke as G,d as H,jn as I,Ue as J,Be as K,_n as L,N as M,qe as N,rn as O,on as P,sn as Q};
|