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.
Files changed (266) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-pipeline.mjs +12 -0
  3. package/bin/sandforge-users.mjs +12 -0
  4. package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
  5. package/lib/chunk-2JZGCCPG.mjs +9 -0
  6. package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
  7. package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
  8. package/lib/chunk-3C2ZZIFN.mjs +7 -0
  9. package/lib/chunk-3CX7GPCR.mjs +7 -0
  10. package/lib/chunk-3HEMJTAP.mjs +925 -0
  11. package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
  12. package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  13. package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
  14. package/lib/chunk-3XG25GTF.mjs +7 -0
  15. package/lib/chunk-42BFLWHR.mjs +7 -0
  16. package/lib/chunk-466F37VD.mjs +7 -0
  17. package/lib/chunk-47UHTN3Q.mjs +7 -0
  18. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  19. package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
  20. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  21. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  22. package/lib/chunk-5K2I2DMP.mjs +11 -0
  23. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  24. package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  25. package/lib/chunk-6KP6WETK.mjs +9 -0
  26. package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
  27. package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
  28. package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
  29. package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
  30. package/lib/chunk-7PY3VQP3.mjs +7 -0
  31. package/lib/chunk-7SDZR6SR.mjs +7 -0
  32. package/lib/chunk-7WSLT5VX.mjs +8 -0
  33. package/lib/chunk-A32ISQ6M.mjs +28 -0
  34. package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
  35. package/lib/chunk-A7JJWOLT.mjs +7 -0
  36. package/lib/chunk-AUS6NFLZ.mjs +8 -0
  37. package/lib/chunk-BMTNTBBM.mjs +7 -0
  38. package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
  39. package/lib/chunk-BNKT3R3F.mjs +7 -0
  40. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  41. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  42. package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
  43. package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  44. package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
  45. package/lib/chunk-CCEH7L53.mjs +7 -0
  46. package/lib/chunk-CELEBWEZ.mjs +7 -0
  47. package/lib/chunk-CV47FDQW.mjs +7 -0
  48. package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
  49. package/lib/chunk-DBBPDSFN.mjs +7 -0
  50. package/lib/chunk-DIL62SUN.mjs +7 -0
  51. package/lib/chunk-DIS254AN.mjs +7 -0
  52. package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
  53. package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
  54. package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
  55. package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
  56. package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
  57. package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  58. package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  59. package/lib/chunk-FOIWWK7G.mjs +156 -0
  60. package/lib/chunk-FZF23M6R.mjs +7 -0
  61. package/lib/chunk-G2JR3F63.mjs +7 -0
  62. package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
  63. package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
  64. package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
  65. package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
  66. package/lib/chunk-GHPR5UVV.mjs +7 -0
  67. package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  68. package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
  69. package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
  70. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  71. package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
  72. package/lib/chunk-HIHCYMSL.mjs +7 -0
  73. package/lib/chunk-HKUWHVI7.mjs +9 -0
  74. package/lib/chunk-HQQVANWQ.mjs +20 -0
  75. package/lib/chunk-ICIYL45C.mjs +7 -0
  76. package/lib/chunk-IRZJU2PG.mjs +22 -0
  77. package/lib/chunk-ISSP2FZ5.mjs +7 -0
  78. package/lib/chunk-IVZJSDJD.mjs +7 -0
  79. package/lib/chunk-J24TIGSI.mjs +10 -0
  80. package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
  81. package/lib/chunk-JFNLKHY6.mjs +8 -0
  82. package/lib/chunk-JH27IKCO.mjs +9 -0
  83. package/lib/chunk-JJITOWZK.mjs +7 -0
  84. package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  85. package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
  86. package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
  87. package/lib/chunk-JQZTMFO7.mjs +7 -0
  88. package/lib/chunk-KIMQQ6JQ.mjs +7 -0
  89. package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
  90. package/lib/chunk-KKOA62S4.mjs +474 -0
  91. package/lib/chunk-KP5G6FUC.mjs +7 -0
  92. package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  93. package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
  94. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  95. package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
  96. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  97. package/lib/chunk-LXDSRP2W.mjs +7 -0
  98. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  99. package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
  100. package/lib/chunk-MUEQRIK7.mjs +9 -0
  101. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
  102. package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
  103. package/lib/chunk-O2PUGRNW.mjs +10 -0
  104. package/lib/chunk-O4BROUGM.mjs +7 -0
  105. package/lib/chunk-OETEC3P7.mjs +7 -0
  106. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  107. package/lib/chunk-P55MKIZX.mjs +37 -0
  108. package/lib/chunk-P63WJMXQ.mjs +7 -0
  109. package/lib/chunk-PBE44M2Y.mjs +7 -0
  110. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  111. package/lib/chunk-PE435FVH.mjs +15 -0
  112. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  113. package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
  114. package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
  115. package/lib/chunk-PWVDNN2C.mjs +7 -0
  116. package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
  117. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  118. package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  119. package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  120. package/lib/chunk-QAPVKPEC.mjs +7 -0
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
  123. package/lib/chunk-RLWB7F26.mjs +7 -0
  124. package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
  125. package/lib/chunk-RYRMUPMY.mjs +7 -0
  126. package/lib/chunk-SAMWHL22.mjs +13 -0
  127. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
  128. package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
  129. package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
  130. package/lib/chunk-SZGGFST2.mjs +272 -0
  131. package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
  132. package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
  133. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  134. package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
  135. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  136. package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
  137. package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
  138. package/lib/chunk-UV74P4H2.mjs +7 -0
  139. package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
  140. package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
  141. package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
  142. package/lib/chunk-VV3B6IC3.mjs +7 -0
  143. package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
  144. package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  145. package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WEMLDUQA.mjs +7 -0
  148. package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
  149. package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
  150. package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
  151. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  152. package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
  153. package/lib/chunk-XK5W7BVE.mjs +7 -0
  154. package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
  155. package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
  156. package/lib/chunk-XU25YA46.mjs +9 -0
  157. package/lib/chunk-XZISAZA6.mjs +7 -0
  158. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  159. package/lib/chunk-YAIIRFKJ.mjs +8 -0
  160. package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
  161. package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
  162. package/lib/chunk-YH4DYI6D.mjs +7 -0
  163. package/lib/chunk-YMDFF657.mjs +10 -0
  164. package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
  165. package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  166. package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  167. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
  170. package/lib/chunk-ZUOPC4W2.mjs +7 -0
  171. package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  172. package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  173. package/lib/sandforge-autopilot.mjs +11 -11
  174. package/lib/sandforge-backup.mjs +63 -32
  175. package/lib/sandforge-checkpoint.mjs +1 -348
  176. package/lib/sandforge-cleanup.mjs +1 -1
  177. package/lib/sandforge-clone.mjs +1 -1
  178. package/lib/sandforge-compare.mjs +1 -1
  179. package/lib/sandforge-dataops.mjs +1 -1
  180. package/lib/sandforge-empty.mjs +11 -11
  181. package/lib/sandforge-env.mjs +186 -140
  182. package/lib/sandforge-frozen.mjs +1 -266
  183. package/lib/sandforge-mcp.mjs +33 -14
  184. package/lib/sandforge-monitor.mjs +1 -1
  185. package/lib/sandforge-pipeline.mjs +88 -0
  186. package/lib/sandforge-seed.mjs +1 -1
  187. package/lib/sandforge-sync.mjs +1 -1
  188. package/lib/sandforge-users.mjs +157 -0
  189. package/lib/sandforge.mjs +1 -22
  190. package/lib/sf/sandforge/autopilot.mjs +20 -0
  191. package/lib/sf/sandforge/backup.mjs +20 -0
  192. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  193. package/lib/sf/sandforge/cleanup.mjs +20 -0
  194. package/lib/sf/sandforge/clone.mjs +20 -0
  195. package/lib/sf/sandforge/compare.mjs +20 -0
  196. package/lib/sf/sandforge/dataops.mjs +20 -0
  197. package/lib/sf/sandforge/empty.mjs +20 -0
  198. package/lib/sf/sandforge/env.mjs +20 -0
  199. package/lib/sf/sandforge/frozen.mjs +20 -0
  200. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  201. package/lib/sf/sandforge/index.mjs +20 -0
  202. package/lib/sf/sandforge/mcp.mjs +20 -0
  203. package/lib/sf/sandforge/monitor.mjs +20 -0
  204. package/lib/sf/sandforge/pipeline.mjs +20 -0
  205. package/lib/sf/sandforge/seed.mjs +20 -0
  206. package/lib/sf/sandforge/sync.mjs +20 -0
  207. package/lib/sf/sandforge/users.mjs +20 -0
  208. package/lib/sfHelpHook.mjs +7 -0
  209. package/lib/sfPlugin.mjs +11 -0
  210. package/oclif.manifest.json +1 -0
  211. package/package.json +18 -3
  212. package/lib/chunk-2CNCDM56.mjs +0 -7
  213. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  214. package/lib/chunk-4VS2V6WU.mjs +0 -25
  215. package/lib/chunk-5P4PHJRL.mjs +0 -9
  216. package/lib/chunk-5TC3QB4U.mjs +0 -10
  217. package/lib/chunk-7ABODJ4G.mjs +0 -7
  218. package/lib/chunk-7EGQP6S4.mjs +0 -7
  219. package/lib/chunk-7FFGJWHN.mjs +0 -7
  220. package/lib/chunk-7YDNUBO5.mjs +0 -7
  221. package/lib/chunk-A527W53V.mjs +0 -7
  222. package/lib/chunk-ADOAS63R.mjs +0 -7
  223. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  224. package/lib/chunk-CION3VMZ.mjs +0 -7
  225. package/lib/chunk-CSBS5U5I.mjs +0 -7
  226. package/lib/chunk-DB7RBE5D.mjs +0 -7
  227. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  228. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  229. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  230. package/lib/chunk-EQNW3UC2.mjs +0 -7
  231. package/lib/chunk-F43REJDZ.mjs +0 -10
  232. package/lib/chunk-GSG7WZHM.mjs +0 -7
  233. package/lib/chunk-HOJYWTP7.mjs +0 -20
  234. package/lib/chunk-HS4YRX4J.mjs +0 -7
  235. package/lib/chunk-I7O6C2B5.mjs +0 -8
  236. package/lib/chunk-IFETCRWE.mjs +0 -10
  237. package/lib/chunk-IQXHJEYB.mjs +0 -7
  238. package/lib/chunk-JPUR2CFX.mjs +0 -10
  239. package/lib/chunk-K327QKMD.mjs +0 -7
  240. package/lib/chunk-KRCA6IPH.mjs +0 -8
  241. package/lib/chunk-LPBMBW3O.mjs +0 -13
  242. package/lib/chunk-LWW4U276.mjs +0 -7
  243. package/lib/chunk-MFG4MUIO.mjs +0 -9
  244. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  245. package/lib/chunk-OAZRPP4I.mjs +0 -7
  246. package/lib/chunk-OO6CLPEH.mjs +0 -7
  247. package/lib/chunk-OPXCV2KL.mjs +0 -7
  248. package/lib/chunk-P33PSCXK.mjs +0 -7
  249. package/lib/chunk-Q3DM32KF.mjs +0 -11
  250. package/lib/chunk-QR3WELJQ.mjs +0 -7
  251. package/lib/chunk-QWT2C74M.mjs +0 -7
  252. package/lib/chunk-R3X3LV64.mjs +0 -14
  253. package/lib/chunk-RMBPOTD7.mjs +0 -7
  254. package/lib/chunk-SIHORWVK.mjs +0 -7
  255. package/lib/chunk-T62WNR54.mjs +0 -7
  256. package/lib/chunk-TTFDUKUS.mjs +0 -47
  257. package/lib/chunk-VE6XKGGD.mjs +0 -7
  258. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  259. package/lib/chunk-VS7ZXUII.mjs +0 -824
  260. package/lib/chunk-VXQLDM4R.mjs +0 -7
  261. package/lib/chunk-VYXMVJL5.mjs +0 -7
  262. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  263. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  264. package/lib/chunk-YS4G22C2.mjs +0 -7
  265. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  266. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -0,0 +1,7 @@
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 $}from"./chunk-ZUOPC4W2.mjs";import{a as F}from"./chunk-PPGDAUEQ.mjs";import{a as N}from"./chunk-4TLYUZD5.mjs";import{b as O}from"./chunk-CA5NAXSU.mjs";import{Qc as k,k as M}from"./chunk-ZQO5PDX5.mjs";var x=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,r){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=r?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=r?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,r,n){let s=this.connections.get(t);if(s&&s.active)return s.lastUsedAt=Date.now(),s.accessToken=n,s;this.connections.size>=this.config.maxConnections&&this.evictOldest();let i={orgId:t,instanceUrl:r,accessToken:n,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,i),i}release(t){let r=this.connections.get(t);r&&(r.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,r){if(!Number.isFinite(r)||r<0)return;let n=this.latencySamples.get(t);n||(n=[],this.latencySamples.set(t,n)),n.push(r),n.length>1e3&&n.splice(0,n.length-1e3)}getLatencyMetrics(t){let r=this.latencySamples.get(t);if(!r||r.length===0)return;let n=[...r].sort((a,c)=>a-c),s=n.reduce((a,c)=>a+c,0),i=Math.floor(n.length*.95),u=Math.floor(n.length*.99);return{min:n[0],max:n[n.length-1],avg:Math.round(s/n.length),p95:n[Math.min(i,n.length-1)],p99:n[Math.min(u,n.length-1)],sampleCount:n.length}}getAllLatencyMetrics(){let t=new Map;for(let r of this.latencySamples.keys()){let n=this.getLatencyMetrics(r);n&&t.set(r,n)}return t}cleanupIdle(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(n),r++);return r}recycleStale(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.createdAt>this.recycleIntervalMs&&(s.active=!1,this.connections.delete(n),r++);return r}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,r=1/0;for(let[n,s]of this.connections)s.lastUsedAt<r&&(r=s.lastUsedAt,t=n);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var S=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 B=0;function we(){return B}async function I(e,t){let r=$(e);try{return await t()}finally{B+=r()}}var C=class extends Error{constructor(r,n,s){super(`${r}: ${s}`);this.code=r;this.orgId=n;this.name="OrgConnectionError"}code;orgId};import{homedir as ee,userInfo as te}from"node:os";var ne=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],V=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function X(e){return ne.some(t=>t.test(e))}function P(e=process.env){let t={};for(let[r,n]of Object.entries(e))X(r)||(t[r]=n);return t.NO_COLOR="1",t}function Ee(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),r=V.filter(c=>t.some(d=>d.toUpperCase()===c)),n=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),s=t.filter(c=>X(c)),i=s.filter(c=>c.startsWith("ELECTRON_")).sort(),u=s.length-i.length,a=s.length===0?"none":[...i,...u>0?[`${u} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${r.length>0?r.join(", "):"none of "+V.join(", ")}; SF_/SFDX_: ${n.length>0?n.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${a}`}function re(){try{return te().username}catch{return process.env.USERNAME??process.env.USER??""}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,t=ee(),r=re()){let n=e;return t.length>3&&(n=n.replace(new RegExp(H(t),"gi"),"~")),r.length>=2&&(n=n.replace(new RegExp(`(?<=[\\\\/])${H(r)}(?=[\\\\/]|$)`,"gim"),"<user>")),n.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function ve(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function se(e,t){if(process.platform!=="win32")return e[0];let n=(Object.entries(t).find(([s])=>s.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);return e.find(s=>{let i=s.lastIndexOf(".");return i>Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))&&n.includes(s.slice(i).toLowerCase())})}async function Oe(e=1e4){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=process.platform==="win32"?"where sf node":"which -a sf node",s=P(),i,u;try{let l=await r(t)(n,{timeout:e,windowsHide:!0,env:s});i=String(l.stdout)}catch(l){let o=l;i=String(o.stdout??""),i.trim()===""&&(u=j(o.message??String(l)))}let a=i.split(/\r?\n/).map(l=>l.trim()).filter(l=>l.length>0).map(l=>j(l)),c=l=>a.filter(o=>new RegExp(`(^|[\\\\/])${l}(\\.[A-Za-z0-9]+)?$`,"i").test(o)),d=c("sf"),p=se(d,s);return{sf:d,node:c("node"),...p!==void 0?{runs:p}:{},...u?{failure:u}:{}}}function R(e,t){let r=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return r===""?void 0:r}function ie(e,t){if(t===void 0)return!1;let r=e.hostname.toLowerCase(),n=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(s=>s!=="").some(s=>{if(s==="*")return!0;let[,i="",u]=/^(.*?)(?::(\d+))?$/.exec(s.toLowerCase())??[];if(u!==void 0&&u!==n)return!1;let a=i.replace(/^\*?\.?/,"");return a!==""&&(r===a||r.endsWith(`.${a}`))})}function G(e,t=process.env){let r;try{r=new URL(e)}catch{return}let n=r.protocol==="https:"?R(t,"https_proxy")??R(t,"http_proxy"):R(t,"http_proxy");if(n!==void 0)return ie(r,R(t,"no_proxy"))?void 0:n}var oe="https://login.salesforce.com";async function v(e,t=process.env){let{jsforce:r,HttpProxyTransport:n}=await import("./chunk-L5FGY6YA.mjs"),s=G(e.instanceUrl??e.loginUrl??oe,t),i=new r.Connection({...e,...s!==void 0?{httpProxy:s}:{}});return s===void 0&&(i._transport=new n("")),i}var ae=10*1024*1024,L=3e4,q=L+2e3,A=`sf did not answer within ${L/1e3} s \u2014 check the Salesforce CLI`;function J(e){return e instanceof Error&&e.message===A}var D=2e4;function U(e,t,r){let n,s=new Promise((i,u)=>{n=setTimeout(()=>u(new Error(r)),t)});return Promise.race([e,s]).finally(()=>clearTimeout(n))}var E=new x,ce=300*1e3,_=new Map,le={failureThreshold:3,resetTimeout:3e4},z=new Map;function Ne(){return E}function ue(e){let t=z.get(e);return t||(t=new S({...le}),z.set(e,t)),t}var Y;var b="panel";function Be(e){b=e}function fe(e,t=b){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 W(e=b){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function K(e,t){let r=t?.organization_id;if(!(!Y||typeof r!="string"))try{Y(e,{organizationId:r})}catch(n){N.warn("Identity observer threw",{orgId:e,error:O(n)})}}var de="[REDACTED]";function Z(e){return typeof e=="string"&&e.length>0&&!e.startsWith(de)&&!/\s/.test(e)}async function pe(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:r}=await import("child_process"),{promisify:n}=await import("util"),s={maxBuffer:ae,timeout:L,windowsHide:!0,env:P()},i=o=>U(n(t)("sf",o,s),q,A),u=o=>{let f=!1,h,y=new Promise((T,m)=>{h=r(o,s,(g,w)=>{f=!0,g?m(g):T({stdout:w})})});return U(y,q,A).catch(T=>{throw!f&&h?.pid!==void 0&&t("taskkill",["/pid",String(h.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},a=(o,f)=>process.platform==="win32"?u(o):i(f),c=(o,f)=>{let h=o.replace(/\[[0-9;]*m/g,""),y=h.search(/[{[]/);if(y===-1)throw new Error(`Failed to parse "${f}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(h.slice(y)).result??{}},d;try{let{stdout:o}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),f=c(o,"sf org display");d=typeof f.instanceUrl=="string"?f.instanceUrl:void 0}catch(o){if(J(o))throw o;d=void 0}try{let{stdout:o}=await a(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),f=c(o,"sf org auth show-access-token");if(Z(f.accessToken))return{accessToken:f.accessToken,instanceUrl:d}}catch(o){if(J(o))throw o}let{stdout:p}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),l=c(p,"sf org display");if(!Z(l.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 l.instanceUrl=="string"&&(d=l.instanceUrl),{accessToken:l.accessToken,instanceUrl:d}}async function Ve(e,t){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function He(e){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function je(e,t,r){let n=e,s=r.getOrg(e);if(!s)throw new Error(`Org not found: ${e}`);let i=await t.getCredentials(e);if(!i?.accessToken||!i.instanceUrl)throw new Error(`No credentials for org "${s.alias}" (${e}). Reconnect the org.`);let u=s.metadata.apiVersion||M.DEFAULT_API_VERSION,a=E.get(n),c=Date.now()-(_.get(e)??0)<ce;if(a&&a.active&&a.accessToken===i.accessToken&&c)return a.lastUsedAt=Date.now(),v({instanceUrl:a.instanceUrl,accessToken:a.accessToken,version:u});let d=await v({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:u}),p=ue(e);if(!p.acquirePermit())throw new C("ORG_TEMPORARILY_UNREACHABLE",e,`"${s.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let l=Date.now(),o=`identity check did not answer within ${D/1e3} s`;try{let f=await I(d,()=>U(d.identity(),D,o)),h=Date.now()-l;return p.recordSuccess(),E.acquire(n,i.instanceUrl,i.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,f),d}catch(f){let h=Date.now()-l;if(E.remove(n),_.delete(e),F(f))try{let m=await pe(s.username),g=m.instanceUrl??i.instanceUrl;if(m.accessToken===i.accessToken&&g===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let w=await v({instanceUrl:g,accessToken:m.accessToken,version:u}),Q=await I(w,()=>U(w.identity(),D,o));return await t.saveOrg(s,{...i,accessToken:m.accessToken,instanceUrl:g}),p.recordSuccess(),E.acquire(n,g,m.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,Q),w}catch(m){p.recordFailure();let g=O(m);r.updateStatus(e,"expired");let w=k(s,new Date().toISOString().slice(0,10));throw w!==void 0?new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${w}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${g})`):new C("ORG_AUTH_EXPIRED",e,`The session with "${s.alias}" has expired and could not be renewed. ${fe(s.alias)} (cause: ${g})`)}p.recordFailure();let y=O(f),T=k(s,new Date().toISOString().slice(0,10));throw T!==void 0?(r.updateStatus(e,"expired"),new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${y})`)):new Error(`Connection failed for "${s.alias}": ${y}`)}finally{p.releasePermit()}}export{we as a,I as b,C as c,P as d,Ee as e,j as f,ve as g,Oe as h,G as i,v as j,U as k,Ne as l,Be as m,Z as n,pe as o,Ve as p,He as q,je as r};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as g,b as O,d as E}from"./chunk-TUACWKIH.mjs";import{b as p,e as A,v as x,z as L}from"./chunk-7EANH5PY.mjs";import{randomBytes as I,randomUUID as q}from"node:crypto";import{linkSync as $,mkdirSync as D,readFileSync as F,renameSync as _,unlinkSync as z,writeFileSync as R}from"node:fs";import{hostname as T}from"node:os";import{dirname as C}from"node:path";var K=448,N=384,j={version:x(1),host:p().min(1).max(255),pid:A().int().nonnegative(),hostStartedAt:L.datetime({offset:!0}),acquiredAt:L.datetime({offset:!0}),token:p().min(1).max(64)},b={host:T(),pid:g.pid,startedAt:g.startedAt};function G(e){let n=new Map,r=t=>{try{return e(JSON.parse(t))}catch{return}},u=(t,s,i,o)=>t.host!==i.host?(o?.now?.()??Date.now())-Date.parse(t.acquiredAt)<O:t.pid===i.pid&&t.hostStartedAt===i.startedAt?n.get(m(i,s))?.token===t.token:E({writer:{pid:t.pid,hostStartedAt:t.hostStartedAt},startedAt:t.acquiredAt,lastWriteAt:t.acquiredAt},{pid:i.pid,startedAt:i.startedAt},o);return{acquire(t,s,i={}){let o=i.self??b,d=m(o,t),c=n.get(d);if(c!==void 0)return{busy:c};D(C(t),{recursive:!0,mode:K});let a=s({version:1,host:o.host,pid:o.pid,hostStartedAt:o.startedAt,acquiredAt:new Date(i.checks?.now?.()??Date.now()).toISOString(),token:q()}),H=JSON.stringify(a);for(let l=0;l<3;l+=1){if(W(t,H))return n.set(d,a),{lock:{release:()=>{if(n.get(d)?.token!==a.token)return;n.delete(d);let w=f(t);w!==void 0&&r(w)?.token===a.token&&S(t)}}};let k=f(t);if(k===void 0)continue;let h=r(k);if(h!==void 0&&u(h,t,o,i.checks))return{busy:h};M(t,k)}let y=f(t);return{busy:(y!==void 0?r(y):void 0)??a}},holder(t,s={}){let i=s.self??b,o=n.get(m(i,t));if(o!==void 0)return o;let d=f(t),c=d!==void 0?r(d):void 0;return c!==void 0&&u(c,t,i,s.checks)?c:void 0}}}function m(e,n){return`${e.host}
7
+ import{a as g,b as O,d as E}from"./chunk-TUACWKIH.mjs";import{b as p,e as A,v as x,z as L}from"./chunk-WZQEK4WT.mjs";import{randomBytes as I,randomUUID as q}from"node:crypto";import{linkSync as $,mkdirSync as D,readFileSync as F,renameSync as _,unlinkSync as z,writeFileSync as R}from"node:fs";import{hostname as T}from"node:os";import{dirname as C}from"node:path";var K=448,N=384,j={version:x(1),host:p().min(1).max(255),pid:A().int().nonnegative(),hostStartedAt:L.datetime({offset:!0}),acquiredAt:L.datetime({offset:!0}),token:p().min(1).max(64)},b={host:T(),pid:g.pid,startedAt:g.startedAt};function G(e){let n=new Map,r=t=>{try{return e(JSON.parse(t))}catch{return}},u=(t,s,i,o)=>t.host!==i.host?(o?.now?.()??Date.now())-Date.parse(t.acquiredAt)<O:t.pid===i.pid&&t.hostStartedAt===i.startedAt?n.get(m(i,s))?.token===t.token:E({writer:{pid:t.pid,hostStartedAt:t.hostStartedAt},startedAt:t.acquiredAt,lastWriteAt:t.acquiredAt},{pid:i.pid,startedAt:i.startedAt},o);return{acquire(t,s,i={}){let o=i.self??b,d=m(o,t),c=n.get(d);if(c!==void 0)return{busy:c};D(C(t),{recursive:!0,mode:K});let a=s({version:1,host:o.host,pid:o.pid,hostStartedAt:o.startedAt,acquiredAt:new Date(i.checks?.now?.()??Date.now()).toISOString(),token:q()}),H=JSON.stringify(a);for(let l=0;l<3;l+=1){if(W(t,H))return n.set(d,a),{lock:{release:()=>{if(n.get(d)?.token!==a.token)return;n.delete(d);let w=f(t);w!==void 0&&r(w)?.token===a.token&&S(t)}}};let k=f(t);if(k===void 0)continue;let h=r(k);if(h!==void 0&&u(h,t,o,i.checks))return{busy:h};M(t,k)}let y=f(t);return{busy:(y!==void 0?r(y):void 0)??a}},holder(t,s={}){let i=s.self??b,o=n.get(m(i,t));if(o!==void 0)return o;let d=f(t),c=d!==void 0?r(d):void 0;return c!==void 0&&u(c,t,i,s.checks)?c:void 0}}}function m(e,n){return`${e.host}
8
8
  ${e.pid}
9
9
  ${e.startedAt}
10
10
  ${n}`}function W(e,n){let r=`${e}.${process.pid}-${I(4).toString("hex")}.tmp`;R(r,n,{encoding:"utf8",mode:N,flag:"wx"});try{return $(r,e),!0}catch(u){if(v(u)==="EEXIST")return!1;throw u}finally{S(r)}}function M(e,n){let r=`${e}.${process.pid}-${I(4).toString("hex")}.gone`;try{_(e,r)}catch{return}if(f(r)!==n)try{$(r,e)}catch{}S(r)}function f(e){try{return F(e,"utf8")}catch(n){if(v(n)==="ENOENT")return;throw n}}function S(e){try{z(e)}catch{}}function v(e){return e?.code}export{j as a,G as b};
@@ -0,0 +1,15 @@
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 wn}from"./chunk-PWVDNN2C.mjs";import{a as Rr,b as es}from"./chunk-XCA5AONB.mjs";import{a as xt,b as bn,c as Xn}from"./chunk-66NMFCWX.mjs";import{a as Yn,e as wr,i as yr}from"./chunk-WB2RIVO3.mjs";import{Aa as lr,Ac as hr,Ba as ur,Ca as pr,Dc as Zn,Fc as Sr,Hc as is,Ic as $t,Jc as as,Kc as Bt,Lc as ds,Mc as en,Oc as Cr,Pc as Pr,Qc as Mr,b as Vt,d as Kn,e as qn,f as Hn,j as ke,k as hn,l as Yt,m as Mt,n as Ve,o as H,pa as er,qa as tr,ra as nr,s as pe,sa as sr,ta as rr,ua as or,va as ir,wa as kn,wc as Se,xa as ar,ya as dr,za as cr}from"./chunk-ISSP2FZ5.mjs";import{d as gr}from"./chunk-XU25YA46.mjs";import{a as Et,b as Zs}from"./chunk-CE6ZDGBB.mjs";import{a as vr,b as ts,c as $r,d as ns,e as ss,f as Zt,g as Jt,h as Tr,i as rs,j as jr,k as yn,l as os}from"./chunk-IVZJSDJD.mjs";import{k as Ir,r as Er,s as xr}from"./chunk-O2PUGRNW.mjs";import{l as fr}from"./chunk-7SDZR6SR.mjs";import{d as Ar}from"./chunk-T63U4OZJ.mjs";import{a as Jn}from"./chunk-YYZL7UGV.mjs";import{a as br,c as kr}from"./chunk-SAMWHL22.mjs";import{j as Or}from"./chunk-HKUWHVI7.mjs";import{b as Qn,c as zt,d as Vn,h as mr}from"./chunk-VPDEJGPS.mjs";import{a as Ye}from"./chunk-5LFSFYFJ.mjs";import{r as ze}from"./chunk-PBE44M2Y.mjs";import{c as Qt,e as be,f as gn,i as Gn}from"./chunk-JFNLKHY6.mjs";import{b as Nr}from"./chunk-VV3B6IC3.mjs";import{d as Xs,e as Qs,g as Vs,h as Ys}from"./chunk-INIT2UKJ.mjs";import{B as Js}from"./chunk-XZISAZA6.mjs";import{q as se,r as Xt,u as mn}from"./chunk-KIMQQ6JQ.mjs";import{a as Gs,f as Gt,h as bt}from"./chunk-TZE3Y7IQ.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{Hc as xe,Mc as Un,Sc as Pt,Wc as qs,Xc as fn,a as Re,fb as Ws,gb as Us,hb as Ks,ic as Wn,re as Hs,x as _s,y as ht}from"./chunk-ZQO5PDX5.mjs";import{b as ie,e as Ls,f as Ds,k as vt,l as gt,q as Fs,v as _n}from"./chunk-WZQEK4WT.mjs";var vo={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},$o={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function An(i){return i==="production"?{...vo}:{...$o}}function In(i){return i?"sandbox":"production"}var Lt="IsPersonAccount",No=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function Oo(i){if(No.has(i))return i;if(i.endsWith("__c"))return`${i.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(i))return`Person${i}`}function cs(i){let e=(s,r)=>s.fieldPattern.toLowerCase().startsWith(`${r.toLowerCase()}.`)?s.fieldPattern.slice(r.length+1):void 0,t=new Set(i.flatMap(s=>{let r=e(s,se);return r===void 0?[]:[r.toLowerCase()]})),n=[];for(let s of i){let r=e(s,Xt),o=r===void 0?void 0:Oo(r);o===void 0||t.has(o.toLowerCase())||(t.add(o.toLowerCase()),n.push({...s,fieldPattern:`${se}.${o}`}))}return n}function zr(i){if(i.objectApiName.toLowerCase()!==se.toLowerCase()||!i.fields.some(l=>l.name===Lt))return;let e=new Map(i.fields.map(l=>[l.name.toLowerCase(),l])),t=new Set(i.kept.map(l=>l.fieldApiName.toLowerCase())),n=[],s=new Set,r=[],o=(l,p)=>{t.add(p.name.toLowerCase()),s.add(p.name),n.push({...l,objectApiName:se,fieldApiName:p.name})};for(let l of i.derived){let p=e.get(l.fieldApiName.toLowerCase());if(!p){r.push(l.fieldApiName);continue}t.has(p.name.toLowerCase())||o(l,p)}let a=i.fields.filter(l=>qs(l.name)&&l.updateable===!0&&l.calculated!==!0&&!t.has(l.name.toLowerCase())),d=new Map,c=a.map(l=>{let p=Lr(l.name);return d.set(p,l),{...l,name:p,label:l.label??l.name,type:l.type??"string"}});for(let l of wr(i.detector,Xt,c)){let p=d.get(l.field.name);!p||t.has(p.name.toLowerCase())||o({objectApiName:se,fieldApiName:p.name,method:yr({...l.field,name:p.name}),config:{}},p)}return{rules:n,personOnly:s,unseen:r}}function Br(i,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return i.filter(n=>!t.has(Lr(n).toLowerCase()))}function Lr(i){return i.endsWith("__pc")?`${i.slice(0,-4)}__c`:i.startsWith("Person")&&!i.includes("__")?i.slice(6):i}function Dr(i,e,t,n){if(i.toLowerCase()!==se.toLowerCase())return[...t];let s=mn(e,!1);return t.filter(r=>!fn(se,r.fieldApiName,s)&&(s==="person"||!n.has(r.fieldApiName)))}var Fr=200,To=48,jo=64;function Rn(i,e){return Math.max(1,Math.ceil(i/e))}function _r(i,e,t){let n=Math.max(1,Math.ceil(i/e)),s=t.masking?Math.ceil(i/Fr):0;return n+1+s+(t.duplicateRule?2:0)}function ls(i,e,t,n){let s=0,r=0,o=0,a=0,d=[],c=[];for(let l of i){let p=Rn(l.rows,e);p>ht&&c.push(l.objectApiName);let g=Math.floor(l.rows/e),u=l.rows-g*e;s+=g*Math.ceil(e/t)+Math.ceil(u/t)+1,n==="masking"&&(r+=Math.ceil(l.rows/Fr)),o+=p+(l.duplicateRule&&n==="masking"?2*p:0)+2,a+=l.rows*(To+jo*l.fields),d.push({objectApiName:l.objectApiName,size:e,slices:p,...l.approximate?{approximate:!0}:{}})}return{objects:d,requests:s+r+o,parts:{snapshots:s,updates:r,reads:o},diskBytes:a,seconds:Math.round(s*Er+r*xr),tooMany:c}}function Sn(i){return Math.ceil(i*1.1)}function us(i){let e=["bytes","KB","MB","GB","TB"],t=i,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return n===0?`${i} bytes`:`${t.toFixed(t<10?1:0)} ${e[n]}`}import{createHash as Co}from"node:crypto";import{mkdir as Po,readFile as Mo,rm as Eo,writeFile as xo}from"node:fs/promises";import*as ps from"node:path";function vn(i){if(!/^[A-Za-z0-9_-]{1,200}$/.test(i))throw new Error(`Not a set id: "${i}".`);return i}var Wr=/^[0-9a-f]{64}$/;function Ei(i){return{save:async(e,t)=>{await i.storeSecret(`dataops.runKey.${vn(e)}`,t)},load:async e=>{let t=await i.getSecret(`dataops.runKey.${vn(e)}`);return t!==void 0&&Wr.test(t)?t:void 0},delete:async e=>{await i.deleteSecret(`dataops.runKey.${vn(e)}`)}}}var zo=384,Bo=448;function xi(i){let e=ps.join(i,"keys"),t=n=>ps.join(e,`${vn(n)}.key`);return{save:async(n,s)=>{await Po(e,{recursive:!0,mode:Bo}),await xo(t(n),s,{encoding:"utf8",mode:zo})},load:async n=>{try{let s=(await Mo(t(n),"utf8")).trim();return Wr.test(s)?s:void 0}catch{return}},delete:async n=>{await Eo(t(n),{force:!0})}}}function fs(i){return Co("sha256").update(`sandforge-slice-key:${i}`).digest("hex").slice(0,16)}import{randomBytes as Zo}from"node:crypto";import{statfs as Jo}from"node:fs/promises";import*as ho from"node:path";var tn=[{id:"tpl-gdpr-standard",name:"GDPR Standard",description:"Standard GDPR compliance: anonymize personal data fields across common Salesforce objects.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."}]},{id:"tpl-ccpa-california",name:"CCPA California",description:"CCPA compliance: anonymize consumer personal information per California privacy regulations.",complianceFramework:"ccpa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace consumer first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace consumer last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Contact.Phone",ruleType:"nullify",description:"Nullify phone number."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Nullify street address."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Nullify city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"nullify",description:"Nullify postal code."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Lead.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Lead.Phone",ruleType:"nullify",description:"Nullify phone number."}]},{id:"tpl-hipaa-health",name:"HIPAA Health Data",description:"HIPAA compliance: de-identify protected health information (PHI) in healthcare Salesforce orgs.",complianceFramework:"hipaa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace patient first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace patient last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth (PHI)."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Remove address (PHI)."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Remove city (PHI)."},{fieldPattern:"Contact.MailingState",ruleType:"nullify",description:"Remove state (PHI)."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"truncate",description:"Truncate to first 3 digits.",config:{truncateLength:3,truncateKeep:"first"}},{fieldPattern:"Account.Name",ruleType:"fake",description:"Replace facility name."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask facility phone."}]},{id:"tpl-sandbox-scrub",name:"Sandbox Data Scrub",description:"General-purpose sandbox data scrubbing: mask all PII for safe development use.",complianceFramework:"custom",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Contact.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Contact.Phone",ruleType:"preserve_format",description:"Replace keeping phone format."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Lead.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Lead.Company",ruleType:"fake",description:"Fake company name."},{fieldPattern:"Account.Name",ruleType:"fake",description:"Fake account name."},{fieldPattern:"Account.Website",ruleType:"constant",description:"Replace with placeholder URL.",config:{constantValue:"https://example.com"}},{fieldPattern:"Opportunity.Name",ruleType:"fake",description:"Fake opportunity name."}]}];var $n=class{operations=new Map;ttlMs;nowFn;constructor(e=36e5,t=Date.now){this.ttlMs=e,this.nowFn=t}isDuplicate(e){return this.pruneExpired(),this.operations.has(e)}register(e,t,n,s){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let r={operationId:e,objectApiName:t,dmlType:n,recordCount:s,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,r),r}markCompleted(e){let t=this.operations.get(e);t&&(t.status="completed")}markFailed(e){let t=this.operations.get(e);t&&(t.status="failed")}get(e){return this.operations.get(e)}get size(){return this.operations.size}clear(){this.operations.clear()}pruneExpired(){let e=this.nowFn()-this.ttlMs;for(let[t,n]of this.operations)new Date(n.registeredAt).getTime()<e&&this.operations.delete(t);if(this.operations.size>1e4){let t=Array.from(this.operations.entries()),n=t.length-1e4;for(let s=0;s<n;s++)this.operations.delete(t[s][0])}}};var Lo=3e3;function Ze(i){return i.slice(0,15)}function Do(i,e){let t=i??null,n=e??null;return t===n?!0:t===null||n===null?!1:typeof t=="object"||typeof n=="object"?JSON.stringify(t)===JSON.stringify(n):String(t)===String(n)}function Fo(i){let e=[],t=[],n=0;for(let s of i)t.length>0&&n+s.length+2>Lo&&(e.push(t),t=[],n=0),t.push(s),n+=s.length+2;return t.length>0&&e.push(t),e}async function Ur(i,e,t){let n=t.map(a=>a.Id).filter(zt),s=[...new Set(t.flatMap(a=>Object.keys(a)))].filter(a=>a.toLowerCase()!=="id");if(n.length===0||s.length===0)return{write:[...t],unchanged:0};let r=new Map;try{for(let a of Fo(s))for(let d of await mr(i,e,a,n))typeof d.Id=="string"&&r.set(Ze(d.Id),{...r.get(Ze(d.Id)),...d})}catch(a){return{write:[...t],unchanged:0,unread:P(a)}}let o=t.filter(a=>{let d=zt(a.Id)?r.get(Ze(a.Id)):void 0;return d?Object.keys(a).some(c=>c.toLowerCase()!=="id"&&!Do(a[c],d[c])):!0});return{write:o,unchanged:t.length-o.length}}async function Kr(i,e,t,n){let s=bt(e),r=new Set,o=t.filter(zt);for(let a=0;a<o.length;a+=Qn){let d=o.slice(a,a+Qn),[c]=Vn(d,d.length),l=new Set,p=await i.query(`SELECT Id, LastModifiedDate FROM ${s} WHERE Id IN (${c})`);for(let S of p.records){if(typeof S.Id!="string")continue;l.add(Ze(S.Id)),Date.parse(String(S.LastModifiedDate??""))<=n||r.add(Ze(S.Id))}let g=d.filter(S=>!l.has(Ze(S)));if(g.length===0)continue;let[u]=Vn(g,g.length),f=await i.query(`SELECT Id FROM ${s} WHERE Id IN (${u}) AND IsDeleted = true`,{scanAll:!0});for(let S of f.records)typeof S.Id=="string"&&r.add(Ze(S.Id))}return r}function qr(i,e){return{async*[Symbol.asyncIterator](){for await(let t of i){let n=t.filter(s=>!(zt(s.Id)&&e.has(Ze(s.Id))));n.length>0&&(yield n)}}}}function ms(i,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,s=[],r=0;for await(let a of i)for(let d of a){if(r++,!zt(d.Id)){s.push({...d});continue}let c=n.get(Ze(d.Id));if(!c){n.set(Ze(d.Id),{...d});continue}for(let[l,p]of Object.entries(d))l in c||(c[l]=p)}t=r;let o=[...n.values(),...s];for(let a=0;a<o.length;a+=e)yield o.slice(a,a+e)}},lines:()=>t}}var gs="anonymization:template:",Hr="anonymizationTemplates",Gr=gt({id:ie().min(1).max(100),name:ie().trim().min(1).max(Ws),description:ie().max(500),complianceFramework:_n("custom"),rules:vt(Fs(Ks,gt({description:ie().max(500)}))).min(1).max(Us),saved:_n(!0),createdAt:ie()}),Nn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${gs}${e.id}`,e,Hr)}load(e){let t=Gr.safeParse(this.configStore.get(`${gs}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(Hr))){let n=Gr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${gs}${e}`)}};import{createHash as Xr}from"node:crypto";var Wo="anonymization:checkpoint:",Uo="anonymizationCheckpoints",Nt=2e3,hs=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ko=ie().min(1).max(255),qo=gt({id:ie().regex(hs),fields:vt(Ko).min(1).max(800),digest:ie().regex(/^[0-9a-f]{64}$/)}),Ho=gt({objectApiName:ie().min(1).max(255),done:Ds(),afterId:ie().regex(hs).optional(),refused:vt(ie().regex(hs)).max(Nt),unconfirmed:vt(qo).max(Nt).optional(),slice:gt({setId:ie().min(1).max(200),index:Ls().int().positive()}).optional()}),Go=gt({id:ie().min(1).max(200),orgId:ie().min(1).max(200),templateId:ie().min(1).max(200),fingerprint:ie().regex(/^[0-9a-f]{64}$/),savedAt:ie(),objects:vt(Ho),namesGiven:ie().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional(),setId:ie().min(1).max(200).optional()});function sn(i,e,t,n){let s=i.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return Xr("sha256").update(JSON.stringify({rules:s,objects:e,...r?{where:r}:{},...n!==void 0?{slices:n}:{}})).digest("hex")}function Xo(i){return i==null||i===""?null:typeof i=="string"?i.trim():typeof i=="number"||typeof i=="boolean"?String(i):JSON.stringify(i)}function bs(i,e){let t=[...e].sort().map(n=>[n,Xo(i[n])]);return Xr("sha256").update(JSON.stringify(t)).digest("hex")}function nn(i){return i.reduce((e,t)=>e+t.refused.length,0)}var nt=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let s=Go.safeParse(this.configStore.get(this.key(e,t)));if(!s.success)return;let r=s.data;if(!(r.orgId!==e||r.templateId!==t||r.fingerprint!==n))return r}save(e){if(nn(e.objects)>Nt)throw new Error(`A checkpoint keeps at most ${Nt} refused records; this run left ${nn(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,Uo)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${Wo}${e}:${t}`}};async function Qo(i){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:s}=await import("node:crypto"),r=`${i}.${s(4).toString("hex")}.partial`,o=await e(r,"w"),a=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let l=0;l<c.length;){let{bytesWritten:p}=await o.write(c,l,c.length-l,null);l+=p}},close:async()=>{a=!0,await o.close(),await t(r,i)},abort:async()=>{a||await o.close().catch(()=>{}),a=!0,await n(r,{force:!0})}}}function Vo(i){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await i(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var On=class i{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{showSaveDialog:t=>e.window.showSaveDialog(t),writeFile:(t,n)=>e.workspace.fs.writeFile(t,n),fileUri:t=>e.Uri.file(t),openFile:async t=>t.scheme==="file"?Qo(t.fsPath):Vo(n=>e.workspace.fs.writeFile(t,n))}}static filtersOf(e,t){let n=e.includes(".")?e.split(".").pop():void 0;return t?.length?{[t.join("/").toUpperCase()]:t}:n?{[n.toUpperCase()]:[n]}:void 0}static ask(e,t,n){let s=i.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...s?{filters:s}:{}})}async save(e,t,n){let s=this.host??await this.defaultHost();try{let r=await i.ask(s,e,n);return r?(await s.writeFile(r,new TextEncoder().encode(t)),{status:"saved",path:r.fsPath}):{status:"cancelled"}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}async saveStream(e,t,n){let s=this.host??await this.defaultHost(),r;try{let o=await i.ask(s,e,n);if(!o)return{status:"cancelled"};let a=await s.openFile(o);r=a;let d=await t(c=>a.write(c));return await a.close(),r=void 0,{status:"saved",path:o.fsPath,result:d}}catch(o){return await r?.abort().catch(()=>{}),{status:"error",message:o instanceof Error?o.message:String(o)}}}};function rn(i,e,t,n,s=0){i?.register(e,t,n,s);let r=!1,o=a=>{r||(r=!0,a())};return{progress:(a,d,c,l)=>{r||i?.updateProgress(e,a,d,c,l)},complete:()=>o(()=>i?.complete(e)),partial:()=>o(()=>i?.partial(e)),fail:a=>o(()=>i?.fail(e,a)),cancel:()=>o(()=>i?.cancel(e))}}var Ue={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",retries:"PIPELINE_WRITE_NO_RETRIES",filterNeedsObject:"MASKING_FILTER_NEEDS_OBJECT",invalid:"INVALID_PAYLOAD",templateMissing:"TEMPLATE_NOT_FOUND",fieldsUnseen:"MASKING_FIELDS_UNSEEN",masksNothing:"MASKING_MASKS_NOTHING"};function st(i,e){return Object.assign(new Error(e),{code:i})}function Qr(i,e,t){let n=Hs(i);if(n==="refused")return st(Ue.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never masks one, whatever an Approval step answers. Mask a sandbox, a scratch org or a Developer Edition org. Nothing was masked.`);if(n==="needsApproval"&&!e.approved)return st(Ue.needsApproval,`${t} is a sandbox marked Staging, which a pipeline masks only once an Approval step before the masking has approved the run, and none did: put an Approval step before it. Nothing was masked.`)}function ks(i,e){if(i.retries!==void 0&&i.retries>0)return{refusal:st(Ue.retries,"A masking step is never tried again: a second try masks again what the first one masked \u2014 an address it hashed is hashed once more, and no longer gives the same pseudonym on Contact and on Lead. Set its retries to 0. Nothing was masked.")};let t=i.where?.trim();if(t&&i.object===void 0)return{refusal:st(Ue.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=kn.safeParse({orgId:i.orgId,templateId:i.templateId,...i.object!==void 0?{objects:[i.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let s=n.error.issues[0];return{refusal:st(Ue.invalid,`The masking step is not one the DataOps page would run (${s.path.join(".")}: ${s.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:st(Ue.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}var Yo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Vr(i){if(!Yo.test(i))throw new Error(`Not a record id: "${i}".`);return i}function ws(i,e){let t=i?.trim();return[...t?[`(${Gt(t)})`]:[],...e.createdSince!==void 0?[`CreatedDate >= ${Js(e.createdSince)}`]:[],...e.afterId!==void 0?[`Id > '${Vr(e.afterId)}'`]:[],...e.untilId!==void 0?[`Id <= '${Vr(e.untilId)}'`]:[]]}function ys(i){return i.length===0?"":` WHERE ${i.join(" AND ")}`}function Yr(i,e,t,n,s){if(!Number.isInteger(s)||s<=0)throw new Error(`Not a slice size: ${s}.`);return`SELECT ${e} FROM ${bt(i)}${ys(ws(t,n))} ORDER BY Id LIMIT ${s}`}function As(i,e,t,n){return`SELECT COUNT() FROM ${bt(i)}`+ys(ws(e,{...n,createdSince:t}))}function Zr(i,e,t){return`SELECT COUNT() FROM ${bt(i)}`+ys(ws(e,{afterId:t}))}function bo(i){let e=i.fields;return{name:i.name,label:i.label,labelPlural:i.labelPlural??"",keyPrefix:i.keyPrefix??null,custom:i.custom??!1,createable:i.createable,updateable:i.updateable,deletable:i.deletable,queryable:i.queryable,fields:e.map(t=>({name:t.name,label:t.label,type:t.type,length:t.length??0,nillable:t.nillable??!1,createable:t.createable,updateable:t.updateable,externalId:t.externalId??!1,referenceTo:t.referenceTo??[],relationshipName:t.relationshipName??null,picklistValues:t.picklistValues??[],defaultValue:t.defaultValue??null,calculated:t.calculated??!1,autoNumber:t.autoNumber??!1,unique:t.unique??!1,permissionable:t.permissionable??!0})),recordTypeInfos:i.recordTypeInfos??[],childRelationships:i.childRelationships??[]}}var ei=new Set(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:quality-scan","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"]),ti=6e4,ni=10,si=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ri(i,e){return i.slice(0,15)===e.slice(0,15)}var Jr="ORG_REPLACED_SINCE_BACKUP",oi="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",Ot=class extends Error{constructor(){super(oi),this.name="BackupCancelledError"}},cn=class extends Error{constructor(e){super(`The backup could not be written to disk: ${P(e)}`),this.name="BackupWriteError"}},Wt=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},Cs="IsDeleted = false",ii="SystemModstamp",ko=5e4,ai=100,an=_s;function di(i){return typeof i!="number"||!Number.isFinite(i)?ko:Math.min(an,Math.max(ai,Math.floor(i)))}var Dt=200,ci=1440*6e4,li=1440*6e4,eo="backupRetention:since",Is="BACKUP_BUSY";function ui(i,e){return e===0?"success":i===0?"failure":"partial"}function Rs(i){return Un(i)}function to(i,e,t){i.length>=ni||i.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Tn(i,e,t=!1){let n=(e?.rules??[]).map(r=>r.fieldPattern.split(".")[0]).filter((r,o,a)=>a.findIndex(d=>En(d,r))===o);if(i.objects)return i.objects.map(r=>n.find(o=>En(o,r))??(En(r,se)?se:r));if(!e)return[];let s=[...n];return t&&ln(i,e,se)&&s.push(se),s}function En(i,e){return i.toLowerCase()===e.toLowerCase()}var pi=`${Lt} = true`;function ln(i,e,t){return i.objects===void 0&&t.toLowerCase()===se.toLowerCase()&&Ft(e,se).length===0&&cs(e.rules).length>0}function jn(i,e,t){return ln(i,e,t)?pi:zn(i)}async function Ss(i,e){try{return(await i.describe(se)).fields.some(t=>t.name===Lt)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${P(t)}`),!1}}function Ft(i,e){let t=`${e.toLowerCase()}.`;return i.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function dn(i,e){return e.toLowerCase()===se.toLowerCase()?cs(i.rules):[]}function Cn(i){let e=new Map;return{describe:t=>{let n=e.get(t)??i.describe(t);return e.set(t,n),n}}}async function vs(i,e){return new Xn(async n=>bo(await i.describe(n))).deniedOf(e.map(({objectApiName:n,rules:s})=>({objectApiName:n,operation:"update",fieldNames:s.map(r=>r.fieldPattern.includes(".")?r.fieldPattern.split(".")[1]:r.fieldPattern).filter(r=>r!=="*")})))}function no(i,e){return Ft(i,e).length>0||dn(i,e).length>0}function $s(i){return{objectApiName:i.objectApiName,recordCount:i.recordCount,truncated:i.truncated===!0,...i.orgCount!==void 0?{orgCount:i.orgCount}:{},...i.stoppedAt?{stoppedAt:i.stoppedAt}:{},...i.notKept&&i.notKept.length>0?{notKept:[...i.notKept]}:{},...i.where?{where:i.where}:{}}}function Ns(i,e){return i.flatMap(t=>{let n=e?.get(t.objectApiName);if(n!==void 0&&n<t.recordCount)return[`${t.objectApiName} ${n} of the ${t.recordCount} it listed (not found on disk)`];if(!t.truncated)return[];if(t.stoppedAt==="not_reached")return[`${t.objectApiName} none (the backup stopped before it)`];let s=t.orgCount!==void 0?` of ${t.orgCount}`:"",r=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${s}${r}`]}).join(", ")}var rt=200,Os=95,un=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,fi="NOTHING_TO_RESUME",so="TEMPLATE_NOT_FOUND";function Ts(i){return new Error(`Template "${i}" not found.`)}function mi(i){let e=i.Id;if(typeof e!="string"||!un.test(e))return[];let t=Object.keys(i).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:bs(i,t)}]:[]}var gi="COUNT_FAILED",on="SNAPSHOT_NOT_TAKEN",js=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE"]),hi=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Pn(i){if(typeof i=="object"&&i!==null){let{errorCode:e,code:t}=i;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return hi.exec(P(i))?.[1]??"UNKNOWN"}var ro=5;function oo(i){return i==null?null:typeof i=="string"||typeof i=="number"||typeof i=="boolean"?i:JSON.stringify(i)}function wo(i){return i.done?0:Math.max(0,i.total-i.masked-i.nothingToMask-i.refused-i.unanswered-(i.deletedSince??0))}function Bn(i){return i.refused+i.unanswered+wo(i)+(i.late??0)}function _t(i){return i.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Bn(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function bi(i,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:s}=_t(i);return s===0?"success":t>0||e&&n===0?"partial":"failure"}function ki(i,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:s}=_t(i);return n+s>0?{outcome:"cancelled"}:{outcome:"stopped",code:Gn}}function io(i){return i.filter(e=>Bn(e)>0).map(e=>`${e.objectApiName} ${Bn(e)}`).join(", ")}function ao(i){return i.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Bn(e)}))}function co(i){return i.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=wo(e);return{...gn(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function lo(i,e,t,n,s,r){return Zs(i,`SELECT ${t} FROM ${e}${xn(r,s)} ORDER BY Id LIMIT ${n}`,n)}function xn(i,e){let t=i?.trim(),n=[...t?[`(${Gt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function zn(i){let e=i.where?.trim();return e||void 0}function wi(i){let e=i?.trim();return e?`(${Gt(e)}) AND ${Cs}`:Cs}function yi(i){let e=new Map;for(let[t,n]of i){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(s=>bt(s)).join(", "))}return e}function uo(i,e,t){let n=e===void 0?"more records":`${e} records`;return new Wt(`${i} holds ${n}, past the ${t} a snapshot reads of one object: no snapshot was kept, as one holding part of the object would be taken for all of it.`,!1)}function yo(i,e){return`The org stopped answering the read of ${i} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function Ai(i,e,t,n){let s={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},r=await i.query(e,s),o=[...r.records];for(;!r.done;){if(!r.nextRecordsUrl)throw new Wt(yo(n,o.length),!0);r=await i.queryMore(r.nextRecordsUrl,s),o.push(...r.records)}return o}function Ii(i,e,t){let n=i[i.length-1]?.Id;if(typeof n!="string"||!un.test(n)||n===e)throw new Error(`The org answered a page of ${t} that does not end past the page before it: masking stopped there rather than write the same rows again.`);return n}function Ri(i){let e=i?.[0];return e?.statusCode==="ENTITY_IS_DELETED"||e?.errorCode==="ENTITY_IS_DELETED"}function Mn(i){return i.slices.filter(e=>!e.late&&e.state!=="pending"&&e.lastId!==void 0).at(-1)?.lastId}function Si(i){return i.slices.reduce((e,t)=>{let n=t.state==="masking"?Math.max(0,t.rows-t.masked-t.nothingToMask-t.refused-t.deletedSince-(t.unanswered??0)):0;return e+n+t.refused+(t.lateLeft??0)},0)}var po=100,fo=3;function mo(i){return`_refused_${i}`}var go=class{constructor(e,t){this.deps=e;this.saveDialog=t??new On}deps;activeOrgOperations=new Set;writing=new Rr;dmlTracker=new $n;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Zo(32).toString("hex");runKeys;freeBytes=async()=>{let e=this.backupRecords?.directory;if(e!==void 0)for(let t of[e,ho.dirname(e)])try{let n=await Jo(t);return Number(n.bavail)*Number(n.bsize)}catch{}};sliceRunsOn=new Map;saveDialog;get savedTemplates(){return new Nn(this.deps.configStore)}findTemplate(e){return tn.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e,t=this.maskingKey){let n={...e.config};return e.ruleType==="hash"&&(n.hashSalt=t),n}maskingRules(e,t,n=this.maskingKey){return t.map(s=>({objectApiName:e,fieldApiName:s.fieldPattern.includes(".")?s.fieldPattern.split(".")[1]:s.fieldPattern,method:s.ruleType,config:this.ruleConfig(s,n)}))}refuseUnknownTemplate(e,t,n){H(this.deps,e,"dataops:error",t,Ts(n),{code:so})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}setRunKeyStore(e){this.runKeys=e}setFreeBytes(e){this.freeBytes=e}get sliceSets(){return new Mr(this.deps.configStore)}busyMessage(e,t){let n=this.sliceRunsOn.get(e);if(n===void 0)return t;let s=this.onCommandLine?"the same line with --resume masks the rest, and --abandon gives the set up":"Resume masks the rest, and Abandon gives the set up";return`A masking run in slices (set ${n}) writes to org ${e} now, and holds its backups and restores until it ends: wait for it, or stop it; once stopped, ${s}.`}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setOnCommandLine(e){this.onCommandLine=e}onCommandLine=!1;countGaveUp(e,t){if(!js.has(Pn(e)))return e;let n=this.onCommandLine?"give --slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow --where to an indexed field, such as a range of CreatedDate":`mask in slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow the run from the command line with sandforge dataops anonymize --object ${t} --where on an indexed field, such as a range of CreatedDate`;return new Error(`${P(e)} The org gave up counting the ${t} records the run would mask: ${n}. Nothing was masked.`)}duplicatesSettleMs=vr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return $r({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-DIL62SUN.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>ze(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return Pt(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,s,r,o){let a=this.targetAutomation;return jr({act:n,target:this.orgNameOf(t),objects:s,org:Tr(e,d=>new Nr(ti).withTimeout("dataops automation",()=>a.read(t,d)),Un(this.deps.orgManager.getOrg(t))==="production"),accord:r,mayMute:this.muteOffered,muteLeases:this.muteLeases,...o?{voice:o}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let s of Or(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${s}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(ir,e,"dataops:error",this.deps);if(t)try{let n=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),s=await this.readAct(n,t.orgId,t.act,t.objects,t,Jt(t)),r=ke(this.deps,e,"dataops:automation:response",{...s.answer});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} refusals=${s.answer.refusals.length}`)}catch(n){H(this.deps,"dataops:automation","dataops:error",e,n)}}setExpiryListener(e){this.expiryListener=e}setBackupRecordStore(e){this.backupRecords=e,this.sweeping=this.sweepBackupFiles()}swept(){return this.sweeping??Promise.resolve()}async sweepBackupFiles(e=Date.now()){await this.expireBackups(e);let t=this.backupRecords;if(t)try{let n=new Set(this.backupsWriting);for(let r of this.deps.configStore.getKeysByPrefix("backup:"))n.add(r.slice(7).split(":")[0]);let s=await t.sweep(n,ci,e);s.length>0&&this.deps.log(`[INFO] Removed ${s.length} backup file(s) whose backup never saved its metadata: `+s.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+P(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!ei.has(e.type))return!1;switch(e.type){case"backup:execute":return await this.handleBackup(e),!0;case"backup:list":return this.handleBackupList(e),!0;case"backup:objects":return await this.handleBackupObjects(e),!0;case"backup:export":return await this.handleBackupExport(e),!0;case"backup:delete":return await this.handleBackupDelete(e),!0;case"dataops:rollback":return await this.writing.during(es(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(es(e,"orgId"),()=>this.handleAnonymize(e)),!0;case"dataops:anonymization-templates":return this.handleAnonymizationTemplates(e),!0;case"dataops:quality-scan":return await this.handleQualityScan(e),!0;case"dataops:anonymization-template:save":return this.handleTemplateSave(e),!0;case"dataops:anonymization-template:delete":return this.handleTemplateDelete(e),!0;case"dataops:anonymize:coverage":return await this.handleAnonymizeCoverage(e),!0;case"dataops:anonymize:preview":return await this.handleAnonymizePreview(e),!0;case"dataops:automation":return await this.handleAutomation(e),!0;case"precheck:pii-scan":return await this.handlePIIScan(e),!0;default:return!1}}async selectAllFields(e,t,n){let s=await e.describe(t),r=s.fields.filter(d=>d.type===br).map(d=>d.name),o=r.length>0&&n&&!await n()?r:[];return{select:s.fields.filter(d=>!o.includes(d.name)).map(d=>d.name).join(", "),notKept:o}}async maskedFields(e,t,n,s=[]){let r=(await e.describe(t)).fields,o=new Map(r.map(u=>[u.name.toLowerCase(),u.name])),a=[],d=[];for(let u of n){let f=o.get(u.fieldApiName.toLowerCase());f!==void 0?a.push({...u,fieldApiName:f}):u.fieldApiName!=="*"&&!d.includes(u.fieldApiName)&&d.push(u.fieldApiName)}let c=zr({objectApiName:t,fields:r,kept:a,derived:s,detector:this.deps.infraServices?.piiDetector??new Ar});if(c&&c.unseen.length>0){let u=await e.describe(Xt).then(f=>f.fields,()=>{});for(let f of Br(c.unseen,u))d.includes(f)||d.push(f)}let l=c?[...a,...c.rules]:a,p=l.map(u=>u.fieldApiName).filter((u,f,S)=>u!=="Id"&&S.indexOf(u)===f),g=c&&p.length>0&&!p.includes(Lt);return{rules:l,select:["Id",...p,...g?[Lt]:[]].join(", "),missing:d,rulesOf:c?u=>Dr(t,u,l,c.personOnly):()=>l}}async countRows(e,t,n,s){let o=(await e.query(`SELECT COUNT() FROM ${t}${xn(s,n)}`)).totalSize;if(typeof o!="number"||!Number.isInteger(o)||o<0)throw new Error(`The org did not say how many records ${t} holds.`);return o}async organizationIdOf(e){try{let n=(await Et(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&si.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${P(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(er,e,"dataops:error",this.deps);if(!t)return;let n=e.id,s=new Map;for(let[a,d]of Object.entries(t.wheres??{})){let c=t.objects.find(l=>En(l,a));c!==void 0&&d.trim()!==""&&s.set(xe(c),d.trim())}if(t.slices===!0){await this.backupInSlices(e,{orgId:t.orgId,objects:t.objects,wheres:s});return}let r=await this.takeBackup(n,{orgId:t.orgId,objects:t.objects,...s.size>0?{wheres:s}:{}},e.type);if("error"in r){H(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=ke(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map($s),totalRecords:r.totalRecords,...r.partial?{partial:!0}:{},timestamp:r.timestamp});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}async backupInSlices(e,t){let n=e.id,s={module:"dataops",operation:e.type},r=(g,u)=>{H(this.deps,"backup:execute","dataops:error",e,new Error(u),{...g?{code:g}:{}}),pe(this.deps,n,u,!1,{context:s,authored:!0})};if(!this.backupRecords){r(Re.needsStore,"A backup in slices writes each slice to the backup files, and this host keeps none.");return}let o=`backup:${t.orgId}`;if(this.activeOrgOperations.has(o)){r(void 0,this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`));return}this.activeOrgOperations.add(o);let a=new AbortController,d=()=>{},c,l,p=`Backup ${t.objects.length} object(s) in slices`;try{let g=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager);Yt(this.deps,n,"dataops",p),this.deps.infraServices?.backgroundRegistry?.register(n,"dataops",p,new Promise((A,B)=>{d=C=>{C===void 0?A():B(C instanceof Error?C:new Error(String(C)))}}),a),c=rn(this.liveTracker,n,"dataops",p,t.objects.length);let u=0,f=new Date().toISOString(),S=await this.organizationIdOf(g),k={setId:n,kind:"backup",orgId:t.orgId,...S!==void 0?{organizationId:S}:{},size:this.backupCap(),state:"open",startedAt:f,lastActivityAt:f,requestsSpent:0,objects:t.objects.map(A=>{let B=xe(A),C=t.wheres.get(B);return{objectApiName:B,...C?{where:C}:{},done:!1,slices:[]}})},E=this.sliceSets,j=()=>{k.lastActivityAt=new Date().toISOString(),k.requestsSpent=u,E.save(k)};j();let y,b=!1;e:for(let A of k.objects)for(s.objectName=A.objectApiName;;){if(a.signal.aborted){b=!0;break e}let B=A.slices.filter(ve=>!ve.late);if(B.length>=ht){y=`${A.objectApiName} holds more rows than ${ht} slices of ${k.size} do: the backup stopped there.`;break e}let C=as(k),ee=Mn(A),G={index:C,...ee!==void 0?{afterId:ee}:{},rows:0,snapshotId:is(k.setId,C),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:B.at(-1)?.sizeUsed??k.size};A.slices.push(G),j();let W=await this.snapshotSlice(g,t.orgId,k,A,G,{bounds:ee!==void 0?{afterId:ee}:{},stop:a.signal,onRequest:()=>{u++},origin:e.type,clock:!1});if("failed"in W){A.slices=A.slices.filter(ve=>ve!==G),j(),W.cancelled?b=!0:y=this.sliceNotTakenMessage(A.objectApiName,W);break e}if(W.lastId===void 0){await this.removeBackup(`backup:${G.snapshotId}`),A.slices=A.slices.filter(ve=>ve!==G),A.done=!0,j();break}G.rows=W.rows,G.lastId=W.lastId,G.sizeUsed=W.sizeUsed,G.takenAt=new Date().toISOString(),G.state="snapshotted",j();let X=`Backed up ${A.objectApiName} slice ${C} (${W.rows} records)`;Mt(this.deps,n,0,C,C,X),c.progress(0,C,C,X)}k.objects.every(A=>A.done)&&(k.state="done"),j();let I=k.objects.map(A=>({objectApiName:A.objectApiName,recordCount:A.slices.reduce((B,C)=>B+C.rows,0),truncated:!A.done,...A.done?{}:{stoppedAt:"failure"},...A.where?{where:A.where}:{}})),N=I.reduce((A,B)=>A+B.recordCount,0),D=k.state!=="done";b?(this.deps.infraServices?.backgroundRegistry?.abort(n),Ve(this.deps,n,{aborted:!0,totalRecords:N}),c.cancel()):(Ve(this.deps,n,{objects:I.map(A=>({objectApiName:A.objectApiName,recordCount:A.recordCount})),totalRecords:N,...D?{status:"partial"}:{}}),D?c.partial():c.complete()),y&&this.deps.log(`[WARN] backup ${n}: ${y}`);let R=ke(this.deps,e,"dataops:backup:response",{operationId:n,status:D?"partial":"completed",objects:I,totalRecords:N,...D?{partial:!0}:{},timestamp:k.lastActivityAt,slices:en(k,{requestsSpent:u})});this.deps.broker.postToWebview(R),this.deps.log(`[TX] ${R.type} id=${R.id} slices=${$t(k).length}`),(y||b)&&hn(this.deps,"warning","Backup",`${b?"The backup in slices was cancelled":y}: set ${k.setId} holds ${N} record(s) in ${$t(k).length} slice(s), listed as partial.`)}catch(g){l=g,H(this.deps,"backup:execute","dataops:error",e,g),pe(this.deps,n,P(g),!0,{context:s}),c?.fail(P(g))}finally{this.activeOrgOperations.delete(o),d(l)}}restoreOfSet(e,t){let n=t===void 0?e.operationId:t.origin==="slice"?t.setId:void 0;if(n===void 0)return e.slices?{refused:{code:"NOT_A_SLICE_SET",message:`Backup ${e.operationId} holds no slices: restore it whole, without naming a slice.`}}:{};let s=this.sliceSets.get(n);if(!s||s.orgId!==e.orgId)return{};if(s.kind==="masking"&&s.state==="open"){let u=this.sliceWays(this.onCommandLine?void 0:"page");return{refused:{code:Re.runOpen,message:`Set ${s.setId} is still open: its masking run stopped part way, and resumed it would mask again over what a restore puts back. Give it up first (${u.abandon}), then restore it; or resume it to its end (${u.resume}). Nothing was written.`}}}let r=e.slices??(t?.slice?[t.slice.index]:void 0),o=s.objects.flatMap(u=>u.slices.filter(f=>f.state!=="pending").map(f=>({objectApiName:u.objectApiName,slice:f})));o.sort((u,f)=>u.slice.index-f.slice.index);let a=(r??[]).filter(u=>!o.some(f=>f.slice.index===u));if(a.length>0)return{refused:{code:"SLICE_NOT_FOUND",message:`Set ${s.setId} holds no slice ${a.join(", ")}: its slices are ${o.map(u=>u.slice.index).join(", ")||"none"}. Nothing was written.`}};let d=r?o.filter(u=>r.includes(u.slice.index)):o,c=u=>r!==void 0||e.rewriteAll===!0||u.slice.restoredAt===void 0,l=d.filter(c).map(u=>({snapshotId:u.slice.snapshotId,objectApiName:u.objectApiName,recordCount:u.slice.rows,slice:u.slice})),p=d.filter(u=>!c(u)).map(u=>({index:u.slice.index,objectApiName:u.objectApiName,restored:0,failed:0,unchanged:0,skipped:!0}));if(l.length===0&&p.length>0){let u=p.map(S=>o.find(k=>k.slice.index===S.index)?.slice.restoredAt??"").sort().at(-1),f=this.onCommandLine?"--rewrite-all":"Write every row back";return{refused:{code:"NOTHING_TO_RESTORE",message:`Every slice of set ${s.setId} was restored already (the last on ${u}): nothing was written. ${f} restores them again.`}}}let g=s.objects.map(u=>({objectApiName:u.objectApiName,recordCount:l.filter(f=>f.objectApiName===u.objectApiName).reduce((f,S)=>f+S.recordCount,0)})).filter(u=>l.some(f=>f.objectApiName===u.objectApiName));return{set:s,meta:{orgId:s.orgId,...s.organizationId!==void 0?{organizationId:s.organizationId}:{},timestamp:s.startedAt,totalRecords:g.reduce((u,f)=>u+f.recordCount,0),objects:g},parts:l,skipped:p}}async backupForPipeline(e,t){let n=e.fields?yi(e.fields):void 0,s=await this.takeBackup(e.operationId,{orgId:e.orgId,objects:e.objects,...n?{fields:n}:{},...e.scanAll?{scanAll:new Set(e.scanAll)}:{},...e.origin?{origin:e.origin}:{},...e.failWhenTruncated===!0?{failWhenTruncated:!0}:{},...e.onConnection?{onConnection:e.onConnection}:{}},e.origin==="checkpoint"?"checkpoint:take":"pipeline:execute",t);if("error"in s){let r=P(s.error);throw this.endBackupNotTaken(e.operationId,s),s.cancelled?new wn(r):s.error instanceof Error?s.error:new Error(r)}return s}endBackupNotTaken(e,t){if(t.cancelled){Ve(this.deps,e,{aborted:!0});return}pe(this.deps,e,P(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,s){let r={module:"dataops",operation:n},o=t.slice,a=`backup:${t.orgId}`;if(!o&&this.activeOrgOperations.has(a)){let y=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${y}`),{error:new Error(this.busyMessage(t.orgId,y)),retryable:!1,context:r}}o||this.activeOrgOperations.add(a);let d=()=>{},c,l=new AbortController,p=()=>l.abort();s?.aborted&&l.abort(),s?.addEventListener("abort",p,{once:!0});let g=this.backupCap(),u=this.backupWriter(e);this.backupsWriting.add(e);let f=[],S,k,E,j=(y,b,I,N)=>{o||(Mt(this.deps,e,y,b,I,N),E?.progress(y,b,I,N))};try{if(!o&&this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:r};o||this.dmlTracker.register(e,"backup","insert",t.objects.length);let y=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager);k=y,t.onConnection?.(y);let b=kr(async C=>(await y.query(C)).records),I=this.deps.orgManager.getOrg(t.orgId),N=In(I?.orgType==="Sandbox"||I?.orgType==="Scratch"),D=An(N).defaultQueryLimit,R=`Backup ${t.objects.length} object(s)`;o||(Yt(this.deps,e,"dataops",R),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",R,new Promise((C,ee)=>{d=G=>{G===void 0?C():ee(G instanceof Error?G:new Error(String(G)))}}),l),E=rn(this.liveTracker,e,"dataops",R,t.objects.length));for(let C of t.objects){if(l.signal.aborted)throw new Ot;let ee=xe(C);r.objectName=ee;let G=t.wheres?.get(ee),W={objectApiName:C,recordCount:0,truncated:!1,...G!==void 0?{where:G}:{}};S=W,await this.readIntoBackup(y,ee,W,u,{pageSize:D,cap:o?.size??g,select:t.fields?.get(ee),where:G,scanAll:t.scanAll?.has(ee)===!0,...t.origin==="checkpoint"?{stamp:ii}:{},whole:t.failWhenTruncated===!0||o!==void 0,viewsEncrypted:b,...o?{slice:{bounds:o.bounds,size:o.size,...o.skip?{skip:o.skip}:{}},onRequest:o.onRequest}:{}},l.signal,()=>{let X=Math.max(1,Math.min(W.orgCount??g,g));j(Math.round((f.length+W.recordCount/X)/t.objects.length*100),f.length,t.objects.length,`Reading ${C} (${W.recordCount} of ${X} records)`)}),S=void 0,f.push(W),W.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${ee} stopped at the cap of ${g} record(s): the object holds ${W.orgCount??"more"}.`),j(Math.round(f.length/t.objects.length*100),f.length,t.objects.length,`Exported ${C} (${W.recordCount} records)`)}let A=o?void 0:await this.organizationIdOf(y);if(l.signal.aborted)throw new Ot;let B=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:A,cap:o?.size??g,...t.origin?{origin:t.origin}:{},...o?{origin:"slice",setId:o.setId,slice:{index:o.index,...o.bounds.afterId!==void 0?{afterId:o.bounds.afterId}:{},...f[0]?.lastId!==void 0?{lastId:f[0].lastId}:{},size:o.size}}:{}},f,u,!1);return o?{operationId:e,objects:f,totalRecords:B.totalRecords,partial:!1,timestamp:B.timestamp}:(this.pruneAfterBackup(t.orgId),Ve(this.deps,e,{objects:f.map(C=>({objectApiName:C.objectApiName,recordCount:C.recordCount})),totalRecords:B.totalRecords,...B.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),B.partial?E?.partial():E?.complete(),{operationId:e,objects:f,totalRecords:B.totalRecords,partial:B.partial,timestamp:B.timestamp})}catch(y){o||this.dmlTracker.markFailed(e);let b=y instanceof Ot,I=b||y instanceof cn||t.failWhenTruncated===!0||o!==void 0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:g,...t.origin?{origin:t.origin}:{}},k,{taken:f,reading:S,planned:t.objects},u);I===void 0&&await u.discard().catch(R=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+P(R))});let N=I===void 0?y:new Error(`${P(y)} \u2014 the backup keeps the ${I.totalRecords} record(s) read before it stopped, listed as partial: ${Ns(I.objects)}.`);c=N,b&&!o&&this.deps.infraServices?.backgroundRegistry?.abort(e),b?E?.cancel():E?.fail(P(N));let D=!(y instanceof Wt)||y.retryable;return{error:N,retryable:D,context:r,cancelled:b}}finally{s?.removeEventListener("abort",p),d(c),o||this.activeOrgOperations.delete(a),this.backupsWriting.delete(e)}}backupCap(){return di(this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",ko))}snapshotCapWay(e,t){let n=this.backupCap(),s=e.filter(d=>d.tally.total>n),r=s.length>0?s.map(d=>d.tally.objectApiName).join(", "):"the object",o=s.reduce((d,c)=>Math.max(d,Rn(c.tally.total,n)),1),a=n<an&&s.every(d=>d.tally.total<=an);return t==="step"?`A pipeline's step masks no slices: mask ${r} from the DataOps panel, in slices each backed up just before it is masked, or with sandforge dataops anonymize --slices.`:t===void 0&&this.onCommandLine?`Give --slices to mask ${r} in ${o} slices, each with its own snapshot (the same line with --dry-run shows the plan)`+(a?`, --max-records up to ${an} (this run held ${n})`:"")+", or narrow the run with --where.":`Tick "Mask in slices" in the confirmation: ${r} is then masked in ${o} slices, each backed up just before it is masked`+(a?`; or raise sandforge.backup.maxRecordsPerObject in Settings (this run held ${n}, 1,000,000 at most)`:"")+"."}backupWriter(e){let t=this.backupRecords;if(t){let s=new Set;return{begin:async r=>{s.add(r),await t.begin(e,r).catch(o=>{throw new cn(o)})},append:async(r,o)=>{await t.append(e,r,o).catch(a=>{throw new cn(a)})},keep:()=>{},discard:async()=>{for(let r of s)await t.delete(e,r)}}}let n=new Map;return{begin:async s=>{n.set(s,[])},append:async(s,r)=>{n.get(s)?.push(...r)},keep:()=>{for(let[s,r]of n)this.deps.configStore.set(`backup:${e}:${s}`,r,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,s,r,o,a){let d=r.scanAll===!0,c=()=>r.onRequest?.(),l={headers:{"Sforce-Query-Options":`batchSize=${r.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=r.select;if(p===void 0){let y=await this.selectAllFields(e,t,r.viewsEncrypted);p=y.select,y.notKept.length>0&&(n.notKept=y.notKept)}let g=d?wi(r.where):r.where,u=r.slice,f=u?Yr(t,p,g,u.bounds,u.size):`SELECT ${p} FROM ${t}${xn(g,void 0)}`,S=r.stamp??Xs(f)?.stamp,k=Qs(f,S===void 0?void 0:["Id",S]),E=d||r.whole===!0?y=>(c(),Ai(e,y,d,t)):y=>(c(),Et(e,y)),j=await e.query(k?.first??f,l);if(c(),Ye(e.limitInfo,`dataops:backup query ${t}`),!u&&typeof j.totalSize=="number"&&Number.isInteger(j.totalSize)&&(n.orgCount=j.totalSize),!u&&r.whole===!0&&n.orgCount!==void 0&&n.orgCount>r.cap)throw uo(t,n.orgCount,r.cap);for(await s.begin(n.objectApiName);;){let y=r.cap-n.recordCount,b=j.records.length>y,I=b?j.records.slice(0,y):j.records,N=I;k&&S!==void 0?N=await Ys(I,k,E,{stamp:S,...d?{idsWhere:Cs}:{}}):k&&await Vs(I,k,E);let D=j.done?void 0:j.nextRecordsUrl;if(r.whole===!0&&!j.done&&D===void 0)throw new Wt(yo(t,n.recordCount+N.length),!0);let R=b||D!==void 0&&n.recordCount+N.length>=r.cap;if(u){let A=N.at(-1)?.Id;typeof A=="string"&&(n.lastId=A);let B=u.skip?N.filter(C=>!u.skip?.(C)):N;if(await s.append(n.objectApiName,B),n.recordCount+=B.length,n.readCount=(n.readCount??0)+N.length,R||D===void 0)return;if(a(),o.aborted)throw new Ot;j=await e.queryMore(D,l),c(),Ye(e.limitInfo,`dataops:backup query ${t}`);continue}if(R&&r.whole===!0)throw uo(t,n.orgCount,r.cap);if(await s.append(n.objectApiName,N),n.recordCount+=N.length,R){n.truncated=!0,n.stoppedAt="cap";return}if(D===void 0)return;if(a(),o.aborted)throw new Ot;j=await e.queryMore(D,l),c(),Ye(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,s){let r={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.setId!==void 0?{setId:e.setId}:{},...e.slice!==void 0?{slice:e.slice}:{},objects:t.map($s),partial:t.some(o=>o.truncated),...s?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((o,a)=>o+a.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,r,"backups"),n.keep(),r}async keepFailedBackup(e,t,n,s){let{taken:r,reading:o}=n,a=o?[...r,{...o,truncated:!0,stoppedAt:"failure"}]:[...r],d=new Set(a.map(p=>p.objectApiName.toLowerCase())),c=n.planned.filter(p=>!d.has(p.toLowerCase())).map(p=>({objectApiName:p,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),l=[...a,...c];if(!l.every(p=>p.recordCount===0))try{let p=t?await this.organizationIdOf(t):void 0,g=this.saveBackupMeta({...e,organizationId:p},l,s,!0);return this.pruneAfterBackup(e.orgId),{...g,objects:l}}catch(p){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+P(p));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=Sr(this.deps.services);if(t<=0)return;let n=e-t*li;try{let s=this.retentionSince(e);for(let r of this.backupMetaKeys()){let o=this.deps.configStore.get(r),a=Date.parse(o?.timestamp??"");if(!Number.isFinite(a)||a>=n||a<s||o?.origin==="checkpoint"||o?.origin==="slice"||o?.orgId!==void 0&&this.backupBusy(o.orgId))continue;await this.removeBackup(r);let d=o?.origin==="sync"?` \u2014 the values the Sync run ${o.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${r}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:r.slice(7),days:t,...o?.timestamp!==void 0?{takenAt:o.timestamp}:{},...o?.origin==="sync"?{syncRunId:o.runId??""}:{}})}for(let r of this.sliceSets.list()){let o=Date.parse(r.lastActivityAt);!Number.isFinite(o)||o>=n||o<s||this.backupBusy(r.orgId)||(await this.removeSliceSet(r),this.deps.log(`[INFO] Removed set of slices ${r.setId}: last moved more than ${t} day(s) ago`+(r.state==="open"?", its run left open and now over":"")),this.expiryListener?.({operationId:r.setId,days:t,takenAt:r.startedAt}))}}catch(s){this.deps.log(`[WARN] the backups past their age were not removed: ${P(s)}`)}}async removeSliceSet(e){for(let t of e.objects)for(let n of t.slices)await this.removeBackup(`backup:${n.snapshotId}`),await this.backupRecords?.delete(n.snapshotId,mo(t.objectApiName));this.sliceSets.delete(e.setId),e.kind==="masking"&&e.state==="open"&&e.templateId!==void 0&&new nt(this.deps.configStore).clear(e.orgId,e.templateId),await this.runKeys?.delete(e.setId).catch(t=>{this.deps.log(`[WARN] the key of set ${e.setId} was not removed: ${P(t)}`)})}retentionSince(e){let t=Date.parse(this.deps.configStore.get(eo)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(eo,new Date(e).toISOString()),e)}backupMetaKeys(){return this.deps.configStore.getKeysByPrefix("backup:").filter(e=>!e.slice(7).includes(":"))}backupBusy(e){return this.activeOrgOperations.has(`backup:${e}`)}async removeBackup(e){let n=this.deps.configStore.get(e)?.objects??[];for(let r of n)this.deps.configStore.delete(`${e}:${r.objectApiName}`);this.deps.configStore.delete(e);let s=e.slice(7);for(let r of n)await this.backupRecords?.delete(s,r.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(rr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){H(this.deps,"backup:delete","dataops:error",e,new Error(this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`)),{code:Is});return}let n=t.operationIds?new Set(t.operationIds):void 0;for(let o of n??[]){let a=this.deps.configStore.get(`backup:${o}`);if(!(a?.origin!=="slice"||a.orgId!==t.orgId)){H(this.deps,"backup:delete","dataops:error",e,new Error(`Backup ${o} is slice ${a.slice?.index??"?"} of set ${a.setId??"?"}: a slice is deleted with its set, which holds the way back of every slice. Delete set ${a.setId??"?"} to delete it. Nothing was deleted.`),{code:Re.deleteAlone});return}}let s=[];try{for(let o of this.backupMetaKeys()){let a=this.deps.configStore.get(o);if(a?.orgId!==t.orgId||a.origin==="slice")continue;let d=a.operationId??o.slice(7);n&&!n.has(d)||(await this.removeBackup(o),s.push(d))}for(let o of this.sliceSets.list(t.orgId))n&&!n.has(o.setId)||(await this.removeSliceSet(o),s.push(o.setId))}catch(o){H(this.deps,"backup:delete","dataops:error",e,o);return}this.deps.log(`[INFO] Deleted ${s.length} backup(s) of org ${t.orgId}`);let r=ke(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} deleted=${s.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${P(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(tr,e,"dataops:error",this.deps);if(!t)return;let n=[];for(let o of this.deps.configStore.getKeysByPrefix("backup:")){if(o.slice(7).includes(":"))continue;let a=this.deps.configStore.get(o);!a||a.orgId!==t.orgId||a.origin!=="slice"&&n.push({operationId:a.operationId??o.slice(7),orgId:a.orgId,timestamp:a.timestamp??"",totalRecords:a.totalRecords??0,totalSize:0,status:a.status==="failed"?"failed":"completed",objectResults:(a.objects??[]).map($s),...a.partial?{partial:!0}:{},...a.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,a)=>a.timestamp.localeCompare(o.timestamp));let s=this.sliceSets.list(t.orgId).map(Cr).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt)),r=ke(this.deps,e,"backup:list:result",{backups:n,...s.length>0?{sets:s}:{}});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${n.length}`)}async handleBackupExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(sr,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,s=this.deps.configStore.get(n);if(!s||s.orgId!==t.orgId){H(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let r=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,a=>this.writeBackupDocument(t,s,a),["json"]);if(r.status==="error"){H(this.deps,"backup:export","dataops:error",e,new Error(r.message));return}let o=ke(this.deps,e,"backup:export:result",r.status==="saved"?{operationId:t.operationId,status:"saved",path:r.path,objects:r.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} ${r.status}`)}async writeBackupDocument(e,t,n){let{operationId:s}=e,o=[["sandforgeBackupVersion",1],["operationId",s],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
8
+ `);await n(`{
9
+ ${o.join("")} "objects": {`);let a=[];for(let{objectApiName:d}of t.objects??[]){if(a.some(l=>l.objectApiName===d))continue;await n(`${a.length>0?",":""}
10
+ ${JSON.stringify(d)}: [`);let c=0;for await(let l of await this.backupBatches(s,d))l.length!==0&&(await n(l.map((p,g)=>`${c+g>0?",":""}
11
+ ${JSON.stringify(p)}`).join("")),c+=l.length);await n(c>0?`
12
+ ]`:"]"),a.push({objectApiName:d,records:c})}return await n(`${a.length>0?`
13
+ `:""}}
14
+ }
15
+ `),a}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,Dt);if(n)return n;let s=this.deps.configStore.get(`backup:${e}:${t}`),r=Array.isArray(s)?s:[];return{async*[Symbol.asyncIterator](){for(let o=0;o<r.length;o+=Dt)yield r.slice(o,o+Dt)}}}async firstBackupRecord(e,t,n){let s=await this.backupBatches(e,t),r=n.origin==="sync"?ms(s,Dt).batches:s;for await(let o of r)if(o[0]!==void 0)return o[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let s of this.deps.configStore.getKeysByPrefix("backup:")){if(s.slice(7).includes(":"))continue;let o=this.deps.configStore.get(s);o?.orgId===e&&o.origin!=="sync"&&o.origin!=="checkpoint"&&o.origin!=="slice"&&n.push({key:s,timestamp:o.timestamp??""})}if(!(n.length<=t)){n.sort((s,r)=>s.timestamp.localeCompare(r.timestamp));for(let{key:s}of n.slice(0,n.length-t))this.removeBackup(s),this.deps.log(`[INFO] Pruned backup ${s} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let s=[];for await(let o of n){let a=o.map(c=>c.Id).filter(c=>typeof c=="string");if(a.length===0)continue;let d=a.map(c=>`'${Gs(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});s.push(...c.records.map(l=>l.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${P(c)}`),{undeleted:0}}}let r=0;for(let o=0;o<s.length;o+=200){let a=await e.soap.undelete(s.slice(o,o+200));r+=a.filter(d=>d.success).length}return{undeleted:r}}refuseWithoutGuard(e,t,n,s){be(this.deps,{...s,outcome:"stopped",source:void 0,code:Vt.code}),e(new Error(Vt.message),{code:Vt.code}),pe(this.deps,t,Vt.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(or,e,"dataops:error",this.deps);if(!t)return;let n=t,s=e.id,r={module:"dataops",operation:e.type},o=`backup:${n.orgId}`;if(this.activeOrgOperations.has(o)){let k=this.busyMessage(n.orgId,`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`);this.deps.log(`[WARN] ${k}`),H(this.deps,"dataops:rollback","dataops:error",e,new Error(k)),pe(this.deps,s,k,!1,{context:r,authored:!0});return}this.activeOrgOperations.add(o);let a,d,c=[],l=!1,p=new AbortController,g=()=>{},u,f,S;try{if(this.dmlTracker.isDuplicate(s)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${s}`),H(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${s}`)),pe(this.deps,s,`Duplicate operation: ${s}`,!1,{context:r,authored:!0});return}this.dmlTracker.register(s,"rollback","upsert",0);let k=await ze(n.orgId,this.deps.orgRegistry,this.deps.orgManager),E=new Xn(async $=>{let z=await k.describe($);return bo(z)}),j=`backup:${n.operationId}`,y=this.deps.configStore.get(j),b=this.restoreOfSet(n,y);if("refused"in b){H(this.deps,"dataops:rollback","dataops:error",e,new Error(b.refused.message),{code:b.refused.code}),pe(this.deps,s,b.refused.message,!1,{context:r,authored:!0});return}d=b.set;let I=b.meta??y;if(!I)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);let N=b.parts??I.objects.map($=>({snapshotId:n.operationId,objectApiName:$.objectApiName,recordCount:$.recordCount}));if(I.orgId!==n.orgId){let $=Pt(this.deps.orgManager.getOrg(I.orgId),I.orgId),z=Pt(this.deps.orgManager.getOrg(n.orgId),n.orgId);throw new Error(`Backup ${n.operationId} was taken from org ${I.orgId} and cannot be restored into org ${n.orgId}. A restore writes back by record Id, and an Id belongs to the org that holds it: to bring these records from ${$} into ${z}, copy them with Forge or Sync.`)}a={action:"backup_restore",module:"dataops",operationId:s,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:I.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let D=this.deps.infraServices?.productionGuard;if(!D){this.refuseWithoutGuard(($,z)=>H(this.deps,"dataops:rollback","dataops:error",e,$,z),s,r,a);return}let R=[],A=new Set;for(let $ of N){if(A.has($.objectApiName.toLowerCase()))continue;let z=await this.firstBackupRecord($.snapshotId,$.objectApiName,I);if(z===void 0)continue;A.add($.objectApiName.toLowerCase());let M=xe($.objectApiName);if(!(await E.checkCrudPermission(M,"upsert")).allowed){R.push({objectApiName:M,operation:"upsert",deniedFields:[]});continue}let{denied:Ke}=await E.partitionWritableFields(M,"upsert",Object.keys(z).filter(Oe=>Oe!=="attributes"));Ke.length>0&&R.push({objectApiName:M,operation:"upsert",deniedFields:Ke})}if(R.length>0){let $=bn(R);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${s}: ${$}`),be(this.deps,{...a,outcome:"stopped",source:void 0,code:xt}),H(this.deps,"dataops:rollback","dataops:error",e,new Error($),{code:xt}),pe(this.deps,s,$,!1,{context:r,authored:!0});return}let B=($,z,M,de=[])=>{be(this.deps,{...M,outcome:"stopped",source:void 0,code:$}),H(this.deps,"dataops:rollback","dataops:error",e,new Error(z),{code:$,...os({alsoRefused:de})}),pe(this.deps,s,z,!1,{context:r,authored:!0})},C=await this.readAct(k,n.orgId,"restore",I.objects.map($=>({objectApiName:$.objectApiName,records:$.recordCount})),n,Jt(n)),ee=yn(C.answer);if(ee){B(ee.code,ee.message,a,ee.alsoRefused);return}S=this.duplicatesWatchOf(k,ts(C.answer.automation,I.objects.filter($=>$.recordCount>0).map($=>$.objectApiName)));let G=this.deps.orgManager.getOrg(n.orgId),W={orgId:n.orgId,orgTier:Rs(G),operation:"upsert",objectName:I.objects.map($=>$.objectApiName).join(", ")||"RollbackData",recordCount:I.totalRecords??0,module:"dataops"},{check:X,decision:ve}=await Zn(D,W);if(a.guard=ve,(ve==="refused"||ve==="declined")&&be(this.deps,{...a,outcome:"stopped",source:void 0}),ve==="refused")throw qn(X.blockedReason??X.impactSummary);if(ve==="declined"){let $="Operation cancelled by user (confirmation declined).";H(this.deps,"dataops:rollback","dataops:error",e,new Error($),{code:Kn.declined}),pe(this.deps,s,$,!1,{context:r,authored:!0});return}if(I.organizationId!==void 0){let $=await this.organizationIdOf(k);if($!==void 0&&!ri(I.organizationId,$)){let z=Pt(G,n.orgId),M=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(M?await M({alias:z,backedUpFrom:I.organizationId,now:$}):!1)){be(this.deps,{...a,outcome:"stopped",source:void 0,code:Jr});let Ke=`Restore not run: ${z} answers as org ${$}, not as org ${I.organizationId}, which backup ${n.operationId} was taken from, `+(M?"and the restore into the org it is now was not confirmed.":"and nothing here can ask whether to restore into the org it is now.");H(this.deps,"dataops:rollback","dataops:error",e,new Error(Ke),{code:Jr}),pe(this.deps,s,Ke,!1,{context:r,authored:!0});return}}}let kt=await rs(C,s,n.acceptEmails===!0,Jt(n));if("refused"in kt){B(kt.refused.code,kt.refused.message,a);return}f=kt.held,Yt(this.deps,s,"dataops",`Rollback ${I.objects.length} object(s)`);let Ge=b.skipped??[];l=!0,this.deps.infraServices?.backgroundRegistry?.register(s,"dataops",`Rollback ${I.objects.length} object(s)`,new Promise(($,z)=>{g=M=>{M===void 0?$():z(M instanceof Error?M:new Error(String(M)))}}),p),u=rn(this.liveTracker,s,"dataops",`Rollback ${I.objects.length} object(s)`,I.objects.length);let we=!1,Ce=0,$e=0,Je=0,ot=[],wt=new Map,Ut=I.origin==="sync"&&n.includeChanged!==!0,Be=Number.NEGATIVE_INFINITY,F=!1;if(Ut){let $=I.runId!==void 0?await this.syncRuns?.get(I.runId).catch(M=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${P(M)}`)}):void 0,z=$?hr($):void 0;F=z===void 0,Be=await gr({serverTime:async()=>(await k.soap.getServerTimestamp()).timestamp},z)}let Q=[];for(let $=0;$<N.length;$++){if(p.signal.aborted){we=!0;break}let z=N[$],M=xe(z.objectApiName);r.objectName=M;let de=await this.backupBatches(z.snapshotId,z.objectApiName),Ke=I.origin==="sync"?ms(de,Dt):void 0,Oe=Ke?.batches??de,De;for await(let ce of Oe)if(De=ce[0],De!==void 0)break;if(Ut&&De!==void 0){let ce=[];for await(let Fe of Oe)for(let Pe of Fe)typeof Pe.Id=="string"&&ce.push(Pe.Id);let tt=await Kr({query:async(Fe,Pe)=>({records:(await k.query(Fe,Pe)).records})},M,ce,Be);tt.size>0&&(Q.push({objectApiName:M,count:tt.size}),Oe=qr(Oe,tt))}if(De===void 0){wt.set(z.objectApiName,wt.get(z.objectApiName)??0),this.deps.log(`[WARN] No backup records for ${z.objectApiName}, skipping.`);continue}let pn=Object.keys(De).filter(ce=>ce!=="attributes"),{skipped:it}=await E.partitionWritableFields(M,"upsert",pn),at=new Set(it.filter(ce=>ce.toLowerCase()!=="id").map(ce=>ce.toLowerCase()));at.size>0&&this.deps.log(`[INFO] Rollback on ${M}: ${at.size} non-writable field(s) excluded from the payload \u2014 ${[...at].sort().join(", ")}`);let yt=await this.undeleteFromRecycleBin(k,M,Oe);yt.undeleted>0&&this.deps.log(`[INFO] Rollback on ${M}: ${yt.undeleted} record(s) brought back from the recycle bin`),r.batchSize=Dt;let dt=0,ct=0,Te=0,At=0;for await(let ce of Oe){if(p.signal.aborted){we=!0;break}At+=ce.length;let tt=ce.map(le=>{let qe=M===se?mn(le,!1):void 0,Z={};for(let[He,ut]of Object.entries(le))He!=="attributes"&&(at.has(He.toLowerCase())||qe!==void 0&&fn(se,He,qe)||(Z[He]=ut));return Z}),Fe=tt;if(n.rewriteAll!==!0){let le=await Ur({query:async qe=>{let Z=await k.query(qe);return{totalSize:Z.totalSize,records:Z.records}}},M,tt);le.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${M}: the org's values could not be read, so ${tt.length} row(s) are written back without comparing \u2014 ${le.unread}`),Fe=le.write,Te+=le.unchanged}if(Fe.length===0)continue;S.beforeWrite(M);let Pe;try{Pe=await k.sobject(M).upsert(Fe,"Id",{headers:Wn()})}catch(le){throw Jn(le)==="may-have-written"&&S.wrote(M,Fe.map(qe=>qe.Id)),le}let qt=Array.isArray(Pe)?Pe:[Pe];S.wrote(M,qt.flatMap((le,qe)=>le.success?[Fe[qe]?.Id]:[]));for(let le of qt){if(le.success){dt++;continue}ct++,to(ot,M,le.errors)}}Ye(k.limitInfo,`dataops:rollback upsert ${M}`),wt.set(z.objectApiName,(wt.get(z.objectApiName)??0)+(Ke&&!we?Ke.lines():At)),Ce+=dt,$e+=ct,Je+=Te;let Kt=c.find(ce=>ce.objectApiName===M);if(Kt?(Kt.updated+=dt,Kt.failed+=ct):c.push({...gn(M),updated:dt,failed:ct}),z.slice&&(Ge.push({index:z.slice.index,objectApiName:M,restored:dt,failed:ct,unchanged:Te}),!we&&d&&(z.slice.restoredAt=new Date().toISOString(),z.slice.state="restored",d.lastActivityAt=z.slice.restoredAt,this.sliceSets.save(d))),we)break;let jt=`Restored ${M}${z.slice?` slice ${z.slice.index}`:""} (${dt}/${At}${Te>0?`, ${Te} unchanged`:""})`,lt=Math.round(($+1)/N.length*100);Mt(this.deps,s,lt,$+1,N.length,jt),u.progress(lt,$+1,N.length,jt)}let re=Q.reduce(($,z)=>$+z.count,0),U=ui(Ce,$e),te=we&&$e===0||re>0&&U==="success"?"partial":U;a&&(l=!1,be(this.deps,{...a,...we?Ce+$e>0?{outcome:"cancelled"}:{outcome:"stopped",code:Gn}:{outcome:te},objects:c}));let Tt=await this.releaseMute(f,n.orgId);f=void 0;let Xe=await S.read();we?(this.deps.infraServices?.backgroundRegistry?.abort(s),Ve(this.deps,s,{aborted:!0,totalRestored:Ce,totalFailed:$e,totalUnchanged:Je})):Ve(this.deps,s,{status:te,totalRestored:Ce,totalFailed:$e,totalUnchanged:Je}),this.dmlTracker.markCompleted(s),we?u.cancel():te==="failure"?u.fail(`The org refused the ${$e} record(s)`):te==="partial"?u.partial():u.complete();let Le=Ns(I.objects,wt),et=(we?`Rollback cancelled: ${Ce} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:$e>0?`Rollback ${te}: ${Ce} restored, ${$e} rejected by the org`:re>0?`Rollback partial: ${Ce} records restored`:`Rollback completed: ${Ce} records restored`)+(Je>0?`; ${Je} already held the backup's values and were not written`:"")+(re>0?`; ${re} changed or deleted since the Sync run were left as they are `+(F?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),me=Zt(Xe,this.orgNameOf(n.orgId),"restore"),Ne=Le===""?et:`${et}. The backup held only part of the org's records, and the rest were left as they are: ${Le}`,Qe=me?`${Ne}. ${me}`:Le===""?Ne:`${Ne}.`,ae=ke(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:te,message:Qe,totalRestored:Ce,totalFailed:$e,totalUnchanged:Je,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...re>0?{keptChanged:{total:re,objects:Q,...F?{runNotKept:!0}:{}}}:{},errors:ot,...Le!==""?{partial:!0}:{},...we?{cancelled:!0}:{},...Tt?{mutedAutomation:Tt}:{},...Xe?{duplicates:Xe}:{},...d?{slices:Ge}:{}});this.deps.broker.postToWebview(ae),this.deps.log(`[TX] ${ae.type} id=${ae.id} status=${te}`),($e>0||Le!==""||we||re>0||ss(Xe))&&hn(this.deps,te==="failure"?"error":"warning","Restore",`${Qe}${ot[0]?` \u2014 e.g. ${ot[0].message}`:""}`)}catch(k){this.dmlTracker.markFailed(s),await this.releaseMute(f,n.orgId),f=void 0;let E=await S?.read(),j=Zt(E,this.orgNameOf(n.orgId),"restore");H(this.deps,"dataops:rollback","dataops:error",e,j?new Error(`${P(k)} ${j}`):k,{code:Hn(k),...E?{extraPayload:{duplicates:E}}:{}}),pe(this.deps,s,P(k),!0,{context:r}),u?.fail(P(k))}finally{await this.releaseMute(f,n.orgId),this.activeOrgOperations.delete(o),g(),l&&a&&be(this.deps,{...a,outcome:"failure",objects:c})}}async snapshotBeforeMasking(e,t,n,s,r){let o=new Map,a=new Map;try{for(let l of s){if(l.tally.total===0)continue;l.where!==void 0&&a.set(l.tally.objectApiName,l.where);let{select:p}=await this.maskedFields(e,l.tally.objectApiName,this.maskingRules(l.objectName,l.objectRules),this.maskingRules(l.objectName,l.personRules));p!=="Id"&&o.set(l.tally.objectApiName,p)}}catch(l){return{refused:`No snapshot was taken, so nothing was masked: ${P(l)}`,retryable:!0}}if(o.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...o.keys()],...a.size>0?{wheres:a}:{},fields:o},r.origin,r.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${P(c.error)}`,retryable:c.retryable&&c.cancelled!==!0}):c.partial?{refused:`Snapshot ${d} holds only part of the records the run would mask, so nothing was masked: a restore could not put back the rest (${Ns(c.objects)}). `+this.snapshotCapWay(s),retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,s){if(s.length===0)return{code:Ue.masksNothing,message:`The template "${t.name}" has no rule for ${n.join(", ")}: the run would mask nothing. Choose an object its rules name, or another template. Nothing was masked.`,gaps:{fieldsNotFound:[],objectsNotCovered:[...n]}};let r=[],o=[];for(let d of s){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:l,missing:p}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));r.push(...p.map(g=>({objectApiName:c,fieldApiName:g}))),l.length===0&&o.push(c)}let a={fieldsNotFound:r,objectsNotCovered:o};if(r.length>0){let d=r.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:Ue.fieldsUnseen,message:`The template "${t.name}" masks ${d}, which the org does not show the user SandForge connects as: it has no such field, or field-level security hides it. `+(o.length>0?`No field of ${o.join(", ")} can be masked. `:"")+"A run masks every field its template names, or nothing: give that user read and edit access to the field, or take the field out of the template. Nothing was masked.",gaps:a}}if(o.length>0)return{code:Ue.masksNothing,message:`The template "${t.name}" masks no field of ${o.join(", ")} in this org: the run would write nothing over its records. Choose an object its rules name, or another template. Nothing was masked.`,gaps:a}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw st(Ue.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let s=Qr(Rs(n),e.answer,Pt(n,e.orgId));if(s)throw s;let r=ks(e,f=>this.findTemplate(f)!==void 0);if("refusal"in r)throw r.refusal;let o=crypto.randomUUID(),a,d,c,l={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,S)=>{a??={err:f,...S},this.deps.log(`[ERR] dataops:anonymize ${o} for the pipeline "${e.pipeline.name}": `+P(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>Ir(e.answer,()=>this.mask(r.asked,o,l,t)));let p=a,g=c;if(p){let f=P(p.err),S=p.err,k=p.code??(typeof S?.code=="string"?S.code:void 0),E=p.extraPayload?.snapshot,j={...k!==void 0?{code:k}:{},...E!==void 0?{snapshot:E}:{},...g?{mutedAutomation:g}:{}};throw Object.assign(k===Qt?new wn(f):new Error(f),j)}let u=d;if(u===void 0)throw new Error("The masking run ended without a result.");return{operationId:o,result:g?{...u,mutedAutomation:g}:u}}async previewMaskingForPipeline(e,t){let n=(b,I)=>st(b,I),s=()=>new wn("The dry run of the masking was stopped: nothing was masked.");if(!this.deps.orgManager.getOrg(e.orgId))throw n(Ue.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=ks(e,b=>this.findTemplate(b)!==void 0);if("refusal"in r)throw r.refusal;let o=r.asked,a=this.findTemplate(o.templateId);if(!a)throw Ts(o.templateId);let d=this.sliceSets.openFor(o.orgId,o.templateId);if(d)throw n(Re.runOpen,this.sliceRunOpenMessage(d,"step"));let c=await ze(o.orgId,this.deps.orgRegistry,this.deps.orgManager),l=Cn(c),p=await this.plannedObjectsIn(l,o,a),g=[];for(let b of p){if(t?.aborted)throw s();let I=Ft(a,b),N=dn(a,b);if(I.length===0&&N.length===0)continue;let D=xe(b),R=jn(o,a,b),A;try{A=await this.countRows(c,D,void 0,R)}catch(B){throw this.countGaveUp(B,D)}g.push({objectName:b,...R!==void 0?{where:R}:{},objectRules:I,personRules:N,tally:{objectApiName:D,total:A,masked:0,nothingToMask:0,refused:0,unanswered:0,done:A===0},progress:{objectApiName:D,done:A===0,refused:[]}})}let u=await this.maskingNotCovered(l,a,p,g);if(u)throw n(u.code,u.message);let f=g.filter(b=>b.tally.total>0),S=await vs(l,f.map(b=>({objectApiName:b.tally.objectApiName,rules:[...b.objectRules,...b.personRules]})));if(S.length>0)throw n(xt,bn(S));let k=this.backupCap();if(g.some(b=>b.tally.total>k))throw n(on,`Nothing was masked: ${g.filter(b=>b.tally.total>k).map(b=>`${b.tally.objectApiName} holds ${b.tally.total} record(s)`).join(", ")}, more than the ${k} a snapshot holds of one object. `+this.snapshotCapWay(g,"step"));if(t?.aborted)throw s();let E=await this.readAct(c,o.orgId,"masking",g.map(b=>({objectApiName:b.tally.objectApiName,records:b.tally.total})),e.accord??{},"step"),j=yn(E.answer);if(j)throw n(j.code,j.message);let y=[];for(let b of g){let{rules:I}=await this.maskedFields(l,b.tally.objectApiName,this.maskingRules(b.objectName,b.objectRules),this.maskingRules(b.objectName,b.personRules));y.push({objectApiName:b.tally.objectApiName,records:b.tally.total,fields:[...new Set(I.map(N=>N.fieldApiName))].filter(N=>N!=="Id")})}return{objects:y,records:y.reduce((b,I)=>b+I.records,0)}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(kn,e,"dataops:error",this.deps);if(!t)return;let n=Jt(t);await this.mask(t,e.id,{...this.pageMaskingReplies(e),accord:{acceptAutomation:t.acceptAutomation===!0,acceptEmails:t.acceptEmails===!0,muteAutomation:t.muteAutomation===!0},...n?{voice:n}:{}})}pageMaskingReplies(e){return{origin:e.type,refused:(t,n)=>H(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=ke(this.deps,e,"dataops:anonymize:response",t);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} status=${t.status}`),(t.recordsNotMasked>0||ss(t.duplicates))&&hn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}pageSizeFor(e){let t=this.deps.orgManager.getOrg(e);return An(In(t?.orgType==="Sandbox"||t?.orgType==="Scratch")).defaultQueryLimit}sliceWays(e){return e==="page"?{resume:"Resume",abandon:"Abandon",restore:()=>"Restore lists the set and puts its values back"}:e===void 0&&this.onCommandLine?{resume:"the same line with --resume",abandon:"--abandon",restore:t=>`the same command with --restore ${t} puts its values back`}:{resume:"Resume on the DataOps panel, or sandforge dataops anonymize --resume",abandon:"Abandon on the DataOps panel, or sandforge dataops anonymize --abandon",restore:()=>"the Restore tab of the DataOps panel lists the set and puts its values back"}}async approximateCount(e,t,n){if(js.has(Pn(n)))try{let s=await e.request(`/services/data/v${e.version}/limits/recordCount?sObjects=${t}`),{recordCountsOf:r}=await import("./chunk-DIS254AN.mjs"),o=r(s)?.get(t);return o!==void 0&&this.deps.log(`[INFO] dataops:anonymize: the org gave up counting ${t}; its own figure, ${o}, plans the slices, approximate.`),o}catch(s){this.deps.log(`[WARN] dataops:anonymize: the org's figure of ${t} was not read: `+P(s));return}}async apiBudgetFor(e,t){let{apiBudgetCheckOf:n,readApiBudget:s}=await import("./chunk-CCEH7L53.mjs"),r=await s(e).catch(a=>({unread:P(a)})),o=n(t,r);return o.verdict==="unread"?{verdict:"unread",unread:o.unread}:{verdict:o.verdict,remaining:o.remaining,max:o.max}}async sliceRunPlan(e,t,n,s){let r=[];for(let o of t){if(o.tally.total===0)continue;let{select:a}=await this.maskedFields(e,o.tally.objectApiName,this.maskingRules(o.objectName,o.objectRules),this.maskingRules(o.objectName,o.personRules));r.push({objectApiName:o.tally.objectApiName,rows:o.tally.total,fields:a.split(",").length})}return ls(r,n,s,"masking")}tooManySlicesMessage(e,t){let n=e.objects.filter(r=>e.tooMany.includes(r.objectApiName)).map(r=>`${r.objectApiName} (${r.slices} slices)`).join(", "),s=this.onCommandLine?`Give --max-records up to ${an}, so that a slice holds more, or narrow the run with --where.`:"Raise sandforge.backup.maxRecordsPerObject in Settings, up to 1,000,000, so that a slice holds more.";return`Nothing was masked: ${n} would take more than the ${ht} slices a set holds, at ${t} records a slice. ${s}`}diskShortMessage(e,t,n=!1){let s=this.backupRecords?.directory??"the backups folder",r=this.onCommandLine?"give --store a folder on another disk, delete the backups no longer needed (sandforge backup --list, then delete them), or keep backups fewer days (--max-age-days)":"delete the backups no longer needed in the Restore tab, or keep backups fewer days (sandforge.backup.maxAgeDays)";return`${n?"Nothing was masked":"The run stopped between two slices"}: the slices' snapshots take about ${us(e)}, and ${s} has ${us(t)} free. To make room, ${r}.`}sliceBudgetStop(e,t,n,s,r){if(t!==void 0&&n+s>t)return`Stopped between slices: the run sent ${n} request(s), and the next slice takes about ${s} more, past the ${t} of ${r==="page"?"the requests it was given":"--max-requests"}.`;let o=Ye(e.limitInfo,"dataops:anonymize slices");if(o&&o.apiLimit>0&&(o.apiUsage+s)/o.apiLimit*100>=Os)return`Stopped between slices: the org used ${o.apiUsage} of its ${o.apiLimit} daily API requests, and the next slice takes about ${s} more, past the ${Os}% the run leaves the org's integrations below.`}sliceNotTakenMessage(e,t){if(t.code===Re.readTooHeavy){let n=this.onCommandLine?"narrow --where to an indexed field, such as a range of CreatedDate, or give a lower --max-records":"mask it from the command line with --where on an indexed field, such as a range of CreatedDate, or lower sandforge.backup.maxRecordsPerObject";return`The org would not read a slice of ${e} in time, even halved ${fo} times (${P(t.failed)}): the run stopped there, and nothing of that slice was masked. To go on, ${n}.`}return`The snapshot of the next slice of ${e} was not taken (${P(t.failed)}): the run stopped there, and nothing of that slice was masked.`}sliceRunOpenMessage(e,t){let n=$t(e),s=this.sliceWays(t);return`A masking run of this template in slices is still open on ${this.orgNameOf(e.orgId)} (set ${e.setId}, ${n.filter(Bt).length} of ${n.length} slice(s) masked, last moved ${e.lastActivityAt}): a new run would mask its rows again and write over where it stopped. Resume it (${s.resume}), or give it up (${s.abandon}), which masks nothing more and keeps its slices to restore. Nothing was masked.`}sliceKeyLostMessage(e,t){let n=this.sliceWays(t);return`The key set ${e.setId} was masked with is not kept where this run reads it: masked with another, the same address would get another digest and the same record another person. Give the set up (${n.abandon}); ${n.restore(e.setId)} if its values are wanted back, and a new run masks again. Nothing was masked.`}slicesSentence(e,t,n,s,r=[]){let o=this.sliceWays(n),a=$t(e),d=ds(e);return[...t?[t.message]:[],`Set ${e.setId}: ${a.filter(Bt).length} of ${a.length} slice(s) of up to ${e.size} records masked, each backed up just before it was masked; ${o.restore(e.setId)}.`,...d>0?[`${d} record(s) were created during the run in a range a slice had masked, or past its last slice: no snapshot holds them, and they were not masked.`]:[],...r.length>0?[`Whether records were created during the run in a range a slice had masked could not be read for ${r.join(", ")}: any such record was not masked.`]:[],...e.state==="open"&&s?[`${o.resume[0].toUpperCase()}${o.resume.slice(1)} masks the rest, each slice backed up first.`]:[]].join(" ")}async snapshotSlice(e,t,n,s,r,o){let a;try{o.clock!==!1&&(a=new Date((await e.soap.getServerTimestamp()).timestamp).toISOString(),o.onRequest())}catch(c){this.deps.log(`[WARN] dataops: the org's clock before slice ${r.index} was not read: `+P(c))}let d=r.sizeUsed;for(let c=0;;c++){let l=await this.takeBackup(r.snapshotId,{orgId:t,objects:[s.objectApiName],...s.where!==void 0?{wheres:new Map([[s.objectApiName,s.where]])}:{},...o.select!==void 0?{fields:new Map([[s.objectApiName,o.select]])}:{},slice:{setId:n.setId,index:r.index,bounds:o.bounds,size:d,...o.skip?{skip:o.skip}:{},onRequest:o.onRequest}},o.origin,o.stop);if(!("error"in l)){let g=l.objects[0];return{rows:g?.recordCount??0,read:g?.readCount??g?.recordCount??0,...g?.lastId!==void 0?{lastId:g.lastId}:{},sizeUsed:d,...a!==void 0?{readSince:a}:{}}}if(l.cancelled)return{failed:l.error,code:Qt,cancelled:!0};if(!js.has(Pn(l.error)))return{failed:l.error,code:on};if(c>=fo||d<=po)return{failed:l.error,code:Re.readTooHeavy};d=Math.max(po,Math.floor(d/2)),this.deps.log(`[INFO] dataops: the org would not read slice ${r.index} of ${s.objectApiName} in time; read again in ${d} records.`)}}async countLateRows(e,t,n){let s=[],r=async o=>{let a=await e.query(o);return n(),typeof a.totalSize=="number"?a.totalSize:0};for(let o of t.objects)try{let a=o.slices.filter(g=>!g.late&&g.lastId!==void 0),d=a.at(-1)?.lastId,c=await r(d!==void 0?Zr(o.objectApiName,o.where,d):`SELECT COUNT() FROM ${o.objectApiName}${xn(o.where,void 0)}`);c>0?(o.tailLeft=c,o.done=!1):delete o.tailLeft;let l=t.serverStartedAt;if(d===void 0||l===void 0||await r(As(o.objectApiName,o.where,l,{untilId:d}))===0)continue;for(let g of a){if(g.lastId===void 0)continue;let u=await r(As(o.objectApiName,o.where,g.readSince??l,{...g.afterId!==void 0?{afterId:g.afterId}:{},untilId:g.lastId}));u>0?g.lateLeft=u:delete g.lateLeft}}catch(a){this.deps.log(`[WARN] dataops: the ${o.objectApiName} records created during set ${t.setId} were not counted: ${P(a)}`),s.push(`${o.objectApiName} (${P(a)})`)}return s}async abandonSliceSet(e,t,n){if(!e){n.refused(new Error(`No masking run of this template in slices is open on ${this.orgNameOf(t.orgId)}: there is nothing to give up.`),{code:Re.nothingToAbandon});return}if(this.sliceRunsOn.get(t.orgId)===e.setId){n.refused(new Error(this.busyMessage(t.orgId,"")),{code:Is});return}e.state="abandoned",e.lastActivityAt=new Date().toISOString(),this.sliceSets.save(e),new nt(this.deps.configStore).clear(t.orgId,t.templateId),await this.runKeys?.delete(e.setId).catch(a=>{this.deps.log(`[WARN] dataops: the key of set ${e.setId} was not removed: ${P(a)}`)});let r=$t(e).filter(Bt).length,o=this.sliceWays(n.voice);this.deps.log(`[INFO] dataops: set ${e.setId} given up, ${r} slice(s) masked`),n.ended({templateId:t.templateId,status:"success",recordsProcessed:0,recordsFailed:0,recordsNotMasked:0,objects:[],message:`Set ${e.setId} given up: nothing more is masked. Its ${r} masked slice(s) stay masked, each with its snapshot; ${o.restore(e.setId)} until the retention removes them. The records no slice reached keep their values.`,errors:[],abandoned:!0,slices:en(e,{requestsSpent:0})})}async mask(e,t,n,s){let r,o={},a,d=async()=>(a??={released:await this.releaseMute(r,e.orgId)},a.released),c={...n,refused:(F,Q)=>{if(!r){n.refused(F,Q);return}o.answer??=re=>n.refused(F,re?{...Q,extraPayload:{...Q.extraPayload,mutedAutomation:re}}:Q)},ended:F=>{if(!r){n.ended(F);return}o.answer??=Q=>n.ended(Q?{...F,mutedAutomation:Q}:F)}},l={module:"dataops",operation:c.origin},p=this.findTemplate(e.templateId),g=Tn(e,p),u={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],S=[],k=zn(e),E=p?sn(p.rules,g,k):"",j=!1,y=!1,b=!1,I=!1,N,D,R,A=0,B=0,C,ee,G=!1,W=[],X=new AbortController,ve=()=>{},kt,Ge,we,Ce=async()=>ns(ee,await we?.read()),$e=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);$e?.signal.addEventListener("abort",()=>X.abort(),{once:!0});let Je=()=>X.abort();s?.aborted&&X.abort(),s?.addEventListener("abort",Je,{once:!0});let ot=async()=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:Qt});let F="The masking run was cancelled before it wrote anything.";c.refused(new Error(F),{code:Qt,...D?{extraPayload:{snapshot:D}}:{}}),await d(),Ve(this.deps,t,{aborted:!0})},wt=(F,Q,re)=>{kt=F;let U=P(F),te=_t(f),Tt=j&&te.recordsNotMasked>0,Xe=Zt(re,this.orgNameOf(e.orgId)),Le={...j?{...te,objects:ao(f)}:{},...D?{snapshot:D}:{},...re?{duplicates:re}:{},...R?{slices:en(R,{requestsSpent:A})}:{}},et=Tt?`${U} \u2014 ${te.recordsProcessed} masked before it stopped; ${te.recordsNotMasked} still hold their original values (${io(f)}).`:U;c.refused(Tt||Xe?new Error(Xe?`${et} ${Xe}`:et):F,{code:Hn(F),extraPayload:Le}),pe(this.deps,t,U,Q,{context:l,extraPayload:Le}),Ge?.fail(U)},Ut=()=>{I=!0;let F=new nt(this.deps.configStore),{recordsNotMasked:Q}=_t(f),re=f.reduce((U,te)=>U+te.masked+te.nothingToMask+te.refused+te.unanswered,0);try{if(Q===0&&R?.state!=="open"||R!==void 0&&R.state!=="open")return F.clear(e.orgId,e.templateId),!1;if(re===0&&R===void 0)return F.load(e.orgId,e.templateId,E)!==void 0;let U=S.map(te=>te.progress);return nn(U)>Nt?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${nn(U)} record(s), more than a resume retries (${Nt}): only a full run masks them.`),F.clear(e.orgId,e.templateId),!1):(F.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:E,savedAt:new Date().toISOString(),objects:U,...N?{namesGiven:N.namesGiven()}:{},...R?{setId:R.setId}:{}}),!0)}catch(U){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+P(U)),!1}},Be=()=>{if(R){R.lastActivityAt=new Date().toISOString(),R.requestsSpent=B+A,this.sliceSets.save(R);try{new nt(this.deps.configStore).save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:E,savedAt:new Date().toISOString(),objects:S.map(F=>F.progress),...N?{namesGiven:N.namesGiven()}:{},setId:R.setId})}catch(F){this.deps.log(`[WARN] dataops:anonymize ${t}: where the run is in set ${R.setId} was not kept: ${P(F)}`)}}};try{let F=this.deps.infraServices?.productionGuard;if(!F){this.refuseWithoutGuard((m,v)=>c.refused(m,v),t,l,u);return}if(!p){c.refused(Ts(e.templateId),{code:so});return}let Q=ln(e,p,se)?Tn(e,p,!0):void 0,re=this.sliceSets,U=re.openFor(e.orgId,e.templateId);if(e.abandon===!0){await this.abandonSliceSet(U,e,c);return}let te=(m,v)=>sn(p.rules,m,k,v),Xe=(Q?[g,Q]:[g]).flatMap(m=>[te(m),...U?[te(m,U.size)]:[]]),Le=m=>c.refused(new Error(m??"There is nothing to resume: the run has finished since, another run of this template has stopped since, its rules have changed, or the slices it masked expired. Apply masks every record of its objects."),{code:fi}),et=(m,v)=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(v),{code:m}),pe(this.deps,t,v,!1,{context:l,authored:!0})},me;if(e.resumeFrom!==void 0){let m=new nt(this.deps.configStore);if(me=Xe.map(v=>m.load(e.orgId,e.templateId,v)).find(v=>v?.id===e.resumeFrom),!me){Le();return}if(me.setId!==void 0&&me.setId!==U?.setId||me.setId===void 0&&e.slices===!0){Le(me.setId===void 0?"The run this one resumes was not in slices: it resumes as it ran, without slices, or Apply masks every record of its objects in slices. Nothing was masked.":void 0);return}}if(U&&me?.setId!==U.setId){et(Re.runOpen,this.sliceRunOpenMessage(U,c.voice));return}let Ne=me?.setId!==void 0?U?.size:e.slices===!0?this.backupCap():void 0;if(E=te(g,Ne),Ne!==void 0&&!this.backupRecords){et(Re.needsStore,"A run in slices writes each slice to the backup files, and this host keeps none. Nothing was masked.");return}let Qe=this.maskingKey;if(me?.setId!==void 0&&U){if(Qe=await this.runKeys?.load(U.setId).catch(v=>{this.deps.log(`[WARN] dataops:anonymize: the key of set ${U.setId} was not read: `+P(v))})??this.maskingKey,U.keyCheck!==void 0&&fs(Qe)!==U.keyCheck){et(Re.keyLost,this.sliceKeyLostMessage(U,c.voice));return}R=U,B=U.requestsSpent}let ae=await ze(e.orgId,this.deps.orgRegistry,this.deps.orgManager),$=Cn(ae);if(Q&&await Ss($,this.deps.log)&&(g=Q,E=te(Q,Ne)),me&&me.fingerprint!==E){Le();return}let z,M=m=>{A++;let v=Ye(ae.limitInfo,m);v&&v.usagePercent>=Os&&(z??=v)},de=()=>z,Ke=new Set;for(let m of g){let v=Ft(p,m),V=dn(p,m);if(v.length===0&&V.length===0)continue;let _=xe(m),L=jn(e,p,m);l.objectName=_;let T=me?.objects.find(Me=>Me.objectApiName===_),x={objectApiName:_,done:T?.done??!1,...T?.afterId!==void 0?{afterId:T.afterId}:{},refused:[...T?.refused??[]],...T?.unconfirmed?.length?{unconfirmed:[...T.unconfirmed]}:{},...T?.slice?{slice:{...T.slice}}:{}},ye=0,J=async Me=>{try{let Y=await this.countRows(ae,_,Me,L);return M(`dataops:anonymize count ${_}`),Y}catch(Y){let ge=Ne!==void 0&&Me===void 0&&L===void 0?await this.approximateCount(ae,_,Y):void 0;if(ge!==void 0)return Ke.add(_),ge;throw be(this.deps,{...u,outcome:"failure",source:void 0,objects:[gn(_)],code:gi,details:{reason:Pn(Y)}}),this.countGaveUp(Y,_)}},je=R?.objects.find(Me=>Me.objectApiName===_);je?(ye=Si(je),je.done||(ye+=await J(Mn(je))),x.done=ye===0):x.done||(ye=await J(x.afterId),ye===0&&(x.done=!0));let St=ye+x.refused.length+(x.unconfirmed?.length??0),mt={objectApiName:_,total:St,masked:0,nothingToMask:0,refused:0,unanswered:0,done:St===0};f.push(mt),S.push({objectName:m,...L!==void 0?{where:L}:{},objectRules:v,personRules:V,tally:mt,progress:x})}let Oe=f.reduce((m,v)=>m+v.total,0),De=await this.maskingNotCovered($,p,g,S);if(De){be(this.deps,{...u,outcome:"stopped",source:void 0,code:De.code}),c.refused(new Error(De.message),{code:De.code,extraPayload:{...De.gaps}}),pe(this.deps,t,De.message,!1,{context:l,authored:!0});return}let pn=await vs($,S.filter(m=>m.tally.total>0).map(m=>({objectApiName:m.tally.objectApiName,rules:[...m.objectRules,...m.personRules]})));if(pn.length>0){let m=bn(pn);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${m}`),be(this.deps,{...u,outcome:"stopped",source:void 0,code:xt}),c.refused(new Error(m),{code:xt}),pe(this.deps,t,m,!1,{context:l,authored:!0});return}let it=(m,v,V=[])=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(v),{code:m,...os({alsoRefused:V})}),pe(this.deps,t,v,!1,{context:l,authored:!0})};if(e.snapshot===!0&&Ne===void 0){let m=this.backupCap();if(S.some(v=>v.tally.total>m)){it(on,`Nothing was masked: ${S.filter(v=>v.tally.total>m).map(v=>`${v.tally.objectApiName} holds ${v.tally.total} record(s)`).join(", ")}, more than the ${m} a snapshot holds of one object. `+this.snapshotCapWay(S,c.voice));return}}if(Ne!==void 0){let m=await this.sliceRunPlan($,S,Ne,this.pageSizeFor(e.orgId));if(m.tooMany.length>0){it(Re.tooMany,this.tooManySlicesMessage(m,Ne));return}let v=await this.freeBytes();if(v!==void 0&&Sn(m.diskBytes)>v){it(Re.diskShort,this.diskShortMessage(Sn(m.diskBytes),v,!0));return}}let at=await this.readAct(ae,e.orgId,"masking",f.map(m=>({objectApiName:m.objectApiName,records:m.total})),c.accord,c.voice),yt=yn(at.answer);if(yt){it(yt.code,yt.message,yt.alsoRefused);return}let dt=ts(at.answer.automation,f.filter(m=>m.total>0).map(m=>m.objectApiName)),ct=()=>this.duplicatesWatchOf(ae,dt),Te=ct();we=Te;let At=this.deps.orgManager.getOrg(e.orgId),Kt={orgId:e.orgId,orgTier:Rs(At),operation:"update",objectName:g.join(", ")||"AnonymizeData",recordCount:Oe,module:"dataops"},{check:jt,decision:lt}=await Zn(F,Kt);if(u.guard=lt,(lt==="refused"||lt==="declined")&&be(this.deps,{...u,outcome:"stopped",source:void 0}),lt==="refused")throw qn(jt.blockedReason??jt.impactSummary);if(lt==="declined"){let m="Operation cancelled by user (confirmation declined).";c.refused(new Error(m),{code:Kn.declined}),pe(this.deps,t,m,!1,{context:l,authored:!0});return}for(let m of jt.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${m}`);if(X.signal.aborted){await ot();return}let ce=await rs(at,t,c.accord.acceptEmails===!0,c.voice);if("refused"in ce){it(ce.refused.code,ce.refused.message);return}if(r=ce.held,j=!0,Ne!==void 0){let m=`backup:${e.orgId}`;if(this.activeOrgOperations.has(m)){it(Is,this.busyMessage(e.orgId,`A backup or rollback operation is already running for org ${e.orgId}. Mask once it has ended.`));return}if(this.activeOrgOperations.add(m),G=!0,!R){let v=new Date().toISOString(),V=await ae.soap.getServerTimestamp().then(L=>new Date(L.timestamp).toISOString()).catch(()=>v);A++;let _=await this.organizationIdOf(ae);A++,R={setId:t,kind:"masking",orgId:e.orgId,..._!==void 0?{organizationId:_}:{},templateId:e.templateId,fingerprint:E,size:Ne,state:"open",startedAt:v,serverStartedAt:V,lastActivityAt:v,requestsSpent:0,keyCheck:fs(Qe),objects:S.map(L=>({objectApiName:L.tally.objectApiName,...L.where!==void 0?{where:L.where}:{},done:L.tally.total===0,slices:[]}))},re.save(R),await this.runKeys?.save(R.setId,Qe).catch(L=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${t} was not kept, so only this window resumes it: ${P(L)}`)})}this.sliceRunsOn.set(e.orgId,R.setId)}let tt=In(At?.orgType==="Sandbox"||At?.orgType==="Scratch"),Fe=An(tt).defaultQueryLimit;if(e.snapshot===!0&&R===void 0){let m=await this.snapshotBeforeMasking($,t,e.orgId,S,{origin:c.origin,stop:X.signal});if("refused"in m&&X.signal.aborted){await ot();return}if("refused"in m){be(this.deps,{...u,outcome:"stopped",source:void 0,code:on}),c.refused(new Error(m.refused),{code:on}),await d(),pe(this.deps,t,m.refused,m.retryable,{context:l,authored:!0});return}if(D=m.taken,X.signal.aborted){await ot();return}}let Pe=c.pipeline?`Pipeline anonymization with ${p.name}`:`Anonymizing with ${p.name}`;Yt(this.deps,t,"dataops",Pe),y=!0,b=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Pe,new Promise((m,v)=>{ve=V=>{V===void 0?m():v(V instanceof Error?V:new Error(String(V)))}}),X),Ge=rn(this.liveTracker,t,"dataops",Pe,Oe);let{AnonymizationEngine:qt}=await import("./chunk-PZBZ7MNC.mjs"),le=new qt(void 0,Qe);N=le,me&&!(me.namesGiven!==void 0&&le.continueFrom(me.namesGiven))&&this.deps.log(`[INFO] dataops:anonymize ${t}: the run it resumes kept no record of the names it made up, so this one may give again a name or an address that run gave.`);let qe=[],Z=!1,He=m=>m.masked+m.nothingToMask+m.refused+(m.deletedSince??0),ut,Ps=(m,v)=>{let V=f.reduce((x,ye)=>x+He(ye),0),_=Math.max(Oe,V),L=Math.round(V/_*100),T=`Anonymized ${m}${ut?` ${ut}`:""} (${He(v)}/${Math.max(v.total,He(v))})`;Mt(this.deps,t,L,V,_,T),Ge?.progress(L,V,_,T)},Ln=[],Ao=async m=>{let v=R,V=this.backupRecords,{safeObj:_,fields:L,tally:T,progress:x,writeBack:ye}=m,J=v?.objects.find(h=>h.objectApiName===_);if(!v||!V||!J)throw new Error(`The set of slices holds no ${_}: nothing more was masked.`);let je=mo(_),St=L.split(",").length,mt=()=>({masked:T.masked,nothing:T.nothingToMask,refused:T.refused,gone:T.deletedSince??0}),Me=(h,w)=>{h.masked+=T.masked-w.masked,h.nothingToMask+=T.nothingToMask-w.nothing,h.deletedSince+=(T.deletedSince??0)-w.gone;let O=x.unconfirmed?.length??0;O>0?h.unanswered=O:delete h.unanswered},Y=async h=>{let w=[];for await(let O of await this.backupBatches(h.snapshotId,je))for(let K of O)typeof K.Id=="string"&&w.push(K.Id);return w},ge=async(h,w)=>{w.length===0?await V.delete(h.snapshotId,je):(await V.begin(h.snapshotId,je),await V.append(h.snapshotId,je,w.map(O=>({Id:O})))),h.refused=w.length},_e=async(h,w)=>{w.length!==0&&(await V.append(h.snapshotId,je,w.map(O=>({Id:O}))),h.refused+=w.length)},Ae=J.slices.find(h=>h.state==="masking")??J.slices.at(-1);if(Ae){Ae.masked+=T.masked,Ae.nothingToMask+=T.nothingToMask,Ae.deletedSince+=T.deletedSince??0,await _e(Ae,x.refused),x.refused=[];let h=x.unconfirmed?.length??0;h>0?Ae.unanswered=h:delete Ae.unanswered}for(let h of J.slices){if(h.refused===0)continue;let w=await Y(h),O=[...w],K=[];for(let oe=0;oe<w.length;oe+=rt){if(X.signal.aborted)return Z=!0,"stopped";if(de())return"stopped";let ue=w.slice(oe,oe+rt),Ie=await Et(ae,`SELECT ${L} FROM ${_} WHERE Id IN (${ue.map(Ht=>`'${Ht}'`).join(", ")})`);M(`dataops:anonymize query ${_}`);let he=ue.length-Ie.length;h.deletedSince+=he,T.deletedSince=(T.deletedSince??0)+he;let We=mt(),q=[],ne=!1;try{ne=await ye(Ie,(Ht,Fn)=>q.push(...Fn),(Ht,Fn)=>{x.unconfirmed=[...x.unconfirmed??[],...Fn]})}finally{Me(h,We),O=O.slice(ue.length),K.push(...q),await ge(h,[...K,...ne?ue:[],...O]),Be()}if(ne)return"stopped"}}let Ee=async h=>{let w=new Set;for(let O of J.slices)if(!(O!==h&&O.lateOf!==h.index)&&O.state!=="pending")for await(let K of await this.backupBatches(O.snapshotId,_))for(let oe of K)typeof oe.Id=="string"&&w.add(oe.Id);return w},fe=async h=>{let w=x.slice?.index===h.index?x.afterId:void 0,O=w===void 0;for await(let K of await this.backupBatches(h.snapshotId,_)){let oe=K;if(!O){let q=oe.findIndex(ne=>ne.Id===w);if(q<0)continue;O=!0,oe=oe.slice(q+1)}if(oe.length===0)continue;if(X.signal.aborted)return Z=!0,!0;if(de())return!0;let ue=mt(),Ie=[],he=q=>{let ne=q[q.length-1]?.Id;typeof ne=="string"&&un.test(ne)&&(x.afterId=ne)},We=!0;try{We=await ye(oe,(q,ne)=>{Ie.push(...ne),he(q)},(q,ne)=>{x.unconfirmed=[...x.unconfirmed??[],...ne],he(q)}),We||he(oe)}finally{Me(h,ue),await _e(h,Ie)}if(We)return!0}if(!O)throw new Error(`The snapshot of slice ${h.index} of ${_} no longer holds the row the run stopped at: it is not the file the slice was masked from, and nothing more of it was masked.`);return!1};for(;;){if(X.signal.aborted)return Z=!0,"stopped";if(de())return"stopped";let h=J.slices.find(w=>!Bt(w));if(!h){let w=J.slices.find(We=>!We.late&&(We.lateLeft??0)>0);if(!w&&J.done)break;let O=J.slices.filter(We=>!We.late),K=O.at(-1)?.sizeUsed??v.size,oe=Math.max(1,Math.min(K,T.total-He(T))),ue=_r(oe,Fe,{masking:!0,duplicateRule:Te.covers(_)}),Ie=this.sliceBudgetStop(ae,e.maxRequests,A,ue,c.voice);if(Ie)return C={budget:!0,message:Ie},"stopped";if(!w&&O.length>=ht)return C={code:Re.tooMany,message:`${_} holds more rows than ${ht} slices of ${K} do, as it grew during the run: the run stopped between two slices.`},"stopped";let he=as(v);h={index:he,...w?{late:!0,lateOf:w.index,...(w.lateAfterId??w.afterId)!==void 0?{afterId:w.lateAfterId??w.afterId}:{}}:Mn(J)!==void 0?{afterId:Mn(J)}:{},rows:0,snapshotId:is(v.setId,he),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:K},J.slices.push(h),Be()}if(h.state==="pending"){let w=h.late===!0?J.slices.find(ne=>ne.index===h?.lateOf):void 0,O=await this.freeBytes(),K=Sn(h.sizeUsed*(48+64*St));if(O!==void 0&&K>O)return J.slices=J.slices.filter(ne=>ne!==h),Be(),C={code:Re.diskShort,message:this.diskShortMessage(K,O)},"stopped";let oe=w?{...h.afterId!==void 0?{afterId:h.afterId}:{},...w.lastId!==void 0?{untilId:w.lastId}:{},createdSince:w.readSince??v.serverStartedAt??v.startedAt}:h.afterId!==void 0?{afterId:h.afterId}:{},ue=w?await Ee(w):void 0,Ie=Rn(Math.max(T.total,He(T)),h.sizeUsed);ut=`slice ${h.index} of about ${Math.max(Ie,h.index)}`;let he=f.reduce((ne,Ht)=>ne+He(Ht),0),We=`Backing up ${_} ${ut}`;Mt(this.deps,t,Math.round(he/Math.max(Oe,he,1)*100),he,Math.max(Oe,he),We);let q=await this.snapshotSlice(ae,e.orgId,v,J,h,{select:L,bounds:oe,...ue?{skip:ne=>ue.has(String(ne.Id))}:{},stop:X.signal,onRequest:()=>{A++},origin:c.origin});if("failed"in q)return J.slices=J.slices.filter(ne=>ne!==h),Be(),q.cancelled?(Z=!0,"stopped"):(C={code:q.code,message:this.sliceNotTakenMessage(_,q)},"stopped");if(q.lastId===void 0){await this.removeBackup(`backup:${h.snapshotId}`),J.slices=J.slices.filter(ne=>ne!==h),w?(delete w.lateLeft,delete w.lateAfterId,q.readSince&&(w.readSince=q.readSince)):J.done=!0,Be();continue}h.rows=q.rows,h.lastId=q.lastId,h.sizeUsed=q.sizeUsed,h.takenAt=new Date().toISOString(),q.readSince&&(h.readSince=q.readSince),w&&(q.read<q.sizeUsed?(delete w.lateLeft,delete w.lateAfterId,q.readSince&&(w.readSince=q.readSince)):w.lateAfterId=q.lastId),h.state="masking",x.slice={setId:v.setId,index:h.index},delete x.afterId,Be()}if(ut??=`slice ${h.index}`,await fe(h))return"stopped";Ln.push(h.index),ut=void 0,h.state="masked",delete h.unanswered,ee=ns(ee,await Te.read()),Te=ct(),we=Te,le.forgetRecords(),delete x.slice,delete x.afterId,Be()}return T.done=!0,x.done=!0,"done"};for(let{objectName:m,where:v,objectRules:V,personRules:_,tally:L,progress:T}of S){if(L.total===0)continue;if(X.signal.aborted){Z=!0;break}if(de())break;let x=L.objectApiName;l.objectName=x;let{select:ye,rulesOf:J}=await this.maskedFields($,x,this.maskingRules(m,V,Qe),this.maskingRules(m,_,Qe));l.batchSize=rt;let je=async(Y,ge,_e)=>{let Ae=Y.map(J),Ee=Y.map((h,w)=>le.anonymize([h],Ae[w])[0]),fe=[];Y.forEach((h,w)=>{let O={Id:h.Id};for(let K of Ae[w])Yn(h[K.fieldApiName])&&(O[K.fieldApiName]=Ee[w][K.fieldApiName]);Object.keys(O).length>1?fe.push(O):L.nothingToMask++});for(let h=0;h<fe.length;h+=rt){if(X.signal.aborted)return Z=!0,!0;if(de())return!0;let w=fe.slice(h,h+rt),O;Te.beforeWrite(x);try{O=await ae.sobject(m).update(w,{headers:Wn()})}catch(ue){throw Jn(ue)==="may-have-written"&&(L.unanswered+=w.length,_e(w,w.flatMap(mi)),Te.wrote(x,w.map(Ie=>Ie.Id))),ue}M(`dataops:anonymize update ${x}`);let K=[],oe=Array.isArray(O)?O:[O];Te.wrote(x,oe.flatMap((ue,Ie)=>ue.success?[w[Ie]?.Id]:[])),oe.forEach((ue,Ie)=>{if(ue.success){L.masked++;return}if(R&&Ri(ue.errors)){L.deletedSince=(L.deletedSince??0)+1;return}L.refused++;let he=w[Ie]?.Id;typeof he=="string"&&un.test(he)&&K.push(he),to(qe,x,ue.errors)}),ge(w,K),Ps(m,L)}return fe.length===0&&Ps(m,L),!1},St=T.unconfirmed??[];for(let Y=0;Y<St.length;Y+=rt){if(X.signal.aborted){Z=!0;break}if(de())break;let ge=St.slice(Y,Y+rt),_e=ge.map(O=>`'${O.id}'`).join(", "),Ae=await Et(ae,`SELECT ${ye} FROM ${x} WHERE Id IN (${_e})`);M(`dataops:anonymize query ${x}`);let Ee=new Map(Ae.map(O=>[String(O.Id),O])),fe=[];for(let O of ge){let K=Ee.get(O.id);K===void 0?L.total-=1:bs(K,O.fields)===O.digest?L.nothingToMask++:fe.push(O.id)}let h=new Set(ge.map(O=>O.id)),w=(T.unconfirmed??[]).filter(O=>!h.has(O.id));w.length>0?T.unconfirmed=w:delete T.unconfirmed,T.refused.push(...fe)}if(Z||de())break;let mt=[...T.refused];for(let Y=0;Y<mt.length;Y+=rt){if(X.signal.aborted){Z=!0;break}if(de())break;let ge=mt.slice(Y,Y+rt),_e=await Et(ae,`SELECT ${ye} FROM ${x} WHERE Id IN (${ge.map(h=>`'${h}'`).join(", ")})`);M(`dataops:anonymize query ${x}`),L.total-=ge.length-_e.length;let Ae=[];if(await je(_e,(h,w)=>Ae.push(...w),(h,w)=>{let O=new Set(w.map(K=>K.id));T.refused=T.refused.filter(K=>!O.has(K)),T.unconfirmed=[...T.unconfirmed??[],...w]}))break;let fe=new Set(ge);T.refused=[...T.refused.filter(h=>!fe.has(h)),...Ae]}if(Z||de())break;if(R){if(await Ao({objectName:m,safeObj:x,fields:ye,tally:L,progress:T,writeBack:je})!=="done")break;continue}if(T.done){L.done=!0;continue}let Me=T.afterId;for(;;){if(X.signal.aborted){Z=!0;break}if(de())break;let Y=await lo(ae,x,ye,Fe,Me,v);if(M(`dataops:anonymize query ${x}`),Y.records.length===0){L.done=!0,T.done=!0;break}let ge=Y.truncated?Ii(Y.records,Me,x):void 0;if(X.signal.aborted){Z=!0;break}let _e=Ee=>{let fe=Ee[Ee.length-1]?.Id;typeof fe=="string"&&un.test(fe)&&(T.afterId=fe)};if(await je(Y.records,(Ee,fe)=>{T.refused.push(...fe),_e(Ee)},(Ee,fe)=>{T.unconfirmed=[...T.unconfirmed??[],...fe],_e(Ee)}))break;if(ge===void 0){L.done=!0,T.done=!0;break}Me=ge,T.afterId=ge}if(Z||de())break}if(R){!Z&&!de()&&!C&&(W=await this.countLateRows(ae,R,()=>{A++}));for(let m of f){let v=R.objects.find(_=>_.objectApiName===m.objectApiName),V=m.done&&v?ds({objects:[v]}):0;V>0&&(m.late=V)}if(_t(f).recordsNotMasked===0&&R.objects.every(m=>m.done&&(m.tailLeft??0)===0&&m.slices.every(v=>Bt(v)&&v.refused===0&&(v.lateLeft??0)===0))&&(R.state="done"),$t(R).length===0&&R.state==="open"?(R.state="abandoned",this.sliceSets.delete(R.setId)):Be(),R.state!=="open"){let m=R.setId;await this.runKeys?.delete(m).catch(v=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${m} was not removed: ${P(v)}`)})}}let It=de(),pt=bi(f,Z),{recordsProcessed:Rt,recordsFailed:Ct,recordsNotMasked:ft}=_t(f),Ms=io(f);y=!1,be(this.deps,{...u,...ki(f,pt,Z),objects:co(f),...R?{details:{setId:R.setId,sliceSize:R.size,...Ln.length>0?{slices:Ln.join(",")}:{}}}:{}});let Es=Ut();if(ft>0){let m=Z?"cancelled":It?`stopped at ${It.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${m}: ${ft} record(s) not masked \u2014 ${Ms}`)}await d();let Dn=await Ce();Z?(this.deps.infraServices?.backgroundRegistry?.abort(t),Ve(this.deps,t,{aborted:!0,totalProcessed:Rt,totalFailed:Ct,totalNotMasked:ft}),Ge?.cancel()):(Ve(this.deps,t,{status:pt,totalProcessed:Rt,totalFailed:Ct,totalNotMasked:ft}),pt==="failure"?Ge?.fail(`The org refused the ${Ct} record(s)`):pt==="partial"?Ge?.partial():Ge?.complete());let xs=`${ft} still hold their original values (${Ms})`,Io=Z?`Anonymization cancelled: ${Rt} masked before the cancel \u2014 ${xs}.`:It?`Anonymization stopped at ${It.usagePercent}% of the org's daily API requests (${It.apiUsage} of ${It.apiLimit}): ${Rt} masked \u2014 ${xs}. ${Es?"Resume it":"Run it again"} once the org has requests to spare.`:Ct===0?`Anonymization ${pt==="success"?"completed":pt}: ${Rt} records processed.`:`Anonymization ${pt}: ${Rt} masked, ${Ct} rejected by the org \u2014 those records still hold their original values.`,Ro=Es&&ft>0?" Resume masks only what this run left.":"",zs=Zt(Dn,this.orgNameOf(e.orgId)),Bs=R?this.slicesSentence(R,C,c.voice,ft>0,W):"",So=Io+(Bs?` ${Bs}`:Ro)+(zs?` ${zs}`:"");c.ended({templateId:e.templateId,status:pt,recordsProcessed:Rt,recordsFailed:Ct,recordsNotMasked:ft,objects:ao(f),message:So,errors:qe,...Z?{cancelled:!0}:{},...It?{stoppedAtApiLimit:!0}:{},...D?{snapshot:D}:{},...r?{mutedAutomation:r.outcome}:{},...Dn?{duplicates:Dn}:{},...R?{slices:en(R,{requestsSpent:A,stoppedOnBudget:C?.budget===!0})}:{}})}catch(F){await d();let Q=await Ce().catch(()=>{});wt(F,!0,Q)}finally{let F=await d();if(F&&c.muted?.(F),y){let Q=f.some(re=>re.masked>0);be(this.deps,{...u,outcome:Q?"partial":"failure",objects:j?co(f):[]})}if(b&&!I){try{Be()}catch(Q){this.deps.log(`[WARN] dataops:anonymize ${t}: its set of slices was not kept: `+P(Q))}Ut()}G&&(this.activeOrgOperations.delete(`backup:${e.orgId}`),this.sliceRunsOn.delete(e.orgId)),ve(kt),$e?.release(),s?.removeEventListener("abort",Je),o.answer?.(F)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=ke(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...tn,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(nr,e,"dataops:error",this.deps);if(!t)return;let n=t.templateId!==void 0?this.findTemplate(t.templateId):void 0;if(t.templateId!==void 0&&!n){this.refuseUnknownTemplate("backup:objects",e,t.templateId);return}try{let s,r=()=>s??=ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Ss(d,this.deps.log)),o=[];for(let d of n?[n]:this.listedTemplates()){let c=ln({},d,se)&&await r();for(let l of Tn({},d,c))l!==""&&l!=="*"&&!o.includes(l)&&o.push(l)}let a=ke(this.deps,e,"backup:objects:response",{objects:o});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} objects=${o.length}`)}catch(s){H(this.deps,"backup:objects","dataops:error",e,s)}}async plannedObjectsIn(e,t,n){let s=ln(t,n,se)&&await Ss(e,this.deps.log);return Tn(t,n,s)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(ar,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:coverage",e,t.templateId);return}try{let s=this.latestBackup(t.orgId),r=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=[],a=await this.plannedObjectsIn(r,t,n),d=[];for(let S of a){if(!no(n,S))continue;let k=xe(S),E=jn(t,n,S),j=null,y;try{j=await this.countRows(r,k,void 0,E)}catch(N){this.deps.log(`[WARN] dataops:anonymize:coverage: ${k} not counted: ${P(N)}`),y=await this.approximateCount(r,k,N)}d.push({objectName:S,...j!==null?{rows:j}:y!==void 0?{rows:y}:{},...j===null&&y!==void 0?{approximate:!0}:{}});let b=s?.objects.find(N=>N.objectApiName.toLowerCase()===k.toLowerCase()),I=b?.where!==void 0&&b.where!==E;o.push({objectApiName:k,count:j,backedUp:I?0:b?.recordCount??0,truncated:!I&&b?.truncated===!0,...b?.stoppedAt&&!I?{stoppedAt:b.stoppedAt}:{},...I?{filtered:!0}:{}})}let c=this.sliceSets.openFor(t.orgId,t.templateId),l=c?.size??this.backupCap(),p;if(t.slices===!0||c!==void 0||d.some(S=>(S.rows??0)>this.backupCap())){let S=Cn(r),k=[];for(let y of d){if(y.rows===void 0)continue;let b=Ft(n,y.objectName),I=dn(n,y.objectName),N=await this.maskedFields(S,xe(y.objectName),this.maskingRules(y.objectName,b),this.maskingRules(y.objectName,I)).then(({select:D})=>D.split(",").length,()=>b.length+I.length+1);k.push({objectApiName:xe(y.objectName),rows:y.rows,fields:N,...y.approximate?{approximate:!0}:{}})}let E=ls(k,l,this.pageSizeFor(t.orgId),"masking");for(let y of o){let b=E.objects.find(I=>I.objectApiName===y.objectApiName);b&&(y.slicePlan=b)}let j=await this.freeBytes();p={requests:E.requests,parts:E.parts,bulkBatches:0,diskBytes:E.diskBytes,...j!==void 0?{diskFree:j}:{},seconds:E.seconds,apiBudget:await this.apiBudgetFor(r,E.requests)}}let g=new nt(this.deps.configStore),u=(c?g.load(t.orgId,t.templateId,sn(n.rules,a,zn(t),c.size)):void 0)??g.load(t.orgId,t.templateId,sn(n.rules,a,zn(t))),f=ke(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...s?{backup:{operationId:s.operationId,timestamp:s.timestamp}}:{},objects:o,...u?{checkpoint:{id:u.id,savedAt:u.savedAt}}:{},...p?{plan:p}:{},...c?{sliceSet:Pr(c)}:{}});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id} objects=${o.length}`)}catch(s){H(this.deps,"dataops:anonymize:coverage","dataops:error",e,s)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(dr,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:preview",e,t.templateId);return}try{let s=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:r}=await import("./chunk-PZBZ7MNC.mjs"),o=new r(void 0,this.maskingKey),a=[],d=[],c=Cn(s);for(let p of await this.plannedObjectsIn(s,t,n)){if(!no(n,p))continue;let g=xe(p);try{let u=Ft(n,p),f=dn(n,p),{rules:S,select:k,missing:E,rulesOf:j}=await this.maskedFields(c,g,this.maskingRules(p,u),this.maskingRules(p,f)),y=await lo(s,g,k,ro,void 0,jn(t,n,p));Ye(s.limitInfo,`dataops:anonymize:preview ${g}`);let b=y.records.length>0;b&&d.push(...E.map(A=>({objectApiName:g,fieldApiName:A})));let[I]=b?await vs(c,[{objectApiName:g,rules:[...u,...f]}]):[],N=y.records.map(j),D=y.records.map((A,B)=>o.anonymize([A],N[B])[0]),R=S.map(A=>A.fieldApiName).filter((A,B,C)=>A!=="Id"&&C.indexOf(A)===B);a.push({objectApiName:g,fields:R,...b&&S.length===0?{notCovered:!0}:{},...I?{writeDenied:{deniedFields:[...I.deniedFields]}}:{},methods:Object.fromEntries(S.map(A=>[A.fieldApiName,A.method])),rows:y.records.slice(0,ro).map((A,B)=>{let C={},ee={},G=new Set(N[B].map(W=>W.fieldApiName));for(let W of R)C[W]=oo(A[W]),ee[W]=Yn(A[W])&&G.has(W)?oo(D[B][W]):C[W];return{id:String(A.Id??""),before:C,after:ee}})})}catch(u){let f=P(u);this.deps.log(`[WARN] dataops:anonymize:preview: ${g} not read: ${f}`),a.push({objectApiName:g,fields:[],rows:[],error:f})}}let l=ke(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:a,fieldsNotFound:d});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} objects=${a.length}`)}catch(s){H(this.deps,"dataops:anonymize:preview","dataops:error",e,s)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let s=n.slice(7);if(s.includes(":"))continue;let r=this.deps.configStore.get(n);if(r?.orgId!==e||r.origin==="slice")continue;let o=r.timestamp??"";t&&t.timestamp.localeCompare(o)>=0||(t={operationId:s,timestamp:o,objects:r.objects??[]})}return t}async handleQualityScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(pr,e,"dataops:error",this.deps);if(t)try{let n=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),s=await fr({describe:o=>n.describe(o),query:async o=>{let a=await n.query(o);return Ye(n.limitInfo,"dataops:quality-scan"),{totalSize:a.totalSize,records:a.records}}},t),r=ke(this.deps,e,"dataops:quality-scan:response",{...s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} objects=${s.objects.length}`)}catch(n){H(this.deps,"dataops:quality-scan","dataops:error",e,n)}}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(cr,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...tn,...this.savedTemplates.list()].some(a=>a.name.trim().toLowerCase()===n.toLowerCase())){H(this.deps,"dataops:anonymization-template:save","dataops:error",e,new Error(`A template named "${n}" already exists. Pick another name.`),{code:"DUPLICATE_NAME"});return}let r={id:`tpl-saved-${crypto.randomUUID()}`,name:n,description:"",complianceFramework:"custom",rules:t.rules.map(a=>({...a,description:""})),saved:!0,createdAt:new Date().toISOString()};this.savedTemplates.save(r);let o=ke(this.deps,e,"dataops:anonymization-template:save:response",{template:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){H(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(lr,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(tn.some(s=>s.id===n)){H(this.deps,"dataops:anonymization-template:delete","dataops:error",e,new Error(`Template "${n}" ships with SandForge and cannot be deleted.`),{code:"BUILT_IN"});return}try{let s=this.savedTemplates.delete(n),r=ke(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(s){H(this.deps,"dataops:anonymization-template:delete","dataops:error",e,s)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(ur,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:s}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let r=await ze(n,this.deps.orgRegistry,this.deps.orgManager),o=await Promise.all(s.map(async d=>{let c=xe(d),l=await r.describe(c);Ye(r.limitInfo,`precheck:pii-scan describe ${c}`);let p=l.fields.map(u=>({apiName:u.name,label:u.label,type:u.type,length:u.length})),g=this.deps.infraServices.piiDetector.detectPII(d,p);return{objectName:d,piiFields:g.piiFields.map(u=>({fieldName:u.fieldApiName,piiType:u.classification,confidence:u.confidence}))}})),a=ke(this.deps,e,"precheck:pii-scan:response",{success:!0,results:o});this.deps.broker.postToWebview(a)}catch(r){this.deps.log(`[ERR] precheck:pii-scan: ${P(r)}`);let o=ke(this.deps,e,"precheck:pii-scan:response",{success:!1,error:P(r)});this.deps.broker.postToWebview(o)}}};export{tn as a,$n as b,An as c,In as d,Nn as e,cs as f,On as g,rn as h,ks as i,Sn as j,us as k,Ei as l,xi as m,ai as n,an as o,go as p};
@@ -0,0 +1,7 @@
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 r}from"./chunk-CA5NAXSU.mjs";var o=["INVALID_SESSION_ID","INVALID_AUTH_HEADER","SESSION_EXPIRED"];function i(e){if(typeof e=="object"&&e!==null){let{errorCode:n,statusCode:s}=e;if(typeof n=="string"&&o.includes(n)||s===401)return!0}let t=r(e);return o.some(n=>t.includes(n))||t.includes("Session expired")?!0:/\b401\b/.test(t)&&/unauthorized/i.test(t)}export{i as a};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h}from"./chunk-SOGQW4IG.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-M3ROUWDX.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{d as ARTICLE_OBJECT,b as CASE_STATUS_BY_LABEL_SOQL,a as CASE_STATUS_SOQL,g as prepareScenario,c as readScenarioCaseStatus,f as scenarioCasePicklists,e as scenarioKnowledge,h as toolingQueryAll};
7
+ import{a,b,c,d,e,f,g,h}from"./chunk-T7WREYA5.mjs";import"./chunk-V3R45ZWT.mjs";import"./chunk-A65ADTCR.mjs";import"./chunk-NWOI25WY.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-VPDEJGPS.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{d as ARTICLE_OBJECT,b as CASE_STATUS_BY_LABEL_SOQL,a as CASE_STATUS_SOQL,g as prepareScenario,c as readScenarioCaseStatus,f as scenarioCasePicklists,e as scenarioKnowledge,h as toolingQueryAll};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as c}from"./chunk-YKKRIEH4.mjs";var p=class{apply(n,r,t=[]){return m(n,r,t)}applyAddOns(n,r){let t={...n};for(let o of r)(!(o.fieldApiName in t)||o.overwriteExisting)&&(t[o.fieldApiName]=o.value);return t}},g=new Set(["direct","rename","transform","add_on"]),i=e=>e.toLowerCase();function S(e){return new Set(e.filter(n=>n.type!=="exclude").map(n=>i(n.targetField)))}function w(e,n=[]){let r=new Set(n.map(i));for(let t of e)(g.has(t.type)||t.type==="exclude")&&r.add(i(t.sourceField)),r.add(i(t.targetField));return r}var y=new c;function m(e,n,r=[]){if(n.length===0&&r.length===0)return{...e};let t=new Set(r.map(i)),o=Object.fromEntries(Object.entries(e).filter(([s])=>!t.has(i(s)))),d=w(n,r),l=Object.fromEntries(Object.entries(o).filter(([s])=>!d.has(i(s))));for(let s of n){let u=R(o,s);u!==void 0&&(l[s.targetField]=u)}return l}function a(e,n){if(n in e)return e[n];let r=i(n),t=Object.keys(e).find(o=>i(o)===r);return t===void 0?void 0:e[t]}var f=Symbol("exclude");function R(e,n){let r=F[n.type],t=r(e,n);if(!(t===f||t===void 0))return n.transformRules&&n.transformRules.length>0?y.transform(t,n.transformRules):t}var F={direct:(e,n)=>a(e,n.sourceField),rename:(e,n)=>a(e,n.sourceField),transform:(e,n)=>a(e,n.sourceField),constant:(e,n)=>n.targetField?n.sourceField:void 0,formula:(e,n)=>k(e,n.sourceField),exclude:()=>f,add_on:(e,n)=>a(e,n.sourceField)};function k(e,n){return/\{(\w+)\}/g.test(n)?n.replace(/\{(\w+)\}/g,(t,o)=>{let d=e[o];return d!=null?String(d):""}):e[n]}export{p as a,g as b,S as c,w as d,m as e};
7
+ import{a as c}from"./chunk-TMA34QMA.mjs";var p=class{apply(n,r,t=[]){return m(n,r,t)}applyAddOns(n,r){let t={...n};for(let o of r)(!(o.fieldApiName in t)||o.overwriteExisting)&&(t[o.fieldApiName]=o.value);return t}},g=new Set(["direct","rename","transform","add_on"]),i=e=>e.toLowerCase();function S(e){return new Set(e.filter(n=>n.type!=="exclude").map(n=>i(n.targetField)))}function w(e,n=[]){let r=new Set(n.map(i));for(let t of e)(g.has(t.type)||t.type==="exclude")&&r.add(i(t.sourceField)),r.add(i(t.targetField));return r}var y=new c;function m(e,n,r=[]){if(n.length===0&&r.length===0)return{...e};let t=new Set(r.map(i)),o=Object.fromEntries(Object.entries(e).filter(([s])=>!t.has(i(s)))),d=w(n,r),l=Object.fromEntries(Object.entries(o).filter(([s])=>!d.has(i(s))));for(let s of n){let u=R(o,s);u!==void 0&&(l[s.targetField]=u)}return l}function a(e,n){if(n in e)return e[n];let r=i(n),t=Object.keys(e).find(o=>i(o)===r);return t===void 0?void 0:e[t]}var f=Symbol("exclude");function R(e,n){let r=F[n.type],t=r(e,n);if(!(t===f||t===void 0))return n.transformRules&&n.transformRules.length>0?y.transform(t,n.transformRules):t}var F={direct:(e,n)=>a(e,n.sourceField),rename:(e,n)=>a(e,n.sourceField),transform:(e,n)=>a(e,n.sourceField),constant:(e,n)=>n.targetField?n.sourceField:void 0,formula:(e,n)=>k(e,n.sourceField),exclude:()=>f,add_on:(e,n)=>a(e,n.sourceField)};function k(e,n){return/\{(\w+)\}/g.test(n)?n.replace(/\{(\w+)\}/g,(t,o)=>{let d=e[o];return d!=null?String(d):""}):e[n]}export{p as a,g as b,S as c,w as d,m as e};
@@ -0,0 +1,7 @@
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 f}from"./chunk-CA5NAXSU.mjs";import{Zd as S,_d as h,ce as g,de as y,ee as P}from"./chunk-ZQO5PDX5.mjs";var T=576*60*60*1e3,b=T,m=class extends Error{constructor(e){super(e),this.name="StepCancelledError"}},w=Symbol("stopped");function $(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 u(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 P(t.type)?`Step "${t.name}" is a ${String(t.type)} step, which SandForge no longer supports: remove it from the pipeline.`:y(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 H(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>b)return`Step "${t.name}" has a timeout of ${e} ms, longer than a step can be given: set at most 24 days (${b} ms).`}}function x(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 l(t){return String(Math.round(t/100)/10)}function M(t,e){let n=Math.max(t,e),i=n-t;return i<=Math.max(5e3,t/100)?`Waited ${l(n)} s.`:`Waited ${l(n)} s by the wall clock, ${l(i)} s more than the ${l(t)} s asked: the machine's clock or a sleep may account for it.`}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(x(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 E(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=S(e);return n===void 0?void 0:`Condition step "${t.name}" ${n}.`}function I(t,e){let n=k(t);if(n!==void 0||!t.condition||!e)return n;let i=t.condition,r=g(i,e.steps.slice(0,e.index),e.declared);return r===void 0?void 0:E(t,i.field,r)}function O(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 D=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 u(e,r,i);let o=this.getExecutor(e.type),c=e.retries??0,a="";for(let p=0;p<=c;p++){let s=await this.attempt(o,e,n);if("result"in s)return s.result;if(s.stopped)return{...u(e,s.error,i),status:"stopped"};a=s.error}return u(e,a,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(d=>{o.signal.addEventListener("abort",()=>d(w),{once:!0})}),a=()=>o.abort();r?.addEventListener("abort",a,{once:!0});let p=!1,s=n.timeout,R=s!==void 0&&s>0?setTimeout(()=>{p=!0,o.abort()},s):void 0;try{let d=await Promise.race([e(n,{...i,signal:o.signal}),c]);return d!==w?{result:d}:p?{error:`Step "${n.name}" timed out after ${s} ms.`}:{error:`Step "${n.name}" was stopped before it finished.`,stopped:!0}}catch(d){return d instanceof m?{error:d.message,stopped:!0}:{error:f(d)}}finally{clearTimeout(R),r?.removeEventListener("abort",a)}}check(e,n){return this.handlers.has(e.type)?H(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=>u(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",I)}createDelayHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=x(e.config);if(r===void 0)return u(e,C(e)??"No usable duration",i);let o=Date.now();if(!await O(r,n.signal))return u(e,`Delay step "${e.name}" was stopped before its ${r} ms wait ended.`,i);let a=Math.max(r,Date.now()-o);return $(e,{delayed:r,heldMs:a},i,M(r,a))}}createConditionHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=k(e);if(r||!e.condition)return u(e,r??"No condition",i);try{let o=h(e.condition,n.variables);return $(e,{conditionMet:o},i,o?"The condition held.":"The condition did not hold.")}catch(o){return u(e,`Condition step "${e.name}" could not be evaluated: ${f(o)}.`,i)}}}};export{m as a,x as b,M as c,D as d};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{q as L}from"./chunk-ZUTYVST5.mjs";import{Hb as C,Jb as R,Ob as S,Pb as m,Sb as b}from"./chunk-TTFDUKUS.mjs";var A="PricebookEntryId",F=Object.fromEntries([["OpportunityLineItem","Opportunity"],["QuoteLineItem","Quote"],["OrderItem","Order"],["ContractLineItem","ServiceContract"]].map(([e,o])=>[e,{record:o,field:L[e]}]));function K(e,o,c){if(!e.has(C))return[];let t=new Map;for(let{sourceObject:n,targetObject:a}of c)t.set(n,[...t.get(n)??[],a]);let i=n=>{let a=new Set,l=[C];for(;l.length>0;){let u=l.pop();if(u===n)return!0;a.has(u)||(a.add(u),l.push(...t.get(u)??[]))}return!1};return[...new Set(o.flatMap(n=>F[n]?.record??[]))].filter(n=>e.has(n)&&!i(n)).map(n=>({sourceObject:n,targetObject:C,relationshipName:`${n}Before${C}`,type:"lookup",required:!0}))}function k(e,o){return[e[R],e[S],o?e[m]:""].map(c=>String(c??"")).join("|")}function h(e,o){return`${e}|${o}`}function Y(e){return h([e.book,e.product,e.model].join("|"),e.currency)}function v(e){let o=e[b];return typeof o=="string"&&o!==""?o:void 0}function x(e){let o=e.wanted??new Map,c=e.prices.flatMap(i=>{let d=i.Id,n=v(i);if(typeof d!="string"||n===void 0)return[];let a=e.writtenIn(n),l=new Set(o.get(d)??[]);l.size===0&&!e.active.has(n)&&a!==void 0&&l.add(a);let u=i[R]===e.standardBookId;return[{row:i,id:d,read:n,alone:a,own:l,standard:u}]}),t=new Map;for(let{row:i,read:d,alone:n,own:a,standard:l}of c){if(l)continue;let u=a.size>0?a:n!==void 0?[n]:[],w=h(k({...i,[R]:e.standardBookId},e.sellingModels),d),p=t.get(w)??new Set;for(let y of u)p.add(y);t.set(w,p)}return c.map(({row:i,id:d,read:n,alone:a,own:l,standard:u})=>{let w=k(i,e.sellingModels),p=new Set(o.get(d)??[]);if(u)for(let y of t.get(h(w,n))??[])p.add(y);if(p.size===0)for(let y of l)p.add(y);return{row:i,id:d,key:w,read:n,alone:a,targets:[...p]}})}function _(e,o){let c=new Map;for(let t of e){if(t.alone!==t.read||!o.has(t.read))continue;let i=h(t.key,t.read);c.has(i)||c.set(i,t)}return c}function W(e){let o=x(e),c=_(o,e.active),t=new Map;for(let{row:i,key:d,targets:n}of o)for(let a of n){let l=h(d,a);c.has(l)||t.has(l)||t.set(l,{book:String(i[R]??""),product:String(i[S]??""),model:e.sellingModels?String(i[m]??""):"",currency:a})}return[...t.values()]}function G(e,o){let c=x(e),t=_(c,e.active),i=new Map(c.map(r=>[r.id,r.key])),d=new Map;for(let r of o){let s=r.Id,f=v(r);if(typeof s!="string"||f===void 0||e.writtenIn(f)!==f)continue;let g=k(r,e.sellingModels),P=h(g,f);if(t.has(P))continue;let M=d.get(P);M!==void 0&&!(r.IsActive===!0&&M.IsActive!==!0)||(d.set(P,r),i.set(s,g))}let n=new Map,a=new Set,l=new Set,u=new Map,w=new Set,p=[],y=(r,s,f)=>{s!==r.read&&p.push({from:r.read,to:s,how:f,forLines:s!==r.alone})},E=[];for(let r of c)for(let s of r.targets){let f=h(r.key,s),g=t.get(f);if(g){n.set(f,g.id),a.add(g.id),g!==r&&y(r,s,"replaced");continue}let P=d.get(f);if(P){n.set(f,String(P.Id)),l.add(P),y(r,s,"replaced");continue}E.push({price:r,to:s})}for(let{price:r,to:s}of E){let f=h(r.key,s);n.has(f)?y(r,s,"replaced"):!a.has(r.id)&&!w.has(r.id)?(w.add(r.id),n.set(f,r.id),s!==r.alone&&u.set(r.id,s),y(r,s,"converted")):y(r,s,"none")}let O=new Map,I=[],B=new Map(c.map(r=>[r.row,r]));for(let r of e.prices){let s=B.get(r);if(!s||s.targets.length===0||a.has(s.id)||w.has(s.id)){I.push(r);continue}let f=s.targets.map(g=>n.get(h(s.key,g))).find(g=>g!==void 0&&g!==s.id);if(f===void 0){I.push(r);continue}O.set(s.id,f)}I.push(...o.filter(r=>l.has(r)));for(let r of c){if(r.targets.length>0||r.alone===void 0)continue;let s=h(r.key,r.alone);n.has(s)||n.set(s,r.id)}return{rows:I,standsFor:O,convertedInto:u,written:n,keys:i,said:p}}function N(e){let o=new Map;for(let{from:c,to:t,how:i,forLines:d}of e){let n=[c,t,i,d?"lines":""].join("|"),a=o.get(n)??{from:c,to:t,how:i,forLines:d,prices:0};a.prices++,o.set(n,a)}return[...o.values()]}function $(e){let o=new Map;for(let{from:c,to:t,prices:i}of e){let d=`${c} \u2192 ${t}`;o.set(d,(o.get(d)??0)+i)}return[...o].map(([c,t])=>`${t} ${c}`).join(", ")}function H(e){return T(N(e))}function T(e){let o=(t,i)=>e.filter(d=>d.forLines===t&&d.how===i);return[[o(!1,"replaced"),"price(s) in a currency the target does not hold active replaced by the source's own price in the currency written, for the same product and price book"],[o(!1,"converted"),"no price in the currency written in the source for the same product and price book, written in it at the amount converted at the source's rates"],[o(!0,"replaced"),"price(s) replaced by the source's own price in the currency of the record their lines belong to, for the same product and price book"],[o(!0,"converted"),"no price in the currency of the record their lines belong to in the source for the same product and price book, written in it at its amount converted"],[e.filter(t=>t.how==="none"),"no price in the currency of the record their lines belong to in the source for the same product and price book, and the price goes in another currency for other lines: the target refuses the lines of a record in it"]].filter(([t])=>t.length>0).map(([t,i])=>`${$(t)}: ${i}`)}export{A as a,F as b,K as c,k as d,h as e,Y as f,W as g,G as h,N as i,H as j,T as k};
7
+ import{r as L}from"./chunk-ICIYL45C.mjs";import{Cc as b,rc as C,tc as R,yc as S,zc as m}from"./chunk-ZQO5PDX5.mjs";var A="PricebookEntryId",F=Object.fromEntries([["OpportunityLineItem","Opportunity"],["QuoteLineItem","Quote"],["OrderItem","Order"],["ContractLineItem","ServiceContract"]].map(([e,o])=>[e,{record:o,field:L[e]}]));function K(e,o,c){if(!e.has(C))return[];let t=new Map;for(let{sourceObject:n,targetObject:a}of c)t.set(n,[...t.get(n)??[],a]);let i=n=>{let a=new Set,l=[C];for(;l.length>0;){let u=l.pop();if(u===n)return!0;a.has(u)||(a.add(u),l.push(...t.get(u)??[]))}return!1};return[...new Set(o.flatMap(n=>F[n]?.record??[]))].filter(n=>e.has(n)&&!i(n)).map(n=>({sourceObject:n,targetObject:C,relationshipName:`${n}Before${C}`,type:"lookup",required:!0}))}function k(e,o){return[e[R],e[S],o?e[m]:""].map(c=>String(c??"")).join("|")}function h(e,o){return`${e}|${o}`}function Y(e){return h([e.book,e.product,e.model].join("|"),e.currency)}function v(e){let o=e[b];return typeof o=="string"&&o!==""?o:void 0}function x(e){let o=e.wanted??new Map,c=e.prices.flatMap(i=>{let d=i.Id,n=v(i);if(typeof d!="string"||n===void 0)return[];let a=e.writtenIn(n),l=new Set(o.get(d)??[]);l.size===0&&!e.active.has(n)&&a!==void 0&&l.add(a);let u=i[R]===e.standardBookId;return[{row:i,id:d,read:n,alone:a,own:l,standard:u}]}),t=new Map;for(let{row:i,read:d,alone:n,own:a,standard:l}of c){if(l)continue;let u=a.size>0?a:n!==void 0?[n]:[],w=h(k({...i,[R]:e.standardBookId},e.sellingModels),d),p=t.get(w)??new Set;for(let y of u)p.add(y);t.set(w,p)}return c.map(({row:i,id:d,read:n,alone:a,own:l,standard:u})=>{let w=k(i,e.sellingModels),p=new Set(o.get(d)??[]);if(u)for(let y of t.get(h(w,n))??[])p.add(y);if(p.size===0)for(let y of l)p.add(y);return{row:i,id:d,key:w,read:n,alone:a,targets:[...p]}})}function _(e,o){let c=new Map;for(let t of e){if(t.alone!==t.read||!o.has(t.read))continue;let i=h(t.key,t.read);c.has(i)||c.set(i,t)}return c}function W(e){let o=x(e),c=_(o,e.active),t=new Map;for(let{row:i,key:d,targets:n}of o)for(let a of n){let l=h(d,a);c.has(l)||t.has(l)||t.set(l,{book:String(i[R]??""),product:String(i[S]??""),model:e.sellingModels?String(i[m]??""):"",currency:a})}return[...t.values()]}function G(e,o){let c=x(e),t=_(c,e.active),i=new Map(c.map(r=>[r.id,r.key])),d=new Map;for(let r of o){let s=r.Id,f=v(r);if(typeof s!="string"||f===void 0||e.writtenIn(f)!==f)continue;let g=k(r,e.sellingModels),P=h(g,f);if(t.has(P))continue;let M=d.get(P);M!==void 0&&!(r.IsActive===!0&&M.IsActive!==!0)||(d.set(P,r),i.set(s,g))}let n=new Map,a=new Set,l=new Set,u=new Map,w=new Set,p=[],y=(r,s,f)=>{s!==r.read&&p.push({from:r.read,to:s,how:f,forLines:s!==r.alone})},E=[];for(let r of c)for(let s of r.targets){let f=h(r.key,s),g=t.get(f);if(g){n.set(f,g.id),a.add(g.id),g!==r&&y(r,s,"replaced");continue}let P=d.get(f);if(P){n.set(f,String(P.Id)),l.add(P),y(r,s,"replaced");continue}E.push({price:r,to:s})}for(let{price:r,to:s}of E){let f=h(r.key,s);n.has(f)?y(r,s,"replaced"):!a.has(r.id)&&!w.has(r.id)?(w.add(r.id),n.set(f,r.id),s!==r.alone&&u.set(r.id,s),y(r,s,"converted")):y(r,s,"none")}let O=new Map,I=[],B=new Map(c.map(r=>[r.row,r]));for(let r of e.prices){let s=B.get(r);if(!s||s.targets.length===0||a.has(s.id)||w.has(s.id)){I.push(r);continue}let f=s.targets.map(g=>n.get(h(s.key,g))).find(g=>g!==void 0&&g!==s.id);if(f===void 0){I.push(r);continue}O.set(s.id,f)}I.push(...o.filter(r=>l.has(r)));for(let r of c){if(r.targets.length>0||r.alone===void 0)continue;let s=h(r.key,r.alone);n.has(s)||n.set(s,r.id)}return{rows:I,standsFor:O,convertedInto:u,written:n,keys:i,said:p}}function N(e){let o=new Map;for(let{from:c,to:t,how:i,forLines:d}of e){let n=[c,t,i,d?"lines":""].join("|"),a=o.get(n)??{from:c,to:t,how:i,forLines:d,prices:0};a.prices++,o.set(n,a)}return[...o.values()]}function $(e){let o=new Map;for(let{from:c,to:t,prices:i}of e){let d=`${c} \u2192 ${t}`;o.set(d,(o.get(d)??0)+i)}return[...o].map(([c,t])=>`${t} ${c}`).join(", ")}function H(e){return T(N(e))}function T(e){let o=(t,i)=>e.filter(d=>d.forLines===t&&d.how===i);return[[o(!1,"replaced"),"price(s) in a currency the target does not hold active replaced by the source's own price in the currency written, for the same product and price book"],[o(!1,"converted"),"no price in the currency written in the source for the same product and price book, written in it at the amount converted at the source's rates"],[o(!0,"replaced"),"price(s) replaced by the source's own price in the currency of the record their lines belong to, for the same product and price book"],[o(!0,"converted"),"no price in the currency of the record their lines belong to in the source for the same product and price book, written in it at its amount converted"],[e.filter(t=>t.how==="none"),"no price in the currency of the record their lines belong to in the source for the same product and price book, and the price goes in another currency for other lines: the target refuses the lines of a record in it"]].filter(([t])=>t.length>0).map(([t,i])=>`${$(t)}: ${i}`)}export{A as a,F as b,K as c,k as d,h as e,Y as f,W as g,G as h,N as i,H as j,T as k};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b}from"./chunk-VGW4MXXZ.mjs";import"./chunk-DBFJB2B6.mjs";import"./chunk-NTOVCTRS.mjs";export{b as AnonymizationEngine,a as MissingHashSaltError};
7
+ import{a,b}from"./chunk-ZRUDYB7O.mjs";import"./chunk-QIRO4HTE.mjs";import"./chunk-NTOVCTRS.mjs";export{b as AnonymizationEngine,a as MissingHashSaltError};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{e as $}from"./chunk-7FFGJWHN.mjs";import{A as F,C as A}from"./chunk-CION3VMZ.mjs";import{c as M}from"./chunk-HF6LAK3G.mjs";var k=class{avgSecondsPerApiCall;batchStrategy;constructor(u){this.avgSecondsPerApiCall=u?.avgSecondsPerApiCall??.5,this.batchStrategy=new M}generate(u){let a=u.nodes.filter(o=>o.included);if(a.length===0)return{waves:[],totalRecords:0,totalApiCalls:0,estimatedDurationSeconds:0,cycleResolutions:[]};let{edges:c,components:t}=G(u),i=this.computeTopoLevels(c,t),l=new Map;for(let o of a){let e=i.get(o.objectApiName)??o.level,h=l.get(e);h?h.push(o.objectApiName):l.set(e,[o.objectApiName])}let n=[...l.keys()].sort((o,e)=>o-e),s=new Map(a.map(o=>[o.objectApiName,o])),g=n.map((o,e)=>{let h=l.get(o)??[],v=0,b=0,w=0;for(let N of h){let j=s.get(N);if(!j)continue;v+=j.recordCount;let x=this.batchStrategy.resolve(j.batchStrategy,j.recordCount),C=$(x,j.recordCount).batchCount;b+=C;let O=C*this.avgSecondsPerApiCall;O>w&&(w=O)}return{order:e,objectApiNames:h,totalRecords:v,estimatedDurationSeconds:w,estimatedApiCalls:b}}),r=this.detectCycles(u,c,t),p=g.reduce((o,e)=>o+e.totalRecords,0),f=g.reduce((o,e)=>o+e.estimatedApiCalls,0),m=g.reduce((o,e)=>o+e.estimatedDurationSeconds,0);return{waves:g,totalRecords:p,totalApiCalls:f,estimatedDurationSeconds:m,cycleResolutions:r}}computeTopoLevels(u,a){let c=new Map;a.forEach((n,s)=>{for(let g of n)c.set(g,s)});let t=new Map;for(let n of u){let s=c.get(n.sourceObject),g=c.get(n.targetObject);if(s===void 0||g===void 0||s===g)continue;let r=t.get(s);r?r.push(g):t.set(s,[g])}let i=a.map(()=>0);for(let n=a.length-1;n>=0;n--)for(let s of t.get(n)??[])i[s]=Math.max(i[s],i[n]+1);let l=new Map;for(let[n,s]of c)l.set(n,i[s]);return l}detectCycles(u,a,c){let t=c.filter(n=>n.length>1);if(t.length===0)return[];let i=new Map(A(u).map((n,s)=>[n.objectApiName,s])),l=n=>i.get(n)??0;return t.map(n=>{let s=new Set(n),g=[...n].sort((e,h)=>l(e)-l(h)),r=a.filter(e=>s.has(e.sourceObject)&&s.has(e.targetObject)&&l(e.targetObject)<l(e.sourceObject)),p=r.filter(e=>e.required===!0);if(p.length>0){let e=[...new Set(p.map(b=>b.targetObject))],h=[...new Set(p.map(b=>b.sourceObject))],v=e.length===1;return{objects:g,strategy:"unbreakable",description:`The run cannot break this cycle: ${y(p.map(S))} may not be left empty, and no order writes ${y(h)} first. ${y(e)} ${v?"is":"are"} refused, and what cannot be written without ${v?"it":"them"} is skipped.`}}let f=r.filter(e=>e.insertOnly!==!0),m=r.filter(e=>e.insertOnly===!0),o=[...f.length>0?[`${y(f.map(S))} left empty at insert and filled in by the second pass`]:[],...m.length>0?[`${y(m.map(S))} left empty for good: only an insert sets ${m.length===1?"it":"them"}, and no order writes ${y([...new Set(m.map(e=>e.sourceObject))])} first`]:[]];return{objects:g,strategy:"nullable_lookup",description:`Written in this order, with ${o.join(", and ")}.`}})}};function G(d){let u=d.nodes.filter(t=>t.included).map(t=>t.objectApiName),a=new Set(u),c=d.edges.filter(t=>t.sourceObject!==t.targetObject&&a.has(t.sourceObject)&&a.has(t.targetObject)&&F(t));return{edges:c,components:R(u,c)}}function R(d,u){let a=new Map;for(let r of d)a.set(r,[]);for(let r of u)a.get(r.sourceObject)?.push(r.targetObject);let c=0,t=new Map,i=new Map,l=new Set,n=[],s=[],g=r=>{let p=[];for(t.set(r,c),i.set(r,c),c++,n.push(r),l.add(r),p.push({v:r,neighbors:a.get(r)??[],i:0});p.length>0;){let f=p[p.length-1];if(f.i<f.neighbors.length){let e=f.neighbors[f.i++];t.has(e)?l.has(e)&&i.set(f.v,Math.min(i.get(f.v),t.get(e))):(t.set(e,c),i.set(e,c),c++,n.push(e),l.add(e),p.push({v:e,neighbors:a.get(e)??[],i:0}));continue}let m=f.v;p.pop();let o=p[p.length-1];if(o&&i.set(o.v,Math.min(i.get(o.v),i.get(m))),i.get(m)===t.get(m)){let e=[],h;do h=n.pop(),l.delete(h),e.push(h);while(h!==m);s.push(e)}}};for(let r of d)t.has(r)||g(r);return s}function S(d){return`${d.targetObject}'s lookup to ${d.sourceObject}`}function y(d){return d.length<=1?d.join(""):`${d.slice(0,-1).join(", ")} and ${d[d.length-1]}`}export{k as a,R as b};
7
+ import{e as $}from"./chunk-3XG25GTF.mjs";import{m as F,o as A}from"./chunk-7PY3VQP3.mjs";import{c as M}from"./chunk-HF6LAK3G.mjs";var k=class{avgSecondsPerApiCall;batchStrategy;constructor(u){this.avgSecondsPerApiCall=u?.avgSecondsPerApiCall??.5,this.batchStrategy=new M}generate(u){let a=u.nodes.filter(o=>o.included);if(a.length===0)return{waves:[],totalRecords:0,totalApiCalls:0,estimatedDurationSeconds:0,cycleResolutions:[]};let{edges:c,components:t}=G(u),i=this.computeTopoLevels(c,t),l=new Map;for(let o of a){let e=i.get(o.objectApiName)??o.level,h=l.get(e);h?h.push(o.objectApiName):l.set(e,[o.objectApiName])}let n=[...l.keys()].sort((o,e)=>o-e),s=new Map(a.map(o=>[o.objectApiName,o])),g=n.map((o,e)=>{let h=l.get(o)??[],v=0,b=0,w=0;for(let N of h){let j=s.get(N);if(!j)continue;v+=j.recordCount;let x=this.batchStrategy.resolve(j.batchStrategy,j.recordCount),C=$(x,j.recordCount).batchCount;b+=C;let O=C*this.avgSecondsPerApiCall;O>w&&(w=O)}return{order:e,objectApiNames:h,totalRecords:v,estimatedDurationSeconds:w,estimatedApiCalls:b}}),r=this.detectCycles(u,c,t),p=g.reduce((o,e)=>o+e.totalRecords,0),f=g.reduce((o,e)=>o+e.estimatedApiCalls,0),m=g.reduce((o,e)=>o+e.estimatedDurationSeconds,0);return{waves:g,totalRecords:p,totalApiCalls:f,estimatedDurationSeconds:m,cycleResolutions:r}}computeTopoLevels(u,a){let c=new Map;a.forEach((n,s)=>{for(let g of n)c.set(g,s)});let t=new Map;for(let n of u){let s=c.get(n.sourceObject),g=c.get(n.targetObject);if(s===void 0||g===void 0||s===g)continue;let r=t.get(s);r?r.push(g):t.set(s,[g])}let i=a.map(()=>0);for(let n=a.length-1;n>=0;n--)for(let s of t.get(n)??[])i[s]=Math.max(i[s],i[n]+1);let l=new Map;for(let[n,s]of c)l.set(n,i[s]);return l}detectCycles(u,a,c){let t=c.filter(n=>n.length>1);if(t.length===0)return[];let i=new Map(A(u).map((n,s)=>[n.objectApiName,s])),l=n=>i.get(n)??0;return t.map(n=>{let s=new Set(n),g=[...n].sort((e,h)=>l(e)-l(h)),r=a.filter(e=>s.has(e.sourceObject)&&s.has(e.targetObject)&&l(e.targetObject)<l(e.sourceObject)),p=r.filter(e=>e.required===!0);if(p.length>0){let e=[...new Set(p.map(b=>b.targetObject))],h=[...new Set(p.map(b=>b.sourceObject))],v=e.length===1;return{objects:g,strategy:"unbreakable",description:`The run cannot break this cycle: ${y(p.map(S))} may not be left empty, and no order writes ${y(h)} first. ${y(e)} ${v?"is":"are"} refused, and what cannot be written without ${v?"it":"them"} is skipped.`}}let f=r.filter(e=>e.insertOnly!==!0),m=r.filter(e=>e.insertOnly===!0),o=[...f.length>0?[`${y(f.map(S))} left empty at insert and filled in by the second pass`]:[],...m.length>0?[`${y(m.map(S))} left empty for good: only an insert sets ${m.length===1?"it":"them"}, and no order writes ${y([...new Set(m.map(e=>e.sourceObject))])} first`]:[]];return{objects:g,strategy:"nullable_lookup",description:`Written in this order, with ${o.join(", and ")}.`}})}};function G(d){let u=d.nodes.filter(t=>t.included).map(t=>t.objectApiName),a=new Set(u),c=d.edges.filter(t=>t.sourceObject!==t.targetObject&&a.has(t.sourceObject)&&a.has(t.targetObject)&&F(t));return{edges:c,components:R(u,c)}}function R(d,u){let a=new Map;for(let r of d)a.set(r,[]);for(let r of u)a.get(r.sourceObject)?.push(r.targetObject);let c=0,t=new Map,i=new Map,l=new Set,n=[],s=[],g=r=>{let p=[];for(t.set(r,c),i.set(r,c),c++,n.push(r),l.add(r),p.push({v:r,neighbors:a.get(r)??[],i:0});p.length>0;){let f=p[p.length-1];if(f.i<f.neighbors.length){let e=f.neighbors[f.i++];t.has(e)?l.has(e)&&i.set(f.v,Math.min(i.get(f.v),t.get(e))):(t.set(e,c),i.set(e,c),c++,n.push(e),l.add(e),p.push({v:e,neighbors:a.get(e)??[],i:0}));continue}let m=f.v;p.pop();let o=p[p.length-1];if(o&&i.set(o.v,Math.min(i.get(o.v),i.get(m))),i.get(m)===t.get(m)){let e=[],h;do h=n.pop(),l.delete(h),e.push(h);while(h!==m);s.push(e)}}};for(let r of d)t.has(r)||g(r);return s}function S(d){return`${d.targetObject}'s lookup to ${d.sourceObject}`}function y(d){return d.length<=1?d.join(""):`${d.slice(0,-1).join(", ")} and ${d[d.length-1]}`}export{k as a,R as b};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a}from"./chunk-YKKRIEH4.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as TransformPipeline};
7
+ import{a}from"./chunk-TMA34QMA.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as TransformPipeline};
@@ -0,0 +1,7 @@
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 xe}from"./chunk-Q3DY7TO2.mjs";import{a as Pe,b as Te,c as je,d as Oe,f as Me}from"./chunk-M6P5ZZLE.mjs";import{Ca as Be,Ea as B,Fa as Qe,Ha as We,Z as De,ha as Le,ja as qe,la as Ie,pa as U,wa as Ve,xa as Ue}from"./chunk-JFNLKHY6.mjs";import{b as E}from"./chunk-CA5NAXSU.mjs";import{O as Fe,Od as Ge,Q as ve,R as Ne,S as _e,T as Ae,U as Ce,V as Se,W as Ee,ja as $e}from"./chunk-ZQO5PDX5.mjs";import{e as X,l as ee}from"./chunk-WZQEK4WT.mjs";var v=class extends Error{};function ct(e){let r=[],n=0;for(;n<e.length;){let t=e.slice(n),s=/^\s+/.exec(t);if(s){n+=s[0].length;continue}if(t.startsWith("/*")){let d=e.indexOf("*/",n+2);if(d<0)throw new v("an unclosed comment");n=d+2;continue}let l=t[0];if(l==="'"||l==='"'){let d=1;for(;d<t.length&&t[d]!==l;)d+=t[d]==="\\"?2:1;if(d>=t.length)throw new v("an unclosed text");r.push(t.slice(0,d+1)),n+=d+1;continue}let f=/^(?:\d+(?:\.\d+)?|[A-Za-z_$][A-Za-z0-9_$.]*)/.exec(t);if(f){r.push(f[0]),n+=f[0].length;continue}let p=/^(?:&&|\|\||==|!=|<>|<=|>=|[=<>+\-*/^&!(),])/.exec(t);if(!p)throw new v(`an unexpected character: ${t[0]}`);r.push(p[0]),n+=p[0].length}return r}var Ke=[new Set(["||"]),new Set(["&&"]),new Set(["=","==","<>","!=","<",">","<=",">="]),new Set(["+","-","&"]),new Set(["*","/"]),new Set(["^"])];function dt(e){let r=ct(e),n=0,t=()=>r[n],s=u=>{if(r[n]!==u)throw new v(`${u} expected`);n++},l=u=>{if(u>=Ke.length)return f();let o=l(u+1);for(let a=t();a!==void 0&&Ke[u].has(a);a=t())n++,o={kind:"binary",op:a,left:o,right:l(u+1)};return o},f=()=>{if(t()==="!")return n++,{kind:"not",arg:f()};if(t()==="-"||t()==="+"){let u=r[n++],o=f();return u==="-"?{kind:"negative",arg:o}:o}return p()},p=()=>{let u=r[n++];if(u===void 0)throw new v("the formula ends early");if(u==="("){let a=l(0);return s(")"),a}if(u.startsWith("'")||u.startsWith('"'))return{kind:"literal",value:`text:${u.slice(1,-1)}`};if(/^\d/.test(u))return{kind:"literal",value:`number:${Number(u)}`};if(!/^[A-Za-z_$]/.test(u))throw new v(`${u} out of place`);if(t()==="("){n++;let a=[];if(t()!==")")for(a.push(l(0));t()===",";)n++,a.push(l(0));return s(")"),{kind:"call",name:u.toUpperCase(),args:a}}let o=u.toUpperCase();return o==="TRUE"||o==="FALSE"||o==="NULL"?{kind:"literal",value:o.toLowerCase()}:{kind:"reference",name:u.toLowerCase()}},d=l(0);if(n!==r.length)throw new v(`${r[n]} out of place`);return d}function $(e){switch(e.kind){case"call":return e.name==="PRIORVALUE"&&e.args.length===1?$(e.args[0]):{...e,args:e.args.map($)};case"binary":return{...e,left:$(e.left),right:$(e.right)};case"not":case"negative":return{...e,arg:$(e.arg)};default:return e}}function N(e){switch(e.kind){case"call":return`${e.name}(${e.args.map(N).join(",")})`;case"binary":{let r=e.op==="=="?"=":e.op==="!="?"<>":e.op,n=[N(e.left),N(e.right)];return(r==="="||r==="<>")&&n.sort(),`(${n[0]} ${r} ${n[1]})`}case"not":return`NOT(${N(e.arg)})`;case"negative":return`-(${N(e.arg)})`;case"literal":return e.value;case"reference":return e.name}}var ze=e=>e==="true"?"false":e==="false"?"true":"unknown";function O(e){return e.kind==="call"&&e.name==="AND"?e.args.flatMap(O):e.kind==="binary"&&e.op==="&&"?[...O(e.left),...O(e.right)]:[e]}function M(e){return e.kind==="call"&&e.name==="OR"?e.args.flatMap(M):e.kind==="binary"&&e.op==="||"?[...M(e.left),...M(e.right)]:[e]}function te(e){if(e.kind==="not"){let r=te(e.arg);return{condition:r.condition,holds:!r.holds}}if(e.kind==="call"&&e.name==="NOT"&&e.args.length===1){let r=te(e.args[0]);return{condition:r.condition,holds:!r.holds}}return e.kind==="binary"&&(e.op==="<>"||e.op==="!=")?{condition:N({...e,op:"="}),holds:!1}:{condition:N(e),holds:!0}}function ne(e){if(e.kind==="literal"){if(e.value==="true")return"true";if(e.value==="false")return"false"}}function R(e){let r=ne(e);if(r)return r;if(e.kind==="not")return ze(R(e.arg));if(e.kind==="call")switch(e.name){case"ISCHANGED":return"false";case"ISNEW":return"true";case"NOT":return e.args.length===1?ze(R(e.args[0])):"unknown";case"AND":return He(O(e));case"OR":return Ze(M(e));case"IF":{if(e.args.length!==3)return"unknown";let[n,t,s]=e.args,l=R(n);if(l==="true")return R(t);if(l==="false")return R(s);let f=R(t);return f===R(s)?f:"unknown"}default:return"unknown"}return e.kind==="binary"?e.op==="&&"?He(O(e)):e.op==="||"?Ze(M(e)):ft(e):"unknown"}function He(e){let r=e.map(R);if(r.includes("false"))return"false";let n=new Map;for(let t of e){let{condition:s,holds:l}=te(t),f=n.get(s);if(f!==void 0&&f!==l)return"false";n.set(s,l)}return r.every(t=>t==="true")?"true":"unknown"}function Ze(e){let r=e.map(R);return r.includes("true")?"true":r.every(n=>n==="false")?"false":"unknown"}function ft(e){let r=e.op==="="||e.op==="==",n=e.op==="<>"||e.op==="!=";if(N(e.left)===N(e.right))return n||e.op==="<"||e.op===">"?"false":"unknown";if(!r&&!n)return"unknown";let t=ne(e.left)??R(e.left),s=ne(e.right)??R(e.right);return t==="unknown"||s==="unknown"?"unknown":t===s===r?"true":"false"}function Ye(e){try{return R($(dt(e)))==="false"}catch(r){if(r instanceof v)return!1;throw r}}var nt=25,W=20,ie=W*De,G=4,Je=10,pt=2e3,gt=.8,Xe=["validationRules","validationRuleFormulas","duplicateRules","duplicateRuleActions","userPermissions","permissionSets","targetFields","sourceFields","apiBudget"];function mt(e){return typeof e!="object"||e===null?null:{optional:e.optionalFilter===!0}}function Bt(e){return{name:e.name,type:String(e.type),createable:e.createable===!0,nillable:e.nillable!==!1,defaultedOnCreate:e.defaultedOnCreate===!0,referenceTo:(e.referenceTo??[]).filter(r=>typeof r=="string"),picklistValues:(e.picklistValues??[]).filter(r=>r?.active!==!1&&typeof r?.value=="string").map(r=>r?.value),lookupFilter:mt(e.filteredLookupInfo)}}function oe(e){return`SELECT Id, ValidationName, NamespacePrefix, ErrorDisplayField, ErrorMessage, EntityDefinition.QualifiedApiName FROM ValidationRule WHERE Active = true AND EntityDefinition.QualifiedApiName IN (${e.map(n=>`'${n}'`).join(", ")})`}function ht(e){return`SELECT QualifiedApiName, Label FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${x.test(e)?e:""}'`}function q(e){return`SELECT Metadata FROM ValidationRule WHERE Id = '${e}'`}var yt="SELECT DeveloperName, MasterLabel, NamespacePrefix, SobjectType FROM DuplicateRule WHERE IsActive = true",ae=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,x=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,wt=ee({DailyApiRequests:ee({Max:X(),Remaining:X()}).loose()}).loose(),y=e=>typeof e=="string"?e:"";function le(e){if(typeof e!="object"||e===null)return;let r=e.QualifiedApiName;return typeof r=="string"&&r!==""?r:void 0}function Q(e,r){return e?`${e}__${r}`:r}function L(e){return typeof e=="string"?[e]:Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function bt(e){return{...e,nodes:e.nodes.map(r=>r.leftOutByUser===!0?{...r,included:!0}:r)}}function se(e,r){let n=y(e).trim(),t=n.slice(n.lastIndexOf(".")+1);if(x.test(t))return r?r.find(s=>s.name.toLowerCase()===t.toLowerCase())?.name:t}function rt(e){let r=Ve({filterFormula:e}).filter(t=>t.bypass).map(t=>t.name),n=Ue(e).map(t=>t.value===void 0?t.reference:`${t.reference} = '${t.value}'`);return{bypasses:[...r.map(t=>`$Permission.${t}`),...n],permissions:r}}function Rt(e,r={}){let n=r.maxRecordsPerObject,t=e.nodes.filter(d=>d.included),s=$e(r)?"atMost":"exact",l=t.map(d=>d.recordCountUnknown===!0?(n===void 0?s="unknown":s==="exact"&&(s="atMost"),{...d,recordCount:n??0}):{...d,recordCount:n===void 0?d.recordCount:Math.min(d.recordCount,n)}),f=new xe().generate({...e,nodes:l}).totalApiCalls,p=l.reduce((d,u)=>d+Math.max(1,Math.ceil(u.recordCount/pt)),0);return{writes:f,reads:p,bound:s}}function P(e){let{idValue:r,...n}=e;return{id:Fe(e.kind,e.objectApiName,e.field,e.recordType,r??e.value),source:"metadata",rows:0,...n}}function ue(e){return e?{field:e}:{}}function Qt(e){return async r=>Ie(await e.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(qe(`/services/data/v${e.version}`,r)),headers:{"Content-Type":"application/json"}}),r.length)}async function kt(e,r,n){let t=e.filter(({id:s})=>ae.test(s));t.length!==0&&await U(r,[{queries:t.map(({id:s,rule:l})=>({soql:q(s),retrieve:{sobject:"ValidationRule",id:s},take:f=>{let p=f[0]?.Metadata,d=typeof p=="object"&&p!==null?p.errorConditionFormula:void 0;typeof d=="string"&&Ye(d)&&(l.onChangeOnly=!0)},refused:()=>{}})),requests:W}],G,n)}async function Ft(e,r,n,t,s){let l=[...new Set(r)].filter(m=>x.test(m));if(l.length===0)return[];let f=new Map(l.map(m=>[m.toLowerCase(),m])),p=new Map(l.map((m,b)=>[m,b])),d=await e(oe(l)),u=new Map,o=async(m,b)=>{let k=se(b,void 0);if(!n)return k;let F=u.get(m);F||(F=n(m).catch(()=>[]),u.set(m,F));let C=y(b).trim().toLowerCase();if(!C)return;let _=k?.toLowerCase(),S=await F;return S.length===0?k:S.find(A=>A.name.toLowerCase()===_)?.name??S.find(A=>A.label?.trim().toLowerCase()===C)?.name},h=(await Promise.all(d.map(async m=>{let b=le(m.EntityDefinition),k=b===void 0?void 0:f.get(b.toLowerCase()),F=y(m.ValidationName);return!k||!F?[]:[{id:y(m.Id),rule:{objectApiName:k,name:Q(y(m.NamespacePrefix),F),message:y(m.ErrorMessage),...ue(await o(k,m.ErrorDisplayField))}}]}))).flat().sort((m,b)=>(p.get(m.rule.objectApiName)??0)-(p.get(b.rule.objectApiName)??0)||m.rule.name.localeCompare(b.rule.name));return t&&await kt(h,t,s),h.map(({rule:m})=>m)}async function Wt(e,r,n,t){let s=[...new Set(r)].filter(a=>x.test(a));if(s.length===0)return{rules:[],notRead:0,requests:0};let l=new Map(s.map(a=>[a.toLowerCase(),a])),f=await e(oe(s)),p=f.requests,d=f.records.flatMap(a=>{let h=le(a.EntityDefinition),m=h===void 0?void 0:l.get(h.toLowerCase()),b=y(a.ValidationName);return!m||!b?[]:[{id:y(a.Id),objectApiName:m,name:Q(y(a.NamespacePrefix),b),read:!1,permissions:[]}]}),u=d.filter(a=>ae.test(a.id)),o=(a,h)=>{let m=typeof h=="object"&&h!==null?h.errorConditionFormula:void 0;typeof m=="string"&&(a.read=!0,a.permissions=rt(m).permissions)};return n?p+=await U(n,[{queries:u.slice(0,ie).map(a=>({soql:q(a.id),retrieve:{sobject:"ValidationRule",id:a.id},take:h=>o(a,h[0]?.Metadata),refused:()=>{}})),requests:W}],G,t):await B(u.slice(0,nt).map(a=>async()=>{try{let h=await e(q(a.id));p+=h.requests,o(a,h.records[0]?.Metadata)}catch{p++}}),G),{rules:d.filter(a=>a.permissions.length>0).map(({objectApiName:a,name:h,permissions:m})=>({objectApiName:a,name:h,permissions:m})),notRead:d.filter(a=>!a.read).length,requests:p}}function Kt(e,r,n){let t=async s=>(await e(ht(s))).flatMap(l=>typeof l.QualifiedApiName=="string"?[{name:l.QualifiedApiName,...typeof l.Label=="string"?{label:l.Label}:{}}]:[]);return s=>Ft(e,s,t,r,n)}var et=class{deps;constructor(r){this.deps=r}async read(r,n,t,s={}){let l=new Set(s.excludedObjects??[]),f=Qe(bt(t),l),p=[];if(f.length===0)return{gaps:[],unread:[],requests:0};let d=0,u=(i,c,g)=>{p.push({part:i,reason:c,...g!==void 0?{objectApiName:g}:{}})},o=new Map(f.map(i=>[i.toLowerCase(),i])),a=i=>i===void 0?void 0:o.get(i.toLowerCase()),h=new Map(f.map((i,c)=>[i,c])),m=f.filter(i=>x.test(i)),b=[],k=[],F,C,_=new Map,S=new Map,A=new Set,I=(i,c,g)=>async()=>{try{let w=await c();d+=w.requests,g(w.records)}catch(w){d++,u(i,E(w))}},ce=(i,c,g,w)=>async()=>{try{let{fields:J,sent:lt,createable:ut}=await this.deps.describeFields(i,c);lt&&d++,w.set(c,J),w===_&&ut===!1&&A.add(c)}catch(J){d++,u(g,`${c}: ${E(J)}`,c)}};await B([...m.length>0?[I("validationRules",()=>this.deps.toolingQuery(n,oe(m)),i=>{b=i})]:[],I("duplicateRules",()=>this.deps.query(n,yt),i=>{k=i}),async()=>{try{d++,F=await this.deps.readLimits(n)}catch(i){C=E(i)}},...f.flatMap(i=>[ce(n,i,"targetFields",_),ce(r,i,"sourceFields",S)])],G);let T=b.flatMap(i=>{let c=a(le(i.EntityDefinition)),g=y(i.ValidationName);if(!c||!g)return[];let w=y(i.Id);return[{id:ae.test(w)?w:null,name:Q(y(i.NamespacePrefix),g),objectApiName:c,...ue(se(i.ErrorDisplayField,_.get(c))),message:y(i.ErrorMessage),formula:"notRead",bypasses:[],permissions:[]}]}).sort((i,c)=>(h.get(i.objectApiName)??0)-(h.get(c.objectApiName)??0)||i.name.localeCompare(c.name)),{toolingQueries:j,toolingRetrieves:de}=this.deps,K=T.filter(i=>i.id!==null).slice(0,j?ie:nt);for(let i of T)i.id===null&&(i.formula="unreadable");let z=k.flatMap(i=>{let c=a(y(i.SobjectType)),g=Q(y(i.NamespacePrefix),y(i.DeveloperName));return!c||!y(i.DeveloperName)?[]:[{objectApiName:c,developerName:g,label:y(i.MasterLabel)||g,fullName:`${y(i.SobjectType)}.${g}`}]}),fe=new Map,pe=[];for(let i=0;i<z.length;i+=Je)pe.push(z.slice(i,i+Je).map(c=>c.fullName));let V,H,ge=(i,c)=>{let g=typeof c=="object"&&c!==null?c.errorConditionFormula:void 0;if(typeof g!="string"){i.formula="unreadable";return}i.formula="read",Object.assign(i,rt(g));let w=se(c.errorDisplayField,_.get(i.objectApiName));w&&(i.field=w)},it=async()=>{if(!j||K.length===0)return;let i=await U(c=>j(n,c),[{queries:K.map(c=>({soql:q(c.id),retrieve:{sobject:"ValidationRule",id:c.id},take:g=>ge(c,g[0]?.Metadata),refused:g=>{c.formula="unreadable",V??=g}})),requests:W}],G,de&&(c=>de(n,c)));d+=i},me=new Map,Z={},he=[...A].filter(i=>x.test(i)),ot=async()=>{let[i,c]=await Promise.all([Oe((g,w)=>this.deps.toolingQuery(g,w),n,he),this.deps.createFacts?this.deps.createFacts(n).then(g=>({facts:g,requests:0})).catch(()=>({facts:{},requests:0})):je(this.deps,n)]);d+=i.requests+c.requests;for(let[g,w]of i.answered)me.set(g,w);Z=c.facts};await B([...he.length>0?[ot]:[],...j?[it]:[],...(j?[]:K).map(i=>async()=>{try{let c=await this.deps.toolingQuery(n,q(i.id));d+=c.requests,ge(i,c.records[0]?.Metadata)}catch(c){d++,i.formula="unreadable",V??=E(c)}}),...pe.map(i=>async()=>{try{d++;for(let c of await this.deps.readDuplicateRules(n,i)){if(typeof c!="object"||c===null)continue;let g=c,w=y(g.fullName);w&&fe.set(w.toLowerCase(),g)}}catch(c){H??=E(c)}})],G),V!==void 0&&u("validationRuleFormulas",V),H!==void 0&&u("duplicateRuleActions",H);let Y=new Set,ye=!1;T.some(i=>i.permissions.length>0)&&await I("userPermissions",()=>this.deps.query(n,Le),i=>{ye=!0;for(let c of i)Y.add(Be(y(c.NamespacePrefix),y(c.DeveloperName)))})();let we=[...new Set(T.flatMap(i=>i.permissions.filter(c=>!Y.has(c.toLowerCase()))))],at=we.length>0?await We(we,async i=>{let c=[];return await I("permissionSets",()=>this.deps.query(n,i),g=>{c=g})(),c},()=>p.some(i=>i.part==="permissionSets")):void 0,be=[...T.map(i=>At(i,ye?Y:void 0,at)),...z.map(i=>Ct(i,fe.get(i.fullName.toLowerCase()))),...f.flatMap(i=>{if(A.has(i))return[_t(i,Pe(i,Z,me.get(i.toLowerCase())),_.get(i)??[],Z)];let c=_.get(i),g=S.get(i);return c&&g?St(i,c,g,s):[]})],Re=wt.safeParse(F),ke=C===void 0&&Re.success?Re.data.DailyApiRequests:void 0;return ke||u("apiBudget",C??"the limits the org answered hold no DailyApiRequests"),be.push(Et(t,s,f[0],ke)),{gaps:Ae(be),unread:vt(p,h),requests:d}}};function vt(e,r){let n=t=>t===void 0?-1:r.get(t)??r.size;return[...e].sort((t,s)=>n(t.objectApiName)-n(s.objectApiName)||Xe.indexOf(t.part)-Xe.indexOf(s.part)||(t.reason<s.reason?-1:t.reason>s.reason?1:0)).map(({part:t,reason:s})=>({part:t,reason:s}))}var Nt={platform:"object_platform_only",setup:"object_setup_only",feature:"object_feature_off",parent:"object_through_parent",user:"object_not_createable"};function _t(e,r,n,t){let s=r==="parent"?Me(n,t):[];return P({kind:Nt[r],severity:Te(r)?"info":"blocking",objectApiName:e,...s.length>0?{detail:{editOn:s}}:{},decisions:["exclude_object"]})}function At(e,r,n){let t=r?e.permissions.filter(f=>r.has(f.toLowerCase())):[],s=t.length>0?[]:e.permissions.flatMap(f=>{let p=n?.find(d=>d.permission.toLowerCase()===f.toLowerCase());return p?[Ce(p)]:[]}),l=e.field?["leave_empty","ignore"]:["ignore"];return P({kind:"validation_rule",severity:t.length>0?"info":"warning",objectApiName:e.objectApiName,...ue(e.field),idValue:e.name,detail:{rule:e.name,message:e.message,formula:e.formula,...e.bypasses.length>0?{bypasses:e.bypasses}:{},...t.length>0?{heldBypasses:t}:{},...s.length>0?{assign:s}:{}},decisions:l,...e.field?{defaultDecision:"leave_empty"}:{}})}function Ct(e,r){let n=y(r?.actionOnInsert).toLowerCase(),t=n==="block"||n==="allow"?n:"unknown",s=L(r?.operationsOnInsert).map(f=>f.toLowerCase());return P({kind:"duplicate_rule",severity:t==="allow"?"info":"warning",objectApiName:e.objectApiName,idValue:e.developerName,detail:{rule:e.label,developerName:e.developerName,action:t,...t==="allow"?{alert:s.includes("alert")}:{},...t==="allow"?{report:s.includes("report")}:{}},decisions:t==="allow"?["ignore"]:["ignore","exclude_object"],...t==="allow"?{defaultDecision:"ignore"}:{}})}function St(e,r,n,t){let s=o=>o.toLowerCase(),l=new Set((t.fieldExclusions?.[e]??[]).map(s)),f=new Map(Object.entries(t.fieldMappings?.[e]??{}).map(([o,a])=>[s(o),s(a)])),p=new Set([...f].filter(([o])=>!l.has(o)).map(([,o])=>o)),d=new Map(n.map(o=>[s(o.name),o])),u=o=>{let a=s(o);if(p.has(a))return;let h=d.get(a);return h?l.has(a)||f.has(a)?"excluded":h.createable?void 0:"notCreateableInSource":"notInSource"};return r.flatMap(o=>{let a=u(o.name);if(o.createable&&!o.nillable&&!o.defaultedOnCreate&&a)return[P({kind:"required_field_missing",severity:"blocking",objectApiName:e,field:o.name,detail:{type:o.type,reason:a,...o.referenceTo.length>0?{referenceTo:o.referenceTo}:{},...o.picklistValues.length>0?{values:o.picklistValues}:{}},decisions:["set_default","exclude_object"]})];if(o.type==="reference"&&o.lookupFilter&&!a){let h=o.nillable;return[P({kind:"lookup_filter",severity:"warning",objectApiName:e,field:o.name,detail:{referenceTo:o.referenceTo,optional:h,filterOptional:o.lookupFilter.optional},decisions:h?["leave_empty","ignore"]:["ignore","exclude_object"],...h?{defaultDecision:"leave_empty"}:{}})]}return[]})}function Et(e,r,n,t){let s=e.nodes[0]?.objectApiName??n,l=Rt(e,r),f=l.writes+l.reads,p="warning";if(t&&l.bound!=="unknown"){let d=f>t.Remaining,u=t.Max-t.Remaining+f>gt*t.Max;p=d&&l.bound==="exact"?"blocking":d||u?"warning":"info"}return P({kind:"api_budget",severity:p,objectApiName:s,detail:{calls:f,writes:l.writes,reads:l.reads,estimate:l.bound,...t?{max:t.Max,remaining:t.Remaining}:{budgetRead:!1}},decisions:["ignore"]})}var $t={blocking:"BLOCKING",warning:"warning",info:"info"},Gt=new Set(["picklist_value_refused","dependent_value_invalid","picklist_value_absent","currency_inactive"]),xt=new Set(["record_type_unmapped","record_type_unavailable"]);function st(e,r,n=[e.id]){if(ve(r.ignoredGaps,e.id,n)!==void 0)return"left as it is";let t=e.objectApiName;if(r.excludedObjects?.includes(t))return`${t} left out of the run`;let s=new Set(e.decisions),{field:l,value:f}=e;if(s.has("skip_rows")&&Ne((r.skippedRows??[]).filter(o=>o.object===t),e.id,n))return"these rows held back";if(Gt.has(e.kind)&&l!==void 0&&f!==void 0&&(s.has("map_value")||s.has("leave_empty"))){let o=(r.picklistValueMappings??[]).filter(h=>h.object===t&&h.field===l&&h.from===f),a=_e(o,e,n);if(a?.to===null&&s.has("leave_empty"))return"the field left empty in these rows";if(a&&a.to!==null&&s.has("map_value"))return`written as "${a.to}"`}let p=xt.has(e.kind)?e.value??e.recordType:void 0;if(p!==void 0&&s.has("map_record_type")){let o=r.recordTypeMappings?.find(a=>a.object===t&&a.from===p);if(o)return o.to===null?"written with the object's default record type":`written as record type ${o.to}`}if(l===void 0)return;let d=o=>o.object===t&&o.field===l,u=s.has("set_default")?r.defaultValues?.find(d):void 0;if(u)return`default "${String(u.value)}"`;if(s.has("truncate")&&r.truncateFields?.some(d))return"cut to the field's length";if(s.has("leave_empty")&&r.fieldExclusions?.[t]?.includes(l))return"the field left out of the rows"}function zt(e,r){let n=e.gaps.map(t=>t.id);return{...e,gaps:e.gaps.map(t=>{let s=st(t,r,n);return s===void 0?t:{...t,answeredBy:s}})}}function tt(e,r,n,t){if(t)return`the mute lifts it (${t.permission}, in ${t.permissionSet}): ${re(e,!0)}`;let s=r?st(e,r,n):void 0;return s===void 0?`${$t[e.severity]}: ${re(e)}`:`answered by the run's decision: ${s} \u2014 ${re(e)}`}var Pt={validationRules:"the validation rules",validationRuleFormulas:"the formulas of some validation rules",duplicateRules:"the duplicate rules",duplicateRuleActions:"what the duplicate rules do on insert",userPermissions:"the custom permissions of the user the run writes as",permissionSets:"the permission sets that hold a bypass of a validation rule the user the run writes as does not",targetFields:"the fields of an object in the target",sourceFields:"the fields of an object in the source",apiBudget:"the daily API requests left"},Tt={notInSource:"the source has no such field",notCreateableInSource:"the source cannot give it",excluded:"the run leaves it out"},D=e=>typeof e=="number"?String(e):"?";function re(e,r=!1){let n=e.detail??{};switch(e.kind){case"required_field_missing":return`required field ${e.field??""} (${y(n.type)}): only the target requires it, and the run does not write it (${Tt[y(n.reason)]??y(n.reason)}): every row is refused unless it is given a value`;case"validation_rule":{let t=e.field?` on ${e.field}`:"",s=[...L(n.bypasses).map(f=>`not when ${f}`),...L(n.heldBypasses).length>0?[`kept quiet for this run: the user it writes as holds ${L(n.heldBypasses).join(", ")}`]:[],...n.formula==="notRead"?["formula not read"]:[],...n.formula==="unreadable"?["formula unreadable"]:[],...e.field&&!r?[`a row it refuses goes again without ${e.field}`]:[]],l=y(n.message)?`: "${y(n.message)}"`:"";return`validation rule "${y(n.rule)}"${t}${l}${s.length>0?` (${s.join("; ")})`:""}`}case"duplicate_rule":{let t=`duplicate rule "${y(n.rule)}"`;if(n.action==="block")return`${t}: blocks an insert it matches: a row it matches is refused, whatever allowSave says`;if(n.action==="allow"){let s=[n.alert===!0?"an alert":"",n.report===!0?"a report":""].filter(Boolean).join(" and ");return`${t}: allows an insert it matches${s?`, with ${s}`:""}: the run saves it (allowSave=true)`}return`${t}: what it does on insert was not read: a rule that blocks refuses a row it matches`}case"lookup_filter":return`lookup filter on ${e.field??""}: not checked before the run; `+(n.optional===!0?"a lookup it refuses is left empty":"the lookup is required, and a row it refuses is refused");case"object_not_createable":return"the user the run writes as may not create its records in the target: every row is skipped, after the objects written before it, unless the object is left out";case"object_platform_only":return"no user can create its records in the target, the platform writes them itself: the run skips every row of it";case"object_setup_only":return"no user can create its records in the target, not even one with Modify All Data, and no permission set gives Create on it: setup the org keeps as records, or the platform's own; the run skips every row of it";case"object_feature_off":return"even a user with Modify All Data may not create its records in the target, though a permission set can give Create on it: a feature or licence the target has not turned on for that user keeps it closed; turn it on, or every row is skipped, after the objects written before it, unless the object is left out";case"object_through_parent":{let t=L(n.editOn);return`no permission set gives Create on it: ${t.length>0?`the user the run writes as creates its records with Edit on ${t.join(" and ")}, which they hang from, or no user can`:"the records they hang from may open it to the user the run writes as, or no user can: read as a user with Modify All Data, the target would tell"}; every row is skipped, after the objects written before it, unless the object is left out`}case"api_budget":{let t=`about ${D(n.calls)} call(s) (${D(n.writes)} write(s) of 200 rows, ${D(n.reads)} read(s))`,s=n.estimate==="atMost"?`at most ${t}, counted on whole tables`:n.estimate==="unknown"?"an unknown number of calls: an object was never counted":t,l=n.budgetRead===!1?"the daily requests left could not be read":`${D(n.remaining)} of ${D(n.max)} daily requests left`;return`API budget: the run takes ${s}; ${l}`}default:return e.kind}}function jt(e,r,n){return Se(e).map(({permission:t,permissionSet:s,others:l})=>{if(!s)return` ${t}: no permission set of ${r} holds it: an admin creates one that includes it`;let f=l.length>0?`; also held by ${l.map(d=>d.name).join(", ")}`:"",p=n?`: ${Ge(s.name,r,n)}`:"";return` ${t}: held by permission set ${s.name}, the smallest${f}${p}`})}function Ht(e,r,n={}){let t=[`target gaps: what ${r} holds against the rows, read from its metadata`],s=e.gaps.map(u=>u.id),l=e.gaps.filter(u=>u.kind==="api_budget"),f=e.gaps.filter(u=>u.kind!=="api_budget"),p=[...new Set(f.map(u=>u.objectApiName))].sort((u,o)=>u.localeCompare(o));for(let u of p){t.push(` ${u}`);for(let o of f.filter(a=>a.objectApiName===u)){let a=Ee(o,n.lifted);t.push(` ${tt(o,n.decisions,s,a)}`),a||t.push(...jt(o,r,n.username))}}f.length===0&&t.push(e.unread.length>0?" nothing found in what could be read":" no validation rule, duplicate rule, field only the target requires or lookup filter");for(let u of l)t.push(` ${tt(u,n.decisions,s)}`);let d=f.filter(u=>u.detail?.formula==="notRead").length;d>0&&t.push(` ${d} validation rule formula(s) not read: the read takes ${n.formulasBound??ie} at most`);for(let{part:u,reason:o}of e.unread)t.push(` ${Pt[u]??u} could not be read: ${o}`);return t.push(` read in ${e.requests} request(s) to ${r}`),t}export{nt as a,W as b,ie as c,Bt as d,oe as e,ht as f,q as g,yt as h,rt as i,Rt as j,Qt as k,Ft as l,Wt as m,Kt as n,et as o,st as p,zt as q,Ht as r};