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
package/lib/chunk-ISSP2FZ5.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as ie,c as se,d as Vt,e as Jt,f as be}from"./chunk-XU25YA46.mjs";import{a as Zt,e as Xt}from"./chunk-O2PUGRNW.mjs";import{J as re,P as Ue,a as Kt}from"./chunk-7SDZR6SR.mjs";import{f as Le,p as ge,s as Be,u as Yt,w as $e}from"./chunk-3SKLBRPL.mjs";import{b as me,d as ue}from"./chunk-VPDEJGPS.mjs";import{c as qt}from"./chunk-PBE44M2Y.mjs";import{G as Ht}from"./chunk-XZISAZA6.mjs";import{c as Wt}from"./chunk-L4INJ5TZ.mjs";import{c as Gt,e as Fe,g as Me,h as pe}from"./chunk-TZE3Y7IQ.mjs";import{a as $t,b as V}from"./chunk-CA5NAXSU.mjs";import{C as dt,D as pt,E as mt,Ea as zt,F as ut,Fa as St,Fb as Rt,J as gt,K as bt,Ka as ae,L as ft,La as Ae,M as yt,N as ht,Pa as M,Qa as xt,Ra as F,Sa as Ee,Sc as Nt,Ta as It,Ua as kt,Va as Ce,Wa as Te,Wb as wt,Xa as _e,Yb as vt,Zb as At,ac as Et,ad as Dt,bc as Ct,bd as Ft,cb as Ne,cc as Tt,cd as Mt,de as Lt,ed as Ut,ee as Bt,fb as jt,fd as De,gb as Pt,hb as Ot,jc as _t,n as rt,s as we,t as it,u as st,v as ct,w as ne,y as lt,z as ve}from"./chunk-ZQO5PDX5.mjs";import{b as a,c as Oe,e as g,f as r,g as et,i as D,k as c,l as o,m as tt,o as de,p as Re,s as x,u as w,v,w as ot,x as nt,y as G,z as at}from"./chunk-WZQEK4WT.mjs";function sa(e,t,n){return async s=>{let d=s.map(f=>`${f.objectApiName} (${f.records})`).join(", ");e.log(`[WARN] ${n}: the user may not delete ${d} in the target: those records stay`);let p=e.infraServices?.confirmRemovalLeavingUndeletable;if(!p)return!0;let u=e.orgManager.getOrg(t);return p({org:Nt(u,t),objects:s})}}var Qt={code:"NOT_INITIALIZED",message:"Production Guard is not initialized \u2014 infrastructure services missing"};function ca(){return Object.assign(new Error(Qt.message),{code:Qt.code})}var qe={blocked:"GUARD_BLOCKED",declined:"GUARD_DECLINED"};function la(e){return Object.assign(new Error(`Operation blocked by Production Guard: ${e}`),{code:qe.blocked})}function da(e){return e instanceof Error&&e.code===qe.blocked?qe.blocked:void 0}function Bo(e){return e.robustness??zt}function pa(e){return e.bulkManager??new Kt(Bo(e).bulk.maxConcurrentJobs)}var $o={"sync:schedule":"sync:schedule:","sync:pipeline":"sync:pipeline:","seed:pipeline":"seed:pipeline:","offline-replay":"offline-replay-"};function ma(e,t,n){return{id:`${$o[e]}${t}`,type:n,timestamp:Date.now()}}function ua(e,t,n,s){return{id:e.nextId(),type:n,timestamp:Date.now(),correlationId:t.id,payload:s}}function ga(e,t,n,s,d={}){let p=t==="error"?null:d.autoDismissMs===void 0?5e3:d.autoDismissMs,u={id:e.nextId(),type:"notification",timestamp:Date.now(),payload:{level:t,title:n,message:s,...p===null?{}:{autoDismissMs:p},...d.actions?{actions:d.actions}:{},...d.code?{code:d.code}:{}}};e.broker.postToWebview(u),e.log(`[TX] notification: ${n}`)}function ba(e,t,n,s){let d={id:e.nextId(),type:"operation:started",timestamp:Date.now(),payload:{operationId:t,module:n,description:s}};e.broker.postToWebview(d)}function fa(e,t,n,s,d,p){let u={id:e.nextId(),type:"operation:progress",timestamp:Date.now(),payload:{operationId:t,percentage:n,processedRecords:s,totalRecords:d,currentStep:p}};e.broker.postToWebview(u)}function ya(e,t,n){let s={id:e.nextId(),type:"operation:completed",timestamp:Date.now(),payload:{operationId:t,result:n}};e.broker.postToWebview(s)}var qo=Symbol("sandforge.uncorrelated");function eo(e,t,n,s,d,p={}){let u=V(d),f=d instanceof qt?d:void 0,k=qo in s,E=p.code??f?.code??"UNKNOWN";k||Ko(e.broker,u,E),e.log(`[ERR] ${t}: ${u}${k?` (uncorrelated: ${String(s.reason)})`:""}`);let O={id:e.nextId(),type:n,timestamp:Date.now(),...k?{}:{correlationId:s.id},payload:{message:u,code:E,retryable:p.retryable??!1,...f?{orgId:f.orgId}:{},...p.extraPayload}};e.broker.postToWebview(O),e.log(`[TX] ${n}: ${u}`)}function ha(e,t){let n={id:e.nextId(),type:t.type,timestamp:Date.now(),payload:t.payload};e.broker.postToWebview(n)}function za(e){let t=e?.getSandforgeSetting;if(!(!t||!t("grappe.enabled",!1)))return{enabled:!0,autoActivateThreshold:t("grappe.autoActivateThreshold",1e4),maxWorkers:rt.maxWorkers,grappeSize:t("grappe.grappeSize",5e3),strategy:"round_robin",backPressure:{enabled:!1,maxQueueDepth:3,highWaterMark:80,lowWaterMark:60,strategy:"pause",monitoringInterval:5e3},checkpointing:!0,isolationLevel:"per_grappe"}}function Sa(e){let t=new Set(e.map(s=>s.batchSize)),[n]=t;return{...e.length>0?{objectName:e.map(s=>s.objectApiName).join(", ")}:{},...t.size===1&&n!==void 0?{batchSize:n}:{}}}function xa(e,t,n,s,d={}){let p={id:e.nextId(),type:"operation:failed",timestamp:Date.now(),payload:{operationId:t,error:n,retryable:s,...d.extraPayload}};e.broker.postToWebview(p),d.authored!==!0&&Zo(e,n,d.context)}var Go=[/^Operation cancelled by user\b/,/^Operation blocked by Production Guard: /,/^Production Guard is not initialized\b/,/^Duplicate operation: /,/^A backup or rollback operation is already running for org /,/^Object describe not available for '/,/^CRUD_FLS_DENIED: /,/^CRUD\/FLS check failed for /,/^No backup found for operation /,/^Backup \S+ was taken from org /,/^Restore not run: /,/^Pipeline failed$/,/^Pipeline did not start: /,/^Pipeline ran out of time: /,/^Org not found: /,/^No credentials for org /,/^Invalid username format: /];function Wo(e){return Go.some(t=>t.test(e))}var to=1e4,Ge=new WeakMap;function Ko(e,t,n){let s=De(t,{code:n});if(!s?.actionKey)return;let d=Ge.get(e)??new Map,p=Date.now();for(let[u,f]of d)p-f>to&&d.delete(u);d.set(s.code,p),Ge.set(e,d)}function Ho(e,t){let n=Ge.get(e)?.get(t);return n!==void 0&&Date.now()-n<=to}function Zo(e,t,n={}){if(!(e.broker.panelCount>0)||Wo(t))return;let d=$t(t,Ut)??"UNKNOWN",p=De(t,{code:d});if(p?.actionKey){if(Ho(e.broker,p.code))return;e.broker.showFixSuggestion({source:"catalogue",code:p.code,actionKey:p.actionKey});return}let u=e.errorResolver;u&&u.resolveError({errorCode:d,message:t},n).then(f=>{e.broker.showFixSuggestion({source:"model",text:Xo(f)})}).catch(f=>{e.log?.(`[ERR] operation:failed resolution: ${V(f)}`)})}function Xo(e){return e.suggestions[0]?.description||e.explanation}import{isAbsolute as tn}from"node:path";var i=a().min(1).max(128),l=a().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Invalid Salesforce API name").max(80),so=c(l).max(300),m=a().min(1).max(200),J=a().max(2e3).refine(Fe,{message:Me}),on=a().refine(Gt,{message:"ORDER BY clause must list only field names with optional ASC/DESC and NULLS FIRST/LAST (no LIMIT, OFFSET, FOR UPDATE or subquery)."}),y=100,co=1e4,B=o({keepDays:g().int().min(ve.min).max(ve.max).optional(),excluded:c(l).max(y).refine(e=>new Set(e).size===e.length,"An object is left out twice").optional()}).strict(),he={sweepLate:r().optional(),sweepUntied:r().optional()};function nn(e){return Wt(e)}function an(e,t='turn on "Copy the files of these records"'){return _t(e)?`Sync copies files with the records they hang on, not as an object of their own: "${e}" keeps its content in a file body. Remove it from this configuration and ${t} instead; the sync was not started.`:`Sync does not copy "${e}": no copy writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Remove it from this configuration; the sync was not started.`}var rn=w(gt,{error:e=>e.input==="manual"?"Manual conflict review is not available for a sync run: no run shows its conflicts to anyone before it writes. Pick source wins, target wins, newest wins or merge \u2014 target wins keeps every value the target holds where the two orgs differ. The sync was not started.":`Conflict strategy "${String(e.input)}" is not one a sync run acts on: pick source wins, target wins, newest wins or merge. The sync was not started.`}),sn=bt.extend({objectApiName:l.refine(e=>!nn(e),{error:e=>an(String(e.input))}),externalIdField:nt(e=>typeof e=="string"&&e.trim()===""?void 0:e,l.optional()),where:J.optional(),orderBy:on.optional(),batchSize:g().int().positive().max(co).optional()}).strip().refine(e=>e.operation!=="upsert"||(e.externalIdField??"Id").toLowerCase()!=="id",{path:["externalIdField"],error:e=>`An upsert of "${String(e.input.objectApiName)}" needs an External ID field: matching on Id cannot work, because the id belongs to the source org and the target has never issued it. Name an External ID field both orgs share, or set the operation to insert. The sync was not started.`}).superRefine((e,t)=>{let n=Ft([e]);n.length!==0&&t.addIssue({code:G.custom,message:`${Mt(n)} The sync was not started.`,params:{unreadablePatterns:n}})});function oo(e){return et({error:()=>`Sync does not run Apex: remove "${e}" from this configuration. The sync was not started so the script cannot be skipped without you knowing.`}).optional()}var Ke=ft.extend({id:m.optional(),sourceOrgId:i,targetOrgId:i,objects:c(sn).min(1).max(y),conflictStrategy:rn,createdAt:a().max(40).optional(),updatedAt:a().max(40).optional(),preScript:oo("preScript"),postScript:oo("postScript"),dryRun:v(!1,{error:()=>'A sync configuration cannot ask for a dry run: remove "dryRun" from it. A run of it writes to the target org; to see what it would write, simulate it from the Sync page. The run was not started, so it cannot write while you believed it was only reporting.'}).optional()}).strip().superRefine((e,t)=>{e.direction==="target_to_source"&&t.addIssue({code:G.custom,path:["direction"],message:'Sync writes source to target only: direction "target_to_source" is not supported. Swap the source and target orgs to copy the other way. The sync was not started, so it cannot write into the org you meant to read from.'}),e.mode!=="full"&&e.mode!=="delta"&&t.addIssue({code:G.custom,path:["mode"],message:`Sync runs a full or a delta sync only: mode "${e.mode}" is not implemented. Set mode to "full" or "delta". The sync was not started, so it cannot replay the whole object set while you believed it was reading changes only.`}),e.mode==="delta"&&e.objects.forEach((n,s)=>{n.operation==="upsert"||n.operation==="update"||t.addIssue({code:G.custom,path:["objects",s,"operation"],message:`A delta sync writes ${n.objectApiName} again for every record it reads twice, and ${n.operation} would ${n.operation==="insert"?"create a second copy":"delete a record already gone"}. Write it by upsert on an External ID, or by update, or run the configuration in full. The sync was not started.`})}),e.propagateDeletes===!0&&(e.mode!=="delta"?t.addIssue({code:G.custom,path:["propagateDeletes"],message:'Deletions are carried by a delta sync only, which knows since when to look for them: set mode to "delta", or turn deletions off. The sync was not started.'}):e.objects.forEach((n,s)=>{if(n.operation!=="upsert"&&n.operation!=="update")return;let d=Ht(n);"refused"in d&&t.addIssue({code:G.custom,path:["objects",s],message:`${d.refused} Turn deletions off, or carry a source field onto the key. The sync was not started.`})}))}),Ea=o({suggestedName:a().min(1).max(255).refine(e=>!e.includes("/")&&!e.includes("\\"),"suggestedName must not contain a path"),content:a().max(32*1024*1024),extensions:c(a().regex(/^[A-Za-z0-9]+$/)).max(8).optional()}),Ca=o({config:Ke,muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ta=o({config:Ke,checkpointFirst:B.optional()}),_a=o({operationId:m}),Na=o({config:Ke}),Da=o({id:m}),Fa=o({orgId:i,targetOrgId:i.optional()}),Ma=o({sourceOrgId:i,targetOrgId:i,objectApiName:l}),lo=w(["source_wins","target_wins","newest_wins","manual","merge"]),cn=Re("kind",[o({kind:v("id")}),o({kind:v("externalId"),field:l}),o({kind:v("syncConfig"),configId:m})]),Ua=o({sourceOrgId:i,targetOrgId:i,watchedObjects:c(l).min(1).max(y),apply:c(o({objectApiName:l,match:cn,applyDeletes:r()})).max(y),conflictStrategy:lo,flushIntervalMs:g().int().min(50).max(6e4),maxBatchSize:g().int().min(1).max(200),keepContactPoints:r().optional()}).refine(e=>e.apply.every(t=>e.watchedObjects.includes(t.objectApiName)),{message:"Every applied object must be watched.",path:["apply"]}),La=o({sessionId:a().max(200)}),Ba=o({sourceOrgId:i,targetOrgId:i}),$a=o({conflictId:a().min(1).max(500),eventReplayId:g().optional(),resolution:lo,fieldResolutions:x(a(),o({value:D(),source:w(["source","target","manual"])})).optional()}),qa=o({entryId:m}),Ga=o({runId:m}),Wa=o({realtime:v(!0).optional()}).optional(),Ka=o({sourceOrgId:i,targetOrgId:i,objects:c(l).max(y),configId:m.optional()}),Ha=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Za=o({runId:m}),Xa=o({runId:m,again:r().optional(),sweptObjects:so.optional()}),Ya=o({runId:m}),Va=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Ja=o({runId:m}),Qa=o({format:w(["csv","json"]),entryIds:c(m).max(500).optional()}),ln=o({id:m,name:a().min(1).max(200),configId:m,cron:a().min(1).max(100),timezone:a().min(1).max(100),enabled:r(),maxRetries:g().int().min(0).max(10),notifyOnComplete:r(),notifyOnFailure:r(),createdAt:a().max(40),updatedAt:a().max(40),version:g().int().positive()}).strip(),er=o({schedule:ln}),tr=o({scheduleId:m,enabled:r()}),or=o({scheduleId:m}),dn=dt.extend({objectApiName:l,recordCount:g().int().positive().max(ne),batchSize:g().int().positive().max(co).optional()}).loose(),pn=pt.extend({childObject:l,lookupField:l,parentObject:l}).superRefine((e,t)=>{e.parents.kind==="existing"&&e.parents.where!==void 0&&!Fe(e.parents.where)&&t.addIssue({code:G.custom,path:["parents","where"],message:Me})}),mn=mt.extend({objects:c(dn).min(1).max(y),relations:c(pn).max(y).optional()}).loose().superRefine(ut),nr=o({orgId:i,template:mn,muteAutomation:r().optional(),checkpointFirst:B.optional(),fit:o({share:g().gt(0).max(1),withinMB:g().positive().max(1e6).optional(),before:g().int().positive().max(ne*y)}).strict().optional(),locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),dryRun:r().optional()}),ar=o({orgId:i}),rr=o({orgId:i,objects:c(l).min(1).max(y),publishes:r().optional()}).strict(),ir=o({orgId:i,objectApiName:l}),sr=o({id:m}),cr=o({template:x(a(),D())}),lr=o({description:a().max(1e4)}),dr=o({}).strict(),pr=o({orgId:i,pack:ae,seed:Ae.shape.seed,articleBodyField:l.optional()}).strict(),mr=o({orgId:i,pack:ae,options:Ae,locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}).strict(),ur=o({orgId:i}).strict(),gr=o({pack:ae,overwrite:r().optional()}).strict(),br=o({runId:m,choice:Rt,overwrite:r().optional()}).strict(),un=131072,gn=o({objectApiName:l,whereClause:J.optional()}).loose(),fr=o({sourceOrgId:i}),yr=o({sourceOrgId:i,targetOrgId:i,objects:c(gn).min(1).max(y),upsert:r().optional(),externalIdField:l.optional(),previewId:m.optional(),keepContactPoints:r().optional(),checkpointFirst:B.optional()}).refine(e=>!e.upsert||e.externalIdField!==void 0,{message:"externalIdField is required when upsert is true",path:["externalIdField"]}),bn=o({csvHeader:a().min(1).max(500),sfFieldApiName:a().max(80),sfFieldType:a().max(40),sfFieldLength:g().int().positive().nullable()}).loose(),hr=o({orgId:i,objectApiName:l,records:c(x(a(),a().max(un))).min(1).max(st),columnMappings:c(bn).min(1).max(ct),externalIdField:l.optional(),checkpointFirst:B.optional()}),zr=o({orgId:i,objects:c(l).min(1).max(y),wheres:x(l,J).optional(),slices:r().optional()}).refine(e=>Object.keys(e.wheres??{}).every(t=>e.objects.some(n=>n.toLowerCase()===t.toLowerCase())),{message:"A filter names an object the backup reads: give it in objects",path:["wheres"]}),Sr=o({orgId:i}),xr=o({orgId:i,templateId:a().min(1).max(200).optional()}),Ir=o({orgId:i,operationId:a().min(1).max(200)}),kr=o({orgId:i,operationIds:c(a().min(1).max(200)).min(1).max(1e3).optional()}),W={acceptAutomation:r().optional(),acceptEmails:r().optional(),muteAutomation:r().optional()},X={fromPage:v(!0).optional()},jr=o({orgId:i,operationId:m,rewriteAll:r().optional(),includeChanged:r().optional(),slices:c(g().int().positive()).min(1).max(lt*y).optional(),...W,...X}),Pr=o({orgId:i,act:w(["masking","restore","cleanup"]),objects:c(o({objectApiName:l,records:g().int().min(0)})).max(y),erasure:r().optional(),...W,...X}),He={objects:c(l).min(1).max(y).optional(),where:J.optional()},Ze=e=>e.where===void 0||e.where.trim()===""||e.objects?.length===1,Xe={message:"A WHERE clause filters the rows of one object: name exactly one in objects",path:["where"]},Or=o({orgId:i,templateId:m,...He,resumeFrom:m.optional(),snapshot:r().optional(),slices:r().optional(),maxRequests:g().int().positive().max(1e9).optional(),abandon:r().optional(),...W,...X}).refine(Ze,Xe).refine(e=>!(e.snapshot===!0&&e.resumeFrom!==void 0&&e.slices!==!0),{message:"A resume takes no snapshot: the run it resumes has written over some of its rows",path:["snapshot"]}).refine(e=>!(e.slices===!0&&e.snapshot===!1),{message:"A run in slices backs each slice up before it masks it: it cannot keep no snapshot",path:["slices"]}).refine(e=>e.maxRequests===void 0||e.slices===!0,{message:"A bound on requests stops a run in slices between two of them: give slices too",path:["maxRequests"]}).refine(e=>e.abandon!==!0||e.resumeFrom===void 0&&e.snapshot!==!0&&e.maxRequests===void 0,{message:"Giving up a set of slices masks nothing: it takes no resume, snapshot or bound",path:["abandon"]}),Rr=o({orgId:i,templateId:m,...He,slices:r().optional()}).refine(Ze,Xe),wr=o({orgId:i,templateId:m,...He}).refine(Ze,Xe),vr=o({name:a().trim().min(1).max(jt),rules:c(Ot).min(1).max(Pt).refine(e=>new Set(e.map(t=>t.fieldPattern.toLowerCase())).size===e.length,"A field has two rules")}),Ar=o({templateId:m}),Er=o({orgId:i,objectNames:c(l).min(1).max(y)}),Cr=o({orgId:i,objects:c(o({objectApiName:l,duplicateKey:l.optional()})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per scan"}),staleDays:g().int().min(1).max(3650)}),po=c(l).min(1).max(10).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),Tr=o({orgId:i,objects:po}),_r=o({orgId:i,objects:po,requestId:Oe().optional(),email:a().trim().refine(Ct,"Not an email address").optional(),name:a().refine(Tt,"Not a name").optional(),phone:a().refine(Et,"Not a phone number").optional()}).refine(e=>e.email!==void 0||e.name!==void 0||e.phone!==void 0,{message:"A search needs an email address, a name or a phone number"}),fn=o({orgId:i,requestId:Oe()}),ze=a().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id"),Nr=o({runId:m,recordId:ze}).strict(),Dr=fn.extend({mode:w(["anonymize","delete"]),records:c(o({objectApiName:l,ids:c(ze).min(1).max(200)})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),dryRun:r(),...W}),yn=Re("kind",[o({kind:v("stale"),days:g().int().min(1).max(3650)}),o({kind:v("orphans"),fieldApiName:l}),o({kind:v("duplicates"),keyField:l})]),mo=o({orgId:i,objectApiName:l,recommendation:yn}),Fr=mo.extend({after:o({skip:g().int().nonnegative().max(1e8),id:ze.optional(),modified:a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/).optional()}).strict().optional()}),Mr=mo.extend({dryRun:r(),...W,...X}),We=2e3,uo={mode:w(["objects","org"]),objects:c(l).min(1).max(We).optional(),excluded:c(l).max(We).optional(),customSettings:r().optional(),files:r().optional(),managedPackages:r().optional(),unrestorable:r().optional()},hn=o(uo).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Ur=o({orgId:i,...uo,objects:c(l).max(We).optional()}).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Lr=o({orgId:i,request:hn,deleteMode:w(["recycle","hard"]),checkpointFirst:r().optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),...W,...X}),Br=o({orgId:i,previewId:m.optional(),resumeRunId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/).optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),checkpointFirst:r().optional(),...W,...X}).refine(e=>e.previewId===void 0!=(e.resumeRunId===void 0),{message:"An emptying acts on a preview, or takes up a run: one of them"}),$r=o({operationId:m}),qr=o({orgId:i,runId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/),...W,...X}),Gr=o({orgId:i}),Wr=o({orgId:i}).strict(),Kr=o({alertId:m}),go=o({sourceOrgId:i,targetOrgId:i}),Hr=go.extend({types:c(a().min(1).max(80)).min(1).max(50),includeManaged:r().optional()}),zn=o({componentType:w(At),fullName:a().min(1).max(400).regex(/^[^\u0000-\u001f\u007f]+$/,"A component name holds no control character")}),Zr=go.extend({components:c(zn).min(1).max(500).refine(e=>new Set(e.map(t=>`${t.componentType}:${t.fullName}`)).size===e.length,{message:"Each component may be named once per deployment"}),testLevel:w(wt),runTests:c(a().max(255).regex(vt,"Not an Apex class name")).max(100).optional()}).refine(e=>e.sourceOrgId!==e.targetOrgId,{message:"The source and the target are the same org",path:["targetOrgId"]}).refine(e=>e.testLevel!=="RunSpecifiedTests"||(e.runTests?.length??0)>0,{message:"RunSpecifiedTests names at least one test class",path:["runTests"]}),Xr=o({validationId:a().regex(/^0Af[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a deployment id"),targetOrgId:i}).strict(),Sn=a().regex(/^\d+\.\d+\.\d+$/,"Invalid semver"),ye=a().regex(/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,"Expected an Object.field key").max(170),xn=o({name:a().min(1).max(80),label:a().min(1).max(200),filterField:l,valuesSoql:a().min(1).max(4e3)}),In=o({name:a().min(1).max(80),label:a().min(1).max(200),whereFragment:J}),no=de([o({action:v("clear")}),o({action:v("replace"),value:a().max(255)})]),bo=o({rootObject:l,axes:c(xn).max(20),edgeCases:c(In).max(50),budgetMaxRecords:g().int().positive().max(1e5).optional(),candidatesPerCombination:g().int().positive().max(20).optional(),expectedObjects:c(l).max(100).optional(),maxNodes:g().int().min(10).max(500).optional(),excludedObjects:c(l).max(200).optional(),excludedFields:x(l,c(l).max(500)).optional(),sasDir:a().min(1).max(500).optional(),datasetDir:a().min(1).max(500).optional(),rulesFilePath:a().min(1).max(500).optional(),datasetVersion:Sn.optional(),protectedOrgIds:c(i).max(50).optional(),identityKeys:x(l,c(l).min(1).max(10)).optional(),undeletableObjects:x(l,l).optional(),requiredLookupPlaceholders:x(ye,o({name:a().min(1).max(200),recordTypeDeveloperName:a().min(1).max(97).optional(),targetObjectApiName:l.optional()})).optional(),requiredFieldDefaults:x(ye,D()).optional(),picklistRules:x(ye,no).optional(),defaultPicklistRule:no.optional(),duplicateErrorPatterns:c(a().min(1).max(200)).max(50).optional(),mockDetection:o({metadataTypeApiName:l,isMockedFieldApiName:l}).optional(),mandatoryLookups:x(l,c(l).min(1).max(50)).optional(),presenceKeys:x(l,l).optional()}),Yr=o({config:bo}),Vr=o({sourceOrgId:i}),Jr=o({fields:c(ye).min(1).max(2e3)}),Qr=o({sourceOrgId:i,author:a().min(1).max(120).optional()}),ce=o({organizationId:kt,checkpointId:F}).strict(),kn=bo.pick({requiredFieldDefaults:!0,requiredLookupPlaceholders:!0,picklistRules:!0,defaultPicklistRule:!0,identityKeys:!0,undeletableObjects:!0,duplicateErrorPatterns:!0,mockDetection:!0,protectedOrgIds:!0}).strict(),fo=ce.extend({choices:Ne,config:kn.optional()}).strict(),jn=fo.extend({choices:Ne.optional()}).strict(),ti=o({targetOrgId:i,replay:fo.optional(),pilot:r().optional(),reload:r().optional(),writeEncrypted:r().optional(),maxRecords:g().int().positive().max(1e6).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional(),sweep:r().optional(),...he,includeChanged:r().optional(),acceptEmails:r().optional(),acceptAutomation:r().optional(),goneFirst:c(ze).max(1e6).optional()}),Pn=o({targetOrgId:i}),oi=Pn.extend({replay:jn.optional()}),ni=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),sweep:r().optional(),...he,muteAutomation:r().optional(),replay:ce.optional()}),ai=o({targetOrgId:i,loadedAt:a().min(1).max(64),reload:r().optional(),replay:ce.optional()}),ri=o({targetOrgId:i,loadedAt:a().min(1).max(64),sweptObjects:so.optional(),reload:r().optional(),replay:ce.optional()}),ii=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),replay:ce.optional()}),yo=1e3,ho=3650,On=200,Z=c(l).min(1).max(yo).refine(e=>new Set(e).size===e.length,"An object is named twice");function zo(e){return e.mode==="picked"?e.objects!==void 0:e.objects===void 0}var So=de([v("all"),c(l.refine(e=>e.toLowerCase().endsWith("__c"),"A custom setting's API name ends in __c")).min(1).max(yo).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,"A custom setting is named twice")]),xo={path:["objects"],message:'Name the objects with "picked", and none with "everything"'},si=o({orgId:i.optional()}).optional(),Rn=1e6,Io=g().int().min(1).max(Rn),ci=o({orgId:i,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional()}).refine(zo,xo),li=o({orgId:i,name:Te,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional(),keepDays:g().int().min(0).max(ho),ignoredFields:Ce.optional()}).refine(zo,xo),di=o({checkpointId:F,objects:Z.optional(),muteAutomation:r().optional(),acceptOutside:r().optional()}),pi=o({checkpointId:F,previewId:Ee,objects:Z.optional(),acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),acceptNoUndo:r(),acceptRecreate:r(),acceptOutside:r(),acceptUnseen:r(),fromPage:v(!0).optional()}),mi=o({checkpointId:F,previewId:Ee,objects:Z,acceptOutside:r()}),ui=o({checkpointId:F}),wn=200,gi=o({token:m,orgId:i,key:a().min(1).max(wn),keepDays:g().int().min(0).max(ho)}),bi=o({checkpointId:F,rewindId:It,acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),fromPage:v(!0).optional()}),fi=o({checkpointIds:c(F).min(1).max(On).refine(e=>new Set(e).size===e.length,"A checkpoint is named twice")}),yi=o({checkpointId:F,keep:r()}),hi=o({checkpointId:F,name:Te}),zi=o({checkpointId:F,fields:Ce}),vn=500,Si=o({orgIds:c(i).min(1).max(vn).refine(e=>new Set(e).size===e.length,"An org is named twice").optional()}).strict().optional(),xi=o({sourceOrgId:i,targetOrgId:i,includeStandardObjects:r()}),Ii=o({sourceOrgId:i,objectApiNames:c(l).min(1).max(it)}),ki=o({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).max(y),includeStandardObjects:r(),maxDepth:g().int().min(1).max(10).optional(),maxObjects:g().int().min(1).max(500).optional()}),ji=o({complianceFramework:ht,objectFilters:x(a(),J).optional(),overrides:c(o({objectApiName:l,fieldApiName:l,method:de([yt,v("skip")])})).max(500).optional()}),Pi=o({grappeThreshold:g().int().nonnegative(),keepContactPoints:r().optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Oi=o({mode:o({share:v(!0).optional(),caps:x(l,g().int().min(1).max(ne)).refine(e=>Object.keys(e).length<=y,"Too many caps").optional(),all:g().int().min(1).max(ne).optional(),withinMB:g().positive().max(1e6).optional()}).strict().refine(e=>e.share===!0||e.caps!==void 0||e.all!==void 0,"Fit by share, by caps, or both"),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ri=o({objectApiName:l}),wi=o({orgId:i.optional(),sourceOrgId:i.optional(),alreadySelected:c(l).max(y).optional()}).loose(),vi=o({orgId:i.optional(),sourceOrgId:i.optional(),objectApiName:l.optional(),alreadySelected:c(l).max(y).optional(),selectedObjects:c(l).max(y).optional(),availableObjects:c(l).max(500).optional()}).loose(),Ai=o({sourceOrgId:i,targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).optional()}).loose(),An=St.extend({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).default([])}).loose(),Ei=o({config:An.optional(),sourceOrgId:i.optional(),targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y).optional(),parentObjects:c(l).max(y).optional()}).loose(),En=a().min(1).max(5e4),Ci=o({conversationId:m,message:a().max(5e4)}),Ti=o({title:a().min(1).max(300)}),_i=o({conversationId:m}),Ni=o({apiKey:a().min(1).max(500),errorResolution:r().optional()}),Di=o({enabled:r().optional(),errorResolution:r().optional()}),Fi=o({orgId:i,objectName:l,sampleSize:g().int().positive().max(1e4).optional()}),Mi=o({orgId:i,prompt:a().trim().min(1).max(2e3).optional(),soql:a().trim().min(1).max(2e4).optional()}).refine(e=>e.prompt===void 0!=(e.soql===void 0),{message:"Send a prompt to draft from or a query to check, not both and not neither"}),Ui=o({description:En,orgIds:c(i).max(50).optional()}),Li=o({requestId:m}),fe=c(a().min(1).max(M.picklistValue)).max(M.picklistValues),ao={label:a().max(M.agentLabel).optional(),description:a().max(M.agentDescription).optional()},Bi=o({text:a().trim().min(1).max(M.text),language:ae.shape.language,casePicklists:o({Status:fe.optional(),Origin:fe.optional(),Priority:fe.optional(),Type:fe.optional()}).optional(),agent:o({topics:c(o({name:a().min(1).max(M.agentName),...ao,actions:c(o({name:a().min(1).max(M.agentName),...ao})).max(M.agentActions)})).max(M.agentTopics)}).optional(),draft:xt.optional(),maskOnly:r().optional()}),$i=o({filePath:a().min(1).max(2e3)}),qi=o({name:a().max(200),config:x(a(),D())}),Gi=o({operationId:m.optional(),executionId:m.optional(),objectName:a().min(1).max(200).optional()}).loose(),Wi=o({policyId:m}),Ki=o({policy:x(a(),D())}),Hi=o({policyId:m,orgId:i}),Zi=o({module:a().min(1).max(50).optional(),orgId:i.optional(),offset:g().int().min(0).max(we).optional(),limit:g().int().min(1).max(we).optional()}).optional(),Xi=o({operationId:m.optional()}).optional(),Cn=w(["syncMappings","forgePlans","pipelines","anonymizationTemplates"]),Yi=o({categories:c(Cn).min(1).max(50)}),Vi=o({json:a().min(1).max(5e6),overwrite:r()}),Ji=o({json:a().min(1).max(5e6)}),Qi=o({orgId:a().max(128),authMethod:a().min(1).max(50),alias:a().max(100).optional(),loginUrl:a().max(500).optional(),username:a().max(300).optional(),password:a().max(500).optional(),securityToken:a().max(100).optional(),clientId:a().max(256).optional(),jwtKeyFile:a().max(4096).optional()}).loose(),ko=a().trim().max(100).regex(/^[\w.-]*$/,"an alias is letters, digits, dots, dashes and underscores").optional(),Tn=a().trim().min(1,"the username is required").max(80).regex(/^[\w.@+-]+$/,"a username is written like an email address"),jo=a().trim().min(1,"the consumer key is required").max(256).regex(/^[A-Za-z0-9._-]+={0,2}$/,"a consumer key is letters, digits, dots, dashes and underscores"),_n=a().trim().min(1,"the private key file is required").max(4096).regex(/^[^\u0000-\u001f\u007f]+$/,"the private key file path holds a control character").refine(e=>tn(e),"give the private key file as an absolute path"),es=o({alias:ko,loginUrl:a().max(500).optional(),username:Tn,clientId:jo,jwtKeyFile:_n}).loose(),ts=o({alias:ko,loginUrl:a().max(500).optional(),clientId:jo}).loose(),os=o({requestId:m}),ns=o({orgId:i}),as=o({orgId:i}),rs=o({orgId:i}).strict(),is=o({orgId:i,alias:a().trim().min(1).max(100),color:a().regex(/^#[0-9A-Fa-f]{6}$/),tags:c(a().trim().min(1).max(50)).max(20),staging:r().optional()}),ss=o({key:a().min(1).max(200),value:D()}),cs=o({enabled:r()}),ls=o({lng:w(["en","fr","de","es","ja","pt-BR"])}),ds=o({targetOrgId:i,sourceOrgId:i.optional()}),ps=o({moduleId:a().min(1).max(64),route:a().min(1).max(64),overlay:r()}),ms=o({moduleId:a().min(1).max(64)}),Nn=80,Dn=ot(e=>Lt(e)||Bt(e)||typeof e=="string"&&e.trim()!==""&&e.length<=Nn,{message:"Not a pipeline step type"}),Fn=o({pipeline:o({name:a().min(1).max(200),steps:c(o({type:Dn,config:x(a(),D()).default({})}).loose()).max(200),variables:c(x(a(),D())).max(200).default([]),triggers:c(x(a(),D())).max(50).default([])}).loose(),variables:x(a(),a().max(2e3)).optional(),dryRun:r().optional()}),Mn=tt({since:at.datetime({offset:!0}),runner:w(["cron","taskScheduler","githubActions"]),file:a().min(1).max(255).refine(e=>!/[\\/]/.test(e),"The file's name, without its folder"),digest:a().regex(/^sha256:[0-9a-f]{64}$/,"Not a digest: sha256: and 64 hex digits")}),us=Fn.shape.pipeline.extend({id:a().min(1).max(200),runsOutside:Mn.optional()}),gs=o({pipelineId:m}),bs=o({id:a().max(200),config:x(a(),D())}),fs=o({id:m}),ys=o({operationId:m,stepId:m,decision:w(["approved","rejected"])}),Un=255,Po={pipelineId:m,stepId:m},hs=o({pipelineId:m}),zs=o({...Po,typed:a().min(1).max(Un)}),Ss=o(Po),xs=o({category:a().max(100).optional(),query:a().max(500).optional()}).loose().optional(),Is=o({templateId:m});function Ln(e){return e.issues.slice(0,3).map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("; ")}function Bn(e){let t=e.issues.map(n=>n.code==="custom"?n.params?.unreadablePatterns:void 0);return t.every(n=>n!==void 0)?t.flat():void 0}function ks(e,t,n,s){let d=e.safeParse(t.payload);if(!d.success){let p=Ln(d.error),u=Bn(d.error);return eo(s,t.type,n,t,new Error(`Invalid payload \u2014 ${p}`),u?{code:Dt,extraPayload:{rules:u}}:{code:"INVALID_PAYLOAD"}),null}return d.data}var $n=5;function Se(e){return e.slice(0,15)}function qn(e){let t=e.errors?.[0];if(t===void 0)return"The org gave no reason.";if(typeof t=="string")return t;let n=t.statusCode??"",s=t.message??"";return n&&s?`${n}: ${s}`:n||s||"The org gave no reason."}function Oo(e){let t=new Set;for(let n of e){let s=n.Id;typeof s=="string"&&t.add(Se(s))}return t}async function Ro(e){let t=[],n=[],s={},d=!1,p=!1,u=e.stampsFor,f=ie(e.org),k=e.org.serverTime?.bind(e.org),E=u&&k?Date.now()+await se({serverTime:k})-re:Number.NaN;for(let{objectApiName:O,ids:A}of e.plan){let I={objectApiName:O,planned:A.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]};t.push(I);let z=_=>{I.reasons.length<$n&&!I.reasons.includes(_)&&I.reasons.push(_)},R=pe(O);for(let _=0;_<A.length;_+=me){let C=A.slice(_,_+me);if(p||e.signal?.aborted){p=!0,I.notReached=(I.notReached??0)+C.length,n.push(...C);continue}let[ee]=ue(C,me),K,te;try{K=Oo((await e.org.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${ee}) AND IsDeleted = true`)).records),te=Oo((await e.org.query(`SELECT Id FROM ${R} WHERE Id IN (${ee})`)).records)}catch(j){I.refused+=C.length,z(`The recycle bin could not be read: ${V(j)}`),n.push(...C);continue}let h=C.filter(j=>K.has(Se(j)));for(let j of C)K.has(Se(j))||(te.has(Se(j))?I.alreadyBack++:I.goneForGood++);if(h.length===0)continue;let U;try{d=!0;let j=await e.undelete(h),T=Array.isArray(j)?j:[j];U=h.map((H,oe)=>T[oe]??{success:!1})}catch(j){let T=V(j);U=h.map(()=>({success:!1,errors:[T]}))}let Y=[];U.forEach((j,T)=>{if(j.success===!0){I.undeleted++,u?.(h[T])&&Y.push(h[T]);return}I.refused++,z(qn(j)),n.push(h[T])}),Y.length>0&&Number.isFinite(E)&&Object.assign(s,await be(e.org,R,Y,E,f))}}return{objects:t,left:n,wrote:d,cancelled:p,stamps:s}}function wo(e){return e.refused+e.goneForGood+(e.notReached??0)}async function Gn(e,t,n,s){let d=new Map(Object.entries(s).map(([u,f])=>[u.slice(0,15),Date.parse(f)])),p=new Set;for(let{objectApiName:u,ids:f}of t){let k=pe(u);for(let E of ue(f)){let O;try{O=(await e.query(`SELECT Id, LastModifiedDate FROM ${k} WHERE Id IN (${E})`)).records}catch{continue}for(let A of O){if(typeof A.Id!="string")continue;let I=A.Id.slice(0,15),z=Date.parse(String(A.LastModifiedDate??""));(z<=n||z<=(d.get(I)??Number.NaN))&&p.add(I)}}}return p}function vo(e){let t=Date.parse(e.startedAt),n=Date.parse(e.lastWrittenAt??e.end?.at??"");return Number.isFinite(n)?{runRecordedAt:new Date(n),...Number.isFinite(t)?{runDurationMs:Math.max(0,n-t)}:{}}:{}}function Wn(e){return e.filter(t=>t.deleted+t.alreadyGone>0).map(t=>t.objectApiName)}async function Ms(e){let{run:t,includeChanged:n}=e,s=e.again===!0,d=ge(t,s),p=d.reduce((b,S)=>b+S.ids.length,0),u=Be(t),f=u.reduce((b,S)=>b+S.ids.length,0),k=Yt(t),E=k.reduce((b,S)=>b+S.ids.length,0),O=[],A=e.backups,I=e.undelete;k.length>0&&!I&&O.push(`The ${E} record(s) the run deleted could not be brought back from the recycle bin here: the next removal offers them again.`),u.length>0&&!A&&O.push(`The values from before the run of ${f} record(s) it wrote over could not be read here: they were not put back, and the next removal offers them again.`);let z,R,_={},C=(e.earlierRuns??[]).map(b=>({runId:b.runId,keys:new Set([...ge(b),...Be(b)].flatMap(({ids:S})=>S.map(L=>L.slice(0,15))))})),ee=b=>C.some(({keys:S})=>S.has(b.slice(0,15))),K=e.sweep,te=u.length>0&&A||k.length>0&&I||K?async b=>{if(k.length>0&&I){let N=u.length>0&&A?await Gn(e.org,u,await Vt(e.org,xe(t)),t.removal?.removalStamps??{}):void 0,q=N?Date.now()+await se(e.org)-re:0;if(R=await Ro({org:e.org,plan:k,undelete:I,...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}}),N&&R.wrote){let P=ie(e.org);for(let{objectApiName:Pe,ids:Mo}of u){let Uo=Mo.filter(Lo=>N.has(Lo.slice(0,15)));Object.assign(_,await be(e.org,Pe,Uo,q,P))}}if(R.cancelled||e.signal?.aborted)return R.wrote}if(u.length>0&&A){let N={...t.removal?.removalStamps,..._};z=await Jt({org:e.org,plan:u,backups:A,...xe(t)!==void 0?{lastWriteAt:xe(t)}:{},includeChanged:n,...Object.keys(N).length>0?{stamps:N}:{},...t.unkept?{unkept:t.unkept}:{},...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}})}let S=(R?.wrote??!1)||(z?.wrote??!1);if(z?.cancelled||e.signal?.aborted)return S;let L=K?await K(b):!1;return S||L}:void 0,h=await Ue(e.org,d,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:n,...te?{sweep:te}:{},...e.afterRemoval?{afterRemoval:e.afterRemoval}:{},...e.automationMade?{automationMade:e.automationMade}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},...e.beforeFirstWrite?{beforeFirstWrite:e.beforeFirstWrite}:{},signal:e.signal,onProgress:e.onProgress}),U=new Date().toISOString();if(h.stoppedForUndeletable)return{result:{runId:t.runId,status:"cancelled",includeChanged:n,objects:[],finishedAt:U},planned:p,plannedBack:f,plannedUndelete:E,notes:[],stoppedForUndeletable:!0};let Y=s?void 0:t.removal?.undo?.removedAt,j={runId:t.runId,status:Zn(Xn(Zt(h.objects,h.cancelled),h.objects,z),h.objects,z,R),includeChanged:n,objects:h.objects,finishedAt:U,...Y?{leftBy:Y}:{},...z&&z.objects.length>0?{restored:z.objects}:{},...R&&R.objects.length>0?{undeleted:R.objects}:{}},T=Xt(j,p,t.removal?.undo,s),H=new Set(h.gone),oe=H.size>0||s&&T?d.flatMap(({ids:b})=>b.filter(S=>!H.has(S))):void 0,Je={..._,...h.stamps},Qe=Object.keys(Je).length>0,No=z?.objects.some(b=>b.restored+(b.restoredWithout??0)>0)===!0,Do=R!==void 0&&!R.cancelled;if(T||Qe||h.span||oe||z||R)try{await e.store.updateRemoval(t.runId,b=>({...b,...T?{undo:T}:{},...Qe?{removalStamps:{...b.removalStamps,...Je}}:{},...h.span?{removalSpans:[...b.removalSpans??[],h.span]}:{},...oe?{removalLeft:oe}:{},...z?{restoreLeft:z.left}:{},...No?{restoredAt:U}:{},...R?{undeleteLeft:R.left}:{},...Do?{undeletedAt:U}:{}}))}catch(b){O.push(`What this removal did could not be kept (${b instanceof Error?b.message:String(b)}): the next removal of the run may set out to take records already gone.`)}let Fo=Object.keys(z?.stamps??{}).length>0?await Kn(e.org,t,e.earlierRuns??[]):new Map,ke=[];for(let{runId:b,keys:S}of C){let L=Fo.get(b),N=Object.fromEntries(Object.entries({...R?.stamps,...z?.stamps}).filter(([P])=>S.has(P.slice(0,15))&&!L?.has(P.slice(0,15)))),q=Object.keys(N).length;if(q!==0)try{await e.store.updateRemoval(b,P=>({...P,removalStamps:{...P.removalStamps,...N},...h.span?{removalSpans:[...P.removalSpans??[],h.span]}:{}})),ke.push({runId:b,records:q})}catch(P){O.push(`What this removal gave back of ${q} record(s) the run ${b} wrote too could not be kept on it (${P instanceof Error?P.message:String(P)}): its removal reads them as changed since it.`)}}let le=e.configs;if(le&&H.size>0&&le.isSaved(t.configId)){let b={sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)};try{let S=d.filter(P=>Le.includes(P.objectApiName)).flatMap(({ids:P})=>P.filter(Pe=>H.has(Pe))),L=le.forgetFiles(t.configId,b,S),N=Wn(h.objects).filter(P=>!Le.includes(P)),q=le.markRemoved(t.configId,b,[...new Set([...N,...L.map(P=>P.objectApiName)])],U);j={...j,...q.length>0?{readWhole:q}:{},...L.length>0?{filesForgotten:L.length}:{}}}catch(S){O.push(`The configuration could not be told what this removal took (${S instanceof Error?S.message:String(S)}): run it full next time.`)}}let je;if(e.links&&H.size>0)try{je=await e.links.forget(t.configId,{sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)},[...H])}catch(b){O.push(`Which records of the target this removal took could not be forgotten (${b instanceof Error?b.message:String(b)}): a later run of the configuration may point a lookup at one of them.`)}return{result:j,planned:p,plannedBack:f,plannedUndelete:E,notes:O,...je?{linksForgotten:je}:{},...ke.length>0?{earlierStamped:ke}:{},...h.duplicateSets?{duplicateSets:h.duplicateSets}:{}}}async function Us(e){let{run:t}=e,n=ge(t);return{outcome:await Ue(e.org,n,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:e.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{},previewOnly:!0,...e.signal?{signal:e.signal}:{}}),planned:n.reduce((d,p)=>d+p.ids.length,0)}}async function Kn(e,t,n){let s=new Map,d=Object.entries(t.heldBefore??{});if(d.length===0||n.length===0)return s;let p=await ie(e)(),u=await se(e);for(let f of n){let k=Date.parse(xe(f)??""),E=Number.isFinite(k)?k+u+re:Number.NEGATIVE_INFINITY,O=new Set;for(let[A,{at:I,by:z}]of d)Date.parse(I)>E&&(p!==void 0&&z!==void 0&&z.slice(0,15)===p||O.add(A));O.size>0&&s.set(f.runId,O)}return s}function xe(e){return e.lastWriteAt??e.lastWrittenAt??e.end?.at}function Hn(e){return e.keptChanged+e.refused+e.notKept+(e.notReached??0)+(e.restoredWithout??0)}function Zn(e,t,n,s){if(!s||e==="cancelled")return e;if(s.cancelled)return"cancelled";let d=s.objects.some(u=>wo(u)>0);if(e==="success"&&!d)return"success";let p=t.some(u=>u.deleted>0)||(n?.objects??[]).some(u=>u.restored>0)||s.objects.some(u=>u.undeleted>0);return e==="partial"||p?"partial":"failure"}function Xn(e,t,n){if(!n||e==="cancelled")return e;if(n.cancelled)return"cancelled";let s=n.objects.some(p=>Hn(p)>0);return e==="success"&&!s?"success":t.some(p=>p.deleted>0)||n.objects.some(p=>p.restored+(p.restoredWithout??0)>0)?"partial":"failure"}function Bs(e){let t=e?.getSandforgeSetting?.("backup.maxAgeDays",30);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function $s(e,t,n){let s=[],d=0,p=Number.POSITIVE_INFINITY;for(let u of e){let f=t(u.backup);if(!f){d+=u.ids.length;continue}s.push(u);let k=Date.parse(f.timestamp??"");n>0&&Number.isFinite(k)&&(p=Math.min(p,k+n*864e5))}return{kept:s,notKept:d,...Number.isFinite(p)?{keptUntil:new Date(p).toISOString()}:{}}}var Ye="backupSet:",Yn="backups",Ve=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/),$=g().int().nonnegative(),Vn=o({index:g().int().positive(),afterId:a().regex(Ve).optional(),lastId:a().regex(Ve).optional(),rows:$,snapshotId:a().min(1).max(240),takenAt:Q.optional(),readSince:Q.optional(),state:w(["pending","snapshotted","masking","masked","restored"]),masked:$,refused:$,deletedSince:$,nothingToMask:$,unanswered:$.optional(),late:v(!0).optional(),sizeUsed:g().int().positive(),lateLeft:$.optional(),lateOf:g().int().positive().optional(),lateAfterId:a().regex(Ve).optional(),restoredAt:Q.optional()}),Jn=o({objectApiName:a().min(1).max(255),where:a().max(2e3).optional(),select:a().max(1e5).optional(),done:r(),tailLeft:$.optional(),slices:c(Vn)}),Ao=o({setId:a().min(1).max(200),kind:w(["masking","backup"]),orgId:a().min(1).max(200),organizationId:a().max(18).optional(),templateId:a().min(1).max(200).optional(),fingerprint:a().regex(/^[0-9a-f]{64}$/).optional(),size:g().int().positive(),state:w(["open","done","abandoned"]),startedAt:Q,serverStartedAt:Q.optional(),lastActivityAt:Q,requestsSpent:$,keyCheck:a().regex(/^[0-9a-f]{16}$/).optional(),objects:c(Jn)});function Gs(e,t){return`${e}-s${String(t).padStart(4,"0")}`}function Ie(e){return e.objects.flatMap(t=>t.slices).sort((t,n)=>t.index-n.index)}function Ws(e){return Ie(e).reduce((t,n)=>Math.max(t,n.index),0)+1}function Co(e){return e.state==="masked"||e.state==="snapshotted"||e.state==="restored"}function Qn(e){return Ie(e).reduce((t,n)=>t+n.rows,0)}function To(e,t,n){return{index:t.index,objectApiName:e,snapshotId:t.snapshotId,rows:t.rows,masked:t.masked,refused:t.refused,deletedSince:t.deletedSince,nothingToMask:t.nothingToMask,state:t.state,...t.late?{late:!0}:{},...t.sizeUsed<n?{sizeUsed:t.sizeUsed}:{},...t.restoredAt?{restoredAt:t.restoredAt}:{}}}function ea(e){return e.objects.reduce((t,n)=>t+(n.tailLeft??0)+n.slices.reduce((s,d)=>s+(d.lateLeft??0),0),0)}function Ks(e,t){return{setId:e.setId,size:e.size,state:e.state,objects:e.objects.map(n=>({objectApiName:n.objectApiName,slices:n.slices.map(s=>To(n.objectApiName,s,e.size))})),lateRecords:ea(e),requestsSpent:t.requestsSpent,...t.stoppedOnBudget?{stoppedOnBudget:!0}:{},slicesLeft:e.objects.some(n=>!n.done||n.slices.some(s=>!Co(s)))}}function ta(e){return e.kind==="backup"&&e.state==="open"?"partial":e.state}function Hs(e){let t=Object.fromEntries(e.objects.flatMap(n=>n.where?[[n.objectApiName,n.where]]:[]));return{setId:e.setId,orgId:e.orgId,kind:e.kind,state:ta(e),startedAt:e.startedAt,lastActivityAt:e.lastActivityAt,size:e.size,totalRecords:Qn(e),...e.templateId?{templateId:e.templateId}:{},slices:e.objects.flatMap(n=>n.slices.map(s=>To(n.objectApiName,s,e.size))),...Object.keys(t).length>0?{wheres:t}:{}}}function Zs(e){let t=Ie(e);return{setId:e.setId,savedAt:e.lastActivityAt,done:t.filter(Co).length,total:t.length,state:e.state,size:e.size}}var Eo=class{constructor(t){this.configStore=t}configStore;get(t){let n=Ao.safeParse(this.configStore.get(this.key(t)));return n.success&&n.data.setId===t?n.data:void 0}save(t){this.configStore.set(this.key(t.setId),Ao.parse(t),Yn)}delete(t){this.configStore.delete(this.key(t))}list(t){return this.configStore.getKeysByPrefix(Ye).map(n=>this.get(n.slice(Ye.length))).filter(n=>n!==void 0).filter(n=>t===void 0||n.orgId===t)}openFor(t,n){return this.list(t).find(s=>s.kind==="masking"&&s.state==="open"&&s.templateId===n)}ofSnapshot(t){return this.list().find(n=>Ie(n).some(s=>s.snapshotId===t))}key(t){return`${Ye}${t}`}};async function Ys(e,t){let n=e.check(t);if(!n.allowed)return{check:n,decision:"refused"};if(!await e.confirmIfNeeded(n,t.orgTier))return{check:n,decision:"declined"};let d=n.requiresConfirmation&&e.canAskForConfirmation===!0;return{check:n,decision:d?"confirmed":"allowed"}}var _o={allowed:0,confirmed:1,declined:2,refused:3};function Vs(e,t){return e===void 0||_o[t]>_o[e]?t:e}export{sa as a,Qt as b,ca as c,qe as d,la as e,da as f,Bo as g,pa as h,ma as i,ua as j,ga as k,ba as l,fa as m,ya as n,eo as o,ha as p,za as q,Sa as r,xa as s,i as t,l as u,so as v,B as w,nn as x,an as y,Ke as z,Ea as A,Ca as B,Ta as C,_a as D,Na as E,Da as F,Fa as G,Ma as H,Ua as I,La as J,Ba as K,$a as L,qa as M,Ga as N,Wa as O,Ka as P,Ha as Q,Za as R,Xa as S,Ya as T,Va as U,Ja as V,Qa as W,er as X,tr as Y,or as Z,mn as _,nr as $,ar as aa,rr as ba,ir as ca,sr as da,cr as ea,lr as fa,dr as ga,pr as ha,mr as ia,ur as ja,gr as ka,br as la,fr as ma,yr as na,hr as oa,zr as pa,Sr as qa,xr as ra,Ir as sa,kr as ta,jr as ua,Pr as va,Or as wa,Rr as xa,wr as ya,vr as za,Ar as Aa,Er as Ba,Cr as Ca,Tr as Da,_r as Ea,fn as Fa,Nr as Ga,Dr as Ha,Fr as Ia,Mr as Ja,Ur as Ka,Lr as La,Br as Ma,$r as Na,qr as Oa,Gr as Pa,Wr as Qa,Kr as Ra,go as Sa,Hr as Ta,Zr as Ua,Xr as Va,bo as Wa,Yr as Xa,Vr as Ya,Jr as Za,Qr as _a,ti as $a,oi as ab,ni as bb,ai as cb,ri as db,ii as eb,si as fb,ci as gb,li as hb,di as ib,pi as jb,mi as kb,ui as lb,gi as mb,bi as nb,fi as ob,yi as pb,hi as qb,zi as rb,Si as sb,xi as tb,Ii as ub,ki as vb,ji as wb,Pi as xb,Oi as yb,Ri as zb,wi as Ab,vi as Bb,Ai as Cb,Ei as Db,Ci as Eb,Ti as Fb,_i as Gb,Ni as Hb,Di as Ib,Fi as Jb,Mi as Kb,Ui as Lb,Li as Mb,Bi as Nb,$i as Ob,qi as Pb,Gi as Qb,Wi as Rb,Ki as Sb,Hi as Tb,Zi as Ub,Xi as Vb,Yi as Wb,Vi as Xb,Ji as Yb,Qi as Zb,es as _b,ts as $b,os as ac,ns as bc,as as cc,rs as dc,is as ec,ss as fc,cs as gc,ls as hc,ds as ic,Fn as jc,Mn as kc,us as lc,gs as mc,bs as nc,fs as oc,ys as pc,hs as qc,zs as rc,Ss as sc,xs as tc,Is as uc,Ln as vc,ks as wc,Ro as xc,Ms as yc,Us as zc,xe as Ac,Zn as Bc,Xn as Cc,Ys as Dc,Vs as Ec,Bs as Fc,$s as Gc,Gs as Hc,Ie as Ic,Ws as Jc,Co as Kc,ea as Lc,Ks as Mc,ta as Nc,Hs as Oc,Zs as Pc,Eo as Qc};
|
package/lib/chunk-IVZJSDJD.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{j as Z,l as T}from"./chunk-VZT4E2OJ.mjs";import{a as Y,b as M,d as K,h as J,j as Q}from"./chunk-HKUWHVI7.mjs";import{d as G}from"./chunk-VPDEJGPS.mjs";import{b as V,c as X,g as z}from"./chunk-JQZTMFO7.mjs";import{$b as te,Ec as re,Pb as ee,tc as se,uc as N}from"./chunk-JFNLKHY6.mjs";import{b as U,c as B}from"./chunk-SU65Z2BA.mjs";import{B as H}from"./chunk-XZISAZA6.mjs";import{b as $}from"./chunk-CA5NAXSU.mjs";import{Dd as C,Id as S,Ld as F,Md as q,zd as I}from"./chunk-ZQO5PDX5.mjs";var _e=5e3,x=2e3,le=1e3,me={masking:{during:"during the masking",records:"records it masked"},restore:{during:"during the restore",records:"records it put back"},erasure:{during:"during the erasure",records:"records it overwrote"}};function ne(e,t){let r=new Set(t.map(s=>s.toLowerCase()));return(e?.objects??[]).filter(s=>r.has(s.objectApiName.toLowerCase())).filter(s=>(s.duplicateRules??[]).length>0).map(s=>({objectApiName:s.objectApiName,rules:(s.duplicateRules??[]).map(n=>n.name)}))}function ae(e){return typeof e=="string"?e.slice(0,15):""}async function pe(e,t){let{rules:r}=t,s=0,n=a=>(s++,e.query(a));try{let a=H(new Date(Date.parse(t.since)-le).toISOString()),i=new Set([...t.masked].map(ae)),c=await n(`SELECT Id, DuplicateRecordSetId, RecordId FROM DuplicateRecordItem WHERE CreatedDate >= ${a} LIMIT ${x+1}`),u=c.done===!1||c.records.length>x,d=c.records.slice(0,x),p=new Set(d.filter(o=>i.has(ae(o.RecordId))).map(o=>String(o.DuplicateRecordSetId??"")).filter(o=>o!=="")),l=d.filter(o=>p.has(String(o.DuplicateRecordSetId??""))).length,m=0;for(let o of G([...p])){let f=await n(`SELECT Id FROM DuplicateRecordSet WHERE CreatedDate >= ${a} AND Id IN (${o})`);m+=f.records.length}return{rules:r,sets:m,items:l,...u?{atLeast:!0}:{},requests:s}}catch(a){return{rules:r,sets:0,items:0,unread:$(a),requests:s}}}function Ie(e,t,r){let s=r.now??Date.now,n=r.sleep??(l=>new Promise(m=>setTimeout(m,l))),a=new Set(t.map(l=>l.objectApiName.toLowerCase())),i=l=>a.has(l.toLowerCase()),c,u=0,d=new Set,p=0;return{covers:i,beforeWrite:l=>{i(l)&&c===void 0&&(u=s())},wrote:(l,m)=>{if(!i(l))return;let o=!1;for(let h of m)typeof h!="string"||h===""||(d.add(h),o=!0);if(!o)return;p=s();let f=u;c??=e.serverTime().then(h=>{let b=Date.parse(h);return Number.isNaN(b)?{unread:`it answered "${h}"`}:{at:new Date(b-Math.max(0,s()-f)).toISOString()}},h=>({unread:$(h)}))},held:()=>d.size,read:async()=>{if(d.size===0)return;let l=c?await c:void 0;if(!l||"unread"in l)return{rules:t,sets:0,items:0,unread:l?`the org's clock: ${l.unread}`:"the org's clock was not read",requests:l?1:0};let m=Math.max(0,p+r.settleMs-s());m>0&&await n(m);let o=await pe(e,{rules:t,since:l.at,masked:d});return{...o,requests:(o.requests??0)+1,waitedMs:m}}}}function Ce(e,t){if(!e)return t;if(!t)return e;let r=[e.unread,t.unread].filter(s=>s!==void 0);return{rules:t.rules.length>=e.rules.length?t.rules:e.rules,sets:e.sets+t.sets,items:e.items+t.items,...e.atLeast||t.atLeast?{atLeast:!0}:{},...r.length>0?{unread:r.join("; ")}:{},requests:(e.requests??0)+(t.requests??0),waitedMs:(e.waitedMs??0)+(t.waitedMs??0)}}function Fe(e){return e!==void 0&&(e.sets>0||e.items>0||e.unread!==void 0)}function ge(e){return e.map(t=>`"${t}"`).join(", ")}function fe(e){return e<=0?"without waiting":e<1e3?"after waiting less than 1 s":`after waiting ${Math.round(e/1e3)} s`}function qe(e,t,r="masking"){if(!e||e.rules.length===0)return"";let s=me[r],n=e.rules.map(c=>`${c.objectApiName} (${ge(c.rules)})`).join(", ");if(e.unread!==void 0)return`What the duplicate rules of ${t} on ${n} wrote ${s.during} could not be read (${e.unread}): a duplicate record set they wrote stays.`;let a=e.requests!==void 0?` Read in ${e.requests} request(s), ${fe(e.waitedMs??0)}.`:"";if(e.sets===0&&e.items===0)return`The duplicate rules of ${t} on ${n} wrote nothing for the ${s.records}.`+a;let i=e.atLeast===!0?"at least ":"";return`The duplicate rules of ${t} on ${n} wrote ${i}${e.sets} duplicate record set(s) and ${i}${e.items} item(s) ${s.during}, for ${s.records}: kept, as they name records that stay.${a}`}var he="AUTOMATION_NOT_ACCEPTED",we="EMAILS_EXCEEDED",Oe="ORG_TEMPORARILY_UNREACHABLE";function Ae(e,t){return e==="cleanup"||e==="empty"?{delete:[...t]}:e==="restore"?{bringBack:[...t],giveBack:[...t]}:e==="emptyUndo"?{bringBack:[...t]}:{giveBack:[...t]}}function be(e,t){let r=e==="cleanup"||e==="empty"?"delete":"update";return t.filter(s=>s.records>0).map(s=>({objectApiName:s.objectApiName,write:r,records:s.records}))}var E={masking:{heading:"masking automation: what {org} runs as the masking writes over the records",the:"the masking",this:"this masking",writes:"writes over",verb:"mask",nothing:"Nothing was written.",flag:"to mask all the same"},restore:{heading:"restore automation: what {org} runs as the restore puts the backup's values back",the:"the restore",this:"this restore",writes:"puts back",verb:"restore",nothing:"Nothing was written.",flag:"to restore all the same"},cleanup:{heading:"cleanup automation: what {org} runs as the cleanup deletes the records",the:"the cleanup",this:"this cleanup",writes:"deletes",verb:"delete",nothing:"Nothing was deleted.",flag:"to delete all the same"},empty:{heading:"emptying automation: what {org} runs as the emptying deletes the records",the:"the emptying",this:"this emptying",writes:"deletes",verb:"empty",nothing:"Nothing was deleted.",flag:"to empty all the same"},emptyUndo:{heading:"undo automation: what {org} runs as the undo brings the records back",the:"the undo",this:"this undo",writes:"brings back",verb:"undo",nothing:"Nothing was written.",flag:"to undo all the same"}},$e={masking:"masking",restore:"restore",cleanup:"cleanup",empty:"empty",emptyUndo:"undo"};function Je(e){return e.erasure===!0?"erasure":e.fromPage===!0?"page":void 0}var ye={"accept-automation":"acceptAutomation","accept-emails":"acceptEmails","mute-automation":"muteAutomation"},De={"accept-emails":"the confirmation's box that lets the org send these emails","mute-automation":"the confirmation's box that mutes the target's automation"},Re={mask:"masking",restore:"restore",delete:"cleanup",erase:"erasure",empty:"emptying",undo:"undo"};function oe(e){let t=r=>De[r]??`--${r}`;return e.replace(/\bAdd --accept-automation to (mask|restore|delete|erase|empty|undo) all the same\b/g,(r,s)=>`Confirm the ${Re[s]??s} from its confirmation, which lists what fires, to ${s} all the same`).replace(/\bWith --mute-automation,/g,`With ${t("mute-automation")} ticked,`).replace(/\bAdd --(accept-emails|mute-automation)\b/g,(r,s)=>`Tick ${t(s)}`).replace(/(^|[.:;] )--(accept-emails|mute-automation)\b/g,(r,s,n)=>`${s}${W(t(n))}`).replace(/--(accept-emails|mute-automation)\b/g,(r,s)=>t(s))}function L(e,t="flags"){return t==="step"?e.replace(/--(accept-automation|accept-emails|mute-automation)\b/g,(r,s)=>`${ye[s]??s} in the step`).replace(/\bAdd (acceptAutomation|acceptEmails|muteAutomation) in the step\b/g,"Turn on $1 in the step"):t==="erasure"?oe(e.replace(/\b(this|the|This|The) (masking|cleanup)\b/g,"$1 erasure").replace(/\bto (mask|delete) all the same\b/g,"to erase all the same").replace(/\b(mask|delete) fewer records\b/g,"erase fewer records")):t==="page"?oe(e):e}var ke={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Ee={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"},ue={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function de({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}function ce(e,t){return t.step==="delete"?Ee[t.when]:t.step==="bringBack"?"as it comes back from the recycle bin":`${e==="restore"?"as its values are put back":"as it is masked"}, ${ke[t.when]}`}function W(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}function ve(e,t,r,s){let n=E[r],a=[n.heading.replace("{org}",t)];if(typeof e.unread=="string")return a.push(` what ${t} runs could not be read: ${e.unread}`),a;let i=e;for(let d of S(i,s))a.push(` ${d.objectApiName}: ${ce(r,d)}: ${de(d)}`);let c=N(i);if(a.length===1&&c.length===0){let d=new Set(Object.values(s).flat()).size;a.push(` nothing fires on the ${d} object(s) it ${n.writes} records of`)}for(let d of ne(i,s.giveBack??[]))a.push(` ${d.objectApiName}: duplicate rules ${d.rules.map(p=>`"${p}"`).join(", ")}: ${n.the} saves a record a rule only alerts on, a rule that blocks still refuses it, and what a rule that reports writes (a duplicate record set and its items) stays`);let u=I(i);u.length>0&&a.push(` bypass held: the user ${n.the} writes as holds ${u.join(", ")}, and what names it stays quiet`);for(let{part:d,reason:p}of c)a.push(` ${ue[d]??d} could not be read: ${p}`);return a}function Se(e,t,r){let s=E[r.act],n=`${s.nothing} Add --accept-automation ${s.flag}, or turn that automation off in ${t} first.`;if(typeof e.unread=="string")return`What ${t} runs as ${s.this} ${s.writes} its records could not be read (${e.unread}), so what fires is not known. ${n}`;let a=e,i=S(a,r.steps),c=N(a);if(i.length===0&&c.length===0)return;let u=[];if(i.length>0){let l=i.map(m=>`${m.objectApiName}: ${de(m)} (${ce(r.act,m)})`);u.push(`${t} runs automation as ${s.this} ${s.writes} its records: ${l.join("; ")}.`)}for(let{part:l,reason:m}of c)u.push(`${W(ue[l]??l)} of ${t} could not be read (${m}), so what fires as ${s.the} ${s.writes} its records is not known.`);let d=r.assign??[];u.push(...re(d,t,s.the));let p=[...new Set(d.flatMap(l=>l.permissionSet??[]))];return r.mayMute===!0&&p.length>0&&u.push(`With --mute-automation, ${s.the} assigns ${p.join(", ")} to the user it writes as for ${s.the} alone, under a lease, and what ${p.length===1?"it keeps":"they keep"} quiet does not fire.`),u.push(n),u.join(" ")}function k(e){let t=e.objects.map(r=>`${r.perRecord} per ${r.objectApiName}`).join(", ");return`about ${te(e.emails,e.limit)} (${t}`+(e.alertsCounted?"; its email alerts among them, as a Developer Edition counts them":"")+")"}function Me(e,t,r){let s=e.map(n=>{if(n.verdict==="unread")return` emails: ${k(n)}; what ${t} has left today could not be read (${n.unread??"not said"})`;let a=`${n.remaining??0} of ${n.max??0} left today`;return n.verdict==="exceeds"?` emails: ${k(n)}, past the ${a}`:` emails: ${k(n)}, ${a}`});return r!==void 0&&s.push(` emails not counted: what sends them was not read (${r})`),s}function Te(e,t,r,s){let n=t.filter(u=>u.verdict==="exceeds");if(n.length===0)return;let a=E[e],i=n.map(u=>`${k(u)}, ${u.remaining??0} of ${u.max??0} left today`).join("; "),c=s?.kind==="enough"?`Turn off what sends them, give the user it writes as the bypass that keeps them quiet (--mute-automation assigns ${s.sets.join(", ")} for ${a.the} alone, and what still sends then fits what is left today), or ${a.verb} fewer records.`:`Turn off what sends them, or ${a.verb} fewer records.`+(s?.kind==="muting"?" What sends them still runs under the mute.":s?.kind==="notEnough"?" --mute-automation would not keep enough of them quiet.":"");return`${W(a.this)} would make ${r} send ${i}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. ${c} ${a.nothing}`}function Qe(e,t,r){return{readAutomation:t,readLimits:()=>ee(e),readDeliverability:()=>r?Promise.resolve(V):X(e),muteOrg:async()=>Y(e),...r?{production:r}:{}}}async function Ze(e,t,r,s){let n=e?.mute?.prepared;if(!e||!n)return{};let a;try{a=await n.acquire(t)}catch(c){if(!M(c))throw c;return{refused:{code:c.code,message:L(c.message,s)}}}let i=e.emails.afterLease(a.outcome,r);return i?(await a.release(),{refused:{code:i.code,message:L(i.message,s)}}):{held:a}}var Ne={objectsRead:[],objects:[],unread:[],conditionsNotRead:0,conditionsBound:0,requests:0};async function et(e){let{act:t,target:r,accord:s}=e,n=e.objects.filter(g=>g.records>0),a=n.map(g=>g.objectApiName),i=e.writes?.steps??Ae(t,a),c=F(i),u=a.length===0?Ne:await e.org.readAutomation(a).catch(g=>{let A=U(g);return{unread:A===void 0?$(g):`the org could not be reached (${A})`}}),d=typeof u.unread=="string"?void 0:u,p=B(u),l=E[t],m=[],o;if(s.muteAutomation===!0&&p===void 0)try{o=await J(e.org.muteOrg,u,{...e.muteLeases,writes:c})}catch(g){if(!M(g))throw g;m.push({code:g.code,message:g.message})}let f=o?.automation??d,h=e.mayMute&&s.muteAutomation!==!0&&e.org.production!==!0,b=[...ve(d??u,r,t,i),...o?Q(o.muted,r).map(g=>` ${g}`):[]],j=Se(f??u,r,{act:t,steps:i,...f?{assign:se(f,q(f,i),e.assignTo)}:{},mayMute:h});j!==void 0&&s.acceptAutomation!==!0&&m.push({code:he,message:j});let D=e.writes?e.writes.written.filter(g=>g.records>0):be(t,n),y=[],R,P;if(f&&p===void 0){if(D.some(A=>C(f,A.write).some(w=>w.objectApiName===A.objectApiName))){let A=await e.org.readLimits().catch(w=>({unread:$(w)}));if(y=T(D,f,A),y.some(w=>w.verdict==="exceeds")){let w=!o&&h&&d?K(d,c):void 0;P=o?{kind:"muting"}:w&&w.plan.assign.length>0?T(D,w.automation,A).some(v=>v.verdict==="exceeds")?{kind:"notEnough"}:{kind:"enough",sets:w.plan.assign.map(v=>v.permissionSet)}:void 0}}R=Z(D,f)}b.push(...Me(y,r,R));let _=Te(t,y,r,P);_!==void 0&&m.push({code:we,message:_});let O=await z({read:u,...o?.plan?{plan:o.plan}:{},writes:c,readDeliverability:p===void 0?e.org.readDeliverability:async()=>({reading:{unread:`${r} could not be reached`},requests:0}),accepted:s.acceptEmails===!0,target:r,run:$e[t],keepsAddresses:!0,mayMute:h});return O.gate.line!==void 0&&b.push(` ${O.gate.line}`),O.gate.stop&&m.push({...O.gate.stop}),p!==void 0&&m.splice(0,m.length,{code:Oe,message:`${r} could not be reached as what it runs was read (${p}), so ${l.the} was not started. ${l.nothing} Check the network, then try again.`}),{answer:{act:t,objects:n,steps:i,...d?{automation:d}:{automationUnread:String(u.unread)},lines:b,emails:y,...R!==void 0?{emailsUncounted:R}:{},...O.gate.deliverability?{deliverability:O.gate.deliverability}:{},emailsAsk:O.gate.verdict==="asks",refusals:m.map(g=>({...g,message:L(g.message,e.voice)})),...o?{mutedAutomation:o.muted}:{},...o?.plan?{mutePlan:o.plan}:{}},...o?{mute:o}:{},emails:O}}var xe=/\bnothing (?:was )?(?:written|deleted)\b/i,ie=/\s*\bNothing was (?:written|deleted)\./g;function tt(e){let[t,...r]=e.refusals;if(!t)return;let s=!1,n=e.refusals.map(a=>s?a.message.replace(ie,"").trim():(s=xe.test(a.message),a.message)).join(" ");return{code:t.code,message:n,alsoRefused:r.map(a=>({code:a.code,message:a.message.replace(ie,"").trim()}))}}function st(e){return e.alsoRefused.length>0?{extraPayload:{alsoRefused:[...e.alsoRefused]}}:{}}export{_e as a,ne as b,Ie as c,Ce as d,Fe as e,qe as f,Je as g,Qe as h,Ze as i,et as j,tt as k,st as l};
|
package/lib/chunk-JESRFE2Z.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{e as ds,f as cs}from"./chunk-CBL42DUU.mjs";import{a as es,b as ts,c as ye,d as ns,e as ss,f as rt,g as rs,h as is,i as os,j as as}from"./chunk-MKTXJCXN.mjs";import{i as ls,l as us}from"./chunk-RCYEBY42.mjs";import{c as Yn}from"./chunk-AUS6NFLZ.mjs";import{b as Vn}from"./chunk-DBBPDSFN.mjs";import{a as jt,b as Gn,c as we,d as Lt,e as Nt,f as Jn,g as Kn,m as Hn}from"./chunk-YMDFF657.mjs";import{d as Pt,f as Ce,l as At,n as tt}from"./chunk-YT22LMF7.mjs";import{a as Xn,b as Qn}from"./chunk-ZXFL2MSN.mjs";import{Bc as bn,Cc as Rn,xc as Ze}from"./chunk-ISSP2FZ5.mjs";import{a as wn,b as mn,c as yn,e as Ye,f as kn,h as Wn,i as _n}from"./chunk-XU25YA46.mjs";import{a as It,d as In,f as On,h as Pn,j as An,k as jn,l as Xe,m as Ln,p as Nn,q as Bn}from"./chunk-VZT4E2OJ.mjs";import{A as $n,B as zn,a as hn,v as Dn,w as Mn,z as Un}from"./chunk-O2PUGRNW.mjs";import{J as vt,K as fn,N as pn,P as Ve}from"./chunk-7SDZR6SR.mjs";import{a as Rt,b as un}from"./chunk-54HYHHVL.mjs";import{l as gn}from"./chunk-3SKLBRPL.mjs";import{B as nt,E as xn,F as st,i as Me,j as Ot,l as Se,p as Ne,q as Tn,r as et,z as qn}from"./chunk-SAMWHL22.mjs";import{b as E,e as Be,g as En}from"./chunk-6KP6WETK.mjs";import{A as $e,H,N as Fn,d as Qe,g as Cn,x as Ue,y as je,z as Le}from"./chunk-J24TIGSI.mjs";import{b as St,d as Sn}from"./chunk-HKUWHVI7.mjs";import{b as Y,d as ge,e as ln}from"./chunk-VPDEJGPS.mjs";import{c as vn}from"./chunk-JQZTMFO7.mjs";import{fc as Zn}from"./chunk-JFNLKHY6.mjs";import{i as He}from"./chunk-INIT2UKJ.mjs";import{E as cn}from"./chunk-XZISAZA6.mjs";import{g as Ae,h as ne,i as an,q as dn}from"./chunk-L4INJ5TZ.mjs";import{da as Ke,ja as rn,ka as on}from"./chunk-KIMQQ6JQ.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{Ad as sn,Hc as nn,Id as kt,Ld as bt,Ra as Qt,Ta as Je,Ua as en,ic as tn}from"./chunk-ZQO5PDX5.mjs";import{b as X,e as Yt,f as De,i as yt,k as le,l as _,o as Ge,p as Zt,u as Pe,v as Z,z as Xt}from"./chunk-WZQEK4WT.mjs";import{randomBytes as Us}from"node:crypto";import{rm as $s}from"node:fs/promises";import{join as zs}from"node:path";var ar=5,dr="005",cr=new Set(["001"]),Bt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",it="Its sharing type stays as it is: Salesforce doesn't change the sharing type of a file's link to an account ('The sharing type cannot be updated because updates are not currently supported for the linked Entity type').";function ue(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function Fe(i,e){i.done+=e.done,i.already+=e.already,i.refused+=e.refused,i.notSent+=e.notSent,i.notReached+=e.notReached;for(let t of e.reasons)ot(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function ot(i,e){i.length<ar&&!i.includes(e)&&i.push(e)}var lr=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function ur(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=lr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:a,id:o,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,f=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(l=>l).join(": ")).filter(u=>u!=="").join("; ");return{success:a,...typeof o=="string"?{id:o}:{},...p!==void 0?{code:p}:{},...f!==""?{words:f}:{}}})}function fr(i){let e=[];for(let t=0;t<i.length;t+=Y)e.push(i.slice(t,t+Y));return e}async function Ct(i,e,t,n){let s=ue();for(let r of fr(i)){if(s.cancelled||e.stopped?.()===!0){s.cancelled=!0,s.notReached+=r.length;for(let d of r)s.left.push({id:d.Id,reason:"Not reached: stopped."});continue}await e.before?.(r);let a=ur(await t(r),r.length),o={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=a[c],f=n(p);if(f==="done"){s.done++,o.done.push(d),p.id!==void 0&&o.made.push({from:d.Id,id:p.id});return}if(o.left.push(d.Id),f==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,ot(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...o.made),await e.after?.(o)}return s}function ps(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,ot(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function at(i,e,t={}){let n=ue(),s=ps(e,a=>a.LinkedEntityId?.startsWith(dr)===!0,Bt,n),r=await Ct(s,t,a=>i.destroy(ne,a.map(o=>o.Id)),a=>a.success?"done":a.code==="ENTITY_IS_DELETED"||a.code==="NOT_FOUND"?"already":"refused");return Fe(r,n),r}async function dt(i,e,t={},n=s=>s){return Ct(e,t,s=>i.create(ne,s.map(r=>({ContentDocumentId:n(r.ContentDocumentId),LinkedEntityId:n(r.LinkedEntityId),ShareType:r.ShareType,Visibility:r.Visibility}))),s=>s.success&&s.id!==void 0?"done":s.code==="DUPLICATE_VALUE"?"already":"refused")}async function ct(i,e,t={}){let n=d=>cr.has(d.LinkedEntityId.slice(0,3)),s=ue(),r=new Map,a=ps(e,d=>d.Visibility===d.now.Visibility&&n(d),it,s);for(let d of a){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&ot(s.reasons,it),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let o=await Ct(a,t,d=>i.update(ne,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return Fe(s,o),s}import{randomBytes as ks}from"node:crypto";import{closeSync as pr,createReadStream as bs,fsyncSync as hr,openSync as gr,readFileSync as wr,renameSync as mr,writeSync as yr}from"node:fs";import{open as ut,readdir as Rs,rm as vs,stat as kr,truncate as Ss}from"node:fs/promises";import{dirname as Is,join as ee}from"node:path";import{createInterface as Os}from"node:readline";var Te="journal.ndjson",br="before.json",J=2e3,Ps=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Tt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),be=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),V=Xt.datetime({offset:!0}),ae=le(Ps).min(1).max(J),As=Yt().int().positive(),js=_({kind:Z("head"),version:Z(1),rewindId:Je,checkpointId:Qt,organizationId:en,startedAt:V,userId:Tt,automatedProcessUserId:Tt.optional(),backup:X().min(1).max(200),at:V}),Rr=_({kind:Z("resumed"),startedAt:V,userId:Tt,at:V}),vr=_({kind:Pe(["bringingBack","withParent","givingBack"]),objectApiName:be,ids:ae,parents:ae.optional(),carriers:Z(!0).optional(),at:V}),Sr=_({kind:Z("bringBackLeft"),objectApiName:be,ids:ae,at:V}),Ir=_({kind:Z("recreating"),objectApiName:be,ids:ae,at:V}),Or=_({kind:Z("recreated"),objectApiName:be,ids:ae,from:ae,at:V}),Pr=_({kind:Pe(["deleting","deleteLeft"]),step:As,objectApiName:be,ids:ae,at:V}),Ar=_({kind:Z("heldInPlace"),objectApiName:be,by:le(be).min(1).max(100),ids:ae,at:V}),jr=_({kind:Z("beforeParent"),objectApiName:be,ids:ae,parents:ae,at:V}),Lr=_({kind:Z("deleted"),step:As,at:V}),Nr=_({kind:Z("removal"),state:yt(),at:V}),Br=_({kind:Z("unlinking"),links:le(we).min(1).max(J),at:V}),Cr=_({kind:Pe(["unlinkLeft","linksUpdateLeft"]),ids:ae,at:V}),Fr=_({kind:Z("relinked"),ids:ae,from:ae,at:V}),Ls=we.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),Tr=_({kind:Z("linksUpdating"),links:le(Ls).min(1).max(J),at:V}),Er=_({kind:Z("linksUndone"),part:Pe(["reinserted","removed","shared"]),ids:ae,at:V}),Dr=_({kind:Z("wrote"),at:V}),Mr=_({kind:Z("end"),at:V}),Ur=_({kind:Z("undo"),state:yt(),status:Pe(["success","partial","failure","cancelled"]),at:V}),$r=Zt("kind",[js,Rr,vr,Sr,Ar,jr,Ir,Or,Pr,Lr,Nr,Br,Cr,Fr,Tr,Er,Dr,Mr,Ur]),zr=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Et(i){let e;try{e=await ut(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ut(i,e){let t=await ut(i,"a",Qe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function Wr(i,e){let t=`${i}.${process.pid}-${ks(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=gr(t,"wx",Qe);try{for(let r=0;r<n.length;)r+=yr(s,n,r,n.length-r);hr(s)}finally{pr(s)}mr(t,i)}function _r(i){let e=[];try{let n=JSON.parse(wr(i,"utf8"));Array.isArray(n.openings)&&(e=n.openings)}catch{}let t=e.length;return{set:(n,s)=>{e[t]=s,Wr(i,`${JSON.stringify({version:1,openings:e})}
|
|
8
|
-
`)}}}function W(i){return i.slice(0,15)}function pe(i){let e=[];for(let t=0;t<i.length;t+=J)e.push(i.slice(t,t+J));return e}async function*qr(i){if(!fn(i)){for(let{objectApiName:e,ids:t}of i)t.length>0&&(yield{objectApiName:e,ids:[...t]});return}for(let{objectApiName:e}of i.objects)for await(let t of i.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}var lt=class i{constructor(e,t,n,s,r,a){this.dir=t;this.resumed=n;this.handle=s;this.step=r;this.now=a;this.rewindId=e.rewindId,this.backup=e.backup;let o=new Set,d=new _n({...Wn(t),appendFile:async(p,f)=>{await Ut(p,f),o.has(p)||(o.add(p),await Et(Is(p)))}}),c={begin:()=>Le(ee(t,"backups")),append:(p,f,u)=>d.append(p,f,u)};if(this.kept=Qn({runId:e.rewindId,orgId:e.organizationId,organizationId:e.organizationId,files:c,meta:_r(ee(t,br)),now:a}),this.kept.id!==e.backup)throw new H("damaged","The rewind\u2019s journal names another backup of its values than the one they are kept in.");this.values=d,this.keep=async(p,f)=>{await this.kept.keep(p,f);let u=f.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);for(let l of pe(u))await this.append({kind:"givingBack",objectApiName:p,ids:l})}}dir;resumed;handle;step;now;keep;values;queue=Promise.resolve();closed=!1;openStep;kept;rewindId;backup;static async opened(e,t,n,s,r){let a=await ut(ee(e,Te),"a",Qe);try{return new i(t,e,n,a,s,r)}catch(o){throw await a.close(),o}}append(e){if(this.closed)return Promise.reject(new Error("The rewind\u2019s journal is closed."));let t=`${JSON.stringify({...e,at:this.now().toISOString()})}
|
|
9
|
-
`,n=this.queue.then(async()=>{await this.handle.appendFile(t,"utf8"),await this.handle.sync()});return this.queue=n.catch(()=>{}),n}async appendIds(e,t,n,s=!1){for(let r of pe(n))await this.append({kind:e,objectApiName:t,ids:r,...s?{carriers:s}:{}})}bringingBack(e,t,n={}){let s=new Map;for(let{objectApiName:r,ids:a}of e){let[o]=a;o!==void 0&&s.set(o.slice(0,3),r)}return async r=>{let a=new Set(r.map(d=>s.get(d.slice(0,3)))),[o]=[...a];if(a.size!==1||o===void 0)throw new Error("These records are not of the plan the journal names: none was sent.");return await this.appendIds("bringingBack",o,r,n.carriers===!0),t(r)}}async withParent(e,t,n,s={}){let r=s.carriers===!0;if(n===void 0){await this.appendIds("withParent",e,t,r);return}if(n.length!==t.length)throw new Error("Each record that comes back with a parent is named beside that parent.");for(let a=0;a<t.length;a+=J)await this.append({kind:"withParent",objectApiName:e,ids:t.slice(a,a+J),parents:n.slice(a,a+J),...r?{carriers:r}:{}})}async bringBackLeft(e,t){for(let n of pe(t))await this.append({kind:"bringBackLeft",objectApiName:e,ids:n})}async heldInPlace(e,t,n){if(t.length!==0)for(let s of pe(n))await this.append({kind:"heldInPlace",objectApiName:e,by:[...t],ids:s})}async beforeParent(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"beforeParent",objectApiName:e,ids:s.map(({id:r})=>r),parents:s.map(({parent:r})=>r)})}}async recreating(e,t){for(let n of pe(t))await this.append({kind:"recreating",objectApiName:e,ids:n})}async recreated(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"recreated",objectApiName:e,ids:s.map(({id:r})=>r),from:s.map(({from:r})=>r)})}}async deleting(e){let t=++this.step;this.openStep=t;for await(let{objectApiName:n,ids:s}of qr(e))for(let r of pe(s))await this.append({kind:"deleting",step:t,objectApiName:n,ids:r})}async deleted(e){let t=this.openStep;if(t===void 0)throw new Error("No removal was named to the journal before it.");for await(let{objectApiName:n,ids:s}of e.left())for(let r of pe(s))await this.append({kind:"deleteLeft",step:t,objectApiName:n,ids:r});await this.append({kind:"deleted",step:t}),this.openStep=void 0}async removal(e){let t={...e.removalStamps&&Object.keys(e.removalStamps).length>0?{removalStamps:e.removalStamps}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:e.removalSpans}:{}};Object.keys(t).length!==0&&await this.append({kind:"removal",state:{version:1,...t}})}async unlinking(e){for(let t=0;t<e.length;t+=J)await this.append({kind:"unlinking",links:e.slice(t,t+J)})}async unlinkLeft(e){for(let t of pe(e))await this.append({kind:"unlinkLeft",ids:t})}async relinked(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J);await this.append({kind:"relinked",ids:n.map(({id:s})=>s),from:n.map(({from:s})=>s)})}}async linksUpdating(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J).map(s=>({Id:s.Id,LinkedEntityId:s.LinkedEntityId,ShareType:s.ShareType,Visibility:s.Visibility}));await this.append({kind:"linksUpdating",links:n})}}async linksUpdateLeft(e){for(let t of pe(e))await this.append({kind:"linksUpdateLeft",ids:t})}async linksUndone(e,t){for(let n of pe(t))await this.append({kind:"linksUndone",part:e,ids:n})}async wrote(){await this.append({kind:"wrote"})}async end(){await this.append({kind:"end"})}async undone(e,t){await this.append({kind:"undo",state:{version:1,...e},status:t})}async read(){return await this.queue,Ns(ee(this.dir,Te))}async facts(){return await this.queue,Gr(ee(this.dir,Te))}async close(){if(!this.closed){this.closed=!0;try{this.kept.close()}catch{}await this.queue,await this.handle.close()}}};async function ke(i,e){let t=(await kr(i)).size,n=t===0;if(t>0){let p=await ut(i,"r");try{let f=Buffer.alloc(1);await p.read(f,0,1,t-1),n=f[0]===10}finally{await p.close()}}let s=0,r=0,a=async p=>{r+=Buffer.byteLength(p,"utf8")+1;let f;try{f=JSON.parse(p)}catch{f=void 0}let u=$r.safeParse(f);if(!u.success)throw new H("damaged",`The rewind\u2019s journal is damaged at line ${s+1}: it is not used.`);xr(u.data),s++,await e(u.data)},o=bs(i,{encoding:"utf8"}),d=Os({input:o,crlfDelay:1/0}),c;try{for await(let p of d)c!==void 0&&await a(c),c=p}finally{d.close(),o.destroy()}return c!==void 0&&n&&await a(c),{count:s,whole:r,size:t}}function xr(i){if(i.kind==="relinked"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names links inserted again without the links they stand for.");if(i.kind==="recreated"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records made again without the Ids they had.");if(i.kind==="beforeParent"&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records deleted before a parent without their parent.");if((i.kind==="withParent"||i.kind==="bringingBack")&&i.parents!==void 0&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records that came back with a parent without it.")}var he=class{byObject=new Map;add(e,t){let n=this.byObject.get(e)??new Map;for(let s of t)n.has(W(s))||n.set(W(s),s);this.byObject.set(e,n)}drop(e,t){let n=this.byObject.get(e);if(n)for(let s of t)n.delete(W(s))}list(e=()=>!0){return[...this.byObject].flatMap(([t,n])=>{let s=[...n].filter(([r])=>e(r)).map(([,r])=>r);return s.length>0?[{objectApiName:t,ids:s}]:[]})}keys(){return new Set([...this.byObject.values()].flatMap(e=>[...e.keys()]))}};function hs(i){let e={};for(let t of i)e={...e,...t,...t.removalStamps||e.removalStamps?{removalStamps:{...e.removalStamps,...t.removalStamps}}:{},...t.removalSpans||e.removalSpans?{removalSpans:[...e.removalSpans??[],...t.removalSpans??[]]}:{}};return e}function gs(i){let e=gn(i);if(e===void 0)throw new H("damaged","The rewind\u2019s journal holds a state it cannot read.");return e}var ze=class{head;step=0;passes=[];rewindStates=[];undoStates=[];undos=[];lastWrite=Number.NEGATIVE_INFINITY;endedAt;line(e){if(this.head===void 0){if(e.kind!=="head")throw new H("damaged","The rewind\u2019s journal does not begin with its head.");this.head=e,this.passes=[{startedAt:e.startedAt,userId:e.userId}];return}switch(zr.has(e.kind)&&(this.lastWrite=Math.max(this.lastWrite,Date.parse(e.at))),"step"in e&&(this.step=Math.max(this.step,e.step)),e.kind){case"head":throw new H("damaged","The rewind\u2019s journal has two heads.");case"resumed":this.passes.push({startedAt:e.startedAt,userId:e.userId});break;case"removal":this.rewindStates.push(gs(e.state));break;case"end":this.endedAt=e.at;break;case"undo":this.undoStates.push(gs(e.state)),this.undos.push({status:e.status,at:e.at});break;default:break}}result(){let e=this.head;if(e===void 0)throw new H("damaged","The rewind\u2019s journal does not begin with its head.");return{head:{rewindId:e.rewindId,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:e.startedAt,userId:e.userId,...e.automatedProcessUserId!==void 0?{automatedProcessUserId:e.automatedProcessUserId}:{},backup:e.backup},passes:this.passes,...Number.isFinite(this.lastWrite)?{lastWriteAt:new Date(this.lastWrite).toISOString()}:{},...this.endedAt!==void 0?{endedAt:this.endedAt}:{},rewind:hs(this.rewindStates),undo:hs(this.undoStates),undos:this.undos}}},Dt=class{broughtBack=new he;recreated=new he;carriers=new he;carried=new Map;givenBack=new he;held=new he;heldBy=new Map;beforeParent=[];withParents=new Map;steps=new Map;stepOf(e){let t=this.steps.get(e);return t||(t={deleting:new he,left:new Set,answered:!1},this.steps.set(e,t)),t}line(e){switch(e.kind){case"bringingBack":case"withParent":this.broughtBack.add(e.objectApiName,e.ids),e.carriers===!0&&e.kind==="bringingBack"&&this.carriers.add(e.objectApiName,e.ids),e.parents?.forEach((t,n)=>{let s=e.ids[n],r=e.carriers===!0?this.carried:this.withParents;r.has(W(s))||r.set(W(s),{objectApiName:e.objectApiName,id:s,parent:t})});break;case"bringBackLeft":this.broughtBack.drop(e.objectApiName,e.ids),this.carriers.drop(e.objectApiName,e.ids);for(let t of e.ids)this.withParents.delete(W(t)),this.carried.delete(W(t));break;case"givingBack":this.givenBack.add(e.objectApiName,e.ids);break;case"recreated":this.recreated.add(e.objectApiName,e.ids);break;case"heldInPlace":{this.held.add(e.objectApiName,e.ids);let t=this.heldBy.get(e.objectApiName)??new Set;for(let n of e.by)t.add(n);this.heldBy.set(e.objectApiName,t);break}case"beforeParent":e.ids.forEach((t,n)=>{this.beforeParent.push({objectApiName:e.objectApiName,id:t,parent:e.parents[n]})});break;case"deleting":this.stepOf(e.step).deleting.add(e.objectApiName,e.ids);break;case"deleteLeft":for(let t of e.ids)this.stepOf(e.step).left.add(W(t));break;case"deleted":this.stepOf(e.step).answered=!0;break;default:break}}result(){let e=new he;for(let{deleting:u,left:l,answered:h}of this.steps.values())for(let{objectApiName:g,ids:w}of u.list(y=>!h||!l.has(y)))e.add(g,w);let t=this.held.list().map(({objectApiName:u,ids:l})=>({objectApiName:u,ids:l,by:[...this.heldBy.get(u)??[]]})),n=e.keys(),s=new Set([...this.steps.values()].flatMap(({deleting:u})=>[...u.keys()])),r=new he;for(let{objectApiName:u,id:l,parent:h}of this.beforeParent){let g=W(h);n.has(W(l))&&(n.has(g)||!s.has(g))&&r.add(u,[l])}let a=r.list(),o=u=>{let l=new Map;for(let{objectApiName:h,id:g,parent:w}of u){let y=l.get(h)??{objectApiName:h,ids:[],parents:[]};y.ids.push(g),y.parents.push(w),l.set(h,y)}return[...l.values()]},d=o(this.withParents.values()),c=o(this.carried.values()),p=this.carriers.list(),f=this.recreated.list();return{broughtBack:this.broughtBack.list(),deleted:e.list(),givenBack:this.givenBack.list(),...t.length>0?{heldInPlace:t}:{},...a.length>0?{deletedBeforeParent:a}:{},...d.length>0?{withParents:d}:{},...f.length>0?{recreated:f}:{},...p.length>0?{carriers:p}:{},...c.length>0?{carried:c}:{}}}};async function Ns(i){let e=new ze,t=new Dt;try{await ke(i,n=>{e.line(n),t.line(n)})}catch(n){throw n instanceof H?n:new H("notFound","No journal of this rewind is kept.")}return{...e.result(),did:t.result()}}async function Gr(i){let e=new ze;try{await ke(i,t=>e.line(t))}catch(t){throw t instanceof H?t:new H("notFound","No journal of this rewind is kept.")}return e.result()}function Jr(i,e,t){if(i.head.rewindId!==t||i.head.checkpointId!==e.checkpointId||i.head.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("damaged","The rewind\u2019s journal names another rewind, checkpoint or org than its folder.")}async function wo(i,e){let t=await We(i,e);if(!t)throw new H("notFound","No journal of this rewind is kept.");return Ns(t.file)}function Bs(i,e){if(i.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("invalid","A rewind\u2019s journal is written under its org\u2019s lock.")}async function We(i,e){let t=je(i,e),n=ee(t,Te),s=new ze,r;try{r=await ke(n,o=>s.line(o))}catch(o){if(o instanceof H)throw o;return}if(r.count===0||s.head===void 0)return;let a=s.result();return Jr(a,i,e),{dir:t,file:n,head:s.head,step:s.step,whole:r.whole,size:r.size,facts:a}}async function Cs(i,e){return i.whole<i.size&&await Ss(i.file,i.whole),lt.opened(i.dir,i.head,!0,i.step,e)}var ws=18;async function Kr(i){let e;try{e=(await Rs(i.rewindsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()&&Je.safeParse(n.name).success).map(n=>n.name).sort().reverse()}catch{return[]}let[t]=e;return t===void 0?[]:e.filter(n=>n.slice(0,ws)===t.slice(0,ws))}async function Fs(i){let{folder:e}=i;Bs(i.lock,e);let t=i.now??(()=>new Date),n;for(let d of await Kr(e)){let c=await We(e,d);if(!c){n??=d;continue}if(c.facts.endedAt!==void 0||c.facts.undos.length>0)continue;let p=await Cs(c,t);try{await p.append({kind:"resumed",startedAt:i.startedAt,userId:i.userId})}catch(f){throw await p.close(),f}return p}let s=n??$e("rw",t()),r=je(e,s);await Le(r),await Le(ee(r,"backups")),await Ss(ee(r,Te),0).catch(()=>{});let a=js.safeParse({kind:"head",version:1,rewindId:s,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:i.startedAt,userId:i.userId,...i.automatedProcessUserId!==void 0?{automatedProcessUserId:i.automatedProcessUserId}:{},backup:Xn(s),at:t().toISOString()});if(!a.success)throw new H("invalid",`Not a rewind to journal: ${a.error.message}`);let o=await lt.opened(r,a.data,!1,0,t);try{await o.append(a.data),await Et(r),await Et(e.rewindsDir)}catch(d){throw await o.close(),d}return o}async function Ts(i,e,t,n=()=>new Date){Bs(t,i);let s=await We(i,e);if(!s)throw new H("notFound","No journal of this rewind is kept.");return Cs(s,n)}async function Es(i,e,t){let n=await i.checkpointsOf(e.organizationId),s=Fn(n),r=[],a=[...n].sort((o,d)=>o.folder.checkpointId<d.folder.checkpointId?-1:1);for(let{folder:o,checkpoint:d}of a){if(d===void 0)continue;let c;try{c=(await Rs(o.rewindsDir,{withFileTypes:!0})).filter(f=>f.isDirectory()&&Je.safeParse(f.name).success).map(f=>f.name).sort()}catch{continue}let p=(f,u)=>u?.checkpointId===o.checkpointId&&u.rewindId===f;for(let f of c){if(p(f,t)||p(f,s))continue;let u=await We(o,f).catch(()=>{});u===void 0||u.facts.endedAt===void 0&&u.facts.undos.length===0||(await vs(je(o,f),{recursive:!0,force:!0}),r.push({checkpointId:o.checkpointId,name:d.name,rewindId:f}))}}return r}var Mt=class i{constructor(e,t,n){this.dir=e;this.objects=t;this.keys=n}dir;objects;keys;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async written(e,t){await Le(e);let n=new E,s=new Map,r=new Map,a=async o=>{let d=r.get(o)??[];d.length!==0&&(await Ut(ms(e,o),d.join("")),r.set(o,[]))};await t(async(o,{id:d,parent:c})=>{if(!n.add(d))return;s.set(o,(s.get(o)??0)+1);let p=r.get(o)??[];p.push(`${d} ${c}
|
|
10
|
-
`),r.set(o,p),p.length>=J&&await a(o)});for(let o of s.keys())await a(o);return new i(e,[...s].map(([o,d])=>({objectApiName:o,count:d})),n)}async*pages(e,t=J){if(!this.objects.some(a=>a.objectApiName===e))return;let n=bs(ms(this.dir,e),{encoding:"utf8"}),s=Os({input:n,crlfDelay:1/0}),r=[];try{for await(let a of s){let[o,d]=a.split(" ");o===void 0||d===void 0||(r.push({id:o,parent:d}),r.length>=t&&(yield r,r=[]))}}finally{s.close(),n.destroy()}r.length>0&&(yield r)}};function ms(i,e){return ee(i,`${nn(e)}.pairs`)}async function Ft(i,e,t){return e.length>0&&(await Le(Is(i)),await Ut(i,e.map(n=>`${JSON.stringify(n)}
|
|
11
|
-
`).join(""))),{count:e.length,pages:async function*(){if(e.length===0)return;let n=[];for await(let s of nt(i))n.push(t(s)),n.length>=J&&(yield n,n=[]);n.length>0&&(yield n)}}}async function Hr(i,e){let t=new Map,n=new Map,s=new Map,r=new Set,a=new Set,o=new Set,d=new Set;await ke(i,u=>{switch(u.kind){case"unlinking":for(let l of u.links)t.has(W(l.Id))||t.set(W(l.Id),l);break;case"unlinkLeft":for(let l of u.ids)t.delete(W(l));break;case"relinked":for(let l of u.ids)n.set(W(l),{Id:l});break;case"linksUpdating":r=new Set;for(let l of u.links)s.has(W(l.Id))||(s.set(W(l.Id),l),r.add(W(l.Id)));break;case"linksUpdateLeft":for(let l of u.ids)r.has(W(l))&&s.delete(W(l));break;case"linksUndone":{let l=u.part==="reinserted"?a:u.part==="removed"?o:d;for(let h of u.ids)l.add(W(h));break}default:break}});for(let u of[...n.keys()])t.has(u)&&(n.delete(u),t.delete(u));let c=[...t].filter(([u])=>!a.has(u)).map(([,u])=>u),p=[...n].filter(([u])=>!o.has(u)).map(([,u])=>u),f=[...s].filter(([u])=>!d.has(u)).map(([,u])=>u);if(c.length+p.length+f.length!==0)return{reinsert:await Ft(ee(e,"links.reinsert.ndjson"),c,u=>we.parse(u)),remove:await Ft(ee(e,"links.remove.ndjson"),p,u=>({Id:_({Id:Ps}).parse(u).Id})),share:await Ft(ee(e,"links.share.ndjson"),f,u=>Ls.parse(u))}}function ys(i,e){let t=new Map(i.map(s=>[s.objectApiName,s.readOrder])),n=s=>t.get(s)??-1;return s=>[...s].sort((r,a)=>e?n(a.objectApiName)-n(r.objectApiName):n(r.objectApiName)-n(a.objectApiName))}async function $t(i,e,t){let n=ee(i,Te),s=ee(i,`undo-${ks(4).toString("hex")}`),r=()=>vs(s,{recursive:!0,force:!0});try{let a=b=>{if(b===void 0)return()=>!0;let R=new E;for(let C of b)R.add(C);return C=>R.has(C)},o=a(e.undo.removalLeft),d=a(e.undo.undeleteLeft),c=a(e.undo.restoreLeft),p=new E,f=new Set,u=new Map,l=new E,h=new Map,g=new E,w=new Set,y=new Map;await ke(n,b=>{switch(b.kind){case"bringBackLeft":for(let R of b.ids)w.add(W(R));break;case"bringingBack":case"withParent":case"recreated":for(let R of b.ids)p.add(R),w.size>0&&w.delete(W(R));b.kind==="withParent"&&b.carriers===!0&&b.parents&&b.ids.forEach((R,C)=>{let te=b.parents?.[C];te!==void 0&&!y.has(W(R))&&y.set(W(R),{objectApiName:b.objectApiName,id:R,parent:W(te)})});break;case"givingBack":for(let R of b.ids)g.add(R);break;case"deleteLeft":{let R=u.get(b.step)??new E;for(let C of b.ids)R.add(C);u.set(b.step,R);break}case"deleted":f.add(b.step);break;case"heldInPlace":{for(let C of b.ids)l.add(C);let R=h.get(b.objectApiName)??new Set;for(let C of b.by)R.add(C);h.set(b.objectApiName,R);break}default:break}});let m=b=>p.has(b)&&!w.has(b),k=new E,L=new Be(ee(s,"bringBack"));await ke(n,async b=>{if(b.kind!=="deleting")return;let R=f.has(b.step)?u.get(b.step):void 0;for(let C of b.ids){if(R?.has(C)===!0)continue;let te=W(C);m(te)?k.add(C):d(te)&&await L.add(b.objectApiName,C)}});let S=new E;for(let b=y.size>0;b;){b=!1;for(let{id:R,parent:C}of y.values())S.has(R)||g.has(R)||(k.has(C)||S.has(C))&&(S.add(R),b=!0)}let T=b=>k.has(b)||S.has(b),F=b=>!w.has(b)&&!T(b)&&o(b),P=new E,j=new E;await ke(n,b=>{b.kind!=="withParent"||b.parents===void 0||b.ids.forEach((R,C)=>{if(!j.add(R))return;let te=W(b.parents?.[C]??"");F(W(R))&&m(te)&&F(te)&&P.add(R)})});let z=new E,q=new Map;for(let{objectApiName:b,id:R,parent:C}of y.values())!F(W(R))||P.has(R)||!g.has(R)||F(C)&&y.has(C)||(z.add(R),q.set(b,(q.get(b)??0)+1));let x=new Be(ee(s,"remove")),A=new Be(ee(s,"giveBack")),B=new E,G=new Map,v=await Mt.written(ee(s,"goesWithParent"),async b=>{await ke(n,async R=>{if(R.kind==="givingBack"){for(let C of R.ids)c(W(C))&&await A.add(R.objectApiName,C);return}if(R.kind==="recreated"){for(let C of R.ids)!F(W(C))||!await x.add(R.objectApiName,C)||(B.add(C),G.set(R.objectApiName,(G.get(R.objectApiName)??0)+1));return}if(!(R.kind!=="bringingBack"&&R.kind!=="withParent"))for(let[C,te]of R.ids.entries()){let fe=W(te);if(!F(fe))continue;let Oe=R.parents?.[C];P.has(fe)?Oe!==void 0&&await b(R.objectApiName,{id:te,parent:Oe}):await x.add(R.objectApiName,te)}})}),N=await A.finish(),M=await Hr(n,s),K=new E,U=new Map;for(let{objectApiName:b}of N.objects)for await(let R of N.pages(b))for(let C of R)l.has(C)&&(K.add(C),U.set(b,(U.get(b)??0)+1));return{remove:await En.of(x,ys(t,!1)),bringBack:await L.finish(ys(t,!0)),giveBack:N,giveBackKeys:A.keys,backup:e.head.backup,held:{keys:K,objects:[...U].map(([b,R])=>({objectApiName:b,count:R,by:[...h.get(b)??[]]}))},goesWithParent:v,remade:{keys:B,objects:[...G].map(([b,R])=>({objectApiName:b,count:R}))},compensated:{has:b=>T(W(String(b)))},carriedAlone:{keys:z,objects:[...q].map(([b,R])=>({objectApiName:b,count:R}))},...M?{links:M}:{},dispose:r}}catch(a){throw await r(),a}}async function mo(i,e,t){let n=await We(i,e);if(!n)throw new H("notFound","No journal of this rewind is kept.");return $t(n.dir,n.facts,t)}function yo(i){let e=new Map,t=s=>{let r=e.get(s);return r||(r={objectApiName:s,deleted:0,broughtBack:0,givenBack:0},e.set(s,r)),r};for(let{objectApiName:s,count:r}of i.bringBack.objects)r>0&&(t(s).deleted+=r);for(let{objectApiName:s,count:r}of i.remove.objects)r>0&&(t(s).broughtBack+=r);for(let{objectApiName:s,count:r}of i.giveBack.objects)r>0&&(t(s).givenBack+=r);for(let{objectApiName:s,count:r}of i.held.objects){let a=t(s);a.givenBackHeld=(a.givenBackHeld??0)+r}let n=i.links;if(n){let s=t(ne);s.deleted+=n.reinsert.count,s.broughtBack+=n.remove.count,s.givenBack+=n.share.count}return[...e.values()]}var Vr=50,Yr=/Entity is not in the recycle bin/,Zr="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good \u2014 deleted on its own, then a record it hangs from was deleted after it, it can no longer come back, with that record or without; deleted with a record still in the bin, it comes back only with that record (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin')",Xr=100;function re(i){return i.slice(0,15)}var Qr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ei(i,e){return{batches:async(t,n,s)=>{let r=await i.batches(t,n,s);return r?{async*[Symbol.asyncIterator](){for await(let a of r)yield a.map(o=>Object.fromEntries(Object.entries(o).filter(([d,c])=>d==="Id"||typeof c!="string"||!Qr.test(c)||!e.has(c))))}}:null}}}function ti(i){return{objects:[],cancelled:i,gone:[],stamps:{},left:async function*(){}}}function Ds(i,e){if(e){i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}}async function*Ms(i,e,t,n=()=>!0){let s=[];for await(let r of i.pages(e,t))for(let a of r)n(re(a))&&(s.push(a),s.length>=t&&(yield s,s=[]));s.length>0&&(yield s)}function ni(i){let e=i.bringBack.objects.filter(({count:r})=>r>0).map(({objectApiName:r})=>r),t=new Set(i.held.objects.flatMap(({by:r})=>r)),n=e.findIndex(r=>t.has(r)),s=n<0||i.held.keys.size===0?e.length:n;return{bringFirst:e.slice(0,s),bringAfter:e.slice(s),held:r=>i.held.keys.has(r)}}function si(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}function ri(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);s?si(s,n):t.push({...n,reasons:[...n.reasons]})}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}function ii(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);if(!s){t.push(n);continue}s.planned+=n.planned,Ds(s,n)}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}async function zt(i,e,t,n){if(e.cancelled)return e;let s=new Set(e.left.map(re)),r=new Set,a=[];for(let o of e.objects){let d=o.reasons.find(l=>Yr.test(l));if(d===void 0||o.refused===0){a.push(o);continue}let c=t.filter(({objectApiName:l})=>l===o.objectApiName).flatMap(l=>l.ids.filter(h=>s.has(re(h)))),p=0;try{let l=de(o.objectApiName);for(let h of ge(c,Y)){let g=await i.query(`SELECT Id FROM ${l} WHERE Id IN (${h})`);for(let w of g.records)typeof w.Id!="string"||r.has(re(w.Id))||(r.add(re(w.Id)),p++)}}catch(l){n.push(`Whether the ${o.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${Q(l)}): they are counted refused.`),a.push(o);continue}let f=Math.min(p,o.refused),u=o.refused-f;a.push({...o,refused:u,alreadyBack:o.alreadyBack+f,reasons:u===0?o.reasons.filter(l=>l!==d):o.reasons.map(l=>l===d?Zr:l)})}return{...e,objects:a,left:e.left.filter(o=>!r.has(re(o)))}}async function oi(i,e,t,n){let s=new Map(n.map(o=>[re(o),o])),r=new Map,a=await i.batches(e,t,Y);for await(let o of a??[])for(let d of o){if(typeof d.Id!="string")continue;let c=s.get(re(d.Id));if(c===void 0)continue;let p=r.get(re(c))??{id:c,values:{}};for(let[f,u]of Object.entries(d))f!=="Id"&&!(f in p.values)&&(p.values[f]=u);r.set(re(c),p)}return r}async function ai(i,e,t,n,s){let r=[],a=e.backup;for(let{objectApiName:o}of e.giveBack.objects){let d=de(o),c={objectApiName:o,count:0,ids:[],by:{}};try{for await(let p of Ms(e.giveBack,o,Se,f=>!n.has(f))){let f=await oi(t,a,o,p);if(f.size===0)continue;let u=new Set;for(let{values:w}of f.values())for(let y of Object.keys(w))u.add(de(y));let l=["Id","LastModifiedById",...u],h=l.length>Xr?Y/4:Y,g=async w=>(await i.query(w)).records;for(let w of ge([...f.values()].map(y=>y.id),h)){let y=await He(`SELECT ${l.join(", ")} FROM ${d} WHERE Id IN (${w})`,g);for(let m of y){if(typeof m.Id!="string")continue;let k=f.get(re(m.Id));if(!k||!Object.entries(k.values).some(([T,F])=>!wn(F,m[T])))continue;c.count++,c.ids.length<Vr&&c.ids.push(k.id);let S=typeof m.LastModifiedById=="string"?m.LastModifiedById:"unknown";c.by[S]=(c.by[S]??0)+1}}}}catch(p){s.push(`The ${o} records the undo gave back could not be read again (${Q(p)}): whether they all hold their values from before the rewind was not checked.`)}c.count>0&&r.push(c)}return r}async function di(i,e,t,n,s){let r=new Map(Object.entries(n).map(([o,d])=>[re(o),Date.parse(d)])),a=new E;for(let{objectApiName:o}of e.objects){let d=de(o);for await(let c of e.pages(o))for(let p of ge(c,Y)){if(s?.aborted)return a;let f;try{f=(await i.query(`SELECT Id, LastModifiedDate FROM ${d} WHERE Id IN (${p})`)).records}catch{continue}for(let u of f){if(typeof u.Id!="string")continue;let l=re(u.Id),h=Date.parse(String(u.LastModifiedDate??""));(h<=t||h<=(r.get(l)??Number.NaN))&&a.add(u.Id)}}}return a}async function Fo(i){let e=await Ts(i.folder,i.rewindId,i.lock);try{let t=await e.facts(),n=await $t(e.dir,t,i.objects);try{return await ci(e,t,n,i)}finally{await n.dispose()}}finally{await e.close()}}async function ci(i,e,t,n){let{org:s,signal:r}=n,a=t.goesWithParent,o=ei(i.values,t.compensated),d={remove:t.remove.spool.count+a.count,bringBack:t.bringBack.count,giveBack:t.giveBack.count},c=[],p={...e.rewind.removalStamps,...e.undo.removalStamps},f=Object.keys(p).length>0?p:void 0,u=[...e.rewind.removalSpans??[],...e.undo.removalSpans??[]],l=mn(s),h,g=new E,w={},y=new Set(n.objects.filter(I=>I.customSetting!==void 0).map(I=>I.objectApiName)),m=I=>!y.has(I),k=ni(t),L,S,T=new Map,F=async I=>{for(let D of I)for await(let $ of t.bringBack.pages(D)){let oe=(L?.cancelled??!1)||r?.aborted===!0?{objects:[{objectApiName:D,planned:$.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,notReached:$.length,reasons:[]}],left:[...$],wrote:!1,cancelled:!0,stamps:{}}:await Ze({org:s,plan:[{objectApiName:D,ids:$}],undelete:n.undelete,...r?{signal:r}:{}});T.set(D,[...T.get(D)??[],...oe.left]),L=ri(L,oe)}return!(L?.cancelled??!1)&&r?.aborted!==!0},P=async(I,D=m)=>{for(let{objectApiName:$}of t.giveBack.objects){if(!D($))continue;let ie=de($),oe={objectApiName:$,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]},ce={objects:[oe],left:[],wrote:!1,cancelled:!1,stamps:{}};for await(let ve of Ms(t.giveBack,$,Se,I)){if(oe.planned+=ve.length,(S?.cancelled??!1)||ce.cancelled||r?.aborted){ce.cancelled=!0,oe.notReached=(oe.notReached??0)+ve.length,ce.left.push(...ve);continue}if(h!==void 0){let ir=ve.filter(or=>g.has(or));Object.assign(w,await kn(s,ie,ir,h,l))}let Vt={...p,...w},Ee=await Ye({org:s,plan:[{objectApiName:$,backup:t.backup,ids:ve}],backups:o,...e.lastWriteAt!==void 0?{lastWriteAt:e.lastWriteAt}:{},includeChanged:!1,...Object.keys(Vt).length>0?{stamps:Vt}:{},...r?{signal:r}:{}});Ds(oe,Ee.objects[0]),ce.left.push(...Ee.left),ce.wrote||=Ee.wrote,ce.cancelled||=Ee.cancelled,Object.assign(ce.stamps,Ee.stamps)}oe.planned>0&&(S=ii(S,ce))}return!(S?.cancelled??!1)&&r?.aborted!==!0},j=async()=>{if(t.bringBack.count>0&&t.giveBack.count>0){let D=await yn(s);h=Date.now()+D-vt;let $=Date.parse(e.lastWriteAt??""),ie=Number.isFinite($)?$+D+vt:Number.NEGATIVE_INFINITY;g=await di(s,t.giveBack,ie,p,r)}return await F(k.bringFirst.filter(m))&&await P(k.held)&&await F(k.bringAfter.filter(m))&&(L&&(L=await zt(s,L,[...T].map(([D,$])=>({objectApiName:D,ids:$})),c)),await P(D=>!k.held(D))),(L?.wrote??!1)||(S?.wrote??!1)},z,q=(I,D)=>{if(typeof I.Id!="string"||!a.keys.has(I.Id))return!1;if(z===void 0){let oe=new E;for(let ce of S?.left??[])oe.add(ce);z={stamps:new Map(Object.entries({...p,...w}).map(([ce,ve])=>[re(ce),Date.parse(ve)])),notGiven:oe}}let $=Date.parse(String(I.LastModifiedDate??I.SystemModstamp??"")),ie=re(I.Id);return $<=D||$<=(z.stamps.get(ie)??Number.NaN)?!0:t.giveBackKeys.has(ie)&&S!==void 0&&!z.notGiven.has(ie)},x=t.links,A={removed:ue(),reinserted:ue(),shared:ue()};if(x&&x.remove.count>0&&!r?.aborted)for await(let I of x.remove.pages())Fe(A.removed,await at(s,I,{after:async({done:D})=>{D.length>0&&await i.linksUndone("removed",D.map($=>$.Id))},stopped:()=>r?.aborted===!0}));let B;if(t.remove.spool.count>0?B=await Ve(s,t.remove,{...n.splitting?{splitting:n.splitting}:{},runStartedAt:new Date(e.head.startedAt),...e.lastWriteAt!==void 0?{runRecordedAt:new Date(e.lastWriteAt)}:{},...f?{removalStamps:f}:{},...u.length>0?{removalSpans:u}:{},includeChanged:!1,...a.count>0?{goesWithParent:q,goesWithParentReadBelow:!0}:{},...t.bringBack.count>0||t.giveBack.count>0?{sweep:j}:{},...n.onUndeletable?{onUndeletable:n.onUndeletable}:{},...r?{signal:r}:{},...n.onProgress?{onProgress:n.onProgress}:{}}):(r?.aborted||await j(),B=ti(r?.aborted===!0&&!L&&!S)),y.size>0&&!B.stoppedForUndeletable&&(await P(()=>!0,I=>y.has(I)),await F([...k.bringFirst,...k.bringAfter].filter(I=>y.has(I)))),x&&!B.stoppedForUndeletable&&!r?.aborted){let I=s.create?.bind(s);for await(let D of x.reinsert.pages()){if(!I){A.reinserted.refused+=D.length,A.reinserted.reasons.push("The links the rewind removed could not be inserted again: this connection inserts no record.");continue}Fe(A.reinserted,await dt({create:I},D,{after:async({made:$})=>{$.length>0&&await i.linksUndone("reinserted",$.map(ie=>ie.from))},stopped:()=>r?.aborted===!0}))}for await(let D of x.share.pages())Fe(A.shared,await ct(s,D.map($=>({...$,now:{ShareType:"",Visibility:""}})),{after:async({done:$})=>{$.length>0&&await i.linksUndone("shared",$.map(ie=>ie.Id))},stopped:()=>r?.aborted===!0}))}let G=x?{unlinked:A.removed.done,relinked:A.reinserted.done,linksUpdated:A.shared.done,linksRefused:A.removed.refused+A.reinserted.refused+A.shared.refused}:void 0;for(let I of[...A.removed.reasons,...A.reinserted.reasons,...A.shared.reasons])c.includes(I)||c.push(`A link between a file and a record: ${I}`);let v=new Date().toISOString();if(B.stoppedForUndeletable)return{rewindId:n.rewindId,status:"cancelled",deleted:[],restored:[],undeleted:[],residual:[],planned:d,notes:[],stoppedForUndeletable:!0,finishedAt:v};let N=[],M=new E,K=new Map,U=new Map;for await(let{objectApiName:I,ids:D}of B.left())for(let $ of D)M.add($),N.push($),t.remade.keys.has($)&&K.set(I,(K.get(I)??0)+1),t.carriedAlone.keys.has($)&&U.set(I,(U.get(I)??0)+1);let b=t.remade.objects.map(({objectApiName:I,count:D})=>({objectApiName:I,count:D-(K.get(I)??0)})).filter(({count:I})=>I>0),R=t.carriedAlone.objects.map(({objectApiName:I,count:D})=>({objectApiName:I,count:D-(U.get(I)??0)})).filter(({count:I})=>I>0),C=[];for(let{objectApiName:I}of a.objects){let D=0;for await(let $ of a.pages(I))for(let{id:ie,parent:oe}of $)M.has(oe)?N.push(ie):D++;D!==0&&C.push({objectApiName:I,planned:D,deleted:D,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})}let te=[...C,...B.objects],fe=bn(Rn(hn(te,B.cancelled),te,S),te,S,L),Oe=[];if(S&&fe!=="cancelled"){let I=new E;for(let D of S.left)I.add(D);Oe=await ai(s,t,o,I,c)}Oe.length>0&&fe==="success"&&(fe="partial"),(G?.linksRefused??0)>0&&fe==="success"&&(fe="partial");let nr=t.remove.spool.count>0,sr=S?.objects.some(I=>I.restored+(I.restoredWithout??0)>0)===!0,Ht={...w,...B.stamps},rr={...Object.keys(Ht).length>0?{removalStamps:Ht}:{},...B.span?{removalSpans:[B.span]}:{},...nr?{removalLeft:N}:{},...S?{restoreLeft:S.left}:{},...sr?{restoredAt:v}:{},...L?{undeleteLeft:L.left}:{},...L&&!L.cancelled?{undeletedAt:v}:{}};try{await i.undone(rr,fe)}catch(I){c.push(`What this undo did could not be kept in the rewind\u2019s journal (${Q(I)}): an undo after it may set out to take back what it took back already.`)}return{rewindId:n.rewindId,status:fe,deleted:te,...b.length>0?{remade:b}:{},...R.length>0?{carriedAlone:R}:{},...C.length>0?{wentAlong:C.map(({objectApiName:I,deleted:D})=>({objectApiName:I,count:D}))}:{},restored:S?.objects??[],undeleted:L?.objects??[],...G?{files:G}:{},residual:Oe,planned:d,notes:c,finishedAt:v}}var li=1e3,ui=Cn*24*60*6e4,Ws=50,Ks=5,Hs=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],_s=[...Hs.filter(i=>i!=="carrier"),"goneForGood","convertedLead","activatedContract","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach"],fi="Left in the recycle bin: deleted since by another user, which only a user with View All Data and Modify All Data restores. Not made again: it is there still.",Jt="Left as it is: out of the user's reach. Without View All Data and Modify All Data, nothing proves the user sees what others deleted of this object in the recycle bin, so it may be there out of sight, and it is never made again.",pi={convertedLead:"Left converted: Salesforce can't unconvert a lead, and refuses any update of a converted one.",activatedContract:"Left activated: Salesforce won't set an activated contract back to Draft, so it is not given back.",deletedWithCreatedParent:"Left in the recycle bin: deleted with a record created since that Salesforce does not undelete on its own, it comes back with that record only.",deletedWithParentOutside:"Left in the recycle bin: deleted with its parent, a record of an object the checkpoint does not hold, it comes back with that record only. A checkpoint that holds that object brings it back.",deletedByOther:fi,outOfReach:Jt},ft={createdSince:"removal",broughtBackSince:"removal",comesBackWithParent:"removal",giveBack:"restore",inBin:"undelete",withParent:"undelete",deletedWhileTaken:"undelete",toRecreate:"recreate",carrier:"undelete"},Wt={outsideNotAccepted:"Kept: records outside the checkpoint created since hang from it, and their deletion was not accepted.",holdsLeft:"Kept: a record the rewind left hangs from it, and its deletion would take that record along.",noUndoNotAccepted:"Kept: Undo couldn't bring it back once deleted on its own, and that was not accepted.",beforeParentNotAccepted:"Kept: Undo couldn't bring it back once deleted before a record it points at, which the rewind deletes next, and that was not accepted.",keyTaken:"Kept in the recycle bin: a row of this custom setting made or changed since holds its owner or its name, and brought back beside it the setting would hold two. It comes back once that row is gone."};function hi(i){return`Kept: records it does not delete hang from it (${i.join(", ")}), and its deletion would take them along.`}var _t="It still differs from the checkpoint once the org was read again.",_e=/Entity is not in the recycle bin/,gi="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin'). Make them again, with new Ids, or --accept-recreate on the command line, makes it again with a new Id.",Ie="No record was written.",qs=4;function wi(i,e,t){let n=e.some(o=>Ke[o]!==void 0)?"as it is created or given its status back":"as it is created",s=[...new Set(t.fired.map(o=>`${o.objectApiName}: '${o.name}'`))],r=s.length-qs;return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and ${s.length>0?`making it again runs what ${i} runs ${n} (${s.slice(0,qs).join(", ")}${r>0?` and ${r} more`:""})`:`what ${i} runs ${n} could not all be read`}, which this rewind did not ask about. Rewind again: its preview counts it to make again, and asks.`}var mi="Account",yi="Contact",ki="001",bi="005",Ri=_({sobjects:le(_({name:X(),queryable:De().optional()}).loose())}).loose(),vi=/No such column 'IsDeleted'/;function qt(i){return i.toLowerCase()===ne.toLowerCase()}function Si(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];if(typeof r!="object"||r===null)return!1;let{success:a,errors:o}=r;return a===!0?!1:(Array.isArray(o)?o:[o]).some(d=>{let c=typeof d=="string"?d:typeof d=="object"&&d!==null?String(d.message??""):"";return _e.test(c)})})}function Ii(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];return typeof r=="object"&&r!==null&&r.success===!1})}function ya(i){let e=Yn(i),t=pn(i,"Checkpoint rewind"),n=t.bulkDestroy;return{get version(){return e.version},request:s=>e.request(s),query:async(s,r)=>await i.query(s,{scanAll:r?.scanAll===!0}),queryMore:s=>e.queryMore(s),describeGlobal:()=>e.describeGlobal(),serverTime:()=>e.serverTime(),userId:()=>e.userId(),describe:s=>t.describe(s),update:(s,r)=>t.update(s,r),create:(s,r)=>i.sobject(s).create(r,{headers:tn()}),destroy:(s,r)=>t.destroy(s,r),queryDeleted:s=>t.queryDeleted(s),...n?{bulkDestroy:(s,r,a)=>n(s,r,a)}:{}}}async function Oi(i,e,t){if(!i||!e)return e?{automation:e}:{};try{let n=await i(e,bt(t));return{automation:n.automation??e,mute:n}}catch(n){if(!St(n))throw n;let s=Sn(e,bt(t));return{refusal:{code:"MUTE",message:`${n.message} ${Ie}`},automation:s.automation,plan:s.plan}}}async function Pi(i,e,t,n){let s=i?.prepared?await i.prepared.acquire(e):void 0;i&&!s&&n(i.muted);let r;try{r=await t(s)}catch(a){if(!s)throw a;let o=await s.release();throw n(o),Object.assign(a instanceof Error?a:new Error(String(a)),{mutedAutomation:o})}return s&&n(await s.release()),r}var qe=class extends Error{constructor(){super("The rewind was stopped before it wrote anything to the org."),this.name="RewindStopped"}};function O(i){return i.slice(0,15)}function pt(i){let e=cn(i);return e===null?Number.NaN:Date.parse(e)}async function*se(i){try{for await(let e of nt(i))yield e}catch(e){if(e.code!=="ENOENT")throw e}}async function xs(i,e){let t=[];for await(let n of se(i)){let s=we.safeParse(n);if(!s.success)throw new Error(`A line of ${i} names no ${e} link: the plan is not whole.`);t.push(s.data)}return t}async function Ai(i){let e=[];for await(let t of se(i)){let n=Nt.safeParse(t);if(!n.success)throw new Error(`A line of ${i} names no link: the plan is not whole.`);e.push(n.data)}return e}var ji=_({sobjects:le(_({name:X(),keyPrefix:X().nullish()}).loose())}).loose();function Li(i){return{query:e=>i.query(e),queryMore:e=>i.queryMore(e)}}function Ni(i,e){return{rewound:!1,refusal:{code:i,message:e}}}function Gs(i,e){return{rewound:!1,refusal:i,...e.length>0?{alsoRefused:[...e]}:{}}}function Bi(i,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${i} is being taken`:e.operation==="rewind"?`A rewind is writing to ${i}`:e.operation==="undo"?`An undo is writing to ${i}`:e.operation==="empty"?`An emptying of its objects is writing to ${i}`:`SandForge is deleting checkpoints of ${i}`} (process ${e.pid} on ${e.host}): rewind once it has ended. No record was read or written.`}}var Vs=new Set(["noUndoNotAccepted","beforeParentNotAccepted"]),Ci={noUndoNotAccepted:"Salesforce undeletes them only with their parent, which stays",beforeParentNotAccepted:"deleted before a record they point at, which the rewind deletes next, Salesforce cannot bring them back after that"};function Fi(i){return{code:"NO_UNDO",message:`${[...Vs].flatMap(t=>{let n=i.filter(a=>a.reason===t);if(n.length===0)return[];let s=n.reduce((a,o)=>a+o.count,0),r=[...new Set(n.map(a=>a.objectApiName))].join(", ");return[`Undo couldn't bring back ${s} ${r} record(s) this rewind deletes: ${Ci[t]??""}.`]}).join(" ")} Rewind refused; accept that Undo couldn't bring them back to rewind all the same. ${Ie}`}}function Ti(i){let e=i.reduce((n,s)=>n+s.count,0),t=[...new Set(i.map(n=>n.objectApiName))].join(", ");return{code:"RECREATE",message:`${e} ${t} record(s) deleted since are no longer in the recycle bin, or Salesforce keeps them there for good: this rewind makes them again from the checkpoint, with new Ids. Anything outside Salesforce that names their old Ids \u2014 an integration, a link, a report filter \u2014 no longer finds them. Rewind refused; accept that they get new Ids to rewind all the same. ${Ie}`}}function Ei(i,e){return{code:"UNSEEN",message:`${e.map(({objectApiName:n,children:s,records:r})=>`Deleting ${r} ${n} record(s) created since also deletes what ${i} can't see under them in ${s.join(", ")}: Rewind can't count those.`).join(" ")} Rewind refused; accept that it deletes what ${i} can't see to rewind all the same. ${Ie}`}}function Di(i,e){return(i.unseen??[]).flatMap(t=>{let n=e.objects.find(r=>r.objectApiName===t.objectApiName),s=(n?.deleted??0)+(n?.withParentDeleted??0);return s>0?[{...t,records:s}]:[]})}function Mi(i,e){if(e.kind==="org")return[];if(i.access.kind==="org")return["View All Data and Modify All Data"];let t=new Set(i.unread.map(n=>n.objectApiName));return[...e.notHeld].filter(([n])=>!t.has(n)).map(([n,s])=>`${n}: ${s}`)}function Ui(i,e){return{code:"PERMISSIONS",message:`The preview read ${i} with permissions its user no longer has (${e.join("; ")}). Preview the rewind again: it reads the org as the user can now. ${Ie}`}}var $i="accept that it runs to rewind all the same";function zi(i,e,t,n){let s=kt(e,t),r=[...new Set(s.map(d=>d.objectApiName))],a=(t.recreate??[]).length>0?"makes them again, ":"",o=s.length>0?`${ds(s)} flow(s), trigger(s) or rule(s) of ${r.join(", ")} run as the rewind brings records back, ${a}gives them their values back or deletes them`:"what runs as the rewind writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${i}: ${o}. ${jn("rewind",n)}Rewind refused; ${$i}. ${Ie}`}}function Wi(i,e){return{objectsRead:[...i],objects:[],unread:["flows","triggers","processes","workflowRules"].map(t=>({part:t,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Js(i){return i.replace(/the value from before is no longer taken/g,"the checkpoint's value is no longer taken").replace(/left as the run wrote it\b/g,"left as it is").replace(/left as the run wrote them\b/g,"left as they are").replace(/^The values from before the run could not be read:/,"The checkpoint's values could not be read:").replace(/record\(s\) of the run stay, and were not sent\./,"record(s) the rewind would delete stay, and were not sent.")}function me(i,e){i.length<Ks&&!i.includes(e)&&i.push(e)}function ht(i,e,t){let n=t;for(let s of e){if(n<=0)return;let r=Number(i[s]??0),a=Math.min(r,n);i[s]=r-a,n-=a}}function wt(i){return{objectApiName:i,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}function Ys(i,e){i.planned+=e.planned,i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)me(i.reasons,t)}function mt(i){return{objectApiName:i,planned:0,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]}}function Zs(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)me(i.reasons,t)}function Re(i){return{objectApiName:i,planned:0,created:0,refused:0,reasons:[]}}function Xs(i,e){i.planned+=e.planned,i.created+=e.created,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)me(i.reasons,t)}function Qs(i,e){i.planned+=e.planned,i.deleted+=e.deleted,i.alreadyGone+=e.alreadyGone,i.keptChanged+=e.keptChanged,i.keptDependents+=e.keptDependents,i.refused+=e.refused,e.notVisible&&(i.notVisible=(i.notVisible??0)+e.notVisible),e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.heldBy)i.heldBy.includes(t)||i.heldBy.push(t);for(let t of e.unchecked)i.unchecked.includes(t)||i.unchecked.push(t);for(let t of e.reasons)me(i.reasons,t);e.filesLeft&&(i.filesLeft={count:(i.filesLeft?.count??0)+e.filesLeft.count,names:[...i.filesLeft?.names??[],...e.filesLeft.names].slice(0,Ks)})}var xe=class{restored=new Map;undeleted=new Map;recreated=new Map;deleted=new Map;left={restore:new Map,undelete:new Map,recreate:new Map,removal:new Map};heldInPlace=new Map;notInBin=new Map;notAsked=new Map;draftsLeft=new Map;lost=new Map;outOfReach=new Map;links={unlink:ue(),relink:ue(),share:ue()};wrote=!1;cancelled=!1;leftBy(e,t,n){let s=this.left[e].get(t);s||(s=new E,this.left[e].set(t,s));for(let r of n)s.add(r)}mark(e,t,n){let s=this[e].get(t);s||(s=new E,this[e].set(t,s)),s.add(n)}cameBackGiven=new Map;cameBackRestored=0;restore(e,t){let n=this.restored.get(e.objectApiName)??wt(e.objectApiName),s=t?.restored.length??0,r=t?.alreadyGone.length??0;if(Ys(n,{...e,planned:e.planned-s-r,restored:e.restored-s,alreadyGone:e.alreadyGone-r,reasons:e.reasons.map(Js)}),this.restored.set(e.objectApiName,n),s+r===0||!t)return;let a=this.cameBackGiven.get(e.objectApiName)??new E;for(let o of[...t.restored,...t.alreadyGone])a.add(o);this.cameBackGiven.set(e.objectApiName,a),this.cameBackRestored+=s}undelete(e){let t=this.undeleted.get(e.objectApiName)??mt(e.objectApiName);Zs(t,e),this.undeleted.set(e.objectApiName,t)}recreate(e){let t=this.recreated.get(e.objectApiName)??Re(e.objectApiName);Xs(t,e),this.recreated.set(e.objectApiName,t)}delete(e){for(let t of e){let n=this.deleted.get(t.objectApiName),s={...t,reasons:t.reasons.map(Js)};n?Qs(n,s):this.deleted.set(t.objectApiName,structuredClone(s))}}};async function _i(i){let e=new Map;for(let t of i)for(let{objectApiName:n}of t.objects){let s=e.get(n)??new E;for await(let r of t.pages(n))for(let a of r)s.add(a);e.set(n,s)}return e}async function gt(i,e,t){let n=await _i(e),s=new Map,r=new Map;for(let a of i)for(let{objectApiName:o}of a.objects){let d=n.get(o);if(!d)continue;let c=s.get(o)??new E;s.set(o,c);let p=t?.get(o);for await(let f of a.pages(o))for(let u of f)d.has(u)&&p?.has(u)!==!0&&c.add(u)&&r.set(o,(r.get(o)??0)+1)}return r}async function qi(i,e){let t=i.tally,n=new Map([...t.deleted].map(([o,d])=>[o,structuredClone(d)])),s=new Map([...t.restored].map(([o,d])=>[o,structuredClone(d)])),r=new Map([...t.undeleted].map(([o,d])=>[o,structuredClone(d)])),a=new Map([...t.recreated].map(([o,d])=>[o,structuredClone(d)]));if(e){let{tally:o,plan:d}=e,c=await gt([d.giveBack.beforeDeletes,d.giveBack.afterDeletes],[i.plan.giveBack.beforeDeletes,i.plan.giveBack.afterDeletes],t.cameBackGiven);for(let[l,h]of o.restored){let g=s.get(l)??wt(l),w=c.get(l)??0;ht(g,["refused","notReached","notKept","keptChanged","restoredWithout","alreadyGone","restored"],w),g.planned-=Math.min(w,g.planned),Ys(g,h),s.set(l,g)}let p=await gt([d.bringBack],[i.plan.bringBack]);for(let[l,h]of o.undeleted){let g=r.get(l)??mt(l),w=p.get(l)??0;ht(g,["refused","notReached","goneForGood","alreadyBack","undeleted"],w),g.planned-=Math.min(w,g.planned),Zs(g,h),r.set(l,g)}let f=await gt([d.recreate],[i.plan.recreate]);for(let[l,h]of o.recreated){let g=a.get(l)??Re(l),w=f.get(l)??0;ht(g,["refused","notReached","created"],w),g.planned-=Math.min(w,g.planned),Xs(g,h),a.set(l,g)}let u=await gt([d.deletes.spool],[i.plan.deletes.spool]);for(let[l,h]of o.deleted){let g=n.get(l);if(!g){n.set(l,structuredClone(h));continue}let w=u.get(l)??0;ht(g,["refused","keptDependents","keptChanged","notVisible","alreadyGone","deleted"],w),g.planned-=Math.min(w,g.planned),Qs(g,h)}}for(let[o,{reason:d}]of[...t.heldInPlace,...e?.tally.heldInPlace??[]]){let c=s.get(o);c&&me(c.reasons,d)}return{deleted:[...n.values()],restored:[...s.values()],undeleted:[...r.values()],recreated:[...a.values()]}}function xi(i){let e=new Map;return{bodies:e,reader:{lane:()=>i.lane(),tooling:t=>i.tooling(t),calls:()=>i.calls(),describe:async(t,n)=>{let s=await i.describe(t,n);return"body"in s&&e.set(t,s.body),s}}}}function Gi(i){let e=i.objects,t=e.filter(n=>n.deleted+n.withParentDeleted+n.nextPassDeleted>0).map(n=>n.objectApiName);return{bringBack:e.filter(n=>n.broughtBack+n.backWithParent+(n.carriers??0)>0).map(n=>n.objectApiName),recreate:e.filter(n=>n.recreated>0).map(n=>n.objectApiName),giveBack:e.filter(n=>n.givenBackFirst+n.givenBackAfter+n.givenBackNextPass+On(n)>0).map(n=>n.objectApiName),setToDraft:e.filter(n=>In(n)>0).map(n=>n.objectApiName),delete:t}}function Ji(i){let e=Gi(i),{unlink:t,relink:n,share:s,unlinkFrom:r}=i.links,a=(o,d)=>d?[...o??[],ne]:[...o??[]];return{...e,delete:a(e.delete,t.count+r.count>0),recreate:a(e.recreate,n.count>0),giveBack:a(e.giveBack,s.count>0)}}function er(i){let{unlink:e,relink:t,share:n,unlinkFrom:s}=i.links;return e.count+t.count+n.count+s.count}function xt(i){return i.deletes.spool.count+i.bringBack.count+i.recreate.count+i.giveBack.beforeDeletes.count+i.giveBack.afterDeletes.count+er(i)>0}function Ki(i,e){let t=0,n=r=>(t++,r()),s=i.bulkDestroy?.bind(i);return{org:{get version(){return i.version},request:r=>n(()=>i.request(r)),query:(r,a)=>n(()=>i.query(r,a)),queryMore:r=>n(()=>i.queryMore(r)),describeGlobal:()=>n(()=>i.describeGlobal()),serverTime:()=>n(()=>i.serverTime()),userId:()=>n(()=>i.userId()),describe:r=>n(()=>i.describe(r)),update:(r,a)=>n(()=>i.update(r,a)),create:(r,a)=>n(()=>i.create(r,a)),destroy:(r,a)=>n(()=>i.destroy(r,a)),queryDeleted:r=>n(()=>i.queryDeleted(r)),...s?{bulkDestroy:async(r,a,o)=>{let d=1;try{let c=await s(r,a,o);return d=c.requests??1,c}finally{t+=d}}}:{}},undelete:r=>n(()=>e(r)),used:()=>t,add:r=>{t+=r}}}async function ka(i,e){let{checkpoint:t,orgName:n}=e;if(e.reusesPreview&&e.reusesPreview.previewId!==e.previewId)throw new Error("A rewind acts on the preview it names: the one given is another.");let s=Ki(i.org,i.undelete),r,a=await Vn(Li(s.org),{act:"rewind",orgName:n,registered:e.registered,username:e.username,organizationId:t.org.organizationId,customSettings:dn(t)},{userId:async()=>r=await s.org.userId()});if(!a.allowed)return{rewound:!1,refusal:a.refusal};let o=i.store.lock(t.org.organizationId,"rewind",t.checkpointId);if("busy"in o)return{rewound:!1,refusal:Bi(n,o.busy)};let d=new Kt(i,e,s,o.lock,a.queryAllFiles,{grants:a.grants,...r!==void 0?{userId:r}:{}});try{let c=await i.runWriting?.(a.org.id);return c!==void 0?Ni("RUN_WRITING",c):await d.go()}finally{await d.cleanUp(),o.lock.release()}}var Kt=class{constructor(e,t,n,s,r,a){this.deps=e;this.request=t;this.count=n;this.lock=s;this.queryAllFiles=r;this.user=a;this.org=this.clock.watched(n.org),this.signal=e.signal,this.now=e.now??(()=>new Date),this.kept=xi(Ot(this.org,this.signal)),this.picked=t.objects!==void 0?new Set(t.objects):void 0}deps;request;count;lock;queryAllFiles;user;org;signal;now;notes=[];ownDirs=[];ended=!1;kept;global;cascadesOfObject=new Map;lifecycles=new Map;unqueried;noBin=new Set;splitting=Rt();stamps={};stampOf=new Map;spans=[];userId="";owners=new Set;carried=new E;comesBack=new E;before=Number.NaN;clock=new ls(()=>this.now().getTime());access=es;picked;leftFields=new Map;asked;emailsCounted;stopped(){return this.signal?.aborted===!0}progress(e,t,n,s){this.deps.onProgress?.({phase:e,pass:t,percentage:n,step:s})}describeGlobal(){return this.global??=this.org.describeGlobal()}async diff(e){let t=$e("pv",this.now()),n=Ue(this.request.folder,t);return this.ownDirs.push(n),{diff:await ss({checkpoint:this.request.checkpoint,folder:this.request.folder,reader:this.kept.reader,describeGlobal:()=>this.describeGlobal(),previewId:t,readAt:e,queryAllFiles:this.queryAllFiles,access:this.access,...this.signal?{signal:this.signal}:{}}),dir:n}}async plan(e,t,n,s){let r=await is({checkpoint:this.request.checkpoint,pass:e,confirmedDir:t,freshDir:n.dir,readAt:s,ownWriters:rt(this.request.checkpoint.takenBy,this.userId),acceptOutside:this.request.acceptOutside,acceptNoUndo:this.request.acceptNoUndo,acceptRecreate:this.request.acceptRecreate,...e===2&&Object.keys(this.stamps).length>0?{removalStamps:{...this.stamps}}:{},...e===2&&this.spans.length>0?{removalSpans:[...this.spans]}:{},...e===2?{recreated:await Ne.read(this.request.folder)}:{},...this.picked!==void 0?{objects:this.picked,heldRows:as(this.request.checkpoint,this.request.folder)}:{},dir:zs(n.dir,`plan${e}-${Us(4).toString("hex")}`),...this.signal?{signal:this.signal}:{}}),a=new Map;for(let{objectApiName:o}of this.request.checkpoint.objects){let d=new E;for(let c of Hs){let p=c==="inBin"||c==="withParent";for await(let f of se(ye(r.dir,o,c)))typeof f.Id=="string"&&(d.add(f.Id),p&&this.comesBack.add(f.Id))}d.size>0&&a.set(o,d)}return{plan:r,acted:a}}async relationships(){let e=this.global,t=e?new Set((await ln({describeGlobal:()=>e})).keys()):void 0,n=new Set(this.request.checkpoint.objects.map(({objectApiName:r})=>r.toLowerCase()));if(this.request.checkpoint.files!==void 0)for(let r of[ne,an])n.add(r.toLowerCase());let s=new Map;for(let[r,a]of this.kept.bodies)s.set(r,Dn(a,{inCheckpoint:n,...t?{worked:t}:{}}));return s}async go(){let{checkpoint:e,orgName:t,folder:n}=this.request,s=await Un(this.org,t);if(this.stopped())throw new qe;this.progress("reading",1,5,`Reading ${t} again`);let r=this.request.reusesPreview,a,o,d;try{this.access=await ts({grants:this.user.grants,...this.user.userId!==void 0?{userId:this.user.userId}:{},username:this.request.username,checkpoint:e,reader:this.kept.reader});let U=r?Mi(r,this.access):[];if(U.length>0)return{rewound:!1,refusal:Ui(t,U)};if(a=r?r.readAt:await this.org.serverTime(),this.before=Date.parse(a)-li,!Number.isFinite(this.before))throw new Error(`Not a date: ${a}`);o=r?{diff:r,dir:Ue(n,this.request.previewId)}:await this.diff(a),d=await this.plan(1,Ue(n,this.request.previewId),o,a)}catch(U){throw U instanceof Me||this.stopped()?new qe:U}let c=[],p=d.plan.left.filter(U=>Vs.has(U.reason));p.length>0&&c.push(Fi(p));let f=d.plan.left.filter(U=>U.reason==="recreateNotAccepted");f.length>0&&c.push(Ti(f));let u=Di(o.diff,d.plan);u.length>0&&!this.request.acceptUnseen&&c.push(Ei(this.request.username,u));let l=zn("rewind",await this.bringBackFiles(d.plan,o.dir),s.fileStorage?.remaining,t);l&&c.push(l);let h=e.lastRewind,g=h!==void 0&&h.endedAt===void 0&&h.undoneAt===void 0,w=xt(d.plan);if(!w){let[U,...b]=c;if(U)return Gs(U,b);if(!g)return this.wroteNothing(o,d,s.remaining)}let y=Ji(d.plan),m;if(w&&this.deps.readAutomation){let U=[...new Set([...y.bringBack??[],...y.recreate??[],...y.giveBack??[],...y.setToDraft??[],...y.delete??[]])];try{m=await this.deps.readAutomation(U)}catch(b){m=Wi(U,Q(b))}this.count.add(m.requests)}let k=m,L=w?await Oi(this.deps.mute,m,y):{},S="refusal"in L?L:void 0,T="refusal"in L?void 0:L.mute;S&&c.push(S.refusal),L.automation&&(m=L.automation);let F=S?S.plan:T?.plan,P=this.request.acceptEmails===!0,j=w&&k?await Nn({act:"rewind",orgName:t,automation:k,steps:y,...F?{plan:F}:{},accepted:P,mayMute:this.deps.mute===void 0&&this.request.canMute===!0,read:()=>vn(this.org)}):void 0,z=Mn({objects:e.objects,diff:os(o.diff,this.picked),automationRequests:0,relationships:await this.relationships(),...r?{reusesPreview:!0}:{}}),q=Zn(j?.ofRun),x=$n("rewind",{run:this.count.used()-(q.deliverability??0)+z.apiRequests,...q},s,t);w&&x&&c.push(x),this.splitting=Rt(un(s.remaining,this.count.used()+z.apiRequests));let A=Pn(d.plan.objects),B=m?Ln("rewind",Xe(A,m,s.emails),t):void 0;w&&B&&c.push(B);let G=m?An(A,m):void 0;m&&!this.request.acceptAutomation&&(kt(m,y).length>0||sn(m.unread)||G!==void 0)&&c.push(zi(t,m,y,G)),w&&j?.refusal&&c.push(j.refusal);let[v,...N]=c;if(v)return Gs(v,N);if(m&&(this.asked={automation:m,steps:y,accepted:this.request.acceptAutomation},this.emailsCounted={written:[...A],limits:s.emails}),this.stopped())throw new qe;this.userId=await this.org.userId(),this.owners=new Set(rt(e.takenBy,this.userId).map(O));let M=await Fs({folder:n,lock:this.lock,startedAt:a,userId:this.userId,...e.takenBy.automatedProcessUserId!==void 0?{automatedProcessUserId:e.takenBy.automatedProcessUserId}:{},now:this.now}),K;try{let U=await Pi(T,`rewind ${e.checkpointId} ${a}`,R=>{let C=R&&F&&k&&j?Bn({act:"rewind",orgName:t,automation:k,steps:y,plan:F,held:R.outcome,planned:j.ofRun.senders,...j.ofRun.read?{reading:j.ofRun.read.reading}:{},accepted:P}):void 0;return C?Promise.resolve({rewound:!1,refusal:C}):this.passes(M,a,o,d,s.remaining)},R=>{K=R}).catch(R=>{if(St(R))return{rewound:!1,refusal:{code:"MUTE",message:`${R.message} ${Ie}`}};throw R}),b=j?.gate.audit;return U.rewound?{...U,...K?{result:{...U.result,mutedAutomation:K}}:{},...b!==void 0?{deliverability:b}:{}}:U}finally{await M.close()}}async wroteNothing(e,t,n){let s=await this.residualOf(e,e,[t],new xe),r=this.pickedOnly(e.diff.unread),a=await this.scopeOf(e,e);return this.ended=!0,{rewound:!0,result:this.resultOf({rewindId:$e("rw",this.now()),status:s.length>0||r.length>0?"partial":"success",tally:{deleted:[],restored:[],undeleted:[],recreated:[]},residual:s,unread:r,passes:1,leftToday:n,...a?{scope:a}:{}}),notes:this.notes}}async passes(e,t,n,s,r){let{checkpoint:a}=this.request,o=await e.read();this.addStamps(o.rewind.removalStamps??{}),this.spans.push(...o.rewind.removalSpans??[]);for(let{ids:v}of o.did.carried??[])for(let N of v)this.carried.add(N);let d=new Date(Date.parse(o.head.startedAt)+ui).toISOString(),c;await this.deps.store.update(a.checkpointId,v=>(v.lastRewind?.rewindId!==e.rewindId&&(c=v.lastRewind),{...v,lastRewind:{rewindId:e.rewindId,undoUntil:d}}));let p=xt(s.plan),f=p?await this.pass(e,s.plan,n.diff,1):new xe,u=[s],l,h,g=f.cancelled;try{if(!g&&f.wrote){this.progress("reading",2,70,`Reading ${this.request.orgName} again`);let v=await this.diff(await this.org.serverTime()),N=await this.plan(2,s.plan.dir,v,t);if(u.push(N),h=v,xt(N.plan)){let M=await this.pass(e,N.plan,v.diff,2);l={tally:M,plan:N.plan},g=M.cancelled,!g&&M.wrote&&(this.progress("checking",2,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime()))}}else!g&&p?(this.progress("checking",1,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime())):g||(h=n)}catch(v){if(!(v instanceof Me)&&!this.stopped())throw v;g=!0}this.stopped()&&(g=!0);let w=await qi({tally:f,plan:s.plan},l),y=!g&&h?await this.residualOf(h,n,u,f,l?.tally):[],m=!g&&h?this.pickedOnly(h.diff.unread):[],k=await this.scopeOf(g?void 0:h,n),L=w.deleted.some(v=>v.deleted>0)||w.restored.some(v=>v.restored+(v.restoredWithout??0)>0)||w.undeleted.some(v=>v.undeleted>0)||w.recreated.some(v=>v.created>0)||f.cameBackRestored+(l?.tally.cameBackRestored??0)>0,S=g?"cancelled":y.some(v=>v.reason==="changedDuringRewind")?"unstable":y.length>0||m.length>0?L?"partial":"failure":"success",T=this.filesOf(y,[f,...l?[l.tally]:[]]),F=(T?.unlinked??0)+(T?.relinked??0)+(T?.linksUpdated??0),P=L||F>0||(g||e.resumed)&&(await e.facts()).lastWriteAt!==void 0,j=[];if(g&&!P)try{await this.deps.store.update(a.checkpointId,v=>(delete v.lastRewind,c?{...v,lastRewind:c}:v))}catch(v){this.notes.push(`The checkpoint could not be told the rewind stopped before it wrote anything (${Q(v)}): its list may not offer to undo the rewind before it.`)}if(!g){await e.end(),this.ended=!0;let v=h?.diff.readAt??this.now().toISOString(),N=P?{rewindId:e.rewindId,endedAt:v,undoUntil:d}:c;try{await this.deps.store.update(a.checkpointId,M=>(delete M.lastRewind,N?{...M,lastRewind:N}:M))}catch(M){this.notes.push(P?`The checkpoint could not be told when the rewind ended (${Q(M)}): its list may not offer to undo it.`:`The checkpoint could not be told the rewind wrote nothing (${Q(M)}): its list may not offer to undo the rewind before it.`)}try{P&&(j=await Es(this.deps.store,this.lock,{checkpointId:a.checkpointId,rewindId:e.rewindId}))}catch(M){this.notes.push(`The journals of the earlier rewinds of ${this.request.orgName} could not be deleted (${Q(M)}): they stay until their checkpoint goes.`)}}let z=await e.read(),q=this.undoCannotOf(z),x=(z.did.carriers??[]).map(({objectApiName:v,ids:N})=>({objectApiName:v,count:N.length}));if(g){let v=new Set(z.did.deleted.flatMap(({ids:M})=>M.map(O))),N=(z.did.carriers??[]).map(({objectApiName:M,ids:K})=>({objectApiName:M,count:K.filter(U=>!v.has(O(U))).length})).filter(({count:M})=>M>0);N.length>0&&this.notes.push(`Stopped with ${N.map(({objectApiName:M,count:K})=>`${K} ${M}`).join(", ")} record(s) brought back for a moment still in the org: they had taken records of the checkpoint along. Rewind again to delete them, with what came back with them.`)}let A=new Map;for(let v of[f,...l?[l.tally]:[]])for(let[N,M]of v.draftsLeft)A.set(N,[...A.get(N)??[],...M]);let B=[...A].map(([v,N])=>({objectApiName:v,count:N.length,ids:N.slice(0,Ws)})),G={rewound:!0,result:this.resultOf({rewindId:e.rewindId,status:S,tally:w,residual:y,unread:m,passes:l?2:1,leftToday:r,...P?{undo:{until:d,cannot:q}}:{},removedJournals:j,carriers:x,draftsLeft:B,...T?{files:T}:{},...k?{scope:k}:{}}),notes:this.notes};if(L||z.lastWriteAt!==void 0&&(g||e.resumed)){let v=await us({folder:this.request.folder,lock:this.lock,checkpoint:a,result:G.result,startedAt:t,...!g&&h?{endedAt:h.diff.readAt}:{},clock:this.clock});v!==void 0&&this.notes.push(v)}if(!P){await e.close();try{await $s(je(this.request.folder,e.rewindId),{recursive:!0,force:!0})}catch(v){this.notes.push(`The journal of this rewind, which wrote nothing, could not be deleted (${Q(v)}): it stays until a later rewind that writes ends, or its checkpoint goes.`)}}return G}filesOf(e,t){if(this.request.checkpoint.files===void 0)return;let n=r=>t.reduce((a,o)=>a+o.links[r].done,0),s={unlinked:n("unlink"),relinked:n("relink"),linksUpdated:n("share"),linksRefused:e.filter(r=>r.objectApiName===ne&&r.reason==="refused").reduce((r,a)=>r+a.count,0)};return s.unlinked+s.relinked+s.linksUpdated+s.linksRefused>0?s:void 0}async bringBackFiles(e,t){let n=new E;for await(let r of e.bringBack.pages(Ae))for(let a of r)n.add(a);if(n.size===0)return{files:0,bytes:0};let s=new Map;for await(let r of se(st(t,Ae)))typeof r.Id=="string"&&typeof r.ContentSize=="number"&&n.has(r.Id)&&s.set(O(r.Id),r.ContentSize);if(s.size<n.size&&this.request.checkpoint.files!==void 0)for await(let r of Hn(this.request.folder))n.has(r.Id)&&!s.has(O(r.Id))&&r.ContentSize!==null&&s.set(O(r.Id),r.ContentSize);return{files:n.size,bytes:[...s.values()].reduce((r,a)=>r+a,0)}}undoCannotOf(e){let t=new Set(this.request.checkpoint.objects.filter(a=>!a.undeletable).map(a=>a.objectApiName)),n=new Set(e.did.broughtBack.flatMap(({ids:a})=>a.map(O))),s=new Set((e.did.deletedBeforeParent??[]).flatMap(({ids:a})=>a.map(O))),r=[];for(let{objectApiName:a,ids:o}of e.did.deleted){let d=o.map(O).filter(f=>!n.has(f)),c=d.filter(f=>s.has(f)).length,p=t.has(a)?d.length-c:0;p>0&&r.push({objectApiName:a,count:p}),c>0&&r.push({objectApiName:a,count:c,reason:"deletedBeforeParent"})}return r}resultOf(e){let t=this.count.used();return{checkpointId:this.request.checkpoint.checkpointId,rewindId:e.rewindId,status:e.status,deleted:e.tally.deleted,restored:e.tally.restored.filter(n=>n.planned>0),undeleted:e.tally.undeleted.filter(n=>n.planned>0),...e.tally.recreated.length>0?{recreated:e.tally.recreated}:{},...(e.carriers??[]).length>0?{carriers:e.carriers}:{},...(e.draftsLeft??[]).length>0?{draftsLeft:e.draftsLeft}:{},residual:e.residual,...e.unread.length>0?{unread:[...e.unread]}:{},passes:e.passes,...e.undo?{undo:e.undo}:{},...(e.removedJournals??[]).length>0?{removedJournals:e.removedJournals}:{},...e.files?{files:e.files}:{},apiRequests:{used:t,leftToday:Math.max(0,e.leftToday-t)},finishedAt:this.now().toISOString(),...e.scope?{scope:e.scope}:{}}}pickedOnly(e){let t=this.picked;return t===void 0?[...e]:e.filter(n=>t.has(n.objectApiName))}async scopeOf(e,t){let n=this.picked;if(n===void 0)return;let{checkpoint:s}=this.request,r=s.objects.map(({objectApiName:d})=>d).filter(d=>n.has(d)),a=[],o=0;if(e!==void 0){let d=[...s.objects].sort((c,p)=>c.readOrder-p.readOrder);for(let{objectApiName:c}of d){if(n.has(c))continue;let p=new E;for await(let u of se(ye(t.dir,c,"goneForGood")))typeof u.Id=="string"&&p.add(u.Id);let f=new E;for(let u of _s)for await(let l of se(ye(e.dir,c,u)))typeof l.Id!="string"||p.has(l.Id)||f.add(l.Id);f.size>0&&(a.push(c),o+=f.size)}if(s.files!==void 0&&!n.has(Ae)){let c=new E;for(let p of["linkAdded","linkRemoved","linkChanged"])for await(let f of se(Lt(e.dir,p)))typeof f.Id=="string"&&c.add(f.Id);c.size>0&&(a.push(ne),o+=c.size)}}return{objects:r,notRewound:{objects:a,records:o}}}async readLeftFields(e){let t=e.limited?.leftFields;if(!(t===void 0||t.count===0))for await(let n of se(t.file)){if(typeof n.Id!="string"||!Array.isArray(n.fields))continue;let s=this.leftFields.get(O(n.Id))??new Set;for(let r of n.fields)typeof r=="string"&&s.add(r.toLowerCase());this.leftFields.set(O(n.Id),s)}}async cleanUp(){let e=[...this.ownDirs];this.ended&&e.push(Ue(this.request.folder,this.request.previewId));for(let t of e)await $s(t,{recursive:!0,force:!0}).catch(()=>{})}async pass(e,t,n,s){let r=new xe;await this.readLeftFields(t);let a={},o=l=>{Object.assign(a,l),this.addStamps(l)},d=this.allowLists(n),c=new E;for(let{objectApiName:l}of t.giveBack.afterDeletes.objects){let h=t.giveBack.heldBy.find(g=>g.objectApiName===l)?.by;for await(let g of t.giveBack.afterDeletes.pages(l)){for(let w of g)c.add(w);h&&await e.heldInPlace(l,h,g)}}await this.keepFirst(e,t.giveBack.afterDeletes,d);let p=this.request.acceptRecreate?new Be(zs(t.dir,`remake-${Us(4).toString("hex")}`)):void 0,f=async()=>{t.bringBack.count>0&&(this.progress("bringingBack",s,s===1?25:80,"Bringing back what was deleted since"),await this.bringBack(e,t.bringBack,t.carriers,r,o,p));let l=p&&p.objects.length>0?await this.withPlanned(p,t.recreate):t.recreate;if(!r.cancelled&&!this.stopped()&&l.count>0)this.progress("recreating",s,s===1?32:81,"Making again what the recycle bin no longer holds"),await this.recreate(e,l,r);else if(l.count>0){for(let{objectApiName:h,count:g}of l.objects)r.recreate({...Re(h),planned:g,notReached:g});r.cancelled=!0}return!r.cancelled&&!this.stopped()&&t.giveBack.beforeDeletes.count>0&&(this.progress("givingBack",s,s===1?40:82,"Giving back what was changed since"),await this.giveBack(e,t,t.giveBack.beforeDeletes,"before",d,c,r,o)),r.wrote},u;if(t.deletes.spool.count>0){this.progress("deleting",s,s===1?55:85,"Deleting what was created since");for(let{objectApiName:w,file:y}of t.beforeParent){let m=[];for await(let k of se(y)){let L=Array.isArray(k.parents)?k.parents:[];for(let S of L)typeof k.Id=="string"&&typeof S=="string"&&m.push({id:k.Id,parent:S});m.length>=J&&await e.beforeParent(w,m.splice(0))}m.length>0&&await e.beforeParent(w,m)}await e.deleting(t.deletes);let l={...this.stamps,...t.removal.removalStamps},h=[...this.spans,...t.removal.removalSpans??[]].filter((w,y,m)=>m.findIndex(k=>JSON.stringify(k)===JSON.stringify(w))===y),g=(w,y)=>{if(typeof w.Id!="string"||!this.carried.has(w.Id)&&!t.goesAlong.has(w.Id))return!1;let m=pt(w.LastModifiedDate??w.SystemModstamp);return m<=y||m<=(this.stampOf.get(O(w.Id))??Number.NaN)};u=await Ve(this.org,t.deletes,{splitting:this.splitting,runStartedAt:t.removal.runStartedAt,runEndedAt:t.removal.runEndedAt,includeChanged:t.removal.includeChanged,alongAccepted:!0,...Object.keys(l).length>0?{removalStamps:l}:{},...h.length>0?{removalSpans:h}:{},...this.carried.size+t.carriers.size+t.goesAlong.size>0?{goesWithParent:g}:{},...t.alongToDraft.spool.count>0?{alongToDraft:t.alongToDraft}:{},...t.bringBack.count+t.recreate.count+t.giveBack.beforeDeletes.count>0?{sweep:f}:{},...this.deps.onUndeletable?{onUndeletable:this.deps.onUndeletable}:{},...this.signal?{signal:this.signal}:{},onProgress:(w,y,m)=>this.progress("deleting",s,s===1?55:85,`Deleting ${m}: ${w} / ${y}`)}),await e.deleted(u),r.delete(u.objects);for await(let{objectApiName:w,ids:y}of u.left())r.leftBy("removal",w,y);u.cancelled&&(r.cancelled=!0),(u.objects.some(w=>w.deleted>0)||u.span)&&(r.wrote=!0),o(u.stamps),u.span&&this.spans.push(u.span)}else this.stopped()?r.cancelled=!0:await f();return!r.cancelled&&!this.stopped()&&t.giveBack.afterDeletes.count>0&&(this.progress("givingBack",s,s===1?65:88,"Giving back what the deleted records held in place"),await this.giveBack(e,t,t.giveBack.afterDeletes,"after",d,c,r,o)),!r.cancelled&&!this.stopped()&&er(t)>0&&(this.progress("givingBack",s,s===1?68:89,"Putting back the links between files and records"),await this.writeLinks(e,t,r)),this.stopped()&&(r.cancelled=!0),await e.removal({removalStamps:a,removalSpans:u?.span?[u.span]:[]}),r}async writeLinks(e,t,n){let s=()=>this.stopped(),r=async d=>{d!==0&&(n.wrote=!0,await e.wrote())},a=await xs(t.links.unlink.file,"linkAdded"),o=new Set(a.map(d=>O(d.Id)));for(let d of await this.heldLinksOf(t.links.unlinkFrom,t))o.has(O(d.Id))||a.push(d);if(n.links.unlink=await at(this.org,a,{before:d=>e.unlinking(d),after:async({done:d,left:c})=>{c.length>0&&await e.unlinkLeft(c),await r(d.length)},stopped:s}),n.links.unlink.cancelled&&(n.cancelled=!0),!n.cancelled&&t.links.relink.count>0){let d=await Ne.read(this.request.folder);n.links.relink=await dt(this.org,await xs(t.links.relink.file,"linkRemoved"),{after:async({made:c})=>{c.length>0&&await e.relinked(c),await r(c.length)},stopped:s},c=>d.currentOf(O(c))??c),n.links.relink.cancelled&&(n.cancelled=!0)}if(!n.cancelled&&t.links.share.count>0){let d=await Ai(t.links.share.file),c=new Map(d.map(p=>[O(p.Id),p.now]));n.links.share=await ct(this.org,d,{before:p=>e.linksUpdating(p.map(f=>({...f,...c.get(O(f.Id))??{}}))),after:async({done:p,left:f})=>{f.length>0&&await e.linksUpdateLeft(f),await r(p.length)},stopped:s}),n.links.share.cancelled&&(n.cancelled=!0)}}async heldLinksOf(e,t){if(e.count===0)return[];let n=ji.safeParse(await this.describeGlobal()),s=Jn(n.success?n.data.sobjects:[],this.request.checkpoint.objects.map(({objectApiName:a})=>a)),r=[];for await(let a of e.pages(Ae,jt))for(let o of ge(a,jt)){let d=await this.org.query(`SELECT ${Gn.join(", ")} FROM ${ne} WHERE ContentDocumentId IN (${o})`);for(;;){for(let c of d.records){let p=we.safeParse(c);!p.success||Kn(p.data,s)===void 0||t.deletes.has(O(p.data.LinkedEntityId))||r.push(p.data)}if(d.done||!d.nextRecordsUrl)break;d=await this.org.queryMore(d.nextRecordsUrl)}}return r}allowLists(e){let t=new Map(e.objects.map(s=>[s.objectApiName,new Set(s.notCompared.map(r=>r.toLowerCase()))])),n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s]));return s=>{let r=n.get(s),a=t.get(s);return At(s,r?.fields??[],this.request.checkpoint.ignoredFields).filter(o=>!a?.has(o.toLowerCase()))}}async keepFirst(e,t,n){for(let{objectApiName:s}of t.objects){let r=n(s);if(r.length===0)continue;let a=de(s),d=this.request.checkpoint.objects.find(f=>f.objectApiName===s)?.fields.some(f=>f===Ce)===!0,c=["Id",...r.map(de),...d?[Ce]:[]],p=async f=>(await this.org.query(f)).records;try{for await(let f of t.pages(s))for(let u of ge(f,Y)){if(this.stopped())return;let h=(await He(`SELECT ${c.join(", ")} FROM ${a} WHERE Id IN (${u})`,p)).map(g=>tt(s,g,r));h.length>0&&await e.keep(s,h)}}catch(f){if(f instanceof Me)return;this.notes.push(`What the ${s} records given back after the deletions held could not be kept before the rewind wrote (${Q(f)}): Undo gives them back what they held once the deletions were through.`)}}}async cascadesOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let o=await this.kept.reader.describe(e);t="body"in o?o.body:void 0}let n=Pt.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=e===mi&&n.data.fields.some(o=>o.name===Ce),r=(n.data.childRelationships??[]).filter(o=>o.cascadeDelete===!0);if(r.length===0)return[];let a=await this.unqueriedObjects();return r.filter(o=>!a.has(o.childSObject)).map(o=>({child:o.childSObject,field:o.field,...s&&o.childSObject===yi&&o.field==="AccountId"?{persons:!0}:{}}))}unqueriedObjects(){return this.unqueried??=this.describeGlobal().then(e=>{let t=Ri.safeParse(e);return t.success?new Set(t.data.sobjects.filter(n=>n.queryable===!1).map(n=>n.name)):new Set},()=>(this.global=void 0,new Set)),this.unqueried}async insertFieldsOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let d=await this.kept.reader.describe(e);t="body"in d?d.body:void 0}let n=Pt.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=new Map(n.data.fields.map(d=>[d.name.toLowerCase(),d])),r=this.request.checkpoint.objects.find(d=>d.objectApiName===e),a=At(e,r?.fields??[],this.request.checkpoint.ignoredFields).filter(d=>s.get(d.toLowerCase())?.createable===!0),o=a.filter(d=>s.get(d.toLowerCase())?.type==="reference");return{fields:a.map(de),lookups:o}}async withPlanned(e,t){for(let{objectApiName:s}of t.objects)for await(let r of t.pages(s))for(let a of r)await e.add(s,a);let n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s.readOrder]));return e.finish(s=>[...s].sort((r,a)=>(n.get(a.objectApiName)??0)-(n.get(r.objectApiName)??0)))}async recreate(e,t,n){let{checkpoint:s,folder:r}=this.request,a=new E;for(let{objectApiName:u}of t.objects)for await(let l of t.pages(u))for(let h of l)a.add(h);let o=await Ne.read(r),d=new Set,c=u=>o.originalOf(u.slice(0,15))??u.slice(0,15),p=[],f=new Map;for(let{objectApiName:u,count:l}of t.objects){if(n.cancelled||this.stopped()){n.recreate({...Re(u),planned:l,notReached:l}),n.cancelled=!0;continue}let h;try{h=await this.insertFieldsOf(u)}catch(y){if(y instanceof Me){n.cancelled=!0,n.recreate({...Re(u),planned:l,notReached:l});continue}let m=Q(y);n.recreate({...Re(u),planned:l,refused:l,reasons:[m]});for await(let k of t.pages(u))n.leftBy("recreate",u,k);continue}let g=h.fields.find(y=>y.toLowerCase()==="status"),w=g!==void 0?await this.lifecycleOf(u):void 0;for await(let y of t.pages(u,Se)){if(n.cancelled||this.stopped()){n.recreate({...Re(u),planned:y.length,notReached:y.length}),n.cancelled=!0;continue}let m=await et.read(r,s.snapshotId,u,o),k=[],L=await m.chunk(y).batches(s.snapshotId,u,Y);for await(let P of L??[])k.push(...P);let S={...Re(u),planned:y.length},T=new E;for(let P of k)typeof P.Id=="string"&&T.add(P.Id);let F=y.filter(P=>!T.has(P));F.length>0&&(S.refused+=F.length,me(S.reasons,"The checkpoint holds no values of it."),n.leftBy("recreate",u,F));for(let P=0;P<k.length;P+=Y){if(this.stopped()){let G=k.length-P;S.notReached=(S.notReached??0)+G,n.leftBy("recreate",u,k.slice(P).map(v=>String(v.Id))),n.cancelled=!0;break}let j=k.slice(P,P+Y),z=j.map(G=>m.snapshotIdOf(String(G.Id))),q=new Map,x=j.map((G,v)=>{let N=tt(u,G,h.fields);delete N.Id;let M=g!==void 0&&w?on(N[g],w):void 0;g!==void 0&&M!==void 0&&(q.set(v,String(N[g])),N[g]=M),tr(N,this.leftFields.get(O(z[v])));for(let K of h.lookups){let U=N[K];if(typeof U!="string"||U.length<15||!a.has(U))continue;let b=c(U),R=d.has(b)?o.currentOf(b):void 0;if(R!==void 0){N[K]=R;continue}p.push({objectApiName:u,from:z[v].slice(0,15),field:K,target:b}),N[K]=null}return N});await e.recreating(u,z);let A=Gt(await this.org.create(u,x)),B=[];if(j.forEach((G,v)=>{let N=A[v];if(N?.success===!0&&typeof N.id=="string"){B.push({objectApiName:u,from:z[v],to:N.id});let M=q.get(v);if(g!==void 0&&M!==void 0){let K=f.get(u)??[];K.push({id:N.id,field:g,status:M}),f.set(u,K)}return}S.refused++,me(S.reasons,N?.error??"The org gave no answer for it."),n.leftBy("recreate",u,[String(G.Id)])}),B.length>0){await Ne.add(r,B),await e.recreated(u,B.map(G=>({from:G.from,id:G.to}))),await e.wrote(),n.wrote=!0,S.created+=B.length;for(let G of B)d.add(G.from.slice(0,15));o=await Ne.read(r)}}n.recreate(S)}}await this.fillOwed(p,o,d,n),await this.giveStatusesBack(f,n)}lifecycleOf(e){let t=Ke[e];if(t===void 0)return Promise.resolve(void 0);let n=this.lifecycles.get(e);return n||(n=rn(async s=>(await this.org.query(s)).records,t),this.lifecycles.set(e,n)),n}async giveStatusesBack(e,t){let n=[...e];for(let[s,[r,a]]of n.entries())for(let o=0;o<a.length;o+=Y){if(this.stopped()){let f=[[r,a.slice(o)],...n.slice(s+1)];for(let[u,l]of f)l.length!==0&&t.draftsLeft.set(u,[...t.draftsLeft.get(u)??[],...l.map(({id:h})=>h)]);return}let d=a.slice(o,o+Y),c=Gt(await this.org.update(r,d.map(({id:f,field:u,status:l})=>({Id:f,[u]:l})))),p=t.recreated.get(r);d.forEach(({id:f},u)=>{let l=c[u];l?.success!==!0&&(p&&me(p.reasons,`Made again as a draft, but its status was refused: ${l?.error??"the org gave no answer for it."}`),t.leftBy("recreate",r,[f]))})}}async fillOwed(e,t,n,s){let r=new Map;for(let{objectApiName:a,from:o,field:d,target:c}of e){if(!n.has(o)||!n.has(c))continue;let p=t.currentOf(o),f=t.currentOf(c);if(p===void 0||f===void 0)continue;let u=r.get(a)??new Map;u.set(p,{...u.get(p),Id:p,[d]:f}),r.set(a,u)}for(let[a,o]of r){let d=[...o.values()];for(let c=0;c<d.length;c+=Y){if(this.stopped())return;let p=d.slice(c,c+Y),f=Gt(await this.org.update(a,p)),u=s.recreated.get(a);f.forEach((l,h)=>{l.success||(u&&me(u.reasons,`Made again, but a lookup to a record made after it was refused: ${l.error}`),s.leftBy("recreate",a,[String(p[h].Id)]))})}}}async bringBack(e,t,n,s,r,a){let o=Ot(this.org),d=this.makesAgain();for(let{objectApiName:c,count:p}of t.objects){if(s.cancelled||this.stopped()){s.undelete({...mt(c),planned:p,notReached:p}),s.cancelled=!0;continue}let f;try{f=await this.cascadesOf(c)}catch(l){f=[],this.notes.push(`The records that come back with ${c} could not be told (${Q(l)}): Undo may not send those ${c} records back to the recycle bin.`)}let u=async function*(){for await(let l of t.pages(c,Se)){let h=l.filter(w=>n.has(w));h.length>0&&(yield{ids:h,asCarriers:!0});let g=h.length>0?l.filter(w=>!n.has(w)):l;g.length>0&&(yield{ids:g,asCarriers:!1})}};for await(let{ids:l,asCarriers:h}of u()){if(s.cancelled||this.stopped()){s.undelete({...mt(c),planned:l.length,notReached:l.length}),s.cancelled=!0;continue}let g=e.bringingBack([{objectApiName:c,ids:l}],this.count.undelete,{carriers:h}),w=new Map,y=new Map,m=async S=>{let{byParent:T,under:F}=await this.nameChildren(e,o,f,c,S,h),P=await g(S);r(await this.undeleteStamps(c,S,T));for(let j of Si(P,S))w.set(O(j),F.get(O(j))??[]);for(let j of Ii(P,S))y.set(O(j),{id:j,under:F.get(O(j))??[]});return P},k=await zt(this.org,await Ze({org:this.org,plan:[{objectApiName:c,ids:l}],undelete:m,...this.signal?{signal:this.signal}:{}}),[{objectApiName:c,ids:l}],this.notes);await this.notBroughtBack(e,c,y,k.left);let L=await this.settleGone(c,k,w,s,a,d);for(let S of L.objects)s.undelete(S);s.leftBy("undelete",c,L.left),L.wrote&&(s.wrote=!0,await e.wrote()),L.cancelled&&(s.cancelled=!0)}}}makesAgain(){let e=new Map,{checkpoint:t,folder:n}=this.request;return async(s,r)=>{let a=t.objects.find(d=>d.objectApiName===s);if(!a||!ns(a))return!1;let o=e.get(s);return o||(o=et.read(n,t.snapshotId,s).catch(()=>{}),e.set(s,o)),(await o)?.has(r)===!0}}remakeUnaskedWords(e){let t=this.asked;if(!t)return;let n=[...new Set(e)],s=cs(t.automation,t.steps,n,t.accepted);if(!(s.fired.length===0&&!s.blind))return wi(this.request.orgName,n,s)}remakeEmailsWords(e){let t=this.emailsCounted,n=this.asked;if(!t||!n)return;let s=e.flatMap(c=>[{objectApiName:c,write:"insert",records:1},...Ke[c]!==void 0?[{objectApiName:c,write:"update",records:1}]:[]]),r=Xe(t.written,n.automation,t.limits),o=Xe([...t.written,...s],n.automation,t.limits).filter(c=>c.verdict==="exceeds");if(o.length===0){t.written.push(...s);return}return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and making it again sends ${o.map(c=>{let p=c.emails-(r.find(f=>f.limit===c.limit)?.emails??0);return`${It(p,c.limit)} more than the ${It(c.emails-p,c.limit)} it counted, past the ${c.remaining??0} of ${c.max??0} ${this.request.orgName} has left today`}).join("; ")}. Rewind again: its preview counts it to make again, and its emails.`}async settleGone(e,t,n,s,r,a){let o=t.left.filter(h=>n.has(O(h)));if(o.length===0)return t;let d=new Set,c=0,p=0,f,u=h=>this.access.heldAs(h)==="parent";await this.keepNotInBin(e,o);for(let h of o){if(u(e)){p++,s.mark("outOfReach",e,h);for(let m of n.get(O(h))??[])s.mark("outOfReach",m.objectApiName,m.id);continue}if(!await a(e,h)){s.mark("lost",e,h);continue}let g=[];for(let m of n.get(O(h))??[])u(m.objectApiName)?s.mark("outOfReach",m.objectApiName,m.id):await a(m.objectApiName,m.id)&&g.push(m);let w=[e,...g.map(m=>m.objectApiName)],y=r?this.remakeUnaskedWords(w)??this.remakeEmailsWords(w):void 0;if(r&&y===void 0){await r.add(e,h);for(let m of g)await r.add(m.objectApiName,m.id);d.add(O(h));continue}if(y!==void 0){f=y,s.notAsked.set(O(h),y);for(let m of g)s.notAsked.set(O(m.id),y);continue}c++,s.mark("notInBin",e,h);for(let m of g)s.mark("notInBin",m.objectApiName,m.id)}let l=o.length-d.size;return{...t,objects:t.objects.map(h=>{if(h.objectApiName!==e)return h;let g=l===0?h.reasons.filter(w=>!_e.test(w)):c>0?h.reasons.map(w=>_e.test(w)?gi:w):f!==void 0?h.reasons.map(w=>_e.test(w)?f??w:w):p>0?h.reasons.map(w=>_e.test(w)?Jt:w):h.reasons;return{...h,planned:h.planned-d.size,refused:Math.max(0,h.refused-d.size),reasons:g}}),left:t.left.filter(h=>!d.has(O(h)))}}async notBroughtBack(e,t,n,s){if(n.size===0)return;let r=new Set(s.map(O)),a=new Map,o=(d,c)=>{let p=a.get(d)??[];p.push(c),a.set(d,p)};for(let[d,{id:c,under:p}]of n)if(r.has(d)){o(t,c);for(let f of p)o(f.objectApiName,f.id)}try{for(let[d,c]of a)await e.bringBackLeft(d,c)}catch(d){this.notes.push(`Which ${t} records ${this.request.orgName} refused to bring back could not be kept in the rewind\u2019s journal (${Q(d)}): its undo may count them among what it sends back to the recycle bin.`)}}async keepNotInBin(e,t){try{await Tn.add(this.request.folder,e,t)}catch(n){this.notes.push(`The ${e} records ${this.request.orgName} answered are no longer in the recycle bin could not be kept with the checkpoint (${Q(n)}): a later preview counts them to bring back again.`)}}async nameChildren(e,t,n,s,r,a=!1){let o=new Map,d=new Map,c=new Set(r.map(O)),p=new Map(r.map(h=>[O(h),O(h)])),f=new Map,u=new Map,l=[{objectApiName:s,cascades:n,ids:[...r]}];for(;l.length>0;){let h=new Map;for(let{objectApiName:g,cascades:w,ids:y}of l)for(let m of ge(y,Y)){let k=w.filter(({child:T})=>!this.noBin.has(T));if(k.length===0)break;let L=k.map(({child:T,field:F,persons:P})=>({objectApiName:T,soql:`SELECT Id, ${de(F)}${P?`, ${Ce}`:""}${qt(T)?", IsDeleted":""} FROM ${de(T)} WHERE ${F} IN (${m})${qt(T)?"":" AND IsDeleted = true"}`,scanAll:!0}));(await qn(t,L,(T,F)=>{let{child:P,field:j,persons:z}=k[T];for(let q of F){let x=q[j];if(typeof q.Id!="string"||typeof x!="string"||qt(P)&&q.IsDeleted!==!0)continue;let A=O(q.Id),B=p.get(O(x));B===void 0||c.has(A)||(c.add(A),p.set(A,B),o.set(B,[...o.get(B)??[],q.Id]),!(z&&q[Ce]===!0)&&(d.set(B,[...d.get(B)??[],{objectApiName:P,id:q.Id}]),f.set(P,[...f.get(P)??[],q.Id]),u.set(P,[...u.get(P)??[],a?O(x):B]),h.set(P,[...h.get(P)??[],q.Id])))}})).forEach((T,F)=>{if(!T.read){if(vi.test(T.reason)){this.noBin.add(k[F].child);return}this.notes.push(`The ${k[F].child} records that come back with ${g} could not be read (${T.reason}): Undo may not send those ${s} records back to the recycle bin.`)}})}l=[];for(let[g,w]of h)l.push({objectApiName:g,cascades:await this.cascadesUnder(g),ids:w})}for(let[h,g]of f)await e.withParent(h,g,u.get(h),{carriers:a});if(a)for(let h of o.values())for(let g of h)this.carried.add(g);return{byParent:o,under:d}}cascadesUnder(e){let t=this.cascadesOfObject.get(e);return t||(t=this.cascadesOf(e).catch(n=>(this.notes.push(`The records that come back with ${e} records could not be told (${Q(n)}): Undo may not send them back to the recycle bin.`),[])),this.cascadesOfObject.set(e,t)),t}async undeleteStamps(e,t,n){let s={},r=de(e);try{for(let a of ge(t,Y)){let o=await this.org.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${a})`);for(let d of o.records)if(!(typeof d.Id!="string"||typeof d.LastModifiedDate!="string")){s[d.Id]=d.LastModifiedDate;for(let c of n.get(O(d.Id))??[])s[c]=d.LastModifiedDate}}}catch(a){this.notes.push(`What bringing back ${e} records left on them could not be read (${Q(a)}): the second pass may read them as changed by someone else.`)}return s}async giveBack(e,t,n,s,r,a,o,d){let{checkpoint:c,folder:p}=this.request;for(let{objectApiName:f,count:u}of n.objects){if(o.cancelled||this.stopped()){o.restore({...wt(f),planned:u,notReached:u}),o.cancelled=!0;continue}let l=r(f),h=await et.read(p,c.snapshotId,f),g=t.giveBack.heldBy.find(y=>y.objectApiName===f),w=l.find(y=>y.toLowerCase()==="status");for await(let y of n.pages(f,Se)){let m=y.filter(j=>!h.retired(j));if(m.length===0)continue;if(o.cancelled||this.stopped()){o.restore({...wt(f),planned:m.length,notReached:m.length}),o.cancelled=!0;continue}let k=async(j,z,q,x)=>{let A=await Ye({org:this.org,plan:[{objectApiName:f,backup:c.snapshotId,ids:[...j]}],backups:Hi(h.chunk(j),f,z,q,this.leftFields),fields:{[f]:[...z]},changedAfter:t.restore.changedAfter,ownWriters:rt(c.takenBy,this.userId),includeChanged:!1,stamps:{...t.restore.stamps,...this.stamps},keep:e.keep,stampsFor:()=>!0,...x?{counted:x}:{},...this.signal?{signal:this.signal}:{}});return d(A.stamps),A.wrote&&(o.wrote=!0,await e.wrote()),A.cancelled&&(o.cancelled=!0),A};if(f==="Order"&&w!==void 0&&(await k(m,[w],j=>j[w]==="Draft"),o.cancelled))continue;let L=s==="before"?m.filter(j=>a.has(j)):[];if(L.length>0&&(await k(L,l),o.cancelled))continue;let S=L.length>0?m.filter(j=>!a.has(j)):m;if(S.length===0)continue;let T={restored:[],alreadyGone:[]},F=await k(S,l,void 0,(j,z)=>{this.comesBack.has(j)&&T[z].push(j)});for(let j of F.objects)o.restore(j,T);o.leftBy("restore",f,F.left);let P=F.objects[0];if(s==="after"&&g&&P&&P.refused+(P.restoredWithout??0)>0){let j=o.heldInPlace.get(f)??{reason:rs(f,g.by),ids:new E};for(let z of F.left)j.ids.add(z);o.heldInPlace.set(f,j)}}}}async residualOf(e,t,n,s,r){let a=new Map,o=(u,l,h,g={})=>{let w=`${u}\0${l}\0${g.by??""}\0${g.message??""}`,y=a.get(w);y||(y={objectApiName:u,reason:l,...g.by!==void 0?{by:g.by}:{},count:0,ids:[],...g.message!==void 0?{message:g.message}:{}},a.set(w,y)),y.count++,y.ids.length<Ws&&y.ids.push(h)},d=n[n.length-1],c=r?[r,s]:[s],p=[...this.request.checkpoint.objects].sort((u,l)=>u.readOrder-l.readOrder),f=await this.throughCarriers(e.dir);for(let u of p){let l=u.objectApiName;if(this.picked!==void 0&&!this.picked.has(l))continue;let h=[];for(let m of _s)for await(let k of se(ye(e.dir,l,m)))typeof k.Id=="string"&&(m==="comesBackWithParent"&&f.has(k.Id)||h.push({cls:m,id:k.Id}));if(h.length===0)continue;let g=await this.whoChanged(e.dir,l,h),w=this.keptOf(d,l),y=new E;for await(let m of se(ye(t.dir,l,"goneForGood")))typeof m.Id=="string"&&y.add(m.Id);for(let{cls:m,id:k}of h){if(y.has(k))continue;if(m==="goneForGood"){o(l,"goneForGood",k);continue}let L=pi[m];if(L!==void 0){o(l,"kept",k,{message:L});continue}let S=g.get(O(k)),T=pt(S?.at)>this.before,F=T&&this.isOwn(k,S);if(T&&!F){o(l,"changedDuringRewind",k,S?.by?{by:S.by}:{});continue}let P=n.map(({plan:A})=>A.limited?.why.get(O(k))).find(A=>A!==void 0);if(P!==void 0){o(l,"kept",k,{message:P});continue}if(!n.some(({acted:A})=>A.get(l)?.has(k)===!0)){o(l,F?"automation":"changedSincePreview",k);continue}let z=w(k,m);if(z!==void 0){o(l,"kept",k,{message:z});continue}if(m==="withParent"&&c.some(A=>A.left.restore.get(l)?.has(k)===!0)){o(l,"refused",k,{message:this.refusalOf(c,"restore",l,k)});continue}if(F){o(l,"automation",k);continue}if(ft[m]==="undelete"||m==="toRecreate"){if(c.some(B=>B.outOfReach.get(l)?.has(k)===!0)){o(l,"kept",k,{message:Jt});continue}if(c.some(B=>B.lost.get(l)?.has(k)===!0)){o(l,"goneForGood",k);continue}let A=c.map(B=>B.notAsked.get(O(k))).find(B=>B!==void 0);if(A!==void 0){o(l,"kept",k,{message:A});continue}if(c.some(B=>B.notInBin.get(l)?.has(k)===!0)){o(l,"notInBin",k);continue}}let q=ft[m]==="undelete"&&c.some(A=>A.left.recreate.get(l)?.has(k)===!0)?"recreate":ft[m],x=q==="removal"?this.keptForDependents(c,l,k):void 0;if(x!==void 0){o(l,"kept",k,{message:hi(x)});continue}o(l,"refused",k,{message:q?this.refusalOf(c,q,l,k):_t})}}return await this.linksStillDiffering(e.dir,n,c,o),[...a.values()]}async linksStillDiffering(e,t,n,s){if(this.request.checkpoint.files===void 0||this.picked!==void 0&&!this.picked.has(Ae))return;let r=d=>`${O(d.ContentDocumentId)}:${O(d.LinkedEntityId)}`,a=new Set;for(let{plan:d}of t)for(let{file:c}of[d.links.unlink,d.links.relink,d.links.share])for await(let p of se(c)){let f=we.safeParse(p);f.success&&a.add(r(f.data))}let o=new Map;for(let d of[...n].reverse())for(let c of["unlink","relink","share"])for(let{id:p,reason:f}of d.links[c].left)o.set(O(p),f);for(let d of["linkAdded","linkRemoved","linkChanged"])for await(let c of se(Lt(e,d))){let p=we.safeParse(c);if(!p.success)continue;let f=p.data,u=d==="linkChanged"?Nt.safeParse(c):void 0;if(u?.success===!0&&u.data.now.Visibility===f.Visibility&&u.data.now.ShareType!==f.ShareType&&f.LinkedEntityId.startsWith(ki)){s(ne,"kept",f.Id,{message:it});continue}if(d==="linkAdded"&&f.LinkedEntityId.startsWith(bi)){s(ne,"kept",f.Id,{message:Bt});continue}if(!a.has(r(f))){s(ne,"changedSincePreview",f.Id);continue}s(ne,"refused",f.Id,{message:o.get(O(f.Id))??_t})}}async throughCarriers(e){let t=new E,n=this.request.checkpoint.objects;for(let{objectApiName:s}of n)for await(let r of se(ye(e,s,"carrier")))typeof r.Id=="string"&&t.add(r.Id);for(let s=t.size>0;s;){s=!1;for(let r of n){let a=new E;for await(let o of se(ye(e,r.objectApiName,"comesBackWithParent")))typeof o.Id=="string"&&a.add(o.Id);if(a.size!==0)for await(let o of se(st(e,r.objectApiName)))typeof o.Id!="string"||!a.has(o.Id)||t.has(o.Id)||r.cascadeParents.some(d=>t.has(o[d]))&&(t.add(o.Id),s=!0)}}return t}async whoChanged(e,t,n){let s=new Set(n.map(({id:a})=>O(a))),r=new Map;for(let a of[xn(e,t),st(e,t)])for await(let o of se(a))typeof o.Id!="string"||!s.has(O(o.Id))||r.set(O(o.Id),{...typeof o.LastModifiedById=="string"?{by:o.LastModifiedById}:{},...typeof o.LastModifiedDate=="string"?{at:o.LastModifiedDate}:{}});return r}isOwn(e,t){return t?.by!==void 0&&this.owners.has(O(t.by))?!0:pt(t?.at)<=(this.stampOf.get(O(e))??Number.NaN)}addStamps(e){for(let[t,n]of Object.entries(e)){this.stamps[t]=n;let s=pt(n),r=O(t);Number.isFinite(s)&&!((this.stampOf.get(r)??Number.NEGATIVE_INFINITY)>s)&&this.stampOf.set(r,s)}}keptOf(e,t){let n=e.plan.left.filter(s=>s.objectApiName===t&&Wt[s.reason]!==void 0);return(s,r)=>{if(n.length===0)return;let a=n.find(o=>o.ids.some(d=>O(d)===O(s)));if(a)return Wt[a.reason];if(ft[r]==="removal"&&!e.plan.deletes.has(O(s)))return Wt[n[0].reason]}}keptForDependents(e,t,n){for(let s of e){if(s.left.removal.get(t)?.has(n)!==!0)continue;let r=s.deleted.get(t);return r&&r.refused===0&&r.keptDependents>0&&r.heldBy.length>0?r.heldBy:void 0}}refusalOf(e,t,n,s){let r=t==="restore"?e.map(a=>a.heldInPlace.get(n)).find(a=>a?.ids.has(s)===!0)?.reason:void 0;for(let a of e){if(a.left[t].get(n)?.has(s)!==!0)continue;let d=(t==="restore"?a.restored.get(n)?.reasons:t==="undelete"?a.undeleted.get(n)?.reasons:t==="recreate"?a.recreated.get(n)?.reasons:a.deleted.get(n)?.reasons)?.find(c=>c!==r);if(d!==void 0)return r?`${d} \u2014 ${r}`:d}return r??_t}};function Hi(i,e,t,n,s){return{batches:async(r,a,o)=>{let d=await i.batches(r,a,o);return d?{async*[Symbol.asyncIterator](){for await(let c of d){let p=c.filter(f=>n?.(f)??!0).map(f=>tr(tt(e,f,t),typeof f.Id=="string"?s?.get(O(f.Id)):void 0));p.length>0&&(yield p)}}}:null}}}function tr(i,e){if(e===void 0)return i;for(let t of Object.keys(i))t!=="Id"&&e.has(t.toLowerCase())&&delete i[t];return i}var Vi=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function Gt(i){return(Array.isArray(i)?i:[i]).map(t=>{let n=Vi.safeParse(t);if(!n.success)return{success:!1};let{success:s,id:r,errors:a}=n.data,o=(a??[]).map(d=>typeof d=="string"?d:[d.statusCode,d.message].filter(c=>c).join(": ")).filter(d=>d!=="");return{success:s,...typeof r=="string"?{id:r}:{},...o.length>0?{error:o.join("; ")}:{}}})}export{wo as a,mo as b,yo as c,Fo as d,Ws as e,fi as f,Jt as g,gi as h,wi as i,ya as j,Oi as k,Pi as l,qe as m,$i as n,Wi as o,Js as p,Ki as q,ka as r};
|