sandforge 1.80.0 → 1.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/bin/sandforge-pipeline.mjs +12 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/chunk-2JZGCCPG.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
- package/lib/chunk-3C2ZZIFN.mjs +7 -0
- package/lib/chunk-3CX7GPCR.mjs +7 -0
- package/lib/chunk-3HEMJTAP.mjs +925 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
- package/lib/chunk-3XG25GTF.mjs +7 -0
- package/lib/chunk-42BFLWHR.mjs +7 -0
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/chunk-5K2I2DMP.mjs +11 -0
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/chunk-6KP6WETK.mjs +9 -0
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/chunk-7PY3VQP3.mjs +7 -0
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/chunk-7WSLT5VX.mjs +8 -0
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/chunk-AUS6NFLZ.mjs +8 -0
- package/lib/chunk-BMTNTBBM.mjs +7 -0
- package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/chunk-CCEH7L53.mjs +7 -0
- package/lib/chunk-CELEBWEZ.mjs +7 -0
- package/lib/chunk-CV47FDQW.mjs +7 -0
- package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/chunk-DBBPDSFN.mjs +7 -0
- package/lib/chunk-DIL62SUN.mjs +7 -0
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/chunk-FOIWWK7G.mjs +156 -0
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/chunk-G2JR3F63.mjs +7 -0
- package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/chunk-HIHCYMSL.mjs +7 -0
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/chunk-IRZJU2PG.mjs +22 -0
- package/lib/chunk-ISSP2FZ5.mjs +7 -0
- package/lib/chunk-IVZJSDJD.mjs +7 -0
- package/lib/chunk-J24TIGSI.mjs +10 -0
- package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
- package/lib/chunk-JFNLKHY6.mjs +8 -0
- package/lib/chunk-JH27IKCO.mjs +9 -0
- package/lib/chunk-JJITOWZK.mjs +7 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/chunk-JQZTMFO7.mjs +7 -0
- package/lib/chunk-KIMQQ6JQ.mjs +7 -0
- package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/chunk-KP5G6FUC.mjs +7 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/chunk-LXDSRP2W.mjs +7 -0
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
- package/lib/chunk-MUEQRIK7.mjs +9 -0
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/chunk-O2PUGRNW.mjs +10 -0
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-P55MKIZX.mjs +37 -0
- package/lib/chunk-P63WJMXQ.mjs +7 -0
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PE435FVH.mjs +15 -0
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/chunk-PWVDNN2C.mjs +7 -0
- package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/chunk-SAMWHL22.mjs +13 -0
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/chunk-SZGGFST2.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/chunk-XK5W7BVE.mjs +7 -0
- package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/chunk-XU25YA46.mjs +9 -0
- package/lib/chunk-XZISAZA6.mjs +7 -0
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/chunk-YAIIRFKJ.mjs +8 -0
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/chunk-YMDFF657.mjs +10 -0
- package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/chunk-ZUOPC4W2.mjs +7 -0
- package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +186 -140
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +157 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +18 -3
- package/lib/chunk-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MFG4MUIO.mjs +0 -9
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QR3WELJQ.mjs +0 -7
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
package/lib/chunk-IFETCRWE.mjs
DELETED
|
@@ -1,10 +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{a as B,b as J}from"./chunk-TYYOBZMU.mjs";import{a as S}from"./chunk-GGD7ON3M.mjs";import{Ca as b,ta as h,ua as E,va as U,wa as D}from"./chunk-TTFDUKUS.mjs";import{b as l,l as m,s as C,u as H,v as K}from"./chunk-7EANH5PY.mjs";import{randomBytes as L}from"node:crypto";import{mkdirSync as we,statSync as Y}from"node:fs";import{mkdir as w,open as ye,readFile as A,readdir as _,rename as Oe,rm as f,rmdir as Fe,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as xe}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Ie,gzip as Ce}from"node:zlib";import{createHash as ke}from"node:crypto";var G=16,Z=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:C(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return ke("sha256").update(n).digest("hex")}function me(n){return JSON.stringify([n.name.toLowerCase(),n.type,n.createable===!0,n.updateable===!0,n.nillable===!0,[...n.referenceTo??[]].sort(),n.encrypted===!0])}function an(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:me(t)})).sort((t,r)=>t.key<r.key?-1:t.key>r.key?1:0);return{digest:W(e.map(({line:t})=>t).join(`
|
|
8
|
-
`)),fields:Object.fromEntries(e.map(({name:t,line:r})=>[t,W(r).slice(0,G)]))}}function dn(n,e){let t={added:[],removed:[],changed:[]};if(n.digest===e.digest)return t;let r=new Map(Object.entries(n.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}])),i=new Map(Object.entries(e.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}]));for(let[o,{name:s,print:a}]of i){let p=r.get(o);p===void 0?t.added.push(s):p.print!==a&&t.changed.push(s)}for(let[o,{name:s}]of r)i.has(o)||t.removed.push(s);return t.added.sort(),t.removed.sort(),t.changed.sort(),t}var g=448,be=384,Pe=30,ee=3,Ee=15,ne=1440*6e4,I=1440*6e4,De=Q(Ce),Se=Q(Ie),T="checkpoint.json",ve="fingerprints.json.gz",ze="fingerprints.json",Re="snapshots.json",te=/^[A-Za-z][A-Za-z0-9_]*$/;function xn(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?xe(e):c(V(),".sandforge");return c(t,"checkpoints")}function Le(n=V()){return c(n,".sandforge","locks")}function k(n){let e=D.safeParse(n).success?S(n.slice(0,15)):void 0;if(e===void 0)throw new d("invalid","Not an Organization Id");return e}function Ae(n){return n.length===18&&D.safeParse(n).success&&S(n.slice(0,15))===n}function v(n,e,t){return re(c(n,e,t),e,t)}function re(n,e,t){return{organizationId:e,checkpointId:t,dir:n,checkpointFile:c(n,T),fingerprintsFile:c(n,ve),plainFingerprintsFile:c(n,ze),snapshotsFile:c(n,Re),indexDir:c(n,"index"),binDir:c(n,"bin"),filesDir:c(n,"files"),previewsDir:c(n,"previews"),rewindsDir:c(n,"rewinds")}}function ie(n){if(!te.test(n)||n.length>80)throw new d("invalid","Not a Salesforce API name");return n}function In(n,e){return c(n.indexDir,`${ie(e)}.idx`)}function Cn(n){return c(n.indexDir,"recreated.ndjson")}function bn(n){return c(n.indexDir,"notInBin.ndjson")}function Pn(n,e){return c(n.binDir,`${ie(e)}.ids`)}function En(n){return c(n.filesDir,"documents.ndjson")}function Dn(n){return c(n.filesDir,"links.ndjson")}var $e=[/^checkpoint\.json$/,/^fingerprints\.json(?:\.gz)?$/,/^snapshots\.json$/,/^backups\/[A-Za-z0-9_-]{1,200}__[A-Za-z][A-Za-z0-9_]{0,79}\.ndjson(?:\.gz)?$/,/^bin\/[A-Za-z][A-Za-z0-9_]{0,79}\.ids$/,/^files\/(?:links|documents)\.ndjson(?:\.gz)?$/,/^index\/(?:recreated|notInBin)\.ndjson$/],je=["","backups","bin","files","index"],Sn=T;function oe(n){return $e.some(e=>e.test(n))}async function vn(n){let e=[];for(let t of je){let r;try{r=await _(c(n.dir,t),{withFileTypes:!0})}catch(i){if(F(i)==="ENOENT"||F(i)==="ENOTDIR")continue;throw i}for(let i of r){let o=t===""?i.name:`${t}/${i.name}`;if(!i.isFile()||!oe(o))continue;let s=c(n.dir,t,i.name);e.push({path:o,file:s,bytes:(await x(s)).size})}}return e.sort((t,r)=>he(t.path,r.path))}function zn(n,e){if(!oe(e))throw new d("invalid","Not a file a checkpoint holds");return c(n,...e.split("/"))}function Rn(n,e){return c(n.previewsDir,O(E,e))}function M(n,e){return c(n.rewindsDir,O(U,e))}function O(n,e){let t=n.safeParse(e);if(!t.success)throw new d("invalid","Not an id of this store");return t.data}async function X(n){await w(n,{recursive:!0,mode:g})}var q="abcdefghijklmnopqrstuvwxyz0123456789";function Ln(n,e=new Date){let t=e.toISOString(),r=`${t.slice(0,4)}${t.slice(5,7)}${t.slice(8,10)}`,i=`${t.slice(11,13)}${t.slice(14,16)}${t.slice(17,19)}`,o=Array.from(L(4),s=>q[s%q.length]).join("");return`${n}-${r}-${i}-${o}`}function Ne(n,e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Not a number of days: ${e}`);return e===0?null:new Date(n.getTime()+e*I).toISOString()}function se(n,e){return n.expiresAt!==null&&Date.parse(n.expiresAt)<=e}function _e(n,e){if(n.expiresAt===null)return!1;let t=Date.parse(n.expiresAt);return t>e&&t-e<=ee*I}function Te(n,e){let t=e-Ee*I;return Date.parse(n.readFrom)<t?new Date(t).toISOString():void 0}function Me(n,e){let t=ce(n);return t!==void 0&&t<=e}function ce(n){let e=n.scratchExpiresAt;if(e===void 0)return;let t=Date.parse(e);if(Number.isFinite(t))return/^\d{4}-\d{2}-\d{2}$/.test(e)?t+I:t}function He(n,e){let t=ce(n);return t!==void 0&&t>e&&t-e<=ee*I}var d=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointStoreError"}code};function An(n,e,t){let r=n.detail!==void 0?` (${n.detail})`:"";if(n.path===e)switch(n.reason){case"otherOwner":return`another user of this machine owns it, and could read and replace the checkpoints in it. ${t} names a folder of your own.`;case"notAFolder":return`it is a file, not a folder. ${t} names a folder for them, or move the file away.`;case"cannotMake":return`it could not be made${r}. ${t} names a folder this user can write.`}let i="the folder of every org\u2019s lock, whatever the store";switch(n.reason){case"otherOwner":return`${i}, is owned by another user of this machine: run as its owner, or remove it.`;case"notAFolder":return`${i}, is a file, not a folder: move the file away.`;case"cannotMake":return`${i}, could not be made${r}: make it a folder this user can write.`}}var ae=m({version:K(1),objects:C(l().regex(te).max(80),Z)});async function Ke(n,e){let t;try{t=JSON.parse(await Be(n))}catch{throw new d("damaged","The checkpoint\u2019s field prints cannot be read")}let r=ae.safeParse(t);if(!r.success)throw new d("damaged","The checkpoint\u2019s field prints do not parse");let i=new Map(Object.entries(r.data.objects));for(let o of e)if(i.get(o.objectApiName)?.digest!==o.fingerprint)throw new d("damaged",`The field prints of ${o.objectApiName} are not the checkpoint\u2019s`);return i}async function Ue(n){let e=ae.safeParse({version:1,objects:n});if(!e.success)throw new d("invalid",`Not field prints: ${e.error.message}`);return De(`${JSON.stringify(e.data)}
|
|
9
|
-
`)}async function Be(n){let e;try{e=await A(n.fingerprintsFile)}catch(t){if(t.code!=="ENOENT")throw t;return A(n.plainFingerprintsFile,"utf8")}return(await Se(e)).toString("utf8")}function $n(n){let e=n.uid??(()=>process.getuid?.()),t=n.locksDir??Le();for(let r of[n.root,t]){let i=Je(r,e);if(i!==void 0)return{refusal:i}}return{store:new $({...n,locksDir:t})}}function Je(n,e){try{let t=Y(n,{throwIfNoEntry:!1});if(t!==void 0&&!t.isDirectory())return{reason:"notAFolder",path:n};we(n,{recursive:!0,mode:g});let r=e();return r!==void 0&&Y(n).uid!==r?{reason:"otherOwner",path:n}:void 0}catch(t){return{reason:"cannotMake",path:n,detail:sn(t)}}}var $=class{root;locksDir;renameFile;lockOptions;changes=new Map;constructor(e){this.root=e.root,this.locksDir=e.locksDir,this.renameFile=e.rename??((t,r)=>Oe(t,r)),this.lockOptions={...e.lockSelf?{self:e.lockSelf}:{},...e.lockChecks?{checks:e.lockChecks}:{}}}folderOf(e,t){return v(this.root,k(e),O(h,t))}async create(e,t){let r=this.folderOf(e,t);await X(c(this.root,r.organizationId));try{await w(r.dir,{mode:g})}catch(i){throw F(i)==="EEXIST"?new d("exists",`A checkpoint ${t} is kept already`):i}return await w(r.indexDir,{mode:g}),await w(r.binDir,{mode:g}),r}async write(e){let t=z(e),r=this.folderOf(t.org.organizationId,t.checkpointId);await this.writeWhole(r.checkpointFile,j(t))}async writeFingerprints(e,t){await this.writeWhole(e.fingerprintsFile,await Ue(t))}async readFingerprints(e,t){return Ke(e,t.objects)}async checkpointsOf(e){return this.readsOf(k(e))}async read(e){let t=O(h,e);for(let r of await this.organizationKeys()){let i=v(this.root,r,t);if(await y(i.dir))return R(i)}}async update(e,t){let r=async()=>{let a=await this.read(e);if(a===void 0)throw new d("notFound",`No checkpoint ${e} is kept`);if(a.checkpoint===void 0)throw new d("damaged",`The checkpoint ${e} is damaged`);let p=t(structuredClone(a.checkpoint));if(p.checkpointId!==a.folder.checkpointId||N(p.org.organizationId)!==a.folder.organizationId)throw new d("invalid","A change never moves a checkpoint");return await this.write(p),b.parse(p)},o=(this.changes.get(e)??Promise.resolve()).then(r,r),s=o.catch(()=>{});return this.changes.set(e,s),s.then(()=>{this.changes.get(e)===s&&this.changes.delete(e)}),o}keep(e,t,r=new Date){return this.update(e,i=>({...i,expiresAt:t?null:Ne(r,Pe)}))}async list(e={}){let t=(e.now??new Date).getTime(),r=e.organizationId!==void 0?k(e.organizationId):void 0,i=[];for(let o of await this.organizationKeys(r)){let s=await this.readsOf(o),a=Xe(s);for(let p of s)i.push(await Ve(p,t,a,e.refreshedAt))}return i.sort((o,s)=>he(s.checkpointId,o.checkpointId))}async delete(e){let t=await this.read(e);if(t===void 0)return{outcome:"notFound"};let r=this.lock(t.folder.organizationId,"delete",t.folder.checkpointId);if("busy"in r)return{outcome:"busy",holder:r.busy};try{await f(t.folder.dir,{recursive:!0,force:!0})}finally{r.lock.release()}return t.checkpoint?{outcome:"deleted",checkpoint:t.checkpoint}:{outcome:"deleted"}}async importInto(e,t,r){let i=this.folderOf(e,t),o=c(this.root,i.organizationId);await X(o);let s=re(c(o,`${We}${L(6).toString("hex")}`),i.organizationId,i.checkpointId);await w(s.dir,{mode:g});try{let a=z(await r(s));if(a.checkpointId!==i.checkpointId||N(a.org.organizationId)!==i.organizationId)throw new d("invalid","An import keeps the checkpoint it was asked to");let p=z({...a,bytes:await Ye(s.dir,a)});if(await this.writeWhole(s.checkpointFile,j(p)),await y(i.dir))return{outcome:"exists"};try{await this.renameFile(s.dir,i.dir)}catch(u){if(await y(i.dir))return{outcome:"exists"};throw u}return{outcome:"imported",checkpoint:p}}finally{await f(s.dir,{recursive:!0,force:!0}),await Fe(o).catch(()=>{})}}async sweep(e=new Date){let t=e.getTime(),r={checkpoints:[],journals:[],previews:0,skipped:[]};for(let i of await this.organizationKeys()){await Ze(c(this.root,i),t);let o=await Qe(await this.readsOf(i),t);if(o.length===0)continue;let s=this.lock(i,"sweep");if("busy"in s){r.skipped.push(i);continue}try{for(let a of o)await en(await R(a),t,r)}finally{s.lock.release()}}return r}lock(e,t,r){return rn(this.locksDir,e,{operation:t,...r!==void 0?{checkpointId:r}:{}},this.lockOptions)}heldBy(e){return on(this.locksDir,e,this.lockOptions)}async organizationKeys(e){return(await P(this.root)).filter(r=>Ae(r)&&(e===void 0||r===e))}async readsOf(e){let t=(await P(c(this.root,e))).filter(i=>h.safeParse(i).success),r=[];for(let i of t)r.push(await R(v(this.root,e,i)));return r}async writeWhole(e,t){let r=`${e}.${process.pid}-${L(4).toString("hex")}.tmp`,i=await ye(r,"wx",be);try{try{await i.writeFile(t,typeof t=="string"?"utf8":void 0),await i.sync()}finally{await i.close()}await this.renameFile(r,e)}catch(o){throw await f(r,{force:!0}),o}}},We=".importing-",Ge=/^\.importing-[0-9a-f]{12}$/;async function Ze(n,e){for(let t of await P(n)){if(!Ge.test(t))continue;let r=c(n,t),i=await x(r).catch(()=>{});i!==void 0&&i.mtimeMs+ne<=e&&await f(r,{recursive:!0,force:!0})}}function z(n){let e=b.safeParse(n);if(!e.success)throw new d("invalid",`Not a checkpoint: ${e.error.message}`);return e.data}function j(n){return`${JSON.stringify(n,null,2)}
|
|
10
|
-
`}async function de(n,e){let t=0;for(let r of await _(n,{withFileTypes:!0})){let i=c(n,r.name);r.isDirectory()?t+=await de(i,e):r.isFile()&&i!==e&&(t+=(await x(i)).size)}return t}async function Ye(n,e){let t=await de(n,c(n,T)),r=o=>Buffer.byteLength(j({...e,bytes:o}),"utf8"),i=t+r(t);return i=t+r(i),i}async function R(n){let e;try{e=JSON.parse(await A(n.checkpointFile,"utf8"))}catch{return{folder:n}}let t=b.safeParse(e);return t.success?t.data.checkpointId!==n.checkpointId||N(t.data.org.organizationId)!==n.organizationId?{folder:n}:{folder:n,checkpoint:t.data}:{folder:n}}function Xe(n){let e;for(let{folder:t,checkpoint:r}of n){let i=r?.lastRewind?.rewindId;i!==void 0&&(e===void 0||i>e.rewindId)&&(e={checkpointId:t.checkpointId,rewindId:i})}return e}function qe(n,e,t,r){if(n.status==="taking")return{why:"taking"};if(n.status==="failed")return{why:"failed"};let i=r?.(e);if(i!==void 0)return{why:"refreshed",refreshedAt:i};if(Me(n.org,t))return{why:"scratchExpired"}}async function Ve({folder:n,checkpoint:e},t,r,i){let o={checkpointId:n.checkpointId,organizationId:n.organizationId};if(e===void 0)return{...o,valid:!1,why:"damaged"};let s=qe(e,n.organizationId,t,i);if(s!==void 0)return{...o,checkpoint:e,valid:!1,why:s.why,...s.refreshedAt!==void 0?{refreshedAt:s.refreshedAt}:{}};let a={...o,checkpoint:e,valid:!0};_e(e,t)&&(a.expiresSoon=!0),He(e.org,t)&&(a.scratchExpiresSoon=!0);let p=Te(e,t);p!==void 0&&(a.binReachSince=p);let u=e.lastRewind;return u!==void 0&&r?.checkpointId===n.checkpointId&&u.undoUntil!==void 0&&u.undoneAt===void 0&&Date.parse(u.undoUntil)>t&&await y(M(n,u.rewindId))&&(a.undo={rewindId:u.rewindId,until:u.undoUntil}),a}async function Qe(n,e){let t=[];for(let{folder:r,checkpoint:i}of n)i!==void 0&&(se(i,e)||await pe(r,i,e)||(await ue(r,e)).length>0)&&t.push(r);return t}async function pe(n,e,t){let r=e.lastRewind?.undoUntil;return e.lastRewind!==void 0&&r!==void 0&&Date.parse(r)<=t&&await y(M(n,e.lastRewind.rewindId))}async function ue(n,e){let t=[];for(let r of await P(n.previewsDir)){if(!E.safeParse(r).success)continue;let i=c(n.previewsDir,r),o=await x(i).catch(()=>{});o!==void 0&&o.mtimeMs+ne<=e&&t.push(i)}return t}async function en(n,e,t){let{folder:r,checkpoint:i}=n;if(i===void 0)return;if(i.expiresAt!==null&&se(i,e)){await f(r.dir,{recursive:!0,force:!0});let s=i.lastRewind?.undoUntil,a=s!==void 0&&i.lastRewind?.undoneAt===void 0&&Date.parse(s)>e;t.checkpoints.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,expiresAt:i.expiresAt,...a?{undoUntil:s}:{}});return}let o=i.lastRewind;o?.undoUntil!==void 0&&await pe(r,i,e)&&(await f(M(r,o.rewindId),{recursive:!0,force:!0}),t.journals.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,rewindId:o.rewindId,undoUntil:o.undoUntil}));for(let s of await ue(r,e))await f(s,{recursive:!0,force:!0}),t.previews+=1}var nn=m({...B,operation:H(["take","rewind","undo","delete","sweep","empty"]),checkpointId:h.optional()}),fe=J(n=>{let e=nn.safeParse(n);return e.success?e.data:void 0});function tn(n,e){return c(n,`${k(e)}.lock`)}function rn(n,e,t,r={}){let i=k(e),o=t.checkpointId!==void 0?O(h,t.checkpointId):void 0,s=fe.acquire(c(n,`${i}.lock`),a=>({...a,operation:t.operation,...o!==void 0?{checkpointId:o}:{}}),r);return"busy"in s?{busy:le(s.busy)}:{lock:{organizationId:i,release:s.lock.release}}}function on(n,e,t={}){let r=fe.holder(tn(n,e),t);return r!==void 0?le(r):void 0}function le({version:n,token:e,...t}){return t}async function P(n){try{return(await _(n,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch(e){if(F(e)==="ENOENT"||F(e)==="ENOTDIR")return[];throw e}}async function y(n){return(await x(n).catch(()=>{}))?.isDirectory()===!0}function N(n){try{return k(n)}catch{return}}function he(n,e){return n<e?-1:n>e?1:0}function F(n){return n?.code}function sn(n){return n instanceof Error?n.message:String(n)}export{an as a,dn as b,g as c,be as d,Pe as e,ee as f,Ee as g,ne as h,xn as i,Le as j,k,In as l,Cn as m,bn as n,Pn as o,En as p,Dn as q,Sn as r,oe as s,vn as t,zn as u,Rn as v,M as w,X as x,Ln as y,Ne as z,se as A,_e as B,Te as C,Me as D,He as E,d as F,An as G,Ke as H,Ue as I,$n as J,$ as K,Xe as L,tn as M,rn as N,on as O};
|
package/lib/chunk-IQXHJEYB.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{a,b,c,d,e,f,g,h,i,j}from"./chunk-Q3DM32KF.mjs";import"./chunk-LPBMBW3O.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as ARCHIVE_CHUNK_BYTES,a as ARCHIVE_EXTENSION,f as CheckpointExportError,d as archiveKeyText,h as exportCheckpointArchive,j as importCheckpointArchive,c as newArchiveKey,e as parseArchiveKey,g as portableCheckpointOf,i as readArchiveHeader};
|
package/lib/chunk-JPUR2CFX.mjs
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{o as ht}from"./chunk-LPBMBW3O.mjs";import{F as ze,d as pt,x as mt}from"./chunk-IFETCRWE.mjs";import{a as dn,d as cn,e as ln,g as un,h as fn,i as gn,j as pn,k as gt}from"./chunk-SAR5622P.mjs";import{C as sn,v as on}from"./chunk-EQNW3UC2.mjs";import{a as Ue,b as re,d as ee,e as an,f as ft,h as z}from"./chunk-GSKCGQIP.mjs";import{c as rn}from"./chunk-EADHKH3A.mjs";import{e as mn,h as hn,i as yn}from"./chunk-L77FJZEP.mjs";import{ca as Oe,da as ut,fa as Ee,ia as qe}from"./chunk-A527W53V.mjs";import{h as F}from"./chunk-TZE3Y7IQ.mjs";import{b as N}from"./chunk-CA5NAXSU.mjs";import{Bb as Xt,Gb as en,Hb as fe,Lb as $e,Ob as ke,Pb as ct,Rb as lt,Sb as tn,Wb as K,qc as nn}from"./chunk-TTFDUKUS.mjs";import{b as x,e as ue,f as $,i as Ae,k as X,l as W,o as Be,s as Fe,v as Zt}from"./chunk-7EANH5PY.mjs";var He=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function Rr(r,e){let t=gt(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Je(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>Rr(mn(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>gt(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var bn=100,yt=2e3,wn=20,Rn=20,Sr=W({name:x(),label:x(),type:x(),createable:$().optional(),updateable:$().optional(),nillable:$().optional(),defaultedOnCreate:$().optional(),aggregatable:$().optional(),groupable:$().optional(),filterable:$().optional(),nameField:$().optional(),autoNumber:$().optional(),calculated:$().optional(),referenceTo:X(x()).optional()}).loose(),de=W({name:x(),label:x(),queryable:$().optional(),updateable:$().optional(),deletable:$().optional(),fields:X(Sr),childRelationships:X(W({childSObject:x(),field:x(),cascadeDelete:$().optional(),restrictedDelete:$().optional()}).loose()).optional()}).loose(),Ar=Fe(x(),Ae()),kr=W({k:Be([x(),ue(),$()]).nullable(),n:ue().int().nonnegative()}).loose();function Sn(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function Or(r){return r.groupable===!0&&(Sn(r)||r.nameField===!0)}function Er(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Xt(r,e.name)}function Qe(r,e,t){let n=N(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Dr(r,e,t,n){let o=new Map,s=[],i=[],a=(f,l)=>{s.push({fieldApiName:f.name,label:f.label,reason:l})},d=t.filter(f=>f.aggregatable===!0),c=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&a(f,"not-countable");if(n===0)for(let f of[...d,...c])o.set(f.name,0);else{for(let f=0;f<d.length;f+=bn){let l=d.slice(f,f+bn);try{let g=l.map(b=>`COUNT(${F(b.name)})`).join(", "),p=await r.query(`SELECT ${g} FROM ${e}`),m=Ar.parse(p.records[0]??{});l.forEach((b,h)=>{let R=m[`expr${h}`];if(typeof R!="number")throw new Error(`The org answered no count for ${e}.${b.name}.`);o.set(b.name,R)})}catch(g){Qe(i,"fill",g);for(let p of l)o.delete(p.name),a(p,"refused")}}for(let[f,l]of c.entries()){if(f>=Rn){a(l,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${F(l.name)} != null`);o.set(l.name,g.totalSize)}catch(g){Qe(i,"fill",g),a(l,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Er(e,f)})).sort((f,l)=>f.filled-l.filled||f.fieldApiName.localeCompare(l.fieldApiName)),unmeasured:s,errors:i}}async function Ir(r,e,t,n,o){let s=[],i=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!i)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let a={keyField:i.name,keyLabel:i.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:a,errors:s};try{let d=await Pr(r,e,i.name),c=d.rows.map(u=>({value:String(u.value),count:u.count}));return{duplicates:{...a,groups:c.slice(0,wn),groupCount:c.length,recordCount:c.reduce((u,f)=>u+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Qe(s,"duplicates",d),{duplicates:null,errors:s}}}async function Pr(r,e,t){let n=F(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${yt}`),s=[];for(let i of o.records){let a=kr.safeParse(i);!a.success||a.data.k===null||s.push({value:a.data.k,count:a.data.n})}return{rows:s,truncated:o.records.length>=yt}}async function Cr(r,e,t,n,o){let s=[];if(!t.some(i=>i.name==="LastModifiedDate"&&i.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let i=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:i.totalSize},errors:s}}catch(i){return Qe(s,"stale",i),{stale:null,errors:s}}}async function Nr(r,e,t){let n,o,s;try{if(n=de.parse(await r.describe(F(e.objectApiName))),o=F(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(u){return{status:"failed",objectApiName:e.objectApiName,message:N(u)}}let i=n.fields.filter(Or).sort((u,f)=>u.label.localeCompare(f.label)),[a,d,c]=await Promise.all([Dr(r,o,n.fields.filter(Sn),s),Ir(r,o,i,e.duplicateKey,s),Cr(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:a.fields,unmeasured:a.unmeasured,duplicates:d.duplicates,stale:c.stale,keyFields:i.map(u=>({fieldApiName:u.name,label:u.label})),errors:[...a.errors,...d.errors,...c.errors]}}async function Ps(r,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Nr(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:yt,duplicateSample:wn,singleFieldQueries:Rn},objects:o}}var wt=1e4,Ve=5e4,An="DELETE_FAILED",Rt="UNABLE_TO_LOCK_ROW",kn=3,jr=2e3,On="FEATURENOTENABLED",St="ContentVersion",En="ContentDocument",At=new Set([St,En]);async function De(r,e,t,n,o="delete"){let s=!1,i={},a=0,d=0,c=(g,p)=>(d+=g,p()),u={bulk2:{createJob:g=>{let p=r.bulk2.createJob(g);return{get id(){return p.id},open:()=>c(1,()=>p.open()),uploadData:m=>c(1,()=>p.uploadData(m)),close:async()=>{await c(1,()=>p.close()),s=!0},abort:()=>c(1,()=>p.abort()),check:async()=>{let m=await c(1,()=>p.check());return i={state:m.state,message:m.errorMessage},m},getAllResults:async()=>{let m=await c(yn,()=>p.getAllResults());return a=Array.isArray(m)?m.length:(m.successfulResults?.length??0)+(m.failedResults?.length??0),m}}}}},f;try{f=await new hn().executeBulk({connection:u,bulkManager:new He(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let p=g?.errorCode;return{kind:"untouched",reason:N(g),...typeof p=="string"&&p!==""?{code:p}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(i.state!=="JobComplete"&&a===0)return{kind:"untouched",reason:i.message||`job ${i.state??"not complete"}`,requests:d};let l=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,p)=>{let m=l.get(p);return m?.success?{success:!0}:{success:!1,error:m?.error??"The job gave no result for it."}})}}function $s(r,e){let t=Je(r);return{...Ue(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>De(t,n,o,s),bulkHardDestroy:(n,o,s)=>De(t,n,o,s,"hardDelete")}}var kt=W({success:$(),errors:X(Be([W({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ge(r){return r.slice(0,15)}function We(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function Ot(r){if(typeof r=="string")return r;let e=We(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function be(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function vr(r){return new Promise(e=>setTimeout(e,r))}function Mr(r){let e=jr*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Dn(r,e,t,n){let o=[...t];for(let s=0;s<kn;s++){let i=o.flatMap((d,c)=>d.kind==="refused"&&d.locked===!0?[c]:[]);if(i.length===0||n.stopped?.()===!0||(await(n.wait??vr)(Mr(s)),n.stopped?.()===!0))break;let a=await e(i.map(d=>r[d]));if(a===void 0)break;i.forEach((d,c)=>{let u=a[c];u&&(o[d]={...u,lockResends:s+1})})}return o}async function Et(r,e,t,n={}){if(e===St)return $r(r,t,n);let o=s=>Lr(r,e,s);return Dn(t,o,await o(t),n)}async function Lr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let i=N(s);return t.map(()=>({kind:"refused",reason:i,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,i)=>{let a=kt.safeParse(o[i]);if(a.success&&a.data.success)return{kind:"deleted"};let d=a.success?a.data.errors??[]:[];if(d.some(u=>We(u)==="ENTITY_IS_DELETED"))return{kind:"gone"};let c=d.length>0&&d.every(u=>We(u)===Rt);return{kind:"refused",reason:d.length>0?Ot(d[0]):"The org gave no reason.",dependency:d.some(u=>We(u)===An),...c?{locked:!0}:{}}})}async function Tr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:xr}:"untouched";let i=async d=>{let c;try{c=await s(e,d,o.signal)}catch(f){let l=N(f);return d.map(()=>({kind:"refused",reason:l,dependency:!1}))}if(c.kind==="aborted")return"aborted";if(c.kind==="untouched"){if(n!=="hard")return"untouched";if(c.code===On)return{hardRefused:_r(c.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${c.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:u}=c;return d.map((f,l)=>{let g=u[l];if(g?.success===!0)return{kind:"deleted"};let{code:p,message:m}=Fr(g?.error??"");return p==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:p&&m?`${p}: ${m}`:g?.error||p||m||"The org gave no reason.",dependency:p===An,...p===Rt?{locked:!0}:{}}})},a=await i(t);return Array.isArray(a)?Dn(t,async d=>{let c=await i(d);return Array.isArray(c)?c:void 0},a,o):a}var xr="Records cannot be deleted for good through this connection: nothing was sent.";function _r(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${On}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var Br="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function Fr(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function $r(r,e,t){let n;try{n=await z(r,St,["ContentDocumentId"],e)}catch(d){let c=N(d);return e.map(()=>({kind:"refused",reason:c,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ge(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],i=s.length>0?await Et(r,En,s,t):[],a=new Map(s.map((d,c)=>[d,i[c]]));return e.map(d=>{let c=o.get(ge(d));return c===void 0?{kind:"gone"}:a.get(c)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function In(r){let e=[];for(let t=0;t<r.length;t+=re)e.push({ids:r.slice(t,t+re),byJob:!1});return e}function Pn(r,e,t,n="recycle"){return At.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=wt}async function qr(r,e,t,n="recycle"){let o=[],s=!At.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),i=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<wt){o.push(...In(d));return}let c=Math.ceil(d.length/Math.ceil(d.length/Ve));for(let u=0;u<d.length;u+=c)o.push({ids:d.slice(u,u+c),byJob:!0})};if(!$e(e)||t.length===0)return i(t),o;let a=new Set;try{a=new Set([...await Ee(be(r),t)].map(ge))}catch{}return i(t.filter(d=>!a.has(ge(d)))),i(t.filter(d=>a.has(ge(d)))),o}function Cn(r){return{objectApiName:r,op:"delete"}}async function Nn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:i}=await pn(t,{key:Cn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async a=>({answers:await Et(r,e,a,s)}),limited:a=>a?.kind==="refused"?nn([a.reason]):void 0,settle:(a,d,c,u)=>{let f=[],l=[];a.forEach((g,p)=>{if(c.has(p))return;let m=d[p]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},b=u.get(p);f.push(g),l.push(b!==void 0&&m.kind==="refused"?{...m,dependency:!1,limit:b}:m)}),f.length>0&&o.settle(f,l)}});return i!==void 0}function Dt(r,e){let t=Cn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(un(n)),n.notSplit>0&&o.push(fn(n.notSplit,gn(e.allowance,t),"removal")),n.keptWhole>0?o.push(ln):n.alone>0&&o.push(cn),o}function jn(r){let e=0,t=0,n=0,o=0;for(let i of r)e++,i==="deleted"?t++:i==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${Rt}), each sent again up to ${kn} times, a wait before each: ${s.join(", ")}.`]}async function vn(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&At.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:Br,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},i=await qr(r,e,t,o);for(let a=i.shift();a!==void 0;a=i.shift()){let{ids:d,byJob:c}=a;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!c){if(await Nn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let u=await Tr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(u==="aborted")return{stopped:!0};if(u==="untouched"){i.unshift(...In(d));continue}if(!Array.isArray(u))return{stopped:!0,hardRefused:u.hardRefused};n.settle(d,u)}return{stopped:!1}}async function Mn(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let i=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>i&&(n=!0)}}return!1}async function Ke(r,e){let t=new Set(e.map(i=>i.objectApiName)),n=new Map;for(let{objectApiName:i}of e){let a;try{a=(de.parse(await r.describe(i)).childRelationships??[]).map(c=>c.childSObject)}catch{continue}for(let d of a){if(d===i||!t.has(d))continue;let c=n.get(d)??new Set;c.add(i),n.set(d,c)}}let o=[...e],s=[];for(;o.length>0;){let i=o.findIndex(a=>!o.some(d=>d!==a&&n.get(d.objectApiName)?.has(a.objectApiName)));s.push(...o.splice(i>=0?i:0,1))}return s}async function It(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(i){return{gone:[],unchecked:[...r],failure:N(i)}}let o=new Set(n.map(i=>ge(String(i.Id)))),s=r.filter(i=>!o.has(ge(i)));return{gone:s.filter(t),unchecked:s.filter(i=>!t(i))}}function Ur(r){return r.filter(e=>Oe[e]!==void 0&&!ut.has(e))}async function Pt(r,e,t,n,o,s){let i=be(r),a=[];for(let{objectApiName:d}of e){let c=Oe[d];if(!c||ut.has(d))continue;let u;for await(let f of t.pages(d)){let l=f.filter(R=>n(d,R));if(l.length===0)continue;if(o())return{drafted:a,cancelled:!0};u??=await qe(i,c);let g=u,p=g?.draft;if(!g||!p)break;let m=await s(d,l),b;try{b=await z(r,d,["Status"],l)}catch{continue}let h=b.filter(R=>typeof R.Id=="string"&&!m.has(R.Id.slice(0,15))).filter(R=>{let S=g.categoryOf.get(String(R.Status));return S!==void 0&&S!=="Draft"}).map(R=>({objectApiName:d,id:String(R.Id),draft:p,status:String(R.Status)}));for(let R=0;R<h.length;R+=re){if(o())return{drafted:a,cancelled:!0};let S=h.slice(R,R+re);a.push(...S);try{await r.update(d,S.map(({id:j})=>({Id:j,Status:p})))}catch{}}}}return{drafted:a,cancelled:!1}}function Qs(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function Ln(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(u=>u.objectApiName===o),i=new Map(s.map(u=>[u.id.slice(0,15),u])),a=s.map(u=>u.id),d;try{d=await z(r,o,["Status"],a)}catch(u){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${N(u)}`,!0);continue}let c=d.flatMap(u=>{let f=typeof u.Id=="string"?i.get(u.Id.slice(0,15)):void 0;return f&&u.Status===f.draft?[f]:[]});for(let u=0;u<c.length;u+=re){let f=c.slice(u,u+re),l;try{l=await r.update(o,f.map(({id:p,status:m})=>({Id:p,Status:m})))}catch(p){l=f.map(()=>({success:!1,errors:[N(p)]}))}let g=Array.isArray(l)?l:[l];f.forEach(({draft:p,status:m},b)=>{let h=kt.safeParse(g[b]);if(h.success&&h.data.success){t.note(o,`Status set to ${p} for the delete, then back to ${m}.`,!1,f[b]);return}let R=h.success?h.data.errors??[]:[],S=R.length>0?Ot(R[0]):"The org gave no reason.";t.note(o,`Status set to ${p} for the delete, and left there: the org refused ${m} back \u2014 ${S}`,!0,f[b])})}}}var Re="DuplicateRecordSet",zr="DuplicateRecordItem",Ge=2e3,Hr=999,Jr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function V(r){return r.slice(0,15)}function Tn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ct(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function xn(r,e){return(await Qr(r,e)).map(t=>({id:t.id,modified:Wr(t,e)}))}async function Qr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!Jr.test(e.user))return[];let t;try{let d=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${Re} WHERE CreatedDate >= ${Tn(e.start-2e3)} AND CreatedDate <= ${Tn(e.end+6e4)} LIMIT ${Ge}`);if(d.records.length>=Ge)return[];t=d.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[]);if(n.length===0)return[];let o=new Set,s=new Map,i=new Map;try{for(let d of ee(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${zr} WHERE DuplicateRecordSetId IN (${d}) LIMIT ${Ge}`);if(c.records.length>=Ge)return[];for(let u of c.records){let f=u??{},l=f.DuplicateRecordSetId,g=f.RecordId;if(typeof l!="string")continue;let p=Ct(f.CreatedDate);Number.isFinite(p)&&!(p<=(i.get(V(l))??Number.NaN))&&i.set(V(l),p),typeof g!="string"||!e.has(V(g))?o.add(V(l)):s.set(V(l),[...s.get(V(l))??[],V(g)])}}}catch{return[]}let a=V(e.user);return t.flatMap(d=>typeof d.Id=="string"&&!o.has(V(d.Id))&&(s.has(V(d.Id))||typeof d.LastModifiedById=="string"&&V(d.LastModifiedById)===a)?[{id:d.Id,created:Ct(d.CreatedDate),modified:Ct(d.LastModifiedDate),...typeof d.LastModifiedById=="string"?{modifiedBy:d.LastModifiedById}:{},names:s.get(V(d.Id))??[],...i.has(V(d.Id))?{itemsMade:i.get(V(d.Id))}:{}}]:[])}function Wr(r,e){if((r.modifiedBy!==void 0?V(r.modifiedBy):"")===V(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+Hr)?Math.min(r.modified,e.end):r.modified}async function _n(r,e,t,n="recycle"){let o=F(e),s=new Set;try{for(let i of ee(t)){let a=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${i}) AND IsDeleted = true`);for(let d of a.records){let c=d?.Id;typeof c=="string"&&s.add(c.slice(0,15))}}}catch(i){return{error:N(i)}}return{deleted:s,inBin:n!=="hard"}}var Vr=/__kav$/i;function Ie(r){return Vr.test(r)}function Fn(r){return r.replace(/v$/i,"")}var Nt="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",Kr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},Bn=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",Gr="An article version is deleted through its article, over REST.",Yr={success:!1,errors:[{message:"The org gave no reason."}]};function te(r){return r.slice(0,15)}function $n(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>Ie(n)?Zr(r,n):r.describe(n),destroy:(n,o)=>Ie(n)?Xr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>Ie(n)?Promise.resolve({kind:"untouched",reason:Gr,requests:0}):t(n,o,s)}:{}}}async function Zr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(Fn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function qn(r,e,t){let n=F(e),o=new Map,s=new Map,i=(d,c)=>{for(let u of d){let f=u;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;c?.set(te(f.Id),f.KnowledgeArticleId);let l=te(f.KnowledgeArticleId),g=s.get(l)??new Set;g.add(te(f.Id)),s.set(l,g)}};for(let d of["",Bn])for(let c of ee(t)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${c})${d}`);i(u.records,o)}let a=[...new Set(o.values())];for(let d of["",Bn])for(let c of ee(a)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${c})${d}`);i(u.records)}return{articleOf:o,versions:s}}function Un({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(te)),s=i=>[...e.get(i)??[]].some(a=>!o.has(a));return new Set([...r.values()].map(te).filter(s))}async function zn(r,e,t,n){let o=await qn(r,e,t),s=Un(o,t,n);return new Set(t.map(te).filter(i=>{let a=o.articleOf.get(i);return a!==void 0&&s.has(te(a))}))}async function Xr(r,e,t,n){let o=await qn(r,e,t),{articleOf:s}=o,i=[...new Set(s.values())],a=Un(o,t,n),d=i.filter(u=>!a.has(te(u))),c=new Map;if(d.length>0){let u;try{u=await r.destroy(Fn(e),d)}catch(l){let g=N(l);u=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(u)?u:[u];d.forEach((l,g)=>c.set(te(l),f[g]))}return t.map(u=>{let f=s.get(te(u));return f===void 0?{success:!1,errors:[Kr]}:a.has(te(f))?{success:!1,errors:[{message:Nt}]}:c.get(te(f))??Yr})}var Ze="Quote",Ce="QuoteLineItem",Pe="Opportunity",Ne="OpportunityLineItem",Hn=2e3;function eo(r){return r.slice(0,15)}function Jn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function G(r,e){let t=r[e];return typeof t=="string"&&t!==""?eo(t):void 0}function vt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function to(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let p=G(g,"Id"),m=G(g,"SyncedQuoteId");!p||!m||!vt(e,p)||!e.has(m)||(t.add(m),n.add(p))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let p=G(g,"QuoteId");return p!==void 0&&t.has(p)&&G(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let p=G(g,"OpportunityId");return p!==void 0&&n.has(p)&&G(g,"Id")!==void 0}),i=g=>G(g,"CreatedById"),a=(g,p)=>{let m=G(g,"Id");if(!m||vt(e,m)||!p)return!1;let b=e.user??i(p),h=Jn(g.CreatedDate);return b!==void 0&&i(g)===b&&h>=e.start&&h<=e.end},d=g=>({id:String(g.Id),modified:Jn(g.LastModifiedDate)}),c=new Map(s.flatMap(g=>{let p=G(g,"Id");return p&&e.has(p)?[[p,g]]:[]})),u=new Map;for(let g of o){let p=G(g,"Id"),m=G(g,"OpportunityLineItemId");p&&m&&e.has(p)&&!u.has(m)&&u.set(m,g)}let f=o.filter(g=>{let p=G(g,"OpportunityLineItemId");return a(g,p?c.get(p):void 0)}).map(d),l=s.filter(g=>{let p=G(g,"Id");return a(g,p?u.get(p):void 0)}).map(d);return[...f.length>0?[{objectApiName:Ce,copies:f}]:[],...l.length>0?[{objectApiName:Ne,copies:l}]:[]]}function Qn(r,e=[]){let t=new Set(r),n=t.has(Pe)||new Set(e).has(Pe);if(!t.has(Ze)||!n)return[];let o=t.has(Ce),s=t.has(Ne);return o===s?[]:[o?Ne:Ce]}async function jt(r,e,t,n,o){let s=t.map(F).join(", "),i=[];for(let a of ee(o)){let d=await r.query(`SELECT ${s} FROM ${F(e)} WHERE ${F(n)} IN (${a}) LIMIT ${Hn}`);if(d.records.length>=Hn)throw new Error(`More ${e} records than one read takes.`);for(let c of d.records)typeof c=="object"&&c!==null&&i.push(c)}return i}async function Wn(r,e,t,n){let o=n.has(Ce)||n.has(Ne),s=n.has(Pe)||e.otherParts?.objects.has(Pe)===!0;if(t.length===0||!s||!o)return[];try{let a=(await jt(r,Pe,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(u=>{let f=G(u,"Id");return f!==void 0&&vt(e,f)});if(a.length===0)return[];let d=await jt(r,Ce,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(a.map(u=>String(u.SyncedQuoteId)))]),c=await jt(r,Ne,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",a.map(u=>String(u.Id)));return to({syncing:a,quoteLines:d,opportunityLines:c},e)}catch{return[]}}var no=5,ve=4,Xe=2e3,ro=4,nt=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],Lt=1e4,oo="005",Vn="ContentDocumentLink",so="ContentDocument",io="ContentVersion",ao=5;function rt(r){let e=new Set(r.flatMap(n=>n.ids.map(w))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function pe(r){return!Array.isArray(r)}function ki(r){return pe(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function Oi(r){return(pe(r)?r.objects:r).map(e=>e.objectApiName)}var ot=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},Tt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function je(r,e){return typeof r=="string"&&e.has(w(r))}var Kn=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],Mt={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return je(r.ContentDocumentId,e)&&(je(t,e)||typeof t=="string"&&t.startsWith(oo))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>je(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>je(r.ContentDocumentId,e)}};function Ei(r,e){return{...Ue(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>De(Je(r),t,n,o)}}function xt(r,e,t){let n=new Map;for(let o of r??[]){let s=Ft(o.span,[],t);if(Number.isFinite(s.end))for(let i of o[e]??[]){let a=w(i);s.end<=(n.get(a)?.end??Number.NEGATIVE_INFINITY)||n.set(a,s)}}return n}function co(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>pe(n)?n:rt(n)),rt(e)];return{has:n=>t.some(o=>o.has(n))}}function lo(r=[],e=[]){return new Set([...r.map(({plan:t})=>pe(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function er(r,e){return new Map([...xt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function tr(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function _t(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function Gn(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new Me(o,s,t(o)).result,notReached:s}));return r}var Di={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function w(r){return r.slice(0,15)}function uo(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(N(r))}function fo(r,e){let t=/no such column '(\w+)'/i.exec(N(r))?.[1],n=nt.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?nt.length:n}function q(r){return typeof r=="string"?Date.parse(r):Number.NaN}function nr(){return{modified:new Tt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var Me=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ot;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(w(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let i of this.secondTry){let a=w(i);this.deletedLater.has(a)?e++:this.goneLater.has(a)?t++:this.refused.has(i)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let i=this.automationHeld.get(w(s));return i?[i]:[]}),t=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAfter.has(i)}).length,n=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAlong.has(i)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...jn(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,no),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,ao)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function Ii(r,e,t){let n=pe(e)?e:rt(e),o=n,s=o.objects.reduce((y,A)=>y+A.count,0),i=new Map,a=y=>i.get(y)??0,d=()=>t.signal?.aborted===!0,c=t.splitting??dn(),u=()=>({objects:Gn([],o.objects,a),cancelled:!0,gone:[],stamps:{},left:()=>Xn(n)}),f=new Map,l=new Map;for(let{objectApiName:y}of o.objects){let A=nr();f.set(y,A);let E=0;for await(let P of o.pages(y)){if(d())return u();let J=P[0];J!==void 0&&!l.has(J.slice(0,3))&&l.set(J.slice(0,3),y);let B=E;if(E+=P.length,A.error!==void 0)continue;let C=await wo(r,y,P,B,A);if(A.error!==void 0||C.length===0)continue;if(d())return u();let Q=await _n(r,y,C);if("error"in Q)A.binError=Q.error;else for(let ne of Q.deleted)A.binned.add(ne)}}let g=new Map,p=!1,m=r.bulkDestroy?.bind(r),b={query:y=>r.query(y),destroy:(y,A)=>(p=!0,r.destroy(y,A)),...m?{bulkDestroy:(y,A)=>(p=!0,m(y,A,t.signal))}:{},update:(y,A)=>(p=!0,r.update(y,A)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:y=>r.queryDeleted(y),describeGlobal:()=>r.describeGlobal(),describe:y=>{let A=g.get(y);return A||(A=r.describe(y),g.set(y,A)),A}},h=$n(b,{includeChanged:t.includeChanged}),R=await Ke(h,o.objects),S=await yo(h,R,(y,A)=>A-(f.get(y)?.missing.size??0)),j=new Set(S.map(y=>y.objectApiName));if(S.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return u();if(!await t.onUndeletable(S))return{...u(),objects:[],undeletable:S,stoppedForUndeletable:!0}}let[_,U]=await Promise.all([Ao(h),t.previewOnly===!0?void 0:ko(h)]),{start:k,end:O}=Ft(t,f.values(),_.aheadMs);if(d())return u();let I=co(t.otherParts,t.otherPartRecords),D=lo(t.otherParts,t.otherPartRecords),M=await Ro(h,o,{start:k,end:O,...t.runUserId?{user:w(t.runUserId)}:{},...I?{otherParts:{has:y=>I.has(y),objects:D}}:{},undeletable:j,snapshots:f});if(t.runUserId&&t.alongAccepted!==!0){let y=await xn(h,{has:A=>o.has(A),start:k,end:O,user:t.runUserId});y.length>0&&!o.objects.some(A=>A.objectApiName===Re)&&await rr(h,Re)&&M.push({objectApiName:Re,copies:y})}if(M.length>0){o=await So(o,M,f,l);for(let{objectApiName:y,copies:A}of M)i.set(y,A.length);s=o.objects.reduce((y,A)=>y+A.count,0),R=await Ke(h,o.objects)}let H=new Map(Object.entries(t.removalStamps??{}).map(([y,A])=>[w(y),q(A)])),v=er(t.laterParts,_.aheadMs),T=new Set;for(let{objectApiName:y}of o.objects){let A=f.get(y);if(!A||A.error!==void 0)continue;let E=0;for await(let P of o.pages(y))for(let J of P){let B=A.modified.at(E++),C=w(J);if(A.missing.has(C))continue;B<=O||B<=(H.get(C)??Number.NaN)||B<=(v.get(C)??Number.NaN)||T.add(C)}}if(t.previewOnly===!0){if(d())return u();let y=new Set,A=await po(h,o,R,{snapshots:f,changed:T,undeletable:j,includeChanged:t.includeChanged,stopped:d,copiesOf:a,...t.previewHeld===!0?{held:{notSent:y,check:new Le(h,{runRecords:o,reached:{has:()=>!1},stays:E=>y.has(E),runStart:k,runEnd:O,removalStart:_.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(E=>({start:q(E.first),end:q(E.last),user:w(E.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}})}}:{}});return A?{...S.length>0?{undeletable:S}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>Xn(n),preview:A}:u()}let L=await bo(h,t.otherParts??[],_.aheadMs,d);if(!L)return u();let xe=new Set,hr={has:y=>o.has(y)&&xe.has(l.get(y.slice(0,3))??"")},at=new Le(h,{runRecords:o,reached:hr,stays:y=>T.has(y)&&!t.includeChanged,runStart:k,runEnd:O,removalStart:_.start,removalUser:U,earlierRemovals:(t.removalSpans??[]).map(y=>({start:q(y.first),end:q(y.last),user:w(y.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.automationMade?{automationMade:ir(t.automationMade)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}});if(d())return u();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(c)&&(p=!0);let le=[],Kt=y=>le.find(A=>A.result.objectApiName===y);async function*dt(y,A,E){for(let{objectApiName:P}of A){let J=Kt(P),B=0;for await(let C of y.pages(P)){let Q=C.filter(ne=>E(P,ne,J?.isGone(ne,B++)===!0));Q.length>0&&(yield{objectApiName:P,ids:Q})}}}let yr=()=>dt(o,R,(y,A,E)=>{let P=f.get(y),J=w(A);return P?.modifiedColumn==="LastModifiedDate"&&!P.missing.has(J)&&!T.has(J)&&!E}),_e=[],Z=async y=>{await Ln(h,_e,{note:(C,Q,ne)=>{let Y=Kt(C);if(!Y){if(!ne)return;let se=o.objects.find(ie=>ie.objectApiName===C);Y=new Me(C,se?.count??0,a(C)),le.push(Y)}Y.note(Q)}});let A=p?await Yn(h,yr(),{start:_.start,user:U}):{},E=[];if(p)for(let C of L)E.push(await Yn(h,C.unchanged(),{start:_.start,user:U}));let P=p?Oo(_,U):void 0,J=[];if(!pe(e))for await(let{ids:C}of dt(n,R,(Q,ne,Y)=>Y))for(let Q of C)J.push(Q);for(let C of le)C.limitNotes=Dt(C.result.objectApiName,c);let B=le.map(C=>C.settle());return{...S.length>0?{undeletable:S}:{},objects:y?Gn(B,R,a):B,cancelled:y,gone:J,left:()=>dt(n,n.objects,(C,Q,ne)=>!ne),stamps:A,...P?{span:P}:{},...E.length>0?{otherPartStamps:E}:{}}};if(d())return p?Z(!0):u();let Gt=async(y,A)=>(await at.heldAmong(y,A)).held,Yt=await Pt(h,R,o,(y,A)=>{let E=w(A),P=f.get(y);return P!==void 0&&P.error===void 0&&!j.has(y)&&!P.missing.has(E)&&!(T.has(E)&&!t.includeChanged)},d,Gt);if(_e=Yt.drafted,Yt.cancelled)return Z(!0);if(t.alongToDraft){let y=await Pt(h,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,Gt);if(_e=[..._e,...y.drafted],y.cancelled)return Z(!0)}let ae=0;for(let{objectApiName:y,count:A}of R){if(d())return Z(!0);let E=new Me(y,A,a(y));le.push(E),xe.add(y);let P=f.get(y);if(!P||P.error!==void 0){E.unread={reason:P?.error??"The org gave no reason.",count:A},ae+=A,t.onProgress?.(ae,s,y);continue}if(j.has(y)){let Y=0,se=0;for await(let ie of o.pages(y))for(let ye of ie){let Se=w(ye),wr=Y++;P.missing.has(Se)?P.binned.has(Se)?(E.result.alreadyGone++,E.goneAt.add(wr)):E.notVisible++:se++}E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),se>0&&(E.unread={reason:tr(y,se),count:se}),ae+=A,t.onProgress?.(ae,s,y);continue}let J=Pn(h,y,A),B=[],C=new Map,Q=async()=>{let Y=B,se=C;return B=[],C=new Map,Zn(h,at,E,Y,{stopped:d,splitting:c,placeOf:se,onDeleted:ie=>{ae+=ie,t.onProgress?.(ae,s,y)},onHeld:ie=>{ae+=ie,t.onProgress?.(ae,s,y)}})},ne=0;for await(let Y of o.pages(y)){if(d())return Z(!0);let se=B.length;for(let ie of Y){let ye=w(ie),Se=ne++;P.missing.has(ye)?P.binned.has(ye)?(E.result.alreadyGone++,E.goneAt.add(Se)):E.notVisible++:T.has(ye)&&!t.includeChanged?E.result.keptChanged++:(B.push(ie),C.set(ye,Se))}if(E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),ae+=Y.length-(B.length-se),!(J&&B.length<Ve)&&await Q())return Z(!0)}if(J&&B.length>0&&(d()||await Q()))return Z(!0)}let br=le.some(y=>y.result.deleted>0);if(await Mn(le,{stopped:d,idsOf:(y,A)=>{if(A>0)return y.waiting();let E=y.refusedToSendAgain();return E.length>0||br?[...E,...y.held]:[]},send:async(y,A,E)=>{let P=new Set(E===0?y.refusedToSendAgain():[]),J=await Zn(h,at,y,A,{stopped:d,splitting:c,onSent:B=>{for(let C of B)P.has(C)&&y.secondTry.add(C)}});for(let B of y.held)P.has(B)&&y.secondTry.add(B);return J},deleted:y=>y.result.deleted}))return Z(!0);if(t.afterRemoval){if(d())return Z(!0);await t.afterRemoval(c)&&(p=!0)}for(let y of le){if(d())return Z(!0);await ho(h,y,f.get(y.result.objectApiName))}return Z(!1)}async function go(r,e,t,n,o){let{changed:s,includeChanged:i}=o,a=[];for await(let d of e.pages(t))for(let c of d){let u=w(c);!n.has(u)&&(i||!s.has(u))&&a.push(c)}try{return{kept:await zn(r,t,a,{includeChanged:i})}}catch(d){return{kept:new Set,unread:N(d)}}}async function po(r,e,t,n){let o=[],s=new Set;for(let{objectApiName:i,count:a}of t){let d=n.copiesOf(i),c={objectApiName:i,planned:a,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...d>0?{platformCopies:d}:{},reasons:[]};o.push(c);let u=n.snapshots.get(i);if(!u||u.error!==void 0){if(c.unread=a,c.reasons.push(u?.error??"The org gave no reason."),n.held)for await(let m of e.pages(i))for(let b of m)n.held.notSent.add(w(b));continue}let f=Ie(i)&&!n.undeletable.has(i)?await go(r,e,i,u.missing,n):void 0,l=[],g=[],p=m=>{n.held?.notSent.add(m)};for await(let m of e.pages(i))for(let b of m){let h=w(b);u.missing.has(h)?u.binned.has(h)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,p(h)):f?.unread!==void 0?(c.unread++,p(h)):n.changed.has(h)?(c.changedSince++,l.push(b),n.includeChanged?(c.toDelete++,g.push(b)):(c.keptChanged++,p(h))):f?.kept.has(h)?(c.changedSince++,c.keptChanged++,p(h)):(c.toDelete++,g.push(b))}if(n.held&&g.length>0){if(n.stopped())return;let m=await n.held.check.heldAmong(i,g),b=g.filter(R=>m.held.has(w(R)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...m.holders];for(let S of b)n.held.notSent.add(w(S));let R=b.filter(S=>m.byAutomation.has(w(S)));R.length>0&&(c.heldByAutomation=R.length)}let h=new Map;for(let R of g)if(!m.held.has(w(R)))for(let[S,j]of m.cameAlong.get(w(R))??[])h.set(S,j);h.size>0&&(c.cameAlong={count:h.size,objects:[...new Set(h.values())]}),m.reason!==void 0&&c.reasons.push(m.reason),m.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...m.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(f?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${f.unread}`):f!==void 0&&f.kept.size>0&&c.reasons.push(Nt),c.notVisible>0&&c.reasons.push(_t(c.notVisible,u.binError)),c.undeletable>0&&c.reasons.push(tr(i,c.undeletable)),!(l.length===0||u.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let m=await z(r,i,["LastModifiedById"],l,ve);for(let b of m){let h=b.LastModifiedById;typeof h!="string"||h===""||(c.changedBy[h]=(c.changedBy[h]??0)+1,s.add(h))}}catch(m){c.reasons.push(`Who changed them since the run could not be read: ${N(m)}`)}}}if(!n.stopped())return{objects:o,userNames:await mo(r,[...s])}}async function mo(r,e){let t={};if(e.length===0)return t;try{for(let n of await z(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function ho(r,e,t){let{gone:n,unchecked:o,failure:s}=await It(e.refusedSent(),i=>z(r,e.result.objectApiName,[],i),i=>t!==void 0&&t.error===void 0&&!t.missing.has(w(i)));for(let i of n)e.refused.delete(i),e.goneLater.add(w(i)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(s?` \u2014 ${s}`:"."))}function Pi(r,e=[],t={}){return[...new Set([...r,...Qn(r,e),...t.userKept===!0&&r.length>0?[Re]:[]])]}async function yo(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===io||s===0)continue;let i=t(o,s);if(i!==0)try{let a=de.safeParse(await r.describe(o));a.success&&a.data.deletable===!1&&n.push({objectApiName:o,records:i})}catch{}}return n}async function Yn(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:i,ids:a}of e){let d;try{d=await z(r,i,["LastModifiedDate","LastModifiedById"],a)}catch{continue}for(let c of d)typeof c.Id=="string"&&typeof c.LastModifiedDate=="string"&&typeof c.LastModifiedById=="string"&&w(c.LastModifiedById)===s&&q(c.LastModifiedDate)>=o&&(n[c.Id]=c.LastModifiedDate)}return n}async function bo(r,e,t,n){let o=[];for(let s of e){let i=pe(s.plan)?s.plan:rt(s.plan),{end:a}=Ft(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,l])=>[w(f),q(l)])),c=er(s.laterParts,t),u=new Map;if(Number.isFinite(a))for(let{objectApiName:f}of i.objects){let l=new ot,g=0,p=!1;for await(let m of i.pages(f)){if(n())return;let b=g;if(g+=m.length,p)continue;let h;try{h=await z(r,f,["LastModifiedDate"],m,ve)}catch{p=!0;continue}let R=new Map;for(let S of h)typeof S.Id=="string"&&R.set(w(S.Id),q(S.LastModifiedDate));m.forEach((S,j)=>{let _=w(S),U=R.get(_);U!==void 0&&(U<=a||U<=(d.get(_)??Number.NaN)||U<=(c.get(_)??Number.NaN))&&l.add(b+j)})}p||u.set(f,l)}o.push({unchanged:async function*(){for(let{objectApiName:f}of i.objects){let l=u.get(f);if(!l)continue;let g=0;for await(let p of i.pages(f)){let m=p.filter(()=>l.has(g++));m.length>0&&(yield{objectApiName:f,ids:m})}}}})}return o}async function Zn(r,e,t,n,o){let{objectApiName:s}=t.result,i=await e.heldAmong(s,n);i.reason!==void 0&&t.note(i.reason);for(let l of i.unchecked)t.result.unchecked.includes(l)||t.result.unchecked.push(l);let a=n.filter(l=>i.held.has(w(l)));if(o.placeOf){for(let l of a)t.held.push(l);t.result.heldBy=[...new Set([...t.result.heldBy,...i.holders])]}else t.held=a,t.result.heldBy=[...i.holders];for(let l of a)t.refused.delete(l);for(let l of n){let g=w(l),p=i.byAutomation.get(g);p?t.automationHeld.set(g,p):t.automationHeld.delete(g),p&&i.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),p&&i.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(a.length);let d=n.filter(l=>!i.held.has(w(l))),c=new Map,u=(l,g)=>{l.forEach((p,m)=>{let b=g[m],h=w(p);if((b.lockResends!==void 0||t.lockResent.has(h))&&t.lockResent.set(h,b.kind),b.kind==="refused"){t.refused.set(p,{reason:b.reason,dependency:b.dependency,sent:!0,...b.limit?{limit:!0}:{}});return}t.refused.delete(p);let R=o.placeOf?.get(h);if(R!==void 0?t.goneAt.add(R):t.goneLater.add(h),b.kind==="deleted"){t.result.deleted++,R===void 0&&t.deletedLater.add(h);for(let S of c.get(h)??[])t.filesLeft.set(S.key,S.name);for(let[S,j]of i.along.get(h)??[])t.tookAlong.set(S,j);for(let[S,j]of i.cameAlong.get(h)??[])t.cameAlong.set(S,j)}else t.result.alreadyGone++}),o.onSent?.(l),o.onDeleted?.(l.length)},{stopped:f}=await vn(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async l=>{c=await e.filesOn(l)},settle:u});return f}async function wo(r,e,t,n,o){let s,i=o.modifiedColumn?Kn.filter(({modified:a})=>a===o.modifiedColumn):Kn;for(let{created:a,modified:d}of i)try{let u=await z(r,e,a?[a,d]:[d],t,ve),f=new Map;for(let g of u)typeof g.Id=="string"&&f.set(w(g.Id),q(g[d])),a&&(o.firstCreated=or(o.firstCreated,q(g[a])),o.lastCreated=Bt(o.lastCreated,q(g[a])));o.modifiedColumn=d;let l=[];return t.forEach((g,p)=>{let m=w(g),b=f.get(m);b===void 0&&(o.missing.add(m),l.push(g)),o.modified.set(n+p,b??Number.NaN)}),l}catch(c){s??=N(c)}return o.error=s,o.modifiedColumn=void 0,[]}async function*Xn(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function Ro(r,e,t){let n=new Set(e.objects.filter(a=>a.count>0).map(a=>a.objectApiName));if(!n.has(Ze))return[];let o=[];for await(let a of e.pages(Ze))o.push(...a);let s=await Wn(r,{has:a=>e.has(a),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),i=[];for(let a of s){let{objectApiName:d}=a;if(t.undeletable.has(d))continue;let c=t.snapshots.get(d);if(c){if(c.error!==void 0||c.modifiedColumn!=="LastModifiedDate")continue}else if(!await rr(r,d))continue;i.push(a)}return i}async function rr(r,e){try{let t=de.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function So(r,e,t,n){let o=new Map(e.map(({objectApiName:a,copies:d})=>[a,d])),s=new Set(e.flatMap(({copies:a})=>a.map(d=>w(d.id)))),i=r.objects.map(a=>{let d=o.get(a.objectApiName);return d?{objectApiName:a.objectApiName,count:a.count+d.length}:a});for(let[a,d]of o){r.objects.some(l=>l.objectApiName===a)||i.push({objectApiName:a,count:d.length});let c=t.get(a);c||(c={...nr(),modifiedColumn:"LastModifiedDate"},t.set(a,c));let u=0;for await(let l of r.pages(a))u+=l.length;for(let l of d)c.modified.set(u++,l.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,a)}return{objects:i,pages:async function*(a){yield*r.pages(a);let d=o.get(a);d&&d.length>0&&(yield d.map(c=>c.id))},has:a=>r.has(a)||s.has(a)}}async function Ao(r){let e=Date.now(),t=Number.NaN;try{t=q(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function ko(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?w(e):void 0}catch{return}}function Oo(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+Lt).toISOString(),userId:e}}function or(r,e){return Number.isNaN(r)||e<r?e:r}function Bt(r,e){return Number.isNaN(r)||e>r?e:r}var sr=999;function Eo(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=Bt(n,o.lastCreated)),n=Bt(n,o.modified.latestWithin(e,t));return n}function Ft(r,e,t){let n=Do(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+sr;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Do(r,e,t){let n=[...e],o=Number.NaN;for(let c of n)o=or(o,c.firstCreated);let s=r.runDurationMs??0,i=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(i)){let c=i-s-Lt,u=i+Lt,f=r.endedByItsWrites===!0?Eo(n,c,u):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>c?o:c),end:Number.isFinite(f)?Math.min(f+sr,u):u}}let a=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??a+s;return{start:a,end:d}}function ir(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(w)),t=r.size),e.has(n))}}function Ci(r,e){let t=new Le(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:q(n.first),end:q(n.last),user:w(n.userId)})),includeChanged:e.includeChanged,automationMade:ir(e.taken),...e.runUserId?{runUser:w(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var et="IsPersonAccount",Io=50;function tt(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Le=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let l=de.parse(await this.org.describe(e)),g=await this.workedObjects(),p=e==="Account"&&l.fields.some(m=>m.name===et);s=(l.childRelationships??[]).filter(m=>(m.cascadeDelete===!0||m.restrictedDelete===!0)&&g.has(m.childSObject)).map(m=>({childSObject:m.childSObject,field:m.field,restricted:m.cascadeDelete!==!0,...p&&m.childSObject==="Contact"&&m.field==="AccountId"?{personContacts:!0}:{}}))}catch(l){return o.reason=N(l),t.forEach(g=>this.hold(o,w(g))),o}let i=[];for(let l=0;l<t.length;l+=re)i.push(t.slice(l,l+re));let a=i.length>1?await ft(s.map(l=>()=>this.anyPointing(l)),ve):s.map(()=>!0),d=s.filter((l,g)=>a[g]).flatMap(l=>i.map(g=>async()=>({relationship:l,...await this.holdingIn(l,g)}))),c=o.mayBeAutomation,u=new Map;for(let{relationship:l,holding:g,unchecked:p,automation:m,along:b,goes:h}of await ft(d,ve)){p&&o.unchecked.add(l.childSObject),(g.size>0||m.length>0)&&o.holders.add(l.childSObject),g.forEach(R=>this.hold(o,R));for(let R of m)o.held.add(w(R.parent));c.push(...m);for(let{parent:R,key:S}of b){let j=o.along.get(R)??new Map;j.set(S,l.childSObject),o.along.set(R,j)}h.length>0&&u.set(l.childSObject,[...u.get(l.childSObject)??[],...h])}if(await this.heldBelow(u,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),$e(e)&&await this.standardPricesHeld(t,o),e===lt&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(c,o);let f=await this.byAutomationOnly(e,c,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,i,a,d)=>{let c=s.get(i)??new Map;c.set(a,d),s.set(i,c)};for(let[s,i]of e){let a=[...new Set(i.map(c=>c.id))],d=n+1<ro?await this.heldAmong(s,a,n+1):void 0;for(let{parent:c,id:u,came:f}of i){let l=w(u);if(!d||d.held.has(l)){this.hold(t,c),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,c,l,s);for(let[g,p]of d.along.get(l)??[])o(t.along,c,g,p);for(let[g,p]of d.cameAlong.get(l)??[])o(t.cameAlong,c,g,p)}d?.unchecked.forEach(c=>t.unchecked.add(c))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(w(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let i=await this.heldAmong(o,[...new Set(s.map(a=>a.id))],1);for(let a of s){let d=w(a.id),c=i.mayBeAutomation.some(u=>w(u.parent)===d&&u.creator!==a.creator);!i.otherwise.has(d)&&!c||(this.hold(t,w(a.parent)),i.holders.forEach(u=>t.holders.add(u)))}i.unchecked.forEach(a=>t.unchecked.add(a))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,i=t.filter(f=>!n.has(w(f.parent)));if(i.length===0)return{objects:o,after:s,along:new Set};let a;try{let f=await z(this.org,e,["CreatedDate","CreatedById"],[...new Set(i.map(l=>l.parent))]);a=new Map(f.flatMap(l=>typeof l.Id=="string"?[[w(l.Id),l]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,c=new Set;for(let f of i){let l=w(f.parent),g=a.get(l),p=q(g?.CreatedDate),m=g?.CreatedById,b=this.context.runUser??(typeof m=="string"?w(m):void 0),h=f.created-p;if(!(b!==void 0&&f.creator===b&&h>=-2e3&&h<=6e4)){d.add(l);continue}let S=o.get(l)??new Set;S.add(f.object),o.set(l,S),f.created>this.context.runEnd&&s.add(l),f.along||c.add(l)}for(let f of d)o.delete(f),s.delete(f);let u=new Set([...o.keys()].filter(f=>!c.has(f)));return{objects:o,after:s,along:u}}async holdingIn(e,t){let n=F(e.childSObject),o=F(e.field),[s]=ee(t,t.length),i=new Set(["Id",o,...Mt[n]?.ends??[],...e.personContacts?[et]:[]]),a=this.datesKept.get(n)??0;for(;a<nt.length;){let d=nt[a],c;try{c=await this.org.query(`SELECT ${[...i,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Xe}`)}catch(b){uo(b)?(a=fo(b,a),this.datesKept.set(n,a)):a++;continue}if(c.records.length>=Xe)return{holding:new Set(t.map(w)),automation:[],along:[],goes:[],unchecked:!1};let u=new Set,f=[],l=[],g=[],p=new Map;for(let b of c.records){if(typeof b!="object"||b===null)continue;let h=b,R=h[e.field];if(typeof R!="string"||typeof h.Id!="string"||(n===Vn&&o==="LinkedEntityId"&&this.noteFile(h),this.lockedUnder.get(w(h.Id))===w(R)))continue;let S={onlyIncluded:!1};if(!this.stays(h,n,e.restricted,e.personContacts,S)){if(S.onlyIncluded&&l.push({parent:w(R),key:w(h.Id)}),n!==Vn&&this.goesAlongUnread(h)){let U=!(Mt[n]?.cameWithRun(h,this.context.runRecords)===!0||e.personContacts===!0&&h[et]===!0)&&!S.onlyIncluded&&S.byRemoval!==!0&&this.context.goesWithParent?.(h,this.context.runEnd)!==!0;g.push({parent:w(R),id:h.Id,came:U})}continue}let j=this.mayBeAutomation(h);if(j){let _={parent:R,id:h.Id,object:n,along:!e.restricted,...j};f.push(_),e.restricted&&p.set(h.Id,_)}else u.add(w(R))}let m=await this.ofOtherParts(n,[...p.keys()]);for(let[b,h]of p)m.has(w(b))&&(f.splice(f.indexOf(h),1),u.add(w(h.parent)));return{holding:u,automation:f,along:l,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=w(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:i,runEnd:a}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||i?.(e,a)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:i}=this.context;if(t.length===0||!o||!s)return n;let a=this.cascadeEnds.get(e);a||(a=(async()=>{let u=new Set;for(let f of s)try{let l=de.parse(await this.org.describe(f));for(let g of l.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&u.add(g.field)}catch{}return[...u]})(),this.cascadeEnds.set(e,a));let d=await a;if(d.length===0)return n;let c;try{c=await z(this.org,e,d,t)}catch{return n}for(let u of c){if(typeof u.Id!="string")continue;let f=d.flatMap(l=>{let g=u[l];return typeof g=="string"?[w(g)]:[]});f.some(l=>i.has(l))||f.some(l=>o.has(l))&&n.add(w(u.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:i}=this.context;if(typeof e.Id!="string"||t.has(w(e.Id))||i?.has(w(e.Id))===!0||typeof e.CreatedById!="string")return;let a=w(e.CreatedById);if(s!==void 0&&a!==s)return;let d=q(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let c=q(e.LastModifiedDate),u=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;if(!(c>o&&u!==void 0&&u!==a))return{created:d,creator:a}}async anyPointing(e){try{let t=F(e.childSObject),n=F(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||je(n,this.context.runRecords))return;let o=this.files.get(w(t))??new Set;o.add(n),this.files.set(w(t),o)}async filesOn(e){let t=new Map;for(let s of e){let i=this.files.get(w(s));i&&i.size>0&&t.set(w(s),[...i])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await z(this.org,so,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(w(s.Id),s.Title)}catch{}return new Map([...t].map(([s,i])=>[s,i.map(a=>({key:w(a),name:o.get(w(a))??a}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(en)){let i=s.find(l=>l.object===e)?.lookup,a=Oe[o];if(!i||!a)continue;let d=await this.statusCategoriesOf(a);if(!d)continue;let c,u;try{c=await z(this.org,e,[i],t);let l=[...new Set(c.map(g=>g[i]).filter(g=>typeof g=="string"))];u=l.length>0?await z(this.org,o,["Status"],l):[]}catch{continue}let f=new Set(u.filter(l=>{let g=d.categoryOf.get(String(l.Status));return g!==void 0&&g!=="Draft"}).map(l=>w(String(l.Id))));for(let l of c){let g=l[i];typeof l.Id!="string"||typeof g!="string"||f.has(w(g))&&(this.hold(n,w(l.Id)),n.holders.add(o),this.lockedUnder.set(w(l.Id),w(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=qe(be(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=be(this.org),o=[...await Ee(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),i=await z(this.org,fe,s,o),a=await this.pricesOfProducts(i,s),d=a.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]),c=new Set([...await Ee(n,d)].map(w)),u=new Set(e.map(w)),f=new Set;for(let l of a){if(typeof l.Id!="string")continue;let g=w(l.Id);if(c.has(g))continue;(u.has(g)?t.held.has(g):this.stays(l,fe,!0))&&f.add(tt(l,s))}for(let l of i)typeof l.Id!="string"||!f.has(tt(l,s))||(this.hold(t,w(l.Id)),t.holders.add(fe))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ke,ct];try{let o=await z(this.org,lt,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),i=new Set(s.filter(a=>typeof a.Id=="string"&&a.IsActive===!0&&this.stays(a,fe,!0)).map(a=>tt(a,n)));for(let a of o)typeof a.Id!="string"||!i.has(tt(a,n))||(this.hold(t,w(a.Id)),t.holders.add(fe))}catch{}}async priceKeyFields(){let e=de.parse(await this.org.describe(fe)),t=new Set(e.fields.map(n=>n.name));return[ke,...[ct,tn].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(i=>i[ke]).filter(i=>typeof i=="string"))],o=[...new Set(["Id",...t])].map(F).join(", "),s=[];for(let i of ee(n,Io)){let a=await this.org.query(`SELECT ${o} FROM ${fe} WHERE ${ke} IN (${i}) LIMIT ${Xe}`);if(a.records.length>=Xe)throw new Error("More prices than one read takes.");for(let d of a.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let i=w(e.Id),{runRecords:a,reached:d,runStart:c,runEnd:u,removalStart:f,removalUser:l,earlierRemovals:g,includeChanged:p}=this.context;if(a.has(i))return d.has(i)||this.context.stays(i);if(n)return!0;if(this.context.automationMade?.has(i)===!0||this.context.goesWithParent?.(e,u)===!0||this.context.alongToDraft?.has(i)===!0||Mt[t]?.cameWithRun(e,a))return!1;if(o&&e[et]===!0)return!(q(e.LastModifiedDate??e.SystemModstamp)<=u)&&!p;let m="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!m)return!0;let b=q(e[m]),h=q(m==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(b>=c))return!0;let R=this.context.linkedLater?.get(i);if(R&&(b<=u||b>=R.start)&&h<=R.end)return!1;let S=typeof e.CreatedById=="string"?w(e.CreatedById):void 0,j=(U,k)=>U!==void 0&&(U===l&&k>=f||g.some(O=>U===O.user&&k>=O.start&&k<=O.end));if(j(S,b))return s&&(s.byRemoval=!0),!1;if(h<=u)return!1;let _=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;return b<=u&&j(_,h)?!1:(p&&s&&(s.onlyIncluded=!0),!p)}workedObjects(){return this.worked??=an(this.org),this.worked}};var Po="encryptedstring";async function Co(r){try{let[e]=await r("SELECT PermissionsViewEncryptedData FROM UserPermissionAccess");return e?.PermissionsViewEncryptedData===!0}catch{return!1}}function Mi(r){let e;return()=>(e??=Co(r),e)}function Li(r,e){let t=new Map;return n=>{let o=t.get(n);return o||(o=(async()=>{let s;try{s=(await e(n)).fields.filter(a=>a.type===Po).map(a=>a.name)}catch{return[]}return s.length>0&&!await r()?s:[]})(),t.set(n,o)),o}}var me=5,qt=25,Ut=3;function Bi(r){return{get version(){return r.version},request:async e=>await r.request(e),query:async(e,t)=>await r.query(e,{scanAll:t?.scanAll===!0}),queryMore:async e=>await r.queryMore(e)}}var oe=class extends Error{constructor(){super("The read was stopped."),this.name="OrgReadStopped"}},No="PROCESSING_HALTED",ar="If-Modified-Since",jo=/^\d{1,3}\.\d$/,vo=/^\/services\/data\/v\d{1,3}\.\d\/query(?:All)?\/[A-Za-z0-9-]+$/,Mo=W({records:X(Fe(x(),Ae())),done:$(),totalSize:ue().optional(),nextRecordsUrl:x().optional()}).loose(),Lo=W({compositeResponse:X(W({body:Ae(),httpStatusCode:ue(),referenceId:x()}).loose())}),To=X(W({errorCode:x().optional(),message:x().optional()}).loose());function xo(r,e,t){if(!jo.test(r))throw new Error(`Not an API version: ${r}`);if(e.length>me)throw new Error(`A composite runs ${me} queries, not ${e.length}`);if(e.length+t.length>qt)throw new Error(`A composite holds ${qt} subrequests, not ${e.length+t.length}`);let n=`/services/data/v${r}`;return{allOrNone:!1,compositeRequest:[...e.map((o,s)=>({method:"GET",url:o.kind==="first"?`${n}/${o.scanAll?"queryAll":"query"}?q=${encodeURIComponent(o.soql)}`:o.path,referenceId:`q${s}`})),...t.map(({path:o,headers:s},i)=>({method:"GET",url:`${n}/${o}`,referenceId:`d${i}`,...s?{httpHeaders:s}:{}}))]}}function _o(r){let e=Lo.safeParse(r);if(!e.success)return;let t=new Map;for(let n of e.data.compositeResponse){if(n.httpStatusCode<400){t.set(n.referenceId,{ok:!0,status:n.httpStatusCode,body:n.body});continue}let o=To.safeParse(n.body),s=o.success?o.data[0]:void 0;t.set(n.referenceId,{ok:!1,refused:s?[s.errorCode,s.message].filter(Boolean).join(": "):`status ${n.httpStatusCode}`,halted:s?.errorCode===No})}return t}function $t(r){let e=Mo.safeParse(r);return e.success?e.data:void 0}function Bo(r){return typeof r=="object"&&r!==null&&typeof r.errorCode=="string"}function Fo(r){let e=/^https:\/\//i.test(r)?new URL(r).pathname:r;if(!vo.test(e))throw new Error(`Not the next page of a query: ${r}`);return e}function Fi(r,e){let t=new Set,n=[],o=me,s="composite",i=0,a=!1,d=!1,c=0,u=0,f=!1,l=()=>{for(let k of t)k.state==="pending"&&(k.state="idle",k.settle?.reject(new oe));for(let k of n.splice(0))k.settle.reject(new oe)},g=()=>{d||(d=!0,queueMicrotask(()=>{d=!1,R()}))},p=(k,O)=>{k.state="idle";let I=k.settle;k.ask=void 0,k.settle=void 0,O instanceof Error?I?.reject(O):I?.resolve(O)},m=async(k,O)=>{let I=xo(r.version,k.map(v=>v.ask),O),D;u++;try{D=await r.request({method:"POST",url:"/composite",body:JSON.stringify(I),headers:{"Content-Type":"application/json"}})}catch(v){if(Bo(v)){s="single";for(let L of k)L.state="pending";n.unshift(...O);return}let T=new Error(N(v));for(let L of k)p(L,T);for(let L of O)L.settle.reject(T);return}let M=_o(D);if(!M){s="single";for(let v of k)v.state="pending";n.unshift(...O);return}let H=0;if(k.forEach((v,T)=>{let L=M.get(`q${T}`);if(L&&!L.ok&&L.halted){H++,v.state="pending";return}if(!L){p(v,new Error("The org gave no answer to this query of the composite"));return}if(!L.ok){p(v,new Error(L.refused));return}let xe=$t(L.body);p(v,xe??new Error(`The org answered a query with status ${L.status} and no page`))}),H>0){let v=k.length-H;v===0?s="single":o=Math.min(o,v)}O.forEach((v,T)=>{let L=M.get(`d${T}`);L?L.ok?v.settle.resolve(L.status===304?{notModified:!0}:{body:L.body}):v.settle.reject(new Error(L.refused)):v.settle.reject(new Error("The org gave no answer to this describe of the composite"))})},b=async(k,O)=>{for(let I of k){let D=I.ask;u++;try{let M=D.kind==="first"?await r.query(D.soql,{scanAll:D.scanAll}):await r.queryMore(D.path);p(I,$t(M)??new Error("The org answered a query with no page"))}catch(M){p(I,new Error(N(M)))}}for(let I of O){u++;try{let D=await r.request({method:"GET",url:`/services/data/v${r.version}/${I.path}`,...I.headers?{headers:I.headers}:{}}),M=I.headers?.[ar]!==void 0&&(D==null||D==="");I.settle.resolve(M?{notModified:!0}:{body:D})}catch(D){I.settle.reject(new Error(N(D)))}}},h=async(k,O,I)=>{try{s==="composite"?await m(k,O):await b(k,O)}catch(D){let M=new Error(N(D));for(let H of k)H.state==="sent"&&p(H,M);for(let H of O)H.settle.reject(M)}finally{i--,I||(a=!1),g(),_()}},R=()=>{if(e?.aborted){l();return}for(;;){if(a)return;let k=[...t],O=k.filter(T=>T.state==="pending").sort((T,L)=>T.order-L.order);if(!(O.length>0&&!k.some(T=>T.state==="idle"))&&n.length===0)return;let D=O.slice(0,o),M=qt-D.length,H=s==="composite"&&n.length===0&&D.length>0&&D.every(T=>T.oneRow&&T.ask?.kind==="first");if(i>=(H?Ut:1))return;let v=n.splice(0,M);if(D.length===0&&v.length===0)return;for(let T of D)T.state="sent";i++,H||(a=!0),h(D,v,H)}},S=()=>{f=!1,g()},j=()=>{f||e===void 0||e.aborted||(e.addEventListener("abort",S,{once:!0}),f=!0)},_=()=>{!f||i>0||t.size>0||n.length>0||(e?.removeEventListener("abort",S),f=!1)},U=(k,O)=>t.has(k)?k.state!=="idle"?Promise.reject(new Error("A read asks one page at a time.")):e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{k.ask=O,k.settle={resolve:I,reject:D},k.state="pending",k.order=++c,g()}):Promise.reject(new Error("This read is closed."));return{lane(k){let O={state:"idle",order:0,oneRow:k?.oneRow===!0};return t.add(O),j(),{query:(I,D)=>U(O,{kind:"first",soql:I,scanAll:D?.scanAll===!0}),queryMore:I=>{let D;try{D=Fo(I)}catch(M){return Promise.reject(M instanceof Error?M:new Error(String(M)))}return U(O,{kind:"next",path:D})},close(){t.delete(O)&&(O.state==="pending"&&p(O,new Error("This read is closed.")),g(),_())}}},describe(k,O){return e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{let M=K(k),H;if(O!==void 0){let v=Date.parse(O);if(!Number.isFinite(v))throw new Error(`Not a date: ${O}`);H={[ar]:new Date(v).toUTCString()}}j(),n.push({path:`sobjects/${M}/describe`,...H?{headers:H}:{},settle:{resolve:I,reject:D}}),g()})},async tooling(k){if(e?.aborted)throw new oe;u++;let O;try{O=await r.request({method:"GET",url:`/services/data/v${r.version}/tooling/query?q=${encodeURIComponent(k)}`})}catch(D){throw new Error(N(D))}let I=$t(O);if(!I)throw new Error("The org answered a Tooling API query with no page");return I},calls:()=>u}}import{createReadStream as $o}from"node:fs";import{appendFile as qo,mkdir as Uo,rm as zo,writeFile as Ho}from"node:fs/promises";import*as he from"node:path";import{createInterface as Jo}from"node:readline";var Qo="The org stopped answering before it said the read was done: some of its records were not read.",dr=384,Wo=448;function cr(r){let e=typeof r=="number"?r:Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${String(r)}`);let t=e-(e%1e3+1e3)%1e3;return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function zt(r){let e=Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${r}`);return cr(e-on)}function lr(r,e){return[...new Set([...r,...e.map(F)])].join(", ")}function Ht(r,e,t,n){let o=K(r),s=[n,e==="scanAllLive"?"IsDeleted = false":void 0].filter(i=>i!==void 0);return{objectApiName:o,soql:`SELECT ${t} FROM ${o}${s.length>0?` WHERE ${s.join(" AND ")}`:""}`,scanAll:e==="scanAllLive"}}function Vo(r){let e=K(r);return{objectApiName:e,soql:`SELECT SystemModstamp FROM ${e} ORDER BY SystemModstamp DESC LIMIT 1`,scanAll:!0}}var Ko=["Id","SystemModstamp","CreatedDate","LastModifiedDate","LastModifiedById"],Go=["Id","SystemModstamp","CreatedDate"];function Yo(r,e,t,n=[]){return Ht(r,e,lr(Ko,n),`SystemModstamp >= ${zt(t)}`)}function Zo(r,e,t=[]){let n=K(r);return{objectApiName:n,soql:`SELECT ${lr(Go,t)} FROM ${n} WHERE IsDeleted = true AND SystemModstamp >= ${zt(e)}`,scanAll:!0}}function Xo(r,e){return Ht(r,e,"COUNT()")}function Gi(r,e){let t=K(r);return{objectApiName:t,soql:`SELECT Id FROM ${t} WHERE IsDeleted = true AND SystemModstamp < ${cr(e)}`,scanAll:!0}}function Yi(r,e){return Ht(r,e,"Id")}async function es(r,e,t){let n,o,s={query:async a=>{let d=await r.query(a,{scanAll:e.scanAll});return n=d,o=d.totalSize,d},queryMore:async a=>(n=await r.queryMore(a),n)},i=0;try{for await(let a of rn(s,e.soql))await t(a),i+=a.length}catch(a){if(a instanceof oe)throw a;return{objectApiName:e.objectApiName,read:!1,rows:i,reason:N(a)}}return n?.done!==!0?{objectApiName:e.objectApiName,read:!1,rows:i,reason:Qo}:{objectApiName:e.objectApiName,read:!0,rows:i,...o!==void 0?{totalSize:o}:{}}}async function Jt(r,e,t,n,o={}){let s=o.oneRow===!0,i=new Array(e.length),a=async l=>{let g=e.slice(l,l+me),p=g.map(()=>r.lane({oneRow:s})),m=await Promise.allSettled(g.map(async(b,h)=>{let R=p[h];try{return await es(R,b,S=>t(l+h,S))}finally{R.close()}}));for(let[b,h]of m.entries()){if(h.status==="rejected")throw h.reason instanceof Error?h.reason:new Error(String(h.reason));i[l+b]=h.value}},d=0,c=async()=>{for(;d<e.length;){if(n?.aborted)throw new oe;let l=d;d+=me,await a(l)}},u=Math.ceil(e.length/me),f=await Promise.allSettled(Array.from({length:Math.min(s?Ut:1,u)},c));for(let l of f)if(l.status==="rejected")throw l.reason instanceof Error?l.reason:new Error(String(l.reason));if(n?.aborted)throw new oe;return i}function ts(r){return`${JSON.stringify(Object.fromEntries(Object.entries(r).filter(([e])=>e!=="attributes")))}
|
|
8
|
-
`}async function ns(r,e,t){for(let o of e)await Uo(he.dirname(o.file),{recursive:!0,mode:Wo}),await Ho(o.file,"",{encoding:"utf8",mode:dr});let n=await Jt(r,e,async(o,s)=>{s.length!==0&&await qo(e[o].file,s.map(ts).join(""),{encoding:"utf8",mode:dr})},t);return await Promise.all(n.map((o,s)=>o.read?void 0:zo(e[s].file,{force:!0}))),n}async function*Zi(r){let e=$o(r,{encoding:"utf8"}),t=Jo({input:e,crlfDelay:1/0});try{for await(let n of t){if(n==="")continue;let o=JSON.parse(n);if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`${he.basename(r)} holds a line that is no record.`);yield o}}finally{t.close(),e.destroy()}}async function rs(r,e,t,n){let o=Date.parse(zt(t)),s=[];return(await Jt(r,e.map(Vo),(a,d)=>{d.length>0&&(s[a]=d[0].SystemModstamp)},n,{oneRow:!0})).map((a,d)=>{if(!a.read)return{objectApiName:a.objectApiName,unread:a.reason};if(s[d]===void 0)return{objectApiName:a.objectApiName,latest:null,moved:!1};let c=sn(s[d]);return c===null?{objectApiName:a.objectApiName,unread:`${a.objectApiName} answered a SystemModstamp that is not a date.`}:{objectApiName:a.objectApiName,latest:c,moved:Date.parse(c)>=o}})}async function os(r,e,t){return(await Jt(r,e.map(({objectApiName:o,readMode:s})=>Xo(o,s)),()=>{},t,{oneRow:!0})).map(o=>o.read?o.totalSize===void 0?{objectApiName:o.objectApiName,unread:"The org gave no count of its records."}:{objectApiName:o.objectApiName,count:o.totalSize}:{objectApiName:o.objectApiName,unread:o.reason})}function ss(r,e){return he.join(r,`${K(e)}.live.ndjson`)}function is(r,e){return he.join(r,`${K(e)}.deleted.ndjson`)}async function Xi(r,e,t,n,o,s){if(s!==void 0&&s.length!==e.length)throw new Error(`${s.length} pre-checks for ${e.length} objects`);let i=s??await rs(r,e.map(({objectApiName:m})=>m),t,o),a=new Map,d=[];i.forEach((m,b)=>{"unread"in m?a.set(b,m.unread):m.moved&&d.push(b)});let c=d.flatMap(m=>{let{objectApiName:b,readMode:h,fields:R=[]}=e[m],S=K(b);return[{...Yo(S,h,t,R),file:ss(n,S)},{...Zo(S,t,R),file:is(n,S)}]}),u=await ns(r,c,o),f=new Map;d.forEach((m,b)=>{let h=u[b*2],R=u[b*2+1],S=[h,R].find(j=>!j.read);if(S&&!S.read){a.set(m,S.reason);return}f.set(m,{live:{file:c[b*2].file,rows:h.rows},deleted:{file:c[b*2+1].file,rows:R.rows}})});let l=e.map((m,b)=>({object:m,index:b})).filter(({object:m,index:b})=>!a.has(b)&&(f.has(b)||m.held)).map(({index:m})=>m),g=await os(r,l.map(m=>e[m]),o),p=new Map;return l.forEach((m,b)=>{let h=g[b];"unread"in h?a.set(m,h.unread):p.set(m,h.count)}),i.map((m,b)=>{if("unread"in m)return m;let h=a.get(b);if(h!==void 0)return{objectApiName:m.objectApiName,unread:h};let R=f.get(b),S=p.get(b);return{objectApiName:m.objectApiName,latest:m.latest,moved:m.moved,...R?.live?{live:R.live}:{},...R?.deleted?{deleted:R.deleted}:{},...S!==void 0?{count:S}:{}}})}import{randomBytes as as}from"node:crypto";import{createReadStream as ds}from"node:fs";import{appendFile as cs,open as gr,readFile as ls,rename as us,rm as fs}from"node:fs/promises";import{join as Wt}from"node:path";import{createInterface as gs}from"node:readline";var ps=2e3,ce=15,pr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ms=2e3,mr="spool.json",Te="a rewind";function Qt(r){return typeof r=="string"&&pr.test(r)?r.slice(0,ce):void 0}var st=class{bytes=Buffer.alloc(ce*1024);flags=new Uint16Array(1024);slots=new Uint32Array(2048);used=0;get size(){return this.used}find(e){let t=this.slots.length-1;for(let n=ht(e)&t;;n=n+1&t){let o=this.slots[n];if(o===0)return-1;if(this.holds(o-1,e))return o-1}}holds(e,t){let n=e*ce;for(let o=0;o<ce;o++)if(this.bytes[n+o]!==t.charCodeAt(o))return!1;return!0}keyAt(e){let t=e*ce;return this.bytes.toString("latin1",t,t+ce)}place(e,t){let n=this.slots.length-1,o=ht(t)&n;for(;this.slots[o]!==0;)o=o+1&n;this.slots[o]=e+1}add(e,t=0){let n=Qt(e);if(n===void 0)throw new RangeError(`Not a Salesforce id: ${String(e)}`);let o=this.find(n);if(o>=0)return this.flags[o]|=t,!1;if((this.used+1)*2>this.slots.length){let s=this.slots;this.slots=new Uint32Array(s.length*2);for(let i of s)i!==0&&this.place(i-1,this.keyAt(i-1))}if((this.used+1)*ce>this.bytes.length){let s=Buffer.alloc(this.bytes.length*2);this.bytes.copy(s),this.bytes=s;let i=new Uint16Array(this.flags.length*2);i.set(this.flags),this.flags=i}return this.bytes.write(n,this.used*ce,ce,"latin1"),this.flags[this.used]=t,this.place(this.used,n),this.used++,!0}has(e){let t=Qt(e);return t!==void 0&&this.find(t)>=0}count(e){let t=0;for(let n=0;n<this.used;n++)e(this.flags[n])&&t++;return t}flagsOf(e){let t=Qt(e);if(t===void 0)return 0;let n=this.find(t);return n<0?0:this.flags[n]}},hs=W({version:Zt(1),objects:X(W({objectApiName:x().min(1),count:ue().int().nonnegative()}))});function Vt(r,e){return Wt(r,`${K(e)}.ids`)}async function ys(r,e){let t=`${r}.${process.pid}-${as(4).toString("hex")}.tmp`,n=await gr(t,"wx",pt);try{try{await n.writeFile(e,"utf8"),await n.sync()}finally{await n.close()}await us(t,r)}catch(o){throw await fs(t,{force:!0}),o}}async function bs(r){let e=await gr(r,"r+");try{await e.sync()}finally{await e.close()}}async function ws(r,e,t=Te){for(let{objectApiName:n,count:o}of e)o>0&&await bs(Vt(r,n));return await ys(Wt(r,mr),`${JSON.stringify({version:1,objects:e})}
|
|
9
|
-
`),new it(r,e,t)}var ur=class{constructor(e,t=Te){this.dir=e;this.act=t}dir;act;order=[];counts=new Map;lines=new Map;written=new Set;keys=new st;made=!1;async add(e,t){if(!this.keys.add(t))return!1;let n=this.lines.get(e);return n||(K(e),n=[],this.lines.set(e,n),this.order.push(e)),n.push(t),this.counts.set(e,(this.counts.get(e)??0)+1),n.length>=ms&&await this.flush(e),!0}async flush(e){let t=this.lines.get(e)??[];this.made||(await mt(this.dir),this.made=!0);let n=!this.written.has(e);t.length===0&&!n||(await cs(Vt(this.dir,e),t.map(o=>`${o}
|
|
10
|
-
`).join(""),{encoding:"utf8",mode:pt,flag:n?"w":"a"}),this.written.add(e),this.lines.set(e,[]))}get objects(){return this.order.map(e=>({objectApiName:e,count:this.counts.get(e)??0}))}async finish(e){this.made||(await mt(this.dir),this.made=!0);for(let t of this.order)await this.flush(t);return ws(this.dir,e?e(this.objects):this.objects,this.act)}},it=class r{constructor(e,t,n=Te){this.dir=e;this.objects=t;this.act=n}dir;objects;act;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async open(e,t=Te){let n;try{n=JSON.parse(await ls(Wt(e,mr),"utf8"))}catch{throw new ze("damaged",`The list of what ${t} sets out to do is not on this machine.`)}let o=hs.safeParse(n);if(!o.success)throw new ze("damaged",`The list of what ${t} sets out to do does not read as one.`);for(let{objectApiName:s}of o.data.objects)K(s);return new r(e,o.data.objects,t)}async*pages(e,t=ps){let n=this.objects.find(u=>u.objectApiName===e);if(!n||n.count===0)return;let o=()=>new ze("damaged",`The ${e} records ${this.act} sets out to act on are not as they were written.`),s=Math.max(1,Math.floor(t)),i=ds(Vt(this.dir,e),{encoding:"utf8"}),a=gs({input:i,crlfDelay:1/0}),d=0,c=[];try{for await(let u of a)if(u!==""){if(!pr.test(u))throw o();d++,c.push(u),c.length>=s&&(yield c,c=[])}}catch(u){throw u.code==="ENOENT"?o():u}finally{a.close(),i.destroy()}if(d!==n.count)throw o();c.length>0&&(yield c)}},fr=class r{constructor(e,t){this.spool=e;this.keys=t}spool;keys;static async of(e,t){return new r(await e.finish(t),e.keys)}static async open(e,t=Te){let n=await it.open(e,t),o=new st;for(let{objectApiName:s}of n.objects)for await(let i of n.pages(s))for(let a of i)o.add(a);return new r(n,o)}get objects(){return this.spool.objects}pages(e){return this.spool.pages(e)}has(e){return this.keys.has(e)}};export{He as a,yt as b,wn as c,Rn as d,de as e,Sn as f,Or as g,Dr as h,Ir as i,Pr as j,Cr as k,Ps as l,Je as m,wt as n,Ve as o,De as p,$s as q,Et as r,xr as s,Br as t,Pn as u,Nn as v,Dt as w,jn as x,vn as y,Mn as z,Ke as A,It as B,Ur as C,Pt as D,Qs as E,Ln as F,Wn as G,Re as H,Qr as I,Lt as J,pe as K,ki as L,Oi as M,Ei as N,Di as O,Ii as P,Pi as Q,Ci as R,Po as S,Co as T,Mi as U,Li as V,me as W,qt as X,Ut as Y,Bi as Z,oe as _,Fi as $,cr as aa,zt as ba,Xo as ca,Gi as da,Yi as ea,es as fa,Jt as ga,ns as ha,Zi as ia,rs as ja,os as ka,ss as la,is as ma,Xi as na,ps as oa,st as pa,Vt as qa,ws as ra,ur as sa,it as ta,fr as ua};
|
package/lib/chunk-K327QKMD.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{a,b}from"./chunk-OAZRPP4I.mjs";import"./chunk-JEERQRLW.mjs";import"./chunk-HS4YRX4J.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as grantsByObject,b as guardCheckpoint};
|
package/lib/chunk-KRCA6IPH.mjs
DELETED
|
@@ -1,8 +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{i as Ye,k as qe}from"./chunk-5TC3QB4U.mjs";import{d as Le,i as xe}from"./chunk-2BA2XKAY.mjs";import{b as ee}from"./chunk-OAZRPP4I.mjs";import{c as Ze,d as et}from"./chunk-JEERQRLW.mjs";import{a as De,b as Me}from"./chunk-5P4PHJRL.mjs";import{c as Ae,d as je,m as Re}from"./chunk-MJU2PGZQ.mjs";import{a as Te}from"./chunk-LWW4U276.mjs";import{A as te,B as ot,o as Ne,u as tt,v as nt}from"./chunk-F43REJDZ.mjs";import{$ as Y,T as Ce,X as We,Z as Be,_ as X,aa as q,ba as Ge,ca as Ue,da as ze,ga as Ve,ha as He,ia as L,ka as Z,na as Ke}from"./chunk-JPUR2CFX.mjs";import{a as _e,v as Je,w as Qe,z as Xe}from"./chunk-LPBMBW3O.mjs";import{F as Fe,I as Ie,a as Pe,e as ve,o as Q,x as Ee,y as $e,z as I}from"./chunk-IFETCRWE.mjs";import{C as Oe}from"./chunk-EQNW3UC2.mjs";import{g as H}from"./chunk-HS4YRX4J.mjs";import{f as be,g as ke,h as F,m as we,n as ye,o as K,t as Se,u as J}from"./chunk-JWTSEDIQ.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Ba as me,Cd as he,Wb as $,xa as ge,ya as E}from"./chunk-TTFDUKUS.mjs";import{b as fe,k as pe,l as V}from"./chunk-7EANH5PY.mjs";import{readdir as Nt,rm as ct,stat as dt}from"node:fs/promises";import{existsSync as Dt,readFileSync as Mt,writeFileSync as Pt}from"node:fs";import{hostname as vt}from"node:os";import{join as oe}from"node:path";var Et=5e5,x=1e6,$t=100,Ft="taking",st=500;function Wn(e){let t=Be(e),n=[H(e)];return{get version(){return e.version},request:o=>t.request(o),query:(o,s)=>t.query(o,s),queryMore:o=>t.queryMore(o),describeGlobal:async()=>await e.describeGlobal(),toolingObjects:async()=>{try{return(await e.tooling.describeGlobal()).sobjects.map(s=>s.name)}catch{return[]}},serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp,userId:async()=>(await e.soap.getUserInfo()).userId,requestsSent:()=>n.reduce((o,s)=>o+s(),0),countAlso:o=>{n.push(H(o))}}}function It(e){return _e(De(e))}var N=class extends Error{constructor(){super("The checkpoint was stopped before it was taken: nothing of it was kept."),this.name="CheckpointTakeStopped"}},W="No record was read.",Lt={excludedByUser:"Left out as asked.",notFound:"The org has no object of this name.",chatter:"Chatter posts, comments and feeds are left out: Salesforce brings a post back only with what it was posted on.",history:"History is left out: it is the org's own trace of changes.",sharing:"Sharing is left out: the org keeps it itself.",changeEvent:"Change events are left out.",unsupportedKind:"Left out: neither the recycle bin nor an update reaches this kind of object as it reaches a record.",customSetting:"Custom settings are left out unless you pick them as custom settings: they are configuration, which a rewind sets back.",notCustomSetting:"Picked as a custom setting: the org has no custom setting of this name.",files:"Documents of the Documents tab are left out: they are shared content kept in folders, as setup is.",heldWithFiles:"Held with its file (ContentDocument): Salesforce neither deletes nor brings back a file's version on its own, and reads the links of a file through the records they tie it to.",setup:"Users, permissions and setup are left out, and so are the org's own logs and jobs.",platformCreated:"Left out: Salesforce alone creates its records, such as approvals, Einstein insights, Data.com clean info and invoices, and no permission lets a user create one.",metadata:"Left out: it is metadata, which a checkpoint doesn't hold.",notWritable:"Left out: the user SandForge connects as may not create, edit and delete its records.",notDescribed:"Left out: the org would not describe it.",noSystemModstamp:"Left out: it has no SystemModstamp, so nothing would tell a record changed since.",noRecycleBin:"Left out: the org deletes its records for good, with no recycle bin, so nothing would tell one deleted since, nor bring it back.",unreadable:"Left out: the org refuses to read it whole.",noViewAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has neither on this one: a record they cannot see would read as deleted since.",noModifyAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has View All on this one, not Modify All: a rewind could not put back what others changed.",activities:"Without View All Data and Modify All Data, tasks and events are left out: Salesforce has no View All for activities, and a private one linked to no record stays out of sight.",catalog:"Without View All Data and Modify All Data, products and price books are left out: Salesforce has no View All or Modify All for them.",filesNotProven:"Without View All Data and Modify All Data, files are left out: nothing proves the user sees every file.",settingNotProven:"Without View All Data and Modify All Data, custom settings are left out: no permission on an object proves the user sees and writes every row.",parentNotSeen:"Without View All Data and Modify All Data, an object with no permissions of its own is held only when the user has View All and Modify All on every record it hangs from, which is not proven here."};function lt(e){let t=Lt[e.reason],n=e.detail===void 0?t:`${t.replace(/\.$/,"")} (${e.detail}).`;return{objectApiName:e.objectApiName,code:e.reason,reason:it(n),...e.detail===void 0?{}:{detail:it(e.detail)}}}function xt(e,t,n){return{objectApiName:e,code:"pastTheLimit",records:t,limit:n,reason:t>x?`${e} has ${t} records, more than any checkpoint holds of one object (${x}): left out of the checkpoint, and a rewind to it does not touch ${e}. Data Export, in Setup, or a Bulk API query keeps a copy of it.`:`${e} has ${t} records, past the checkpoint's limit of ${n} for one object: left out of the checkpoint, as part of it would be taken for all of it.`}}function Wt(e,t){let n=t;for(;;){let o=e.filter(s=>s<=Math.min(n,x)).reduce((s,a)=>s+a,0);if(o<=n)return n;n=o}}function it(e){return e.length<=st?e:`${e.slice(0,st-1)}\u2026`}function ut(e,t){return{code:"RUN_WRITING",message:`${t.operation==="take"?`A checkpoint of ${e} is being taken`:t.operation==="rewind"?`A rewind is writing to ${e}`:t.operation==="undo"?`An undo is writing to ${e}`:t.operation==="empty"?`An emptying of its objects is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${t.pid} on ${t.host}): take the checkpoint once it has ended. ${W}`}}function ft(e){return typeof e!="object"||e===null?void 0:typeof e.errorCode=="string"?v(e):void 0}function B(e,t){return e instanceof X||e instanceof Te||e instanceof N||t?.aborted===!0}var Bt=V({sobjects:pe(be)}).loose();function D(e){return e.toLowerCase()===ke.toLowerCase()}function _t(e,t,n){if(e===void 0)return{why:`the org lists no ${F}`};let o=t.get(e);if(o===void 0)return{why:n.get(e)??"it was not described"};let a=o.fields.find(d=>d.name.toLowerCase()==="linkedentityid")?.referenceTo??[];return a.length===0?{why:"its describe names no record a link ties a file to"}:{linkable:new Set(a.map(d=>d.toLowerCase()))}}async function se(e,t,n){let o=new Map,s=new Map,a=0,d=await Promise.allSettled(n.map(f=>t.describe(f)));for(let[f,i]of d.entries()){let c=n[f],l;if(i.status==="fulfilled"&&"body"in i.value)l=i.value.body;else{if(i.status==="rejected"&&i.reason instanceof X)throw i.reason;a++;try{l=await e.request({method:"GET",url:`/services/data/v${e.version}/sobjects/${$(c)}/describe`})}catch(h){let r=ft(h);if(r===void 0)throw new Error(`The org did not answer the describe of ${c}: ${v(h)}`);s.set(c,r);continue}}let u=Le.safeParse(l);u.success?o.set(c,u.data):s.set(c,"its describe does not read as one")}return{describes:o,errors:s,alone:a}}async function pt(e,t,n){let o=Bt.parse(await e.describeGlobal()),s=await e.toolingObjects?.()??[],a=ye(o.sobjects,{mode:n.mode,...n.objects?{objects:n.objects}:{},...n.excluded?{excluded:n.excluded}:{},...n.customSettings?{customSettings:n.customSettings}:{}},s),d=a.candidates.some(D),f=d?o.sobjects.find(g=>g.name.toLowerCase()===F.toLowerCase())?.name:void 0,i=f===void 0?a.candidates:[...a.candidates,f],{describes:c,errors:l,alone:u}=await se(e,t,i),h,r;if(d){let g=_t(f,c,l);"linkable"in g?h=g.linkable:r=g.why,f!==void 0&&c.delete(f)}let m=Se(a,c,l);if(r!==void 0){let g=m.objects.find(({objectApiName:j})=>D(j));g!==void 0&&(m=J(m,new Map([[g.objectApiName,`its links to records, ${F}, could not be described: ${r}`]])))}let w=await Ce(async g=>(await e.query(g)).records),S=new Map(o.sobjects.map(g=>[g.name,rt(g)])),O=o.sobjects.filter(we),p=new Set(O.map(g=>g.name)),k=[...c.values()],y=[];for(let g of m.objects){let j=c.get(g.objectApiName);j&&y.push({scoped:g,label:S.get(g.objectApiName)??g.objectApiName,describe:j,capture:await xe(j,k,{viewsEncryptedData:w}),...p.has(g.objectApiName)?{customSetting:K(j)}:{}})}return{described:i.length,describedAlone:u,objects:y,leftOut:m.leftOut,addedToPicked:a.addedToPicked,...h!==void 0&&y.some(({scoped:g})=>D(g.objectApiName))?{linkable:h}:{},settings:O.map(g=>({objectApiName:g.name,label:rt(g)}))}}function rt(e){let t=e.label;return typeof t=="string"&&t!==""?t:e.name}async function Gt(e,t,n,o){let s=await Z(t,n.map(({capture:i})=>({objectApiName:i.objectApiName,readMode:i.readMode})),o),a=new Map,d=new Map,f=0;for(let[i,c]of s.entries()){let{objectApiName:l,readMode:u}=n[i].capture;if("count"in c){a.set(l,c.count);continue}f++;let h=Ue(l,u);try{let r=await e.query(h.soql,{scanAll:h.scanAll});if(typeof r.totalSize!="number")throw new Error("The org gave no count of its records.");a.set(l,r.totalSize)}catch(r){let m=ft(r);if(m===void 0)throw new Error(`The org did not count the records of ${l}: ${v(r)}`);d.set(l,m)}}return{counts:a,refused:d,alone:f}}function gt(e,t){return t?.has(e.toLowerCase())===!0&&!D(e)}async function Ut(e,t,n,o,s){let a=[];for(let{objectApiName:i,records:c}of t){let l=$(i);a.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE IsDeleted = true AND SystemModstamp < ${q(o)}`,scanAll:!0,counts:"inBin"}),c!==0&&(a.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE SystemModstamp >= ${Ge(o)}`,scanAll:!0,counts:"stampedSince"}),gt(l,n)&&a.push({...Ye(l),counts:"links"}))}let d=await Ve(e,a,()=>{},s),f=new Map;return d.forEach((i,c)=>{let{objectApiName:l,counts:u}=a[c],h=i.read?i.totalSize:void 0,r=f.get(l)??{};u==="links"?r.links=h??null:h!==void 0&&(r[u]=h),f.set(l,r)}),{asked:a.length,of:f}}function mt({scoped:e,capture:t,customSetting:n,access:o},s,a,d){return{objectApiName:e.objectApiName,records:s,inBin:a,readOrder:e.readOrder,readMode:t.readMode,undeletable:t.undeletable,cascadeParents:t.cascadeParents,restrictParents:t.restrictParents,fingerprint:d,fields:t.fields,leftOutFields:t.leftOutFields,...n!==void 0?{customSetting:n}:{},...o!==void 0?{access:o}:{}}}function zt(e){let t=e?.orgType==="Sandbox"||e?.orgType==="Scratch";return Ae(je(t)).defaultQueryLimit}async function ht(e,t,n,o,s,a,d,f=kt){let i=n.maxTotal??Et;if(!Number.isInteger(i)||i<1)throw new RangeError(`Not a number of records: ${i}`);let c=Math.min(i,x),{counts:l,refused:u,alone:h}=await Gt(e,t,o.objects,d),r=J({mode:n.mode,objects:o.objects.map(({scoped:b})=>b),leftOut:o.leftOut,packages:[]},u),m=new Map(o.objects.map(b=>[b.scoped.objectApiName,b])),w=r.leftOut.map(lt),S=[];for(let b of r.objects){let A=m.get(b.objectApiName),P=l.get(b.objectApiName);if(!(A===void 0||P===void 0)){if(P>c){w.push(xt(b.objectApiName,P,c));continue}S.push({...A,scoped:{...b,readOrder:S.length},records:P,otherGroups:tt(b.objectApiName,A.capture.fields,A.capture.readMode),recount:{}})}}let O=S.some(({scoped:b})=>D(b.objectApiName))?o.linkable:void 0,p=await Ut(t,S.map(({scoped:b,records:A})=>({objectApiName:b.objectApiName,records:A})),O,a,d);for(let b of S)b.recount=p.of.get(b.scoped.objectApiName)??{};w.sort((b,A)=>b.objectApiName<A.objectApiName?-1:b.objectApiName>A.objectApiName?1:0);let k={};for(let{scoped:b,describe:A}of S)k[b.objectApiName]=Pe(A.fields);let y=Vt(f,nt({described:o.described,describedAlone:o.describedAlone,counted:o.objects.length,countedAlone:h,recounted:p.asked,objects:S.map(b=>({records:b.records,otherGroups:b.otherGroups,...b.recount,entry:mt(b,b.records,0,k[b.scoped.objectApiName].digest)})),pageRows:zt(n.registered),leftOut:w,printsBytes:(await Ie(k)).length})),g={...y,apiRequestsLeft:s.remaining},j={objects:S,leftOut:w,estimate:g,objectLimit:c,prints:k,...O!==void 0?{linkable:O}:{}};if(y.records>i){let b=[...S.map(A=>A.records),...w.flatMap(A=>A.code==="pastTheLimit"?[A.records??0]:[])];return{...j,refusal:{code:"TOO_MANY_RECORDS",message:`The objects this checkpoint would keep hold ${y.records} records in ${n.orgName}, past its limit of ${i}: pick fewer objects. ${W}`,holdingLimit:Wt(b,y.records)}}}let M=ot("take",y.apiRequests,s,n.orgName);return M===void 0?j:{...j,refusal:M}}function bt(e){return{query:t=>e.query(t),queryMore:t=>e.queryMore(t)}}var kt={guard:0,scope:0};function Vt(e,t){if(e.guard+e.scope===0)return t;let n=t.requestsByPhase;return{...t,apiRequests:t.apiRequests+e.guard+e.scope,...n!==void 0?{requestsByPhase:{...n,guard:n.guard+e.guard,scope:n.scope+e.scope}}:{}}}function Ht(e){let t=[...e.mode==="picked"?e.objects??[]:[],...Array.isArray(e.customSettings)?e.customSettings:[]];return new Set(t.map(n=>n.toLowerCase()))}function Kt(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}async function wt(e,t,n,o,s,a){if(s.kind==="org")return{scope:{...o,objects:o.objects.map(p=>({...p,access:"org"}))},reads:kt};let d=o.objects.map(({scoped:p})=>p.objectApiName),f={grants:s.objects,describes:o.objects.map(({describe:p})=>p),customSettings:o.objects.filter(({customSetting:p})=>p!==void 0).map(({scoped:p})=>p.objectApiName)},i=Ze(d,f),c=[],l=0;if(i.length>0)try{let p=await se(e,t,i);c=[...p.describes.values()],l=Math.ceil(i.length/We)+p.alone}catch(p){if(B(p,a))throw p}let u=et(d,{...f,describes:[...f.describes,...c]}),h=Ht(n),r=[],m=[...o.leftOut],w=[];for(let p of o.objects){let k=p.scoped.objectApiName,y=u.get(k);if(y!==void 0&&"access"in y){r.push({...p,access:y.access});continue}let g={objectApiName:k,reason:y?.reason??"noViewAll",...y?.detail!==void 0?{detail:y.detail}:{}};m.push(g),h.has(k.toLowerCase())&&n.unprovenLeftOut!==!0&&w.push(g)}let S=new Set(r.map(({scoped:p})=>p.objectApiName)),O={scope:{...o,objects:r,leftOut:m,addedToPicked:o.addedToPicked.filter(p=>S.has(p))},reads:{guard:s.requests,scope:l}};if(w.length>0){let p=w.length===1;return{...O,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, and the checkpoint can't hold ${Kt(w.map(k=>k.objectApiName))}, asked for by name. ${w.map(k=>`${k.objectApiName}: ${lt(k).reason}`).join(" ")} Leave ${p?"it":"them"} out, or give the user View All Data and Modify All Data. ${W}`}}}return r.length===0&&o.objects.length>0?{...O,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, nor View All and Modify All on any object this checkpoint would hold: without them, a checkpoint holds only the objects its user sees and puts back whole. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. `+W}}:O}function Jt(e){return e.objects.map(({scoped:t,label:n,capture:o,records:s,customSetting:a,access:d})=>({objectApiName:t.objectApiName,label:n,...t.namespace!==void 0?{namespace:t.namespace}:{},records:s,undeletable:o.undeletable,leftOutFields:o.leftOutFields,...a!==void 0?{customSetting:a}:{},...d!==void 0?{access:d}:{}}))}function yt(e){let t=e.customSettings;return t!==void 0&&(t==="all"||t.length>0)}async function Qt(e,t,n,o,s){let a=new Map(o.objects.map(u=>[u.scoped.objectApiName,u])),d=n.settings.filter(({objectApiName:u})=>!a.has(u)),f=new Map;if(d.length>0)try{({describes:f}=await se(e,t,d.map(({objectApiName:u})=>u)))}catch(u){if(B(u,s))throw u}let i=d.filter(({objectApiName:u})=>f.has(u)),c=await Z(t,i.map(({objectApiName:u})=>({objectApiName:u,readMode:"query"})),s),l=new Map;return c.forEach((u,h)=>{"count"in u&&l.set(i[h].objectApiName,u.count)}),n.settings.map(({objectApiName:u,label:h})=>{let r=a.get(u);if(r?.customSetting!==void 0)return{objectApiName:u,label:h,kind:r.customSetting,records:r.records};let m=f.get(u),w=l.get(u);return{objectApiName:u,label:h,...m!==void 0?{kind:K(m)}:{},...w!==void 0?{records:w}:{}}})}var Xt={records:0,apiRequests:0,apiRequestsLeft:0,seconds:0,bytes:0};async function Bn(e,t){let n={mode:t.mode,objects:[],leftOut:[],estimate:Xt},o=await ee(bt(e.org),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:yt(t)},{userId:()=>e.org.userId()});if(!o.allowed)return{...n,refusal:o.refusal};let s=e.store.heldBy(o.org.id),a=s===void 0?await e.runWriting?.(o.org.id):void 0,d=Y(e.org,e.signal);try{let f=await te(e.org,t.orgName),i=await wt(e.org,d,t,await pt(e.org,d,t),o.grants,e.signal),{scope:c}=i,l=await e.org.serverTime(),u=await ht(e.org,d,t,c,f,l,e.signal,i.reads),h={mode:t.mode,objects:Jt(u),leftOut:u.leftOut,estimate:u.estimate,files:{held:u.objects.some(({scoped:m})=>D(m.objectApiName)),queryAllFiles:o.queryAllFiles,addedToPicked:c.addedToPicked},customSettings:await Qt(e.org,d,c,u,e.signal)},r=s!==void 0?ut(t.orgName,s):a!==void 0?{code:"RUN_WRITING",message:a}:i.refusal??u.refusal;return r===void 0?h:{...h,refusal:r}}catch(f){throw B(f,e.signal)?new N:f}}function Yt(e){let t=e.requestsSent?()=>e.requestsSent?.()??0:void 0,n={guard:0,scope:0,start:0,counts:0,bin:0,snapshot:0,stability:0},o="guard",s=t?.()??0,a=()=>{if(!t)return;let d=t();n[o]+=d-s,s=d};return{enter(d){a(),o=d},requests(){return t?(a(),{total:Object.values(n).reduce((f,i)=>f+i,0),byPhase:{...n}}):void 0}}}async function qt(e,t){if(t.edition!==void 0)return t.edition;let o=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;if(typeof o!="string"||o==="")throw new Error("The org did not say its edition (Organization.OrganizationType).");return o}var Zt="Automated Process";async function en(e){let n=(await e.query("SELECT Id, Name FROM User WHERE UserType = 'AutomatedProcess'")).records.filter(s=>typeof s.Id=="string"),o=n.find(s=>s.Name===Zt);return o!==void 0?o.Id:n.length===1?n[0].Id:void 0}function St(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function at(e,t){return e.split(he).join(St(t))}function ne(e){let t=Oe(e);return t===null?Number.NaN:Date.parse(t)}function Ot(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}async function tn(e,t){let n=new Set;for await(let o of L(Q(e,t))){let s=Ot(o.Id);s!==void 0&&n.add(s)}return n}async function nn(e,t,n,o,s,a){let d={changed:0,deleted:0,created:0};if(!o.live&&!o.deleted)return d;let f=await Xe.read(e,t,n);if(o.live)for await(let i of L(o.live.file)){let c=ne(i.SystemModstamp);if(!(c<=a))continue;let l=f.stampOf(i.Id);l===void 0?d.created++:l!==c&&d.changed++}if(o.deleted){let i;for await(let c of L(o.deleted.file)){if(!(ne(c.SystemModstamp)<=a))continue;if(f.has(c.Id)){d.deleted++;continue}if(!(ne(c.CreatedDate)<s))continue;i??=await tn(e,n);let l=Ot(c.Id);l!==void 0&&!i.has(l)&&d.deleted++}}return d}async function At(e){let t=0;for(let n of await Nt(e,{withFileTypes:!0})){let o=oe(e,n.name);n.isDirectory()?t+=await At(o):n.isFile()&&(t+=(await dt(o)).size)}return t}async function on(e,t){let n=await At(e.dir)-(await dt(e.checkpointFile)).size,o=a=>Buffer.byteLength(`${JSON.stringify({...t,bytes:a},null,2)}
|
|
8
|
-
`,"utf8"),s=n+o(n);return s=n+o(s),s}function sn(e){let t=e.snapshotsFile,n=new Ne({getData:()=>Dt(t)?JSON.parse(Mt(t,"utf8")):{},setData:o=>Pt(t,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})});return n.initialize(),n}var rn=V({organizationId:fe().optional()}).loose();async function an(e,t,n,o,s){let a=sn(e),d=0,f={log:n.handler.log,orgManager:n.handler.orgManager,orgRegistry:n.handler.orgRegistry,configStore:a,broker:{postToWebview:c=>{if(c.type!=="operation:progress")return;let l=c.payload;typeof l.percentage=="number"&&typeof l.currentStep=="string"&&s(l.percentage,l.currentStep)}},services:{getSandforgeSetting:(c,l)=>c==="backup.maxRecordsPerObject"?o:l},nextId:()=>`${e.checkpointId}-${++d}`},i=new Re(f);return i.setBackupRecordStore(new Me(t)),await i.swept(),{handler:i,config:a}}function cn(e,t){return e.slice(0,15)===t.slice(0,15)}async function _n(e,t){let{org:n,store:o,signal:s}=e,a=e.now??(()=>new Date),d=ge.parse([...t.ignoredFields??[]]),f=t.name===void 0?void 0:E.parse(t.name),i=t.nameWithDate;i!==void 0&&E.parse(at(i,a().toISOString()));let c=t.customSettings==="all"?[]:t.customSettings??[];for(let y of[...t.objects??[],...t.excluded??[],...c])$(y);let l=t.beforeRun===void 0?void 0:me.parse(t.beforeRun),u=t.keepDays??ve;I(a(),u);let h=(y,g,j=0,M=0)=>e.onProgress?.({percentage:Math.round(y),processedObjects:j,totalObjects:M,step:g});h(0,`Checking ${t.orgName}`);let r=Yt(n),m=await ee(bt(n),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:yt(t)},{userId:()=>n.userId()});if(!m.allowed)return{taken:!1,refusal:m.refusal};let w=m.org.id,S=$e("ck",a()),O=o.lock(w,"take",S);if("busy"in O)return{taken:!1,refusal:ut(t.orgName,O.busy)};let p,k;try{let y=await e.runWriting?.(w);if(y!==void 0)return{taken:!1,refusal:{code:"RUN_WRITING",message:y}};let g=Y(n,s),j=await qt(n,m.org),M=await te(n,t.orgName);h(2,`Reading the objects of ${t.orgName}`),r.enter("scope");let b=await wt(n,g,t,await pt(n,g,t),m.grants,s);if(b.refusal!==void 0)return{taken:!1,refusal:b.refusal};let{scope:A}=b;r.enter("start");let P=await n.userId(),ie=await en(n),R=await n.serverTime();h(8,`Counting the records of ${A.objects.length} objects`),r.enter("counts");let T=await ht(n,g,t,A,M,R,s,b.reads);if(T.refusal!==void 0)return{taken:!1,refusal:T.refusal};if(T.objects.length===0)throw new Error(`None of the objects asked for can be kept in a checkpoint of ${t.orgName}: ${T.leftOut.map(C=>`${C.objectApiName}: ${C.reason}`).join(" ")||"there are none."}`);if(s?.aborted)throw new N;p=await o.create(w,S);let _=`snapshot-${S}`;k={version:1,checkpointId:S,name:f??(i!==void 0?E.parse(at(i,R)):St(R)),org:{organizationId:w,...t.alias!==void 0?{alias:t.alias}:{},username:t.username,instanceUrl:t.instanceUrl,isSandbox:m.org.sandbox,organizationType:j,tier:m.tier,...t.scratchExpiresAt!==void 0?{scratchExpiresAt:t.scratchExpiresAt}:{}},takenBy:{userId:P,...ie!==void 0?{automatedProcessUserId:ie}:{},viewAllData:m.grants.kind==="org"||m.grants.viewAllData,modifyAllData:m.grants.kind==="org"||m.grants.modifyAllData,queryAllFiles:m.queryAllFiles},readFrom:R,takenAt:R,scope:{mode:t.mode,leftOut:T.leftOut},objects:[],ignoredFields:d,snapshotId:_,movedWhileTaken:{changed:0,deleted:0,created:0},bytes:0,expiresAt:I(a(),u),status:"taking",takenOn:{host:vt(),pid:process.pid},...l!==void 0?{beforeRun:l}:{}},await o.write(k),h(12,"Reading the recycle bin as it was at the checkpoint"),r.enter("bin");let jt=await He(g,T.objects.map(({scoped:C})=>({...ze(C.objectApiName,R),file:Q(p,C.objectApiName)})),s),re=new Map;for(let C of jt){if(!C.read)throw new Error(`The recycle bin of ${C.objectApiName} could not be read whole: ${C.reason}`);re.set(C.objectApiName,C.rows)}r.enter("snapshot");let{records:Ct,files:ae}=await dn(p,_,T,t,e,w,g,h);h(88,"Reading the time on the org"),r.enter("stability");let ce=await n.serverTime();h(90,`Checking what changed in ${t.orgName} while it was read`);let{movedWhileTaken:Tt,notChecked:Rt}=await ln(p,_,T,g,R,ce,s),{prints:de}=T;await o.writeFingerprints(p,de);let G=T.objects.map(C=>{let z=C.scoped.objectApiName;return mt(C,Ct.get(z)??0,re.get(z)??0,de[z].digest)});if(s?.aborted)throw new N;let le={...k,takenAt:ce,objects:G,movedWhileTaken:Tt,bytes:0,expiresAt:I(a(),u),status:"ready",...ae!==void 0?{files:ae}:{}},U={...le,bytes:await on(p,le)};await o.write(U),h(100,`Checkpoint '${U.name}' taken`,G.length,G.length);let ue=r.requests();return{taken:!0,checkpoint:U,notChecked:Rt,...ue!==void 0?{requests:ue}:{},estimate:T.estimate}}catch(y){throw p!==void 0&&await un(o,p,k,e),B(y,s)?new N:y}finally{O.lock.release()}}async function dn(e,t,n,o,s,a,d,f){let i=n.objects.filter(r=>r.records>0),c=new Map,l=(s.snapshotFiles??It)(e.dir);if(i.length>0){let r=Math.max($t,n.objectLimit),{handler:m,config:w}=await an(e,l,s,r,(k,y)=>f(15+k*.65,y)),S=await m.backupForPipeline({operationId:t,orgId:o.orgId,objects:i.map(({scoped:k})=>k.objectApiName),fields:new Map(i.map(({scoped:k,capture:y})=>[k.objectApiName,y.fields])),scanAll:i.filter(({capture:k})=>k.readMode==="scanAllLive").map(({scoped:k})=>k.objectApiName),origin:"checkpoint",failWhenTruncated:!0,onConnection:k=>s.org.countAlso?.(k)},s.signal),O=rn.safeParse(w.get(`backup:${t}`)),p=O.success?O.data.organizationId:void 0;if(p===void 0||!cn(p,a))throw new Error(`The snapshot was read from ${p===void 0?"an org that did not say which it is":`another org (${p})`}, not from ${o.orgName}: it is not kept.`);for(let k of S.objects)c.set(k.objectApiName,k.recordCount)}f(82,"Indexing the snapshot",0,n.objects.length);for(let[r,{scoped:m}]of n.objects.entries()){let w=m.objectApiName,S=c.get(w)??0;c.has(w)||(await Ee(oe(e.dir,"backups")),await l.writeFile(Je(e,t,w),""),c.set(w,0));let O=await Qe(e,t,w);if(O.rows!==S)throw new Fe("damaged",`The snapshot of ${w} holds ${O.rows} records where its read kept ${S}: it is not kept.`);f(82+6*(r+1)/n.objects.length,`Indexed ${w}`,r+1,n.objects.length)}let u=n.objects.find(({scoped:r})=>D(r.objectApiName));if(u===void 0||n.linkable===void 0)return{records:c};f(88,"Reading the links of files to the records read");let h=await qe({reader:d,folder:e,snapshotId:t,linked:n.objects.map(({scoped:r})=>r.objectApiName).filter(r=>(c.get(r)??0)>0&>(r,n.linkable)),documentsInSnapshot:(c.get(u.scoped.objectApiName)??0)>0,...s.signal!==void 0?{signal:s.signal}:{}});return{records:c,files:h}}async function ln(e,t,n,o,s,a,d){let f=oe(e.dir,Ft),i={changed:0,deleted:0,created:0},c=[];try{let l=await Ke(o,n.objects.map(({capture:r})=>({objectApiName:r.objectApiName,readMode:r.readMode,held:!1})),s,f,d),u=Date.parse(q(s)),h=Date.parse(a);for(let r of l){if("unread"in r){c.push({objectApiName:r.objectApiName,reason:r.unread});continue}if(!r.moved)continue;let m=await nn(e,t,r.objectApiName,r,u,h);i.changed+=m.changed,i.deleted+=m.deleted,i.created+=m.created}}finally{await ct(f,{recursive:!0,force:!0})}return{movedWhileTaken:i,notChecked:c}}async function un(e,t,n,o){try{n!==void 0&&await e.write({...n,status:"failed"})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: not marked failed: ${v(s)}`)}try{await ct(t.dir,{recursive:!0,force:!0})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: what its take wrote was not removed: ${v(s)}`)}}export{Et as a,x as b,Wn as c,N as d,xt as e,Wt as f,Bn as g,_n as h};
|
package/lib/chunk-LPBMBW3O.mjs
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{F as k,d as I,l as H,m as W,n as K}from"./chunk-IFETCRWE.mjs";import{C as at}from"./chunk-EQNW3UC2.mjs";import{a as J}from"./chunk-GGD7ON3M.mjs";import{b as N,l as j}from"./chunk-7EANH5PY.mjs";import{createReadStream as $t}from"node:fs";import{appendFile as Ut,stat as jt,writeFile as Jt}from"node:fs/promises";import{StringDecoder as Ht}from"node:string_decoder";import{promisify as dt}from"node:util";import{createGunzip as Wt,gunzip as Kt,gzip as Gt}from"node:zlib";var Yt=dt(Gt),Zt=dt(Kt),Xt=64*1024,Vt=".gz",Qt=6,A=10,ft=4,ut=Buffer.from("SF","latin1"),Y=8,F=6+Y,Z=A+F,X=Z+2+8;function B(s){return`${s}${Vt}`}async function qt(s){let t=await Yt(s,{level:Qt});if(t[3]!==0)throw new Error("zlib wrote a gzip header with flags set");let e=Buffer.from(t.subarray(0,A));e[3]=ft;let n=Buffer.alloc(F);return n.writeUInt16LE(F-2,0),ut.copy(n,2),n.writeUInt16LE(Y,4),n.writeUInt32LE(t.length+F,6),n.writeUInt32LE(s.length,10),Buffer.concat([e,n,t.subarray(A)])}function ht(s){if(s.length<Z||s[0]!==31||s[1]!==139||s[2]!==8||s[3]!==ft||s.readUInt16LE(A)!==F-2||!s.subarray(A+2,A+4).equals(ut)||s.readUInt16LE(A+4)!==Y)return;let t=s.readUInt32LE(A+6),e=s.readUInt32LE(A+10);return t>=X&&e>0?{total:t,raw:e}:void 0}function te(s,t=Xt){let e=[],n=0,r=0;for(;r<s.length;){let i=s.indexOf(10,r),o=i<0?s.length:i+1;o-n>t&&r>n&&(e.push(s.subarray(n,r)),n=r),r=o,r-n>=t&&(e.push(s.subarray(n,r)),n=r)}return r>n&&e.push(s.subarray(n,r)),e}async function ct(s){let t=te(Buffer.from(s,"utf8"));return Buffer.concat(await Promise.all(t.map(e=>qt(e))))}function T(s){return s.endsWith(".ndjson")}function _e(s){let t=new Map,e=(n,r)=>{let i=r(t.get(n)??Promise.resolve());return t.set(n,i),i.then(()=>{t.get(n)===i&&t.delete(n)},()=>{}),i};return{...s,writeFile:(n,r)=>{if(!T(n))return s.writeFile(n,r);let i=B(n);return e(i,o=>o.catch(()=>{}).then(async()=>{let a=r===""?Buffer.alloc(0):await ct(r);await Jt(i,a,{mode:I})}))},appendFile:(n,r)=>{if(!T(n))return s.appendFile(n,r);let i=B(n);return e(i,o=>o.then(async()=>{r!==""&&await Ut(i,await ct(r),{mode:I})}))},exists:n=>s.exists(T(n)?B(n):n),rm:n=>s.rm(T(n)?B(n):n),readLines:n=>T(n)?ee(B(n)):s.readLines(n)}}async function*ee(s){if((await jt(s)).size===0)return;let t=$t(s),e=Wt(),n=o=>{e.destroy(o)};t.on("error",n),t.pipe(e);let r=new Ht("utf8"),i="";try{for await(let o of e){let a=(i+r.write(o)).split(`
|
|
8
|
-
`);i=a.pop()??"",yield*a}i+=r.end(),i!==""&&(yield i)}finally{t.off("error",n),t.destroy(),e.destroy()}}async function G(s,t,e){let n=Buffer.alloc(e),r=0;for(;r<e;){let{bytesRead:i}=await s.read(n,r,e-r,t+r);if(i===0)break;r+=i}return r===e?n:n.subarray(0,r)}async function lt(s,t,e,n){let r;try{r=await Zt(s,{maxOutputLength:t.raw})}catch{throw n(`holds a block that does not inflate at byte ${e}`)}if(r.length!==t.raw)throw n(`holds a block at byte ${e} that inflates to other than its header says`);return r}async function pt(s,t,e,n){let r=await G(s,t,e);if(r.length<e)throw n(`is cut short at byte ${t+r.length}`);let i=ht(r);if(i===void 0)throw n(`holds no block where its index says, at byte ${t}`);if(i.total!==e)throw n(`holds another block than its index says at byte ${t}`);return lt(r,i,t,n)}async function*gt(s,t,e){for(let n=0;n<t;){let r=ht(await G(s,n,Math.min(Z,t-n)));if(r===void 0)throw e(`holds no block at byte ${n}`);if(r.total>t-n)throw e(`is cut short: its block at byte ${n} ends past the file's end`);let i=await G(s,n,r.total);yield{at:n,total:r.total,lines:await lt(i,r,n,e)},n+=r.total}}function*mt(s){let t=0;for(;t<s.length;){let e=s.indexOf(10,t),n=e<0?s.length:e;yield{at:t,length:n-t},t=n+1}}import{randomBytes as Se}from"node:crypto";import{open as C,readFile as it,rename as xe,rm as ke,stat as Ae}from"node:fs/promises";import{dirname as Ft,join as Be}from"node:path";import{closeSync as ne,fstatSync as re,openSync as ie,readSync as se,writeSync as oe}from"node:fs";function Ue(s){let t=ie(s,"a+"),e=re(t).size;return{size:()=>e,append:n=>{let r=Buffer.from(n,"utf8"),i=0;for(;i<r.length;)i+=oe(t,r,i);e+=r.length},read:(n,r)=>{let i=Buffer.alloc(r),o=0;for(;o<r;){let a=se(t,i,o,r-o,n+o);if(a===0)break;o+=a}return i.subarray(0,o)},close:()=>ne(t)}}function yt(s,t){return t===void 0?s:`${s}/${t}`}var wt=/^[A-Za-z][A-Za-z0-9]*$/,bt=/^[0-9a-f]{64}$/,x=1,O=2,z=3,S=4,ae={created:x,existing:O,updated:z},St={[x]:"created",[O]:"existing",[z]:"updated"},xt={[x]:"c",[O]:"e",[z]:"u",[S]:"i"},V={c:x,e:O,u:z,i:S},ce="x",de="a",fe="j",Ot="d",Q="n",P="t",kt="found",ue="found-owed";function je(s,t,e,n){return JSON.stringify([Ot,s,t,e,n])}function Je(s){if(!s.startsWith(`["${Ot}"`))return;let t;try{t=JSON.parse(s)}catch{return}if(!Array.isArray(t))return;let[,,,e,n]=t;if(!(typeof e!="string"||!Number.isFinite(Date.parse(e)))&&!(typeof n!="string"||!Number.isFinite(Date.parse(n))))return{orgAt:e,at:n}}function he(s,t=!1){return JSON.stringify([t?"w":"o",s.objectApiName,s.newId,s.sourceId??"",s.fieldName,s.sourceRefId,s.insertOnly?1:0])}var le=1024*1024,pe=1024*1024,ge=2e4,me=2e4,ye=.6,we=3;function g(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return t>>>0}function y(s){let t=2538058380;for(let e=0;e<s.length;e++)t=Math.imul(t^s.charCodeAt(e),1540483477),t^=t>>>15;return t>>>0}var v=class{constructor(t){this.keyAt=t}keyAt;capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);at=new Float64Array(this.capacity);len=new Uint16Array(this.capacity);code=new Uint8Array(this.capacity);get size(){return this.used}get slots(){return this.capacity}find(t,e,n,r){let i=this.capacity-1,o=n&i;for(;;){let a=this.at[o];if(a===0)return~o;if(this.h1[o]===e&&this.h2[o]===n&&(r===a-1||this.keyAt(a-1,this.len[o])===t))return o;o=o+1&i}}offsetOf(t){return this.at[t]-1}lengthOf(t){return this.len[t]}codeOf(t){return this.code[t]}put(t,e,n,r,i,o){let a=t;t<0&&(this.used+1>this.capacity*ye?(this.grow(),a=this.freeSlotFor(n)):a=~t,this.used++,this.h1[a]=e,this.h2[a]=n),this.at[a]=r+1,this.len[a]=i,this.code[a]=o}freeSlotFor(t){let e=this.capacity-1,n=t&e;for(;this.at[n]!==0;)n=n+1&e;return n}grow(){let{h1:t,h2:e,at:n,len:r,code:i}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.at=new Float64Array(this.capacity),this.len=new Uint16Array(this.capacity),this.code=new Uint8Array(this.capacity);for(let o=0;o<n.length;o++){if(n[o]===0)continue;let a=this.freeSlotFor(e[o]);this.h1[a]=t[o],this.h2[a]=e[o],this.at[a]=n[o],this.len[a]=r[o],this.code[a]=i[o]}}};function At(s){return s?s[0]==="p"&&s.length>=3?tt(String(s[1]),String(s[2])):s[0]==="g"&&s.length>=3?et(String(s[2])):s[0]===P&&s.length>=2?q(String(s[1])):"":""}function q(s){return`t\0${s}`}function tt(s,t){return`p\0${s}\0${t}`}function et(s){return`g\0${s}`}function*be(s){let t=s.size(),e=0,n=Buffer.alloc(0),r=0;for(;e<t;){let i=s.read(e,Math.min(pe,t-e));if(i.length===0)break;e+=i.length;let o=n.length>0?Buffer.concat([n,i]):i,a=0;for(;;){let d=o.indexOf(10,a);if(d<0)break;d>a&&(yield{offset:r+a,length:d-a,text:o.toString("utf8",a,d)}),a=d+1}n=o.subarray(a),r+=a}}var Bt=class s{constructor(t){this.file=t;this.index=new v((e,n)=>this.idOfLine(e,n)),this.marks=new v((e,n)=>At(w(this.lineAt(e,n)))),this.createdTargets=new v((e,n)=>{let r=w(this.lineAt(e,n));return r?M(String(r[2]??"")):""})}file;index;cache=new Map;pending=[];pendingBytes=0;flushQueued=!1;partStart=Number.POSITIVE_INFINITY;parts=0;mappedCount=0;counts=new Map;earlierByObject=new Map;earlierPastCheckpoint=new Map;checkpointsByObject=new Map;owedCount=0;statuses=new Map;given=new Map;marks;createdTargets;createdUnattributedKeys=new Set;readsHeld=[];withTheirRecordMarked=0;callsSent=0;foundAfterStop=new Set;foundOwingUntold=new Set;plan;static open(t){let e=new s(t);return e.readWhatIsThere(),e}get partCount(){return this.parts}get resumes(){return this.checkpointsByObject.size>0||this.earlierByObject.size>0||this.owedCount>0}get earlierMapped(){return this.partStart===Number.POSITIVE_INFINITY?this.mappedCount:this.mappedBeforePart}mappedBeforePart=0;beginPart(t){this.flush(),this.mappedBeforePart=this.mappedCount,this.withTheirRecordMarked=0,this.partStart=this.file.size(),this.write({part:{n:this.parts,startedAt:t.toISOString()}}),this.parts++,this.flush()}nameSamplePlan(t){if(!bt.test(t.sha256))throw new Error("Not the SHA-256 of a plan.");this.write({sample:{dir:t.dir,sha256:t.sha256}}),this.plan={dir:t.dir,sha256:t.sha256},this.flush()}get samplePlan(){return this.plan?{...this.plan}:void 0}setMapping(t,e,n,r){let i=ae[t],o=g(e),a=y(e),d=this.cache.get(e),u=this.index.find(e,o,a,d?.at),h=u>=0&&this.index.codeOf(u)!==S;h&&this.uncount(e,u,d);let c=JSON.stringify([xt[i],e,n,r??""]),f=this.write(c);if(this.index.put(u,o,a,f,Buffer.byteLength(c),i),i===x&&this.indexCreated(n,f,Buffer.byteLength(c)),h||this.mappedCount++,r){let l=this.countsOf(r);i===x?l.created++:i===O?l.linked++:l.updated++}this.remember(e,{at:f,code:i,targetId:n,objectApiName:r??""})}uncount(t,e,n){let r=this.index.offsetOf(e);if(r<this.partStart)return;let i=this.index.codeOf(e),o=n?.at===r?n:this.recordAt(t,e),a=o?.objectApiName?this.counts.get(o.objectApiName):void 0;a&&(i===x?a.created--:i===O?a.linked--:a.updated--)}countsOf(t){let e=this.counts.get(t);return e||(e={created:0,linked:0,updated:0},this.counts.set(t,e)),e}mapping(t){let e=this.lookUp(t);if(!(!e||e.code===S))return{kind:St[e.code],sourceId:t,targetId:e.targetId,...e.objectApiName?{objectApiName:e.objectApiName}:{},earlier:e.at<this.partStart}}createdTarget(t){let e=M(t);if(this.createdUnattributedKeys.has(e))return!0;if(this.createdTargets.size===0)return!1;let n=this.createdTargets.find(e,g(e),y(e));if(n<0)return!1;let r=this.createdTargets.offsetOf(n),i=w(this.lineAt(r,this.createdTargets.lengthOf(n)));if(!i)return!1;let o=String(i[1]),a=this.index.find(o,g(o),y(o));return a>=0&&this.index.offsetOf(a)===r&&this.index.codeOf(a)===x}indexCreated(t,e,n){let r=M(t);if(!r)return;let i=g(r),o=y(r);this.createdTargets.put(this.createdTargets.find(r,i,o),i,o,e,n,x)}targetOf(t){let e=this.lookUp(t);return e&&e.code!==S?e.targetId:void 0}get mappedSize(){return this.mappedCount}countsByObject(){let t=[];for(let[e,{created:n,linked:r,updated:i}]of this.counts)n+r+i!==0&&t.push(i>0?{objectApiName:e,created:n,linked:r,updated:i}:{objectApiName:e,created:n,linked:r});return t}linkedToCreatedCount(){let t=0;for(let c of this.counts.values())t+=c.linked;if(t===0)return 0;let e=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart,n=(c,f)=>{let l=w(this.lineAt(c,f));return l?String(l[2]).slice(0,15):""},r=(c,f)=>{if(c.offset<e)return;let l=V[String(f[0])];if(l===void 0||l===S||!f[3])return;let p=String(f[1]),m=this.index.find(p,g(p),y(p),c.offset);return m>=0&&this.index.offsetOf(m)===c.offset?l:void 0},i=(c,f,l)=>{let p=g(f),m=y(f);c.put(c.find(f,p,m),p,m,l.offset,l.length,0)},o=(c,f)=>c.size>0&&c.find(f,g(f),y(f))>=0,a=new v(n);for(let c of this.lines()){if(!c.text.startsWith('["'))continue;let f=w(c.text);!f||r(c,f)!==O||this.markedWithTheirRecord(String(f[1]))||i(a,String(f[2]).slice(0,15),c)}if(a.size===0)return 0;let d=new v(n),u=new Set;for(let c of this.lines()){if(!c.text.startsWith('["')||c.offset<e)continue;let f=w(c.text);if(!f)continue;if(f[0]===Q&&Array.isArray(f[2])){for(let p of f[2]){let m=String(p).slice(0,15);o(a,m)&&u.add(m)}continue}if(r(c,f)!==x)continue;let l=String(f[2]).slice(0,15);o(a,l)&&i(d,l,c)}if(d.size===0&&u.size===0)return 0;let h=0;for(let c of this.lines()){if(!c.text.startsWith('["'))continue;let f=w(c.text);if(!f||r(c,f)!==O||this.markedWithTheirRecord(String(f[1])))continue;let l=String(f[2]).slice(0,15);(o(d,l)||u.has(l))&&h++}return h}earlierRecordsOf(t,e=!1){return(e?this.earlierPastCheckpoint:this.earlierByObject).get(t)??0}*mappings(){for(let t of this.lines()){if(!t.text.startsWith('["'))continue;let e=w(t.text);if(!e)continue;let n=V[String(e[0])];if(n===void 0||n===S)continue;let r=String(e[1]),i=this.index.find(r,g(r),y(r),t.offset);if(i<0||this.index.offsetOf(i)!==t.offset)continue;let o=String(e[3]??"");yield{kind:St[n],sourceId:r,targetId:String(e[2]),...o?{objectApiName:o}:{},earlier:t.offset<this.partStart}}}noteRead(t){this.readsHeld.push(t),this.readsHeld.length>=me&&this.settleReads()}settleReads(){let t=this.readsHeld;this.readsHeld=[];for(let e of t){let n=g(e),r=y(e),i=this.index.find(e,n,r,this.cache.get(e)?.at);if(i>=0)continue;let o=JSON.stringify([xt[S],e]),a=this.write(o);this.index.put(i,n,r,a,Buffer.byteLength(o),S)}}wasRead(t){return this.readsHeld.includes(t)?!0:this.index.find(t,g(t),y(t),this.cache.get(t)?.at)>=0}checkpoint(t,e,n){if(n!==void 0&&!wt.test(n))throw new Error(`Not the name of a pass: ${JSON.stringify(n.slice(0,40))}`);this.settleReads(),this.write({at:{object:t,...n!==void 0?{pass:n}:{},...e}}),this.checkpointsByObject.set(yt(t,n),{...e}),this.flush()}checkpoints(){return new Map(this.checkpointsByObject)}owe(t,e=!1){this.owedCount++,this.write(he(t,e))}get owed(){return this.owedCount}*owedPages(t){let e=[];for(let n of this.lines()){if(!n.text.startsWith('["o"')&&!n.text.startsWith('["w"'))continue;let r=w(n.text);if(!r||r.length<7)continue;let[i,o,a,d,u,h,c]=r;e.push({update:{objectApiName:String(o),newId:String(a),sourceId:d?String(d):void 0,fieldName:String(u),sourceRefId:String(h),...c===1?{insertOnly:!0}:{}},toRowWrittenBefore:i==="w"}),e.length>=t&&(yield e,e=[])}e.length>0&&(yield e)}patched(t,e){this.mark(JSON.stringify(["p",t,e]),tt(t,e))}wasPatched(t,e){return this.hasMark(tt(t,e))}mark(t,e){let n=g(e),r=y(e),i=this.marks.find(e,n,r),o=this.write(t);this.marks.put(i,n,r,o,Buffer.byteLength(t),0)}hasMark(t){return this.marks.size>0&&this.marks.find(t,g(t),y(t))>=0}owedLeftByEarlierParts(){let t=new Set;for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["p"'))continue;let r=w(n.text);r&&r.length>=3&&t.add(`${String(r[1])}\0${String(r[2])}`)}let e=[];for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["o"'))continue;let r=w(n.text);if(!r||r.length<7)continue;let[,i,o,a,d,u,h]=r;t.has(`${String(o)}\0${String(d)}`)||e.push({objectApiName:String(i),newId:String(o),sourceId:a?String(a):void 0,fieldName:String(d),sourceRefId:String(u),...h===1?{insertOnly:!0}:{}})}return e}oweStatus(t,e,n){this.write(JSON.stringify(["s",t,e,n])),this.tallyStatus({objectApiName:t,id:e,status:n})}tallyStatus(t){let e=this.statuses.get(t.objectApiName);e||(e={count:0,samples:[]},this.statuses.set(t.objectApiName,e)),e.count++,e.samples.length<we&&e.samples.push(t)}gaveStatus(t,e){this.statusGiven(e)||(this.mark(JSON.stringify(["g",t,e]),et(e)),this.given.set(t,(this.given.get(t)??0)+1))}statusGiven(t){return this.hasMark(et(t))}statusesOwed(){let t=new Map;for(let[e,n]of this.statuses){let r=n.count-(this.given.get(e)??0);r<=0||t.set(e,{count:r,samples:n.samples.filter(({id:i})=>!this.statusGiven(i))})}return t}*statusLines(){for(let t of this.lines()){if(!t.text.startsWith('["s"'))continue;let e=w(t.text);!e||e.length<4||(yield{objectApiName:String(e[1]),id:String(e[2]),status:String(e[3])})}}withTheirRecord(t){let e=q(t),n=g(e),r=y(e),i=this.marks.find(e,n,r),o=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;if(i>=0&&this.marks.offsetOf(i)>=o)return;let a=JSON.stringify([P,t]),d=this.write(a);this.marks.put(i,n,r,d,Buffer.byteLength(a),0),this.withTheirRecordMarked++}get withTheirRecordCount(){return this.withTheirRecordMarked}markedWithTheirRecord(t){if(this.withTheirRecordMarked===0)return!1;let e=q(t),n=this.marks.find(e,g(e),y(e)),r=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;return n>=0&&this.marks.offsetOf(n)>=r}*withTheirRecordIds(){if(this.withTheirRecordMarked!==0)for(let t of this.lines()){if(t.offset<this.partStart||!t.text.startsWith(`["${P}"`))continue;let e=w(t.text);e&&e.length>=2&&(yield String(e[1]))}}sent(t,e,n,r=new Date,i){this.callsSent++;let o=`${Math.max(0,this.parts-1)}.${this.callsSent}`;return this.write(JSON.stringify([ce,o,t,r.toISOString(),e,n.map(({sourceId:a,fingerprint:d,externalKey:u,jobKey:h})=>i!==void 0&&u!==void 0?[a,d,u]:h!==void 0?[a,d,"",h]:[a,d]),n.flatMap(({owes:a},d)=>(a??[]).map(({field:u,sourceRefId:h,insertOnly:c})=>[d,u,h,c?1:0])),...i!==void 0?[i]:[]])),this.flush(),o}answered(t){this.write(JSON.stringify([de,t]))}jobOpened(t,e){this.write(JSON.stringify([fe,t,e])),this.flush()}createdUnattributed(t,e){if(e.length!==0){this.write(JSON.stringify([Q,t,[...e]]));for(let n of e)this.createdUnattributedKeys.add(M(n))}}wasFoundAfterStop(t){return this.foundAfterStop.has(t)}owesUntold(t){return this.foundOwingUntold.has(t)}flush(){if(this.pending.length===0)return;let t=this.pending.join("");this.pending=[],this.pendingBytes=0,this.file.append(t)}close(){this.settleReads(),this.flush(),this.file.close()}write(t){let e=typeof t=="string"?t:JSON.stringify(t),n=this.file.size()+this.pendingBytes,r=`${e}
|
|
9
|
-
`;return this.pending.push(r),this.pendingBytes+=Buffer.byteLength(r),this.pendingBytes>=le?this.flush():this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()})),n}lineAt(t,e){return t+e>this.file.size()&&this.flush(),this.file.read(t,e).toString("utf8")}idOfLine(t,e){let n=w(this.lineAt(t,e));return n?String(n[1]):""}lookUp(t){let e=this.cache.get(t);if(e)return this.cache.delete(t),this.cache.set(t,e),e;let n=this.index.find(t,g(t),y(t));if(n<0)return;let r=this.recordAt(t,n);return r&&this.remember(t,r),r}recordAt(t,e){let n=this.index.offsetOf(e),r=w(this.lineAt(n,this.index.lengthOf(e)));if(!(!r||String(r[1])!==t))return{at:n,code:this.index.codeOf(e),targetId:String(r[2]??""),objectApiName:String(r[3]??"")}}remember(t,e){if(this.cache.delete(t),this.cache.set(t,e),this.cache.size>ge){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}}*lines(){this.flush(),yield*be(this.file)}readWhatIsThere(){for(let t of this.lines()){if(t.text.startsWith('["')){let n=w(t.text);n&&this.readRegistration(t,n);continue}let e;try{e=JSON.parse(t.text)}catch{continue}if(!(typeof e!="object"||e===null)){if("part"in e)this.parts++;else if("sample"in e){let n=e.sample;if(typeof n!="object"||n===null)continue;let{dir:r,sha256:i}=n;if(typeof r!="string"||r===""||typeof i!="string"||!bt.test(i))continue;this.plan={dir:r,sha256:i}}else if("at"in e){let n=e.at;if(typeof n!="object"||n===null)continue;let{object:r,pass:i,lastId:o,read:a,done:d}=n;if(typeof r!="string"||typeof o!="string"||typeof a!="number"||i!==void 0&&(typeof i!="string"||!wt.test(i)))continue;this.checkpointsByObject.set(yt(r,i),{lastId:o,read:a,...d===!0?{done:d}:{}}),i===void 0&&this.earlierPastCheckpoint.delete(r)}}}}readRegistration(t,e){let n=String(e[0]);if(n==="o"||n==="w"){this.owedCount++;return}if(n==="s"){e.length>=4&&this.tallyStatus({objectApiName:String(e[1]),id:String(e[2]),status:String(e[3])});return}if(n==="p"||n==="g"||n===P){let c=At(e);if(!c)return;let f=g(c),l=y(c),p=this.marks.find(c,f,l);if(n==="g"&&p<0){let m=String(e[1]);this.given.set(m,(this.given.get(m)??0)+1)}this.marks.put(p,f,l,t.offset,t.length,0);return}if(n===Q){if(Array.isArray(e[2]))for(let c of e[2])this.createdUnattributedKeys.add(M(String(c)));return}let r=V[n];if(r===void 0)return;let i=String(e[1]);r===x&&(e[4]===kt||e[4]===ue)&&(this.foundAfterStop.add(i),e[4]===kt&&this.foundOwingUntold.add(i));let o=g(i),a=y(i),d=this.index.find(i,o,a),u=d>=0&&this.index.codeOf(d)!==S;if(r===S&&d>=0||(this.index.put(d,o,a,t.offset,t.length,r),r===S))return;r===x&&this.indexCreated(String(e[2]??""),t.offset,t.length),u||this.mappedCount++;let h=String(e[3]??"");h&&(this.earlierByObject.set(h,(this.earlierByObject.get(h)??0)+1),this.earlierPastCheckpoint.set(h,(this.earlierPastCheckpoint.get(h)??0)+1))}};function M(s){return s.slice(0,15)}function w(s){try{let t=JSON.parse(s);return Array.isArray(t)?t:void 0}catch{return}}var Et=2e3,b=15,nt=b,E=nt+8,st={format:1,head:Buffer.from("SFCKIDX1","latin1"),lengthAt:E+8,rowBytes:E+8+4},Mt={format:2,head:Buffer.from("SFCKIDX2","latin1"),memberBytesAt:E+8,lineAt:E+12,lengthAt:E+16,rowBytes:E+20},Lt={1:st,2:Mt},L=st.head.length,Rt=1<<20,Oe=500,R=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ee=/^[A-Za-z0-9]{15}$/,ot=/^[A-Za-z][A-Za-z0-9_]*$/;function tn(s,t){return L+s*Lt[t].rowBytes}function It(s){return s.replace(/[^A-Za-z0-9_-]/g,"_")}function Ct(s,t,e){if(!ot.test(e)||e.length>80)throw new k("invalid","Not a Salesforce API name");return Be(s.dir,"backups",`${It(t)}__${It(e)}.ndjson`)}var D=class{constructor(t,e){this.layout=t;this.rowBytes=t.rowBytes,this.bytes=e??Buffer.alloc(this.rowBytes*1024),this.size=e?e.length/this.rowBytes:0}layout;bytes;rowBytes;size;push(t,e,n){let r=this.size*this.rowBytes;if(r+this.rowBytes>this.bytes.length){let d=Buffer.alloc(Math.max(this.bytes.length*2,this.rowBytes*1024));this.bytes.copy(d,0,0,r),this.bytes=d}let{memberBytesAt:i,lineAt:o,lengthAt:a}=this.layout;return this.bytes.write(t,r,b,"latin1"),this.bytes.writeDoubleLE(e,r+nt),this.bytes.writeDoubleLE(n.offset,r+E),i!==void 0&&this.bytes.writeUInt32LE(n.memberBytes??0,r+i),o!==void 0&&this.bytes.writeUInt32LE(n.line??0,r+o),this.bytes.writeUInt32LE(n.length,r+a),this.size++}keyAt(t){let e=t*this.rowBytes;return this.bytes.toString("latin1",e,e+b)}holds(t,e){let n=t*this.rowBytes;for(let r=0;r<b;r++)if(this.bytes[n+r]!==e.charCodeAt(r))return!1;return!0}stampAt(t){return this.bytes.readDoubleLE(t*this.rowBytes+nt)}offsetAt(t){return this.bytes.readDoubleLE(t*this.rowBytes+E)}memberBytesAt(t){let e=this.layout.memberBytesAt;return e===void 0?0:this.bytes.readUInt32LE(t*this.rowBytes+e)}lineAt(t){let e=this.layout.lineAt;return e===void 0?0:this.bytes.readUInt32LE(t*this.rowBytes+e)}lengthAt(t){return this.bytes.readUInt32LE(t*this.rowBytes+this.layout.lengthAt)}before(t,e){return this.offsetAt(t)-this.offsetAt(e)||this.lineAt(t)-this.lineAt(e)}wellFormed(t){let e=this.stampAt(t),n=this.offsetAt(t);return Ee.test(this.keyAt(t))&&Number.isFinite(e)&&Number.isSafeInteger(n)&&n>=0&&this.lengthAt(t)>0&&(this.layout.format===1||this.memberBytesAt(t)>=X)}written(){return this.bytes.subarray(0,this.size*this.rowBytes)}},$=class{constructor(t,e){this.rows=t;let n=1024;for(;n<e*2;)n*=2;this.slots=new Uint32Array(n)}rows;slots;used=0;find(t){let e=this.slots.length-1;for(let n=g(t)&e;;n=n+1&e){let r=this.slots[n];if(r===0)return-1;if(this.rows.holds(r-1,t))return r-1}}add(t){let e=this.rows.keyAt(t),n=this.find(e);return n>=0?n:((this.used+1)*2>this.slots.length&&this.grow(),this.place(t,e),this.used++,-1)}place(t,e){let n=this.slots.length-1,r=g(e)&n;for(;this.slots[r]!==0;)r=r+1&n;this.slots[r]=t+1}grow(){let t=this.slots;this.slots=new Uint32Array(t.length*2);for(let e of t)e!==0&&this.place(e-1,this.rows.keyAt(e-1))}};async function U(s,t){try{return await C(s,"r")}catch(e){throw e.code!=="ENOENT"?e:new k("damaged",`The checkpoint\u2019s snapshot of ${t} is not on this machine.`)}}async function*Pt(s,t){let e=await U(s,t);try{let n=Buffer.alloc(Rt),r=Buffer.alloc(0),i=0,o=0,a=0;for(;;){let{bytesRead:d}=await e.read(n,0,Rt,o);if(d===0)break;o+=d;let u=r.length>0?Buffer.concat([r,n.subarray(0,d)]):n.subarray(0,d),h=0;for(let c=u.indexOf(10);c>=0;c=u.indexOf(10,h))a++,c>h&&(yield{number:a,offset:i+h,length:c-h,text:u.toString("utf8",h,c)}),h=c+1;r=Buffer.from(u.subarray(h)),i+=h}r.length>0&&(yield{number:a+1,offset:i,length:r.length,text:r.toString("utf8")})}finally{await e.close()}}async function*Re(s,t,e){let n=await U(s,t);try{let r=0;for await(let i of gt(n,(await n.stat()).size,e))for(let o of mt(i.lines))r++,o.length!==0&&(yield{number:r,offset:i.at,memberBytes:i.total,line:o.at,length:o.length,text:i.lines.toString("utf8",o.at,o.at+o.length)})}finally{await n.close()}}async function Ie(s){try{return await Ae(s),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zt(s){let t=at(s);return t===null?Number.NaN:Date.parse(t)}function _(s){let t;try{t=JSON.parse(s)}catch{return}return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}async function ve(s,t){let e=`${s}.${process.pid}-${Se(4).toString("hex")}.tmp`,n=await C(e,"wx",I);try{try{await n.writeFile(t),await n.sync()}finally{await n.close()}await xe(e,s)}catch(r){throw await ke(e,{force:!0}),r}}async function en(s,t,e){let n=Ct(s,t,e),r=B(n),i=await Ie(r)?2:1,o=H(s,e),a=new D(Lt[i]),d=new $(a,0),u=(f,l)=>new k("damaged",`The snapshot of ${e} holds ${l} at line ${f} of its file: it cannot be indexed.`),h=i===2?Re(r,e,f=>new k("damaged",`The snapshot of ${e} ${f}: it cannot be indexed.`)):Pt(n,e);for await(let f of h){let l=_(f.text);if(!l)throw u(f.number,"no record");let p=l.Id;if(typeof p!="string"||!R.test(p))throw u(f.number,"a record without its Id");let m=zt(l.SystemModstamp);if(!Number.isFinite(m))throw u(f.number,`record ${p} without its SystemModstamp`);let Dt=a.push(p.slice(0,b),m,f);if(d.add(Dt)>=0)throw u(f.number,`record ${p} a second time`)}let c=Buffer.concat([a.layout.head,a.written()]);return await ve(o,c),{rows:a.size,bytes:c.length}}var Ne=j({objectApiName:N().regex(ot).max(80),from:N().regex(R),to:N().regex(R)});async function _t(s){let t;try{t=await C(s,"r"),await t.sync()}catch{}finally{await t?.close().catch(()=>{})}}var rt=class s{constructor(t,e){this.current=t;this.original=e}current;original;static none=new s(new Map,new Map);static of(t){let e=new Map;for(let{from:r,to:i}of t)e.set(r.slice(0,b),i);let n=new Map;for(let[r,i]of e)n.set(i.slice(0,b),r);return new s(e,n)}static async read(t){let e;try{e=await it(W(t),"utf8")}catch(i){if(i.code==="ENOENT")return s.none;throw i}let n=e.split(`
|
|
10
|
-
`).slice(0,-1),r=[];for(let[i,o]of n.entries()){if(o==="")continue;let a;try{a=JSON.parse(o)}catch{a=void 0}let d=Ne.safeParse(a);if(!d.success)throw new k("damaged",`The checkpoint\u2019s list of the records a rewind made again is damaged at line ${i+1}.`);r.push(d.data)}return s.of(r)}static async add(t,e){if(e.length===0)return;let n=W(t),r=e.map(({objectApiName:a,from:d,to:u})=>`${JSON.stringify({objectApiName:a,from:d,to:u})}
|
|
11
|
-
`).join(""),i=await C(n,"a",I),o=!1;try{o=(await i.stat()).size===0,await i.appendFile(r,"utf8"),await i.sync()}finally{await i.close()}o&&await _t(Ft(n))}get empty(){return this.current.size===0}currentOf(t){return this.current.get(t)}originalOf(t){return this.original.get(t)}retired(t){return typeof t=="string"&&R.test(t)&&this.current.has(t.slice(0,b))}remapped(t){return typeof t!="string"||!R.test(t)?t:this.current.get(t.slice(0,b))??t}rowAsNow(t){if(this.empty)return t;let e={...t};for(let[n,r]of Object.entries(t)){if(n==="attributes")continue;let i=this.remapped(r);i!==r&&(e[n]=i)}return e}},Te=j({objectApiName:N().regex(ot).max(80),id:N().regex(R)}),vt=class s{constructor(t){this.held=t}held;static none=new s(new Set);static async read(t){let e;try{e=await it(K(t),"utf8")}catch(r){if(r.code==="ENOENT")return s.none;throw r}let n=new Set;for(let r of e.split(`
|
|
12
|
-
`)){if(r==="")continue;let i;try{i=JSON.parse(r)}catch{continue}let o=Te.safeParse(i);o.success&&n.add(o.data.id.slice(0,b))}return new s(n)}static async add(t,e,n){if(n.length===0)return;let r=K(t),i=n.map(d=>`${JSON.stringify({objectApiName:e,id:d})}
|
|
13
|
-
`).join(""),o=await C(r,"a",I),a=!1;try{a=(await o.stat()).size===0,await o.appendFile(i,"utf8"),await o.sync()}finally{await o.close()}a&&await _t(Ft(r))}has(t){return this.held.has(t.slice(0,b))}keys(){return this.held.values()}},Nt=class s{constructor(t,e,n,r,i,o,a){this.objectApiName=t;this.snapshotId=e;this.snapshotFile=n;this.rows=r;this.byKey=i;this.recreated=o;this.extent=a}objectApiName;snapshotId;snapshotFile;rows;byKey;recreated;extent;static async read(t,e,n,r){let i=H(t,n),o=p=>new k("damaged",`The checkpoint\u2019s index of ${n} ${p}.`),a;try{a=await it(i)}catch(p){throw p.code==="ENOENT"?o("is not on this machine"):p}let d=[st,Mt].find(({head:p})=>a.length>=L&&a.subarray(0,L).equals(p));if(d===void 0||(a.length-L)%d.rowBytes!==0)throw o("is not an index of its snapshot");let u=Ct(t,e,n),h=d.format===2?B(u):u,c=new D(d,a.subarray(L)),f=new $(c,c.size),l=0;for(let p=0;p<c.size;p++){if(!c.wellFormed(p))throw o(`is damaged at row ${p+1}`);if(f.add(p)>=0)throw o(`holds record ${c.keyAt(p)} twice`);d.format===2&&(l=Math.max(l,c.offsetAt(p)+c.memberBytesAt(p)))}return new s(n,e,h,c,f,r??await rt.read(t),l)}get format(){return this.rows.layout.format}get size(){return this.rows.size}rowOf(t){if(typeof t!="string"||!R.test(t))return-1;let e=t.slice(0,b),n=this.recreated.originalOf(e);return n!==void 0?this.byKey.find(n):this.recreated.retired(t)?-1:this.byKey.find(e)}retired(t){return this.recreated.retired(t)&&this.byKey.find(String(t).slice(0,b))>=0}snapshotIdOf(t){let e=this.rowOf(t);if(e<0)return t;let n=this.rows.keyAt(e);return J(n)??n}has(t){return this.rowOf(t)>=0}stampOf(t){let e=this.rowOf(t);return e<0?void 0:this.rows.stampAt(e)}idAt(t){let e=this.rows.keyAt(t);return this.recreated.currentOf(e)??J(e)??e}chunk(t){if(t.length>Et)throw new RangeError(`A chunk of the snapshot reads ${Et} records at most; ${t.length} were asked.`);let e=new Set;for(let r of t){let i=this.rowOf(r);i>=0&&e.add(i)}let n=[...e].sort((r,i)=>this.rows.before(r,i));return{batches:async(r,i,o)=>{if(r!==this.snapshotId||i!==this.objectApiName)return null;let a=o>=1?Math.floor(o):1;return{[Symbol.asyncIterator]:()=>this.rowsAt(n,a)}}}}async*records(){if(this.size===0)return;if(this.format===2){let e=function*(n){for(let r=0;r<n;r++)yield r};for await(let n of this.compressedRowsAt(e(this.size),Oe))yield*n;return}let t=0;for await(let e of Pt(this.snapshotFile,this.objectApiName)){let n=_(e.text);if(t>=this.size)throw this.moreThanIndexed();if(!n||!this.isRowOf(t,n))throw this.notWhereIndexed(t);yield this.recreated.rowAsNow(n),t++}if(t<this.size)throw this.notWhereIndexed(t)}notWhereIndexed(t){return new k("damaged",`The checkpoint\u2019s snapshot of ${this.objectApiName} does not hold record ${this.idAt(t)} where its index says: the file changed since the checkpoint was taken.`)}moreThanIndexed(){return new k("damaged",`The checkpoint\u2019s snapshot of ${this.objectApiName} holds more records than its index: the file changed since the checkpoint was taken.`)}async*rowsAt(t,e){if(t.length===0)return;if(this.format===2){yield*this.compressedRowsAt(t,e);return}let n=await U(this.snapshotFile,this.objectApiName);try{let r=Buffer.alloc(0),i=[];for(let o of t){let a=this.rows.lengthAt(o),d=this.rows.offsetAt(o);r.length<a&&(r=Buffer.alloc(Math.max(a,r.length*2)));let u=0;for(;u<a;){let{bytesRead:c}=await n.read(r,u,a-u,d+u);if(c===0)break;u+=c}let h=u===a?_(r.toString("utf8",0,a)):void 0;if(!h||!this.isRowOf(o,h))throw this.notWhereIndexed(o);i.push(this.recreated.rowAsNow(h)),i.length===e&&(yield i,i=[])}i.length>0&&(yield i)}finally{await n.close()}}async*compressedRowsAt(t,e){let n=i=>new k("damaged",`The checkpoint\u2019s snapshot of ${this.objectApiName} ${i}: the file changed since the checkpoint was taken.`),r=await U(this.snapshotFile,this.objectApiName);try{let i=(await r.stat()).size;if(i!==this.extent)throw n(`takes ${i} bytes where its index says ${this.extent}`);let o=-1,a=0,d=Buffer.alloc(0),u=[];for(let h of t){let c=this.rows.offsetAt(h);(c!==o||this.rows.memberBytesAt(h)!==a)&&(a=this.rows.memberBytesAt(h),d=await pt(r,c,a,n),o=c);let f=this.rows.lineAt(h),l=f+this.rows.lengthAt(h),m=l<=d.length&&(f===0||d[f-1]===10)&&(l===d.length||d[l]===10)?_(d.toString("utf8",f,l)):void 0;if(!m||!this.isRowOf(h,m))throw this.notWhereIndexed(h);u.push(this.recreated.rowAsNow(m)),u.length===e&&(yield u,u=[])}u.length>0&&(yield u)}finally{await r.close()}}isRowOf(t,e){let n=e.Id;return typeof n=="string"&&R.test(n)&&this.rows.holds(t,n.slice(0,b))&&zt(e.SystemModstamp)===this.rows.stampAt(t)}},Tt=class{constructor(t){this.index=t;this.marked=new Uint8Array(Math.ceil(t.size/8))}index;marked;found=0;mark(t){let e=this.index.rowOf(t);if(e<0)return!1;let n=1<<(e&7),r=e>>>3;return(this.marked[r]&n)===0&&(this.marked[r]|=n,this.found++),!0}get count(){return this.index.size-this.found}*ids(){for(let t=0;t<this.index.size;t++)(this.marked[t>>>3]&1<<(t&7))===0&&(yield this.index.idAt(t))}};export{_e as a,Ue as b,yt as c,ce as d,de as e,fe as f,Ot as g,Q as h,P as i,kt as j,ue as k,je as l,Je as m,he as n,g as o,y as p,v as q,be as r,Bt as s,Et as t,tn as u,Ct as v,en as w,rt as x,vt as y,Nt as z,Tt as A};
|
package/lib/chunk-LWW4U276.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 l}from"./chunk-CA5NAXSU.mjs";import{od as m,pd as S,td as h,ud as g,vd as y}from"./chunk-TTFDUKUS.mjs";var T=576*60*60*1e3,P=T,f=class extends Error{constructor(e){super(e),this.name="StepCancelledError"}},b=Symbol("stopped");function w(t,e,n,i){let r=new Date().toISOString();return{stepId:t.id,stepName:t.name,stepType:t.type,status:"completed",output:e,summary:i,startTime:n,endTime:r,duration:new Date(r).getTime()-new Date(n).getTime()}}function d(t,e,n){let i=new Date().toISOString();return{stepId:t.id,stepName:t.name,stepType:t.type,status:"failed",error:e,startTime:n,endTime:i,duration:new Date(i).getTime()-new Date(n).getTime()}}function v(t){return y(t.type)?`Step "${t.name}" is a ${String(t.type)} step, which SandForge no longer supports: remove it from the pipeline.`:g(t.type)?`Step "${t.name}" is a ${String(t.type)} step, and this step type cannot run in a pipeline yet.`:`Step "${t.name}" is a "${String(t.type)}" step, a step type this release of SandForge does not have: the pipeline was saved by a later release, or written by hand. Remove the step, or update SandForge.`}function x(t){let{timeout:e}=t;if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))return`Step "${t.name}" has a timeout that is not a number of milliseconds: ${JSON.stringify(e)}.`;if(e>P)return`Step "${t.name}" has a timeout of ${e} ms, longer than a step can be given: set at most 24 days (${P} ms).`}}function D(t){let e=t.seconds,n=e===void 0?t.durationMs:e;if(typeof n!="number"||!Number.isFinite(n)||n<0)return;let i=e===void 0?n:n*1e3;return i<=T?i:void 0}function C(t){if(t.config.seconds===void 0&&t.config.durationMs===void 0)return`Delay step "${t.name}" has no duration: set how many seconds it waits.`;if(D(t.config)===void 0)return`Delay step "${t.name}" has no usable duration: set a number of seconds, from 0 up to 24 days.`}function H(t,e,n){let i=`Condition step "${t.name}"`;switch(n){case"noEarlierStep":return`${i} tests how the previous step went, and no step comes before it.`;case"noCompare":return`${i} tests how many differences a comparison found, and no Compare step comes before it.`;case"noPrecheck":return`${i} tests ${e}, which a Pre-check hands on, and no Pre-check before it takes that reading.`}}function k(t){let e=t.condition;if(!e||typeof e.field!="string"||e.field.trim()==="")return`Condition step "${t.name}" has no condition to evaluate.`;let n=m(e);return n===void 0?void 0:`Condition step "${t.name}" ${n}.`}function M(t,e){let n=k(t);if(n!==void 0||!t.condition||!e)return n;let i=t.condition,r=h(i,e.steps.slice(0,e.index),e.declared);return r===void 0?void 0:H(t,i.field,r)}function E(t,e){return e?.aborted?Promise.resolve(!1):new Promise(n=>{let i=()=>{clearTimeout(r),n(!1)},r=setTimeout(()=>{e?.removeEventListener("abort",i),n(!0)},t);e?.addEventListener("abort",i,{once:!0})})}var $=class{handlers=new Map;checks=new Map;constructor(){this.registerDefaults()}async execute(e,n){let i=new Date().toISOString(),r=this.check(e);if(r)return d(e,r,i);let o=this.getExecutor(e.type),c=e.retries??0,p="";for(let u=0;u<=c;u++){let s=await this.attempt(o,e,n);if("result"in s)return s.result;if(s.stopped)return{...d(e,s.error,i),status:"stopped"};p=s.error}return d(e,p,i)}async attempt(e,n,i){let r=i.signal;if(r?.aborted)return{error:`Step "${n.name}" was stopped before it started.`,stopped:!0};let o=new AbortController,c=new Promise(a=>{o.signal.addEventListener("abort",()=>a(b),{once:!0})}),p=()=>o.abort();r?.addEventListener("abort",p,{once:!0});let u=!1,s=n.timeout,R=s!==void 0&&s>0?setTimeout(()=>{u=!0,o.abort()},s):void 0;try{let a=await Promise.race([e(n,{...i,signal:o.signal}),c]);return a!==b?{result:a}:u?{error:`Step "${n.name}" timed out after ${s} ms.`}:{error:`Step "${n.name}" was stopped before it finished.`,stopped:!0}}catch(a){return a instanceof f?{error:a.message,stopped:!0}:{error:l(a)}}finally{clearTimeout(R),r?.removeEventListener("abort",p)}}check(e,n){return this.handlers.has(e.type)?x(e)??this.checks.get(e.type)?.(e,n):v(e)}getExecutor(e){return this.handlers.get(e)??this.refusingHandler}registerHandler(e,n,i){this.handlers.set(e,n),i?this.checks.set(e,i):this.checks.delete(e)}wrapHandler(e,n){let i=this.handlers.get(e);i&&this.handlers.set(e,n(i))}refusingHandler=async e=>d(e,v(e),new Date().toISOString());registerDefaults(){this.handlers.set("delay",this.createDelayHandler()),this.checks.set("delay",C),this.handlers.set("condition",this.createConditionHandler()),this.checks.set("condition",M)}createDelayHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=D(e.config);return r===void 0?d(e,C(e)??"No usable duration",i):await E(r,n.signal)?w(e,{delayed:r},i,`Waited ${r/1e3} s.`):d(e,`Delay step "${e.name}" was stopped before its ${r} ms wait ended.`,i)}}createConditionHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=k(e);if(r||!e.condition)return d(e,r??"No condition",i);try{let o=S(e.condition,n.variables);return w(e,{conditionMet:o},i,o?"The condition held.":"The condition did not hold.")}catch(o){return d(e,`Condition step "${e.name}" could not be evaluated: ${l(o)}.`,i)}}}};export{f as a,$ as b};
|
package/lib/chunk-MFG4MUIO.mjs
DELETED
|
@@ -1,9 +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{a as je,b as He}from"./chunk-TYYOBZMU.mjs";import{a as $e,b as be,c as Le,g as Ue}from"./chunk-HS4YRX4J.mjs";import{a as de,b as Ne,c as Fe}from"./chunk-TUACWKIH.mjs";import{a as De}from"./chunk-4TLYUZD5.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{bd as Ce,cd as ce,dc as ae,dd as Ie,gd as ue,hd as Me,id as _e,j as Pe,jd as xe,yb as ve}from"./chunk-TTFDUKUS.mjs";import{b as q,e as Oe,k as B,l as J,v as Re,z as Y}from"./chunk-7EANH5PY.mjs";var Z=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((u,f)=>u-f),r=s.reduce((u,f)=>u+f,0),o=Math.floor(s.length*.95),a=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(a,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var K=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var ze=0;function An(){return ze}async function le(e,t){let n=Ue(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as kt,userInfo as St}from"node:os";var Tt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return Tt.some(t=>t.test(e))}function fe(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function vn(e=process.env){let t=Object.keys(e).filter(f=>(e[f]??"")!==""),n=qe.filter(f=>t.some(d=>d.toUpperCase()===f)),s=t.filter(f=>/^(SF|SFDX)_/i.test(f)).sort(),r=t.filter(f=>We(f)),o=r.filter(f=>f.startsWith("ELECTRON_")).sort(),a=r.length-o.length,u=r.length===0?"none":[...o,...a>0?[`${a} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${u}`}function At(){try{return St().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=kt(),n=At()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function Cn(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Ot(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function In(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=fe(),o,a;try{let h=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(h.stdout)}catch(h){let i=h;o=String(i.stdout??""),o.trim()===""&&(a=Je(i.message??String(h)))}let u=o.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.length>0).map(h=>Je(h)),f=h=>u.filter(i=>new RegExp(`(^|[\\\\/])${h}(\\.[A-Za-z0-9]+)?$`,"i").test(i)),d=f("sf"),c=Ot(d,r);return{sf:d,node:f("node"),...c!==void 0?{runs:c}:{},...a?{failure:a}:{}}}function Q(e,t){let n=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return n===""?void 0:n}function Rt(e,t){if(t===void 0)return!1;let n=e.hostname.toLowerCase(),s=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(r=>r!=="").some(r=>{if(r==="*")return!0;let[,o="",a]=/^(.*?)(?::(\d+))?$/.exec(r.toLowerCase())??[];if(a!==void 0&&a!==s)return!1;let u=o.replace(/^\*?\.?/,"");return u!==""&&(n===u||n.endsWith(`.${u}`))})}function Ve(e,t=process.env){let n;try{n=new URL(e)}catch{return}let s=n.protocol==="https:"?Q(t,"https_proxy")??Q(t,"http_proxy"):Q(t,"http_proxy");if(s!==void 0)return Rt(n,Q(t,"no_proxy"))?void 0:s}var Pt="https://login.salesforce.com";async function F(e,t=process.env){let{jsforce:n,HttpProxyTransport:s}=await import("./chunk-L5FGY6YA.mjs"),r=Ve(e.instanceUrl??e.loginUrl??Pt,t),o=new n.Connection({...e,...r!==void 0?{httpProxy:r}:{}});return r===void 0&&(o._transport=new s("")),o}var vt=10*1024*1024,pe=3e4,Ge=pe+2e3,he=`sf did not answer within ${pe/1e3} s \u2014 check the Salesforce CLI`;function Xe(e){return e instanceof Error&&e.message===he}var ge=2e4;function te(e,t,n){let s,r=new Promise((o,a)=>{s=setTimeout(()=>a(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var U=new Z,Ct=300*1e3,ee=new Map,It={failureThreshold:3,resetTimeout:3e4},Ye=new Map;function Jn(){return U}function Mt(e){let t=Ye.get(e);return t||(t=new K({...It}),Ye.set(e,t)),t}var Ze;var me="panel";function Wn(e){me=e}function _t(e,t=me){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function Ke(e=me){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Qe(e,t){let n=t?.organization_id;if(!(!Ze||typeof n!="string"))try{Ze(e,{organizationId:n})}catch(s){De.warn("Identity observer threw",{orgId:e,error:R(s)})}}var xt="[REDACTED]";function et(e){return typeof e=="string"&&e.length>0&&!e.startsWith(xt)&&!/\s/.test(e)}async function $t(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:vt,timeout:pe,windowsHide:!0,env:fe()},o=i=>te(s(t)("sf",i,r),Ge,he),a=i=>{let g=!1,m,k=new Promise((T,S)=>{m=n(i,r,(E,C)=>{g=!0,E?S(E):T({stdout:C})})});return te(k,Ge,he).catch(T=>{throw!g&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},u=(i,g)=>process.platform==="win32"?a(i):o(g),f=(i,g)=>{let m=i.replace(/\[[0-9;]*m/g,""),k=m.search(/[{[]/);if(k===-1)throw new Error(`Failed to parse "${g}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(k)).result??{}},d;try{let{stdout:i}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=f(i,"sf org display");d=typeof g.instanceUrl=="string"?g.instanceUrl:void 0}catch(i){if(Xe(i))throw i;d=void 0}try{let{stdout:i}=await u(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),g=f(i,"sf org auth show-access-token");if(et(g.accessToken))return{accessToken:g.accessToken,instanceUrl:d}}catch(i){if(Xe(i))throw i}let{stdout:c}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=f(c,"sf org display");if(!et(h.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof h.instanceUrl=="string"&&(d=h.instanceUrl),{accessToken:h.accessToken,instanceUrl:d}}async function Vn(e,t){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function Gn(e){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function Xn(e,t,n){let s=e,r=n.getOrg(e);if(!r)throw new Error(`Org not found: ${e}`);let o=await t.getCredentials(e);if(!o?.accessToken||!o.instanceUrl)throw new Error(`No credentials for org "${r.alias}" (${e}). Reconnect the org.`);let a=r.metadata.apiVersion||Pe.DEFAULT_API_VERSION,u=U.get(s),f=Date.now()-(ee.get(e)??0)<Ct;if(u&&u.active&&u.accessToken===o.accessToken&&f)return u.lastUsedAt=Date.now(),F({instanceUrl:u.instanceUrl,accessToken:u.accessToken,version:a});let d=await F({instanceUrl:o.instanceUrl,accessToken:o.accessToken,version:a}),c=Mt(e);if(!c.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${r.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let h=Date.now(),i=`identity check did not answer within ${ge/1e3} s`;try{let g=await le(d,()=>te(d.identity(),ge,i)),m=Date.now()-h;return c.recordSuccess(),U.acquire(s,o.instanceUrl,o.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,g),d}catch(g){let m=Date.now()-h;if(U.remove(s),ee.delete(e),$e(g))try{let S=await $t(r.username),E=S.instanceUrl??o.instanceUrl;if(S.accessToken===o.accessToken&&E===o.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let C=await F({instanceUrl:E,accessToken:S.accessToken,version:a}),W=await le(C,()=>te(C.identity(),ge,i));return await t.saveOrg(r,{...o,accessToken:S.accessToken,instanceUrl:E}),c.recordSuccess(),U.acquire(s,E,S.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,W),C}catch(S){c.recordFailure();let E=R(S);n.updateStatus(e,"expired");let C=ae(r,new Date().toISOString().slice(0,10));throw C!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${C}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${E})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${r.alias}" has expired and could not be renewed. ${_t(r.alias)} (cause: ${E})`)}c.recordFailure();let k=R(g),T=ae(r,new Date().toISOString().slice(0,10));throw T!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${k})`)):new Error(`Connection failed for "${r.alias}": ${k}`)}finally{c.releasePermit()}}import{randomUUID as bt}from"node:crypto";import{hostname as Lt,homedir as Ut,uptime as Dt}from"node:os";import{mkdir as Nt,readFile as ct,readdir as Ft,rename as ut,writeFile as jt}from"node:fs/promises";import{dirname as we,join as Ee}from"node:path";function tt(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:R(e)}]}}function nt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function as(e){return{typeOrg:()=>be(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:ve()}).then(nt,tt),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(nt,tt)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ht(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var zt=60,qt=5*6e4,Bt=3e4,Jt=6e4,Wt=200,Vt=448,Gt=384,oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(oe),Xt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Yt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Oe().int().nonnegative(),hostStartedAt:Y.datetime({offset:!0}),acquiredAt:Y.datetime({offset:!0}),endsAt:Y.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Xt)}),dt=J({version:Re(1),organizationId:H,userId:H,leases:B(Yt)}),Zt=J(je),Kt=He(e=>{let t=Zt.safeParse(e);return t.success?t.data:void 0});function lt(e=process.env,t=Ut()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Ee(t,".sandforge","mute-leases")}function Qt(e,t,n){if(!oe.test(t)||!oe.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Ee(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var ft={host:Lt(),pid:de.pid,startedAt:de.startedAt},en=6e4,D=new Set;function gt(e,t,n){return`${e}
|
|
8
|
-
${t}
|
|
9
|
-
${n}`}function tn(e,t,n,s={}){let r=s.now?.()??Date.now();if(!(Date.parse(e.endsAt)>r)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return D.has(gt(t,e.runId,e.acquiredAt));let o=s.bootedAt?.()??Date.now()-Dt()*1e3,a=Date.parse(e.hostStartedAt);return Number.isFinite(a)&&a<o-en?!1:(s.isAlive??Fe)(e.pid)}var nn=e=>new Promise(t=>setTimeout(t,e));function ne(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${we(e)} could not be ${t}${typeof s=="string"?` (${s})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function sn(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+Ne).toISOString()}}function ht(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function rn(e){return`nothing was assigned. ${ht(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function se(e,t,n,s,r=rn,o=Jt){let a=n.self??ft,u={self:a,...n.checks?{checks:n.checks}:{}},f=Date.now()+o;for(await Nt(we(e),{recursive:!0,mode:Vt}).catch(d=>{throw ne(e,"made",d)});;){let d;try{d=Kt.acquire(`${e}.lock`,c=>c,u)}catch(c){throw ne(e,"locked",c)}if("lock"in d)try{let c=await on(e,t).catch(i=>{throw ne(e,"read",i)});return await s(c,async i=>{let g=`${e}.${process.pid}-${bt()}.tmp`;try{await jt(g,JSON.stringify(i,null,2),{encoding:"utf8",mode:Gt}),await ut(g,e)}catch(m){throw ne(e,"written",m)}})}finally{d.lock.release()}if(Date.now()>f){let c=sn(d.busy,a);throw new j({code:"MUTE_FAILED",message:`The journal of the mute leases in ${we(e)} stayed locked for a minute by process ${c.pid} on ${c.host}: ${r(c)}`})}await nn(Wt)}}async function on(e,t){let n={version:1,...t,leases:[]},s;try{s=await ct(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=dt.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await ut(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var an=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function re(e,t,n,s){let r=t.leases.filter(c=>c!==n&&s(c)),o=[...n.created],a=new Set,u=n.assigning[0];if(u!==void 0){let c=new Set(t.leases.flatMap(i=>i===n?[]:i.created.map(g=>g.id))),h=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${u}')`).then(i=>i.records).catch(()=>[]);for(let i of h){let g=typeof i.Id=="string"?i.Id:void 0,m=typeof i.PermissionSetId=="string"?i.PermissionSetId:void 0;if(!g||!m||c.has(g)||o.some(T=>T.id===g))continue;let k=i.PermissionSet;o.push({id:g,permissionSetId:m,permissionSet:typeof k?.Name=="string"?k.Name:m}),a.add(g)}}let f={removed:[],passed:[],left:[],found:[]};for(let c of o){let h=r.find(m=>m.needs.includes(c.permissionSetId));if(h){h.created.some(m=>m.id===c.id)||h.created.push(c),f.passed.push(c);continue}let i=await e.deleteAssignment(c.id),g=i.errors?.[0]?.statusCode??i.errors?.[0]?.errorCode;i.success||g!==void 0&&an.has(g)?(f.removed.push(c),a.has(c.id)&&f.found.push(c)):f.left.push({...c,why:i.errors?.[0]?.message??g??"the org refused the delete"})}let d=t.leases.indexOf(n);return f.left.length===0?t.leases.splice(d,1):t.leases[d]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:f.left.map(({id:c,permissionSetId:h,permissionSet:i})=>({id:c,permissionSetId:h,permissionSet:i}))},f}function N(e){return e.map(t=>t.permissionSet)}function st(e,t){let n=r=>N(r).join(", "),s=[];return e.removed.length>0&&s.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&s.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&s.push(`${e.left.map(r=>`${r.permissionSet} (${r.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),s}function rt(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function pt(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function cn(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await re(e,t,r,n)).found);return s}async function un(e){let t;try{t=(await e.query("SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess")).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${R(n)})`}if(!(t?.PermissionsAssignPermissionSets===!0||t?.PermissionsManageUsers===!0))return"the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)"}function ot(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var it=/^[A-Za-z][A-Za-z0-9_]*$/;async function dn(e,t){let s=t.map(ot).filter(a=>it.test(a.developerName)&&(!a.namespace||it.test(a.namespace)));if(s.length===0)return new Map;let r=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(s.map(a=>`'${a.developerName}'`))].join(", ")+")"),o=new Map;for(let a of t){let{namespace:u,developerName:f}=ot(a),d=r.records.find(c=>String(c.Name??"").toLowerCase()===f.toLowerCase()&&String(c.NamespacePrefix??"").toLowerCase()===u.toLowerCase());typeof d?.Id=="string"&&o.set(a,d.Id)}return o}async function at(e,t,n){if(n.length===0)return new Map;let s=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(o=>`'${o}'`).join(", ")})`),r=new Map;for(let o of s.records){let a=o.PermissionSetId,u=o.Id;typeof a=="string"&&typeof u=="string"&&r.set(a,u)}return r}function ye(e,t,n){return{state:t,assigned:[],held:[],permissions:ce(e),silenced:e.silenced.map(s=>({...s})),stillRan:e.stillRuns.map(s=>({...s})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(s=>({...s}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(s=>({...s}))}:{},...n?{reason:n}:{}}}var mt="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function ln(e,t,n={}){let s,r;try{let d=await e.typeOrg();s=Le(d),r=d.id}catch(d){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${R(d)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(s)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:o,automation:a,planned:u}=hn(t,n.writes);if(o.assign.length===0)return{plan:o,automation:t,planned:u,acquire:async()=>({outcome:u,release:async()=>u})};let f=await un(e);return f!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${f}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}}:(wt.set(o,await gn(n.dir??lt(),r)),{plan:o,automation:a,planned:u,acquire:d=>pn(e,o,d,n)})}var wt=new WeakMap,fn=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function gn(e,t){if(!oe.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ft(e)}catch{return 0}let r=0;for(let o of s)if(!(!o.startsWith(n)||!fn.test(o)))try{let a=dt.safeParse(JSON.parse(await ct(Ee(e,o),"utf8")));if(!a.success)continue;for(let u of a.data.leases)r+=(u.assigning.length>0?1:0)+u.created.length}catch{}return r}function hn(e,t){let n=Ce(e,t);return n.assign.length===0?{plan:n,automation:e,planned:ye(n,"nothing",mt)}:{plan:n,automation:Ie(e,ce(n)),planned:ye(n,"planned")}}async function pn(e,t,n,s={}){let r=s.self??ft,o=()=>s.checks?.now?.()??Date.now(),a=s.minutes??zt,u=l=>{throw new j({code:"MUTE_FAILED",message:l})},f=await e.identity().catch(l=>u(`The target would not say who the run writes as (${R(l)}).`)),d={organizationId:f.organization_id,userId:f.user_id},c=Qt(s.dir??lt(),d.organizationId,d.userId),h=t.assign.map(l=>l.permissionSet),i=await dn(e,h).catch(l=>u(`The permission sets to assign could not be read (${R(l)}).`)),g=h.filter(l=>!i.has(l));g.length>0&&u(`The target holds no permission set ${g.join(", ")}: nothing was assigned.`);let m=h.map(l=>i.get(l)),k=new Map(h.map(l=>[i.get(l),l])),T=l=>tn(l,c,r,s.checks),S=new Date(o()).toISOString(),E=gt(c,n,S),C=!1,W=m.map(l=>k.get(l)),yt=s.retryEveryMs??Bt,V,ke=(l,A)=>{if(V!==void 0)return;let p=new Set(l.map(y=>y.id)),O=!1,P=()=>clearInterval(V);V=setInterval(()=>{O||(O=!0,se(c,d,s,async(y,G)=>{let M=y.leases.find(x=>x.runId===n&&x.acquiredAt===S);if(M){M.assigning=[],M.created=[...M.created,...A.filter(b=>!M.created.some(X=>X.id===b.id))].filter(b=>!p.has(b.id));let x=await re(e,y,M,T);for(let b of x.removed)p.add(b.id);await G(y)}P()},void 0,0).catch(()=>{}).finally(()=>{O=!1}))},yt),V.unref?.()},z=await se(c,d,s,async(l,A)=>{let p=N(await cn(e,l,T)),O=await at(e,d.userId,m),P=m.filter(w=>!O.has(w)),y={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:S,endsAt:new Date(o()+a*6e4).toISOString(),needs:m,assigning:[...P],created:[]};l.leases.push(y),D.add(E),await A(l),C=!0;let G=[...y.assigning],M=()=>A(l).then(()=>{G=[...y.assigning]},w=>R(w)),x=async w=>{y.assigning=[];let I=await re(e,l,y,T);D.delete(E);let v=await M();v!==void 0&&ke(I.removed,[...I.passed,...I.left]);let _=v!==void 0&&G.length===0?{sets:W,until:y.endsAt}:void 0,Ae=st(I,v===void 0);return u([w,...v!==void 0&&v!==w?[v]:[],...Ae.length>0?Ae:["Nothing was assigned."],...v!==void 0&&(I.passed.length>0||I.left.length>0||_)?[rt(r.pid,_)]:[],...p.length>0?[`Taking its lease, the run took back ${p.join(", ")}, ${pt(p)}.`]:[]].join(" "))};for(let w of P){let I=await e.createAssignment({AssigneeId:d.userId,PermissionSetId:w});if(y.assigning=y.assigning.filter(_=>_!==w),I.success&&I.id){y.created.push({id:I.id,permissionSetId:w,permissionSet:k.get(w)});let _=await M();if(_!==void 0)return x(_);continue}let v=I.errors?.[0];if((v?.statusCode??v?.errorCode)==="DUPLICATE_VALUE"){let _=await M();if(_!==void 0)return x(_);continue}return x(`${k.get(w)} could not be assigned to the user the run writes as: ${v?.message??v?.statusCode??"the org refused it"}.`)}let b=await at(e,d.userId,m).catch(()=>new Map),X=m.filter(w=>!b.has(w));if(X.length>0)return x(`Read back, the user the run writes as does not hold ${X.map(w=>k.get(w)).join(", ")}.`);let Et=new Set(y.created.map(w=>w.permissionSetId));return{endsAt:y.endsAt,assigned:y.created.map(w=>w.permissionSet),held:m.filter(w=>!Et.has(w)).map(w=>k.get(w)),found:p}}).catch(l=>{if(D.delete(E),Ht(l))throw l;return u(`${R(l)}${C?"":" Nothing was assigned."}`)}),$={...ye(t,"muted"),assigned:z.assigned,held:z.held,leaseEndsAt:z.endsAt,...z.found.length>0?{tookBackOfEnded:z.found}:{}},Se=s.renewEveryMs??qt,ie=Se>0?setInterval(()=>{se(c,d,s,async(l,A)=>{let p=l.leases.find(P=>P.runId===n&&P.acquiredAt===S);if(!p||!D.has(E))return;let O=new Date(o()+a*6e4).toISOString();p.endsAt=O,await A(l),$.leaseEndsAt=O}).catch(()=>{})},Se):void 0;ie?.unref?.();let Te;return{outcome:$,release:()=>(Te??=(async()=>{ie&&clearInterval(ie);let l={};try{await se(c,d,s,async(p,O)=>{let P=p.leases.find(y=>y.runId===n&&y.acquiredAt===S);D.delete(E),P&&(l.done=await re(e,p,P,T),await O(p))},p=>`nothing was taken back. ${ht(p)} Should none of its runs be muting this org, end process ${p.pid}`);let A=l.done?.left??[];return{...$,released:A.length===0,takenBack:N(l.done?.removed??[]),...l.done&&l.done.passed.length>0?{passed:N(l.done.passed)}:{},...A.length>0?{notTakenBack:N(A),reason:`${A.map(p=>`${p.permissionSet} (${p.why})`).join(", ")} could not be taken back: the lease ends at ${$.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(A){D.delete(E);let p=l.done;if(ke(p?.removed??[],p?[...p.passed,...p.left]:[]),p!==void 0){let O=$.leaseEndsAt,P=O!==void 0&&Date.parse(O)>o()?{sets:W,until:O}:void 0;return{...$,released:!1,takenBack:N(p.removed),notTakenBack:N([...p.passed,...p.left]),reason:[R(A),...st({...p,removed:[]},!1),rt(r.pid,P)].join(" ")}}return{...$,released:!1,takenBack:[],reason:`the assignments could not be taken back (${R(A)}): this process tries again while it runs, and takes them back once it can use the journal; past ${$.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),Te)}}var mn=2,wn=3;function yn(e){return!e||e.assign.length===0?0:mn+wn+2*e.assign.length+(wt.get(e)??0)}function cs(e){let t=yn(e);return t>0?{mute:t}:{}}function En(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function us(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function ds(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:En(`the target's automation could not be read (${t.unread})`)};let s=await ln(await e(),t,n);if("refused"in s)throw new j(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function ls(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function fs(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??mt}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+pt(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${ue(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${ue(r)} (${Me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${_e(r)}`);for(let r of e.liftsUnread??[])n.push(` ${xe(r)}`);let s=e.takenBack??(e.released===!0?e.assigned:[]);if(s.length>0&&n.push(` taken back: ${s.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let r=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${r?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}export{An as a,le as b,L as c,fe as d,vn as e,Je as f,Cn as g,In as h,Ve as i,F as j,te as k,Jn as l,Wn as m,et as n,$t as o,Vn as p,Gn as q,Xn as r,as as s,Ht as t,ln as u,hn as v,yn as w,cs as x,us as y,ds as z,ls as A,fs as B};
|