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
@@ -1,15 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as ht,b as on,c as sn}from"./chunk-66NMFCWX.mjs";import{a as cn}from"./chunk-LWW4U276.mjs";import{a as Rr,b as fn}from"./chunk-XCA5AONB.mjs";import{a as pn,e as kr,i as yr}from"./chunk-WR2GIKWE.mjs";import{Aa as cr,Ba as pr,Bc as un,Ca as ur,Dc as vr,b as mt,d as Zt,e as en,f as tn,j as se,k as nn,l as jt,m as Mt,n as xe,o as M,pa as Zn,qa as er,ra as tr,s as de,sa as nr,ta as rr,ua as or,uc as le,va as sr,wa as Et,xa as ar,ya as ir,yc as gr,za as dr}from"./chunk-2CNCDM56.mjs";import{d as mr}from"./chunk-SIHORWVK.mjs";import{a as gt,b as Yn}from"./chunk-CE6ZDGBB.mjs";import{a as Tr,b as mn,c as Ir,d as gn,e as bt,f as kt,g as Nr,h as hn,i as Pr,j as bn,k as kn}from"./chunk-B5QQJ4SI.mjs";import{k as Ar}from"./chunk-F43REJDZ.mjs";import{S as hr,U as br,l as lr}from"./chunk-JPUR2CFX.mjs";import{d as wr}from"./chunk-T63U4OZJ.mjs";import{a as ln}from"./chunk-YYZL7UGV.mjs";import{B as Sr,r as Re}from"./chunk-MFG4MUIO.mjs";import{b as an,c as rt,d as dn,h as fr}from"./chunk-GSKCGQIP.mjs";import{a as Be}from"./chunk-5LFSFYFJ.mjs";import{c as $t,e as oe,f as Ct,i as rn,p as Or}from"./chunk-VYXMVJL5.mjs";import{d as Xn,e as Qn,g as Vn,h as Jn}from"./chunk-INIT2UKJ.mjs";import{p as W,q as ft,t as Pt}from"./chunk-A527W53V.mjs";import{a as qn,f as Yt,h as Nt}from"./chunk-TZE3Y7IQ.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{$b as Jt,Ha as Wn,Ia as Un,Id as Gn,Ja as Hn,Wb as De,ec as nt,hc as Kn,ic as St,w as _n,yb as Vt}from"./chunk-TTFDUKUS.mjs";import{b as Q,f as Bn,k as Ke,l as Ge,q as Fn,v as Qt}from"./chunk-7EANH5PY.mjs";var lo={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},fo={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function yn(s){return s==="production"?{...lo}:{...fo}}function wn(s){return s?"sandbox":"production"}var ot="IsPersonAccount",mo=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function go(s){if(mo.has(s))return s;if(s.endsWith("__c"))return`${s.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(s))return`Person${s}`}function An(s){let e=(r,o)=>r.fieldPattern.toLowerCase().startsWith(`${o.toLowerCase()}.`)?r.fieldPattern.slice(o.length+1):void 0,t=new Set(s.flatMap(r=>{let o=e(r,W);return o===void 0?[]:[o.toLowerCase()]})),n=[];for(let r of s){let o=e(r,ft),a=o===void 0?void 0:go(o);a===void 0||t.has(a.toLowerCase())||(t.add(a.toLowerCase()),n.push({...r,fieldPattern:`${W}.${a}`}))}return n}function $r(s){if(s.objectApiName.toLowerCase()!==W.toLowerCase()||!s.fields.some(p=>p.name===ot))return;let e=new Map(s.fields.map(p=>[p.name.toLowerCase(),p])),t=new Set(s.kept.map(p=>p.fieldApiName.toLowerCase())),n=[],r=new Set,o=[],a=(p,u)=>{t.add(u.name.toLowerCase()),r.add(u.name),n.push({...p,objectApiName:W,fieldApiName:u.name})};for(let p of s.derived){let u=e.get(p.fieldApiName.toLowerCase());if(!u){o.push(p.fieldApiName);continue}t.has(u.name.toLowerCase())||a(p,u)}let i=s.fields.filter(p=>Kn(p.name)&&p.updateable===!0&&p.calculated!==!0&&!t.has(p.name.toLowerCase())),d=new Map,c=i.map(p=>{let u=jr(p.name);return d.set(u,p),{...p,name:u,label:p.label??p.name,type:p.type??"string"}});for(let p of kr(s.detector,ft,c)){let u=d.get(p.field.name);!u||t.has(u.name.toLowerCase())||a({objectApiName:W,fieldApiName:u.name,method:yr({...p.field,name:u.name}),config:{}},u)}return{rules:n,personOnly:r,unseen:o}}function Cr(s,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return s.filter(n=>!t.has(jr(n).toLowerCase()))}function jr(s){return s.endsWith("__pc")?`${s.slice(0,-4)}__c`:s.startsWith("Person")&&!s.includes("__")?s.slice(6):s}function Mr(s,e,t,n){if(s.toLowerCase()!==W.toLowerCase())return[...t];let r=Pt(e,!1);return t.filter(o=>!St(W,o.fieldApiName,r)&&(r==="person"||!n.has(o.fieldApiName)))}import{randomBytes as Po}from"node:crypto";var yt=[{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 zt=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,r){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let o={operationId:e,objectApiName:t,dmlType:n,recordCount:r,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,o),o}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 r=0;r<n;r++)this.operations.delete(t[r][0])}}};var ho=3e3;function Se(s){return s.slice(0,15)}function bo(s,e){let t=s??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 ko(s){let e=[],t=[],n=0;for(let r of s)t.length>0&&n+r.length+2>ho&&(e.push(t),t=[],n=0),t.push(r),n+=r.length+2;return t.length>0&&e.push(t),e}async function Er(s,e,t){let n=t.map(i=>i.Id).filter(rt),r=[...new Set(t.flatMap(i=>Object.keys(i)))].filter(i=>i.toLowerCase()!=="id");if(n.length===0||r.length===0)return{write:[...t],unchanged:0};let o=new Map;try{for(let i of ko(r))for(let d of await fr(s,e,i,n))typeof d.Id=="string"&&o.set(Se(d.Id),{...o.get(Se(d.Id)),...d})}catch(i){return{write:[...t],unchanged:0,unread:R(i)}}let a=t.filter(i=>{let d=rt(i.Id)?o.get(Se(i.Id)):void 0;return d?Object.keys(i).some(c=>c.toLowerCase()!=="id"&&!bo(i[c],d[c])):!0});return{write:a,unchanged:t.length-a.length}}async function zr(s,e,t,n){let r=Nt(e),o=new Set,a=t.filter(rt);for(let i=0;i<a.length;i+=an){let d=a.slice(i,i+an),[c]=dn(d,d.length),p=new Set,u=await s.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${c})`);for(let h of u.records){if(typeof h.Id!="string")continue;p.add(Se(h.Id)),Date.parse(String(h.LastModifiedDate??""))<=n||o.add(Se(h.Id))}let b=d.filter(h=>!p.has(Se(h)));if(b.length===0)continue;let[l]=dn(b,b.length),f=await s.query(`SELECT Id FROM ${r} WHERE Id IN (${l}) AND IsDeleted = true`,{scanAll:!0});for(let h of f.records)typeof h.Id=="string"&&o.add(Se(h.Id))}return o}function Lr(s,e){return{async*[Symbol.asyncIterator](){for await(let t of s){let n=t.filter(r=>!(rt(r.Id)&&e.has(Se(r.Id))));n.length>0&&(yield n)}}}}function Rn(s,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,r=[],o=0;for await(let i of s)for(let d of i){if(o++,!rt(d.Id)){r.push({...d});continue}let c=n.get(Se(d.Id));if(!c){n.set(Se(d.Id),{...d});continue}for(let[p,u]of Object.entries(d))p in c||(c[p]=u)}t=o;let a=[...n.values(),...r];for(let i=0;i<a.length;i+=e)yield a.slice(i,i+e)}},lines:()=>t}}var vn="anonymization:template:",Dr="anonymizationTemplates",xr=Ge({id:Q().min(1).max(100),name:Q().trim().min(1).max(Wn),description:Q().max(500),complianceFramework:Qt("custom"),rules:Ke(Fn(Hn,Ge({description:Q().max(500)}))).min(1).max(Un),saved:Qt(!0),createdAt:Q()}),Lt=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${vn}${e.id}`,e,Dr)}load(e){let t=xr.safeParse(this.configStore.get(`${vn}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(Dr))){let n=xr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${vn}${e}`)}};import{createHash as Br}from"node:crypto";var wo="anonymization:checkpoint:",Ao="anonymizationCheckpoints",qe=2e3,Tn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ro=Q().min(1).max(255),vo=Ge({id:Q().regex(Tn),fields:Ke(Ro).min(1).max(800),digest:Q().regex(/^[0-9a-f]{64}$/)}),To=Ge({objectApiName:Q().min(1).max(255),done:Bn(),afterId:Q().regex(Tn).optional(),refused:Ke(Q().regex(Tn)).max(qe),unconfirmed:Ke(vo).max(qe).optional()}),Io=Ge({id:Q().min(1).max(200),orgId:Q().min(1).max(200),templateId:Q().min(1).max(200),fingerprint:Q().regex(/^[0-9a-f]{64}$/),savedAt:Q(),objects:Ke(To),namesGiven:Q().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional()});function Dt(s,e,t){let n=s.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return Br("sha256").update(JSON.stringify(r?{rules:n,objects:e,where:r}:{rules:n,objects:e})).digest("hex")}function Oo(s){return s==null||s===""?null:typeof s=="string"?s.trim():typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)}function In(s,e){let t=[...e].sort().map(n=>[n,Oo(s[n])]);return Br("sha256").update(JSON.stringify(t)).digest("hex")}function wt(s){return s.reduce((e,t)=>e+t.refused.length,0)}var st=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let r=Io.safeParse(this.configStore.get(this.key(e,t)));if(!r.success)return;let o=r.data;if(!(o.orgId!==e||o.templateId!==t||o.fingerprint!==n))return o}save(e){if(wt(e.objects)>qe)throw new Error(`A checkpoint keeps at most ${qe} refused records; this run left ${wt(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,Ao)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${wo}${e}:${t}`}};async function So(s){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:r}=await import("node:crypto"),o=`${s}.${r(4).toString("hex")}.partial`,a=await e(o,"w"),i=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let p=0;p<c.length;){let{bytesWritten:u}=await a.write(c,p,c.length-p,null);p+=u}},close:async()=>{i=!0,await a.close(),await t(o,s)},abort:async()=>{i||await a.close().catch(()=>{}),i=!0,await n(o,{force:!0})}}}function No(s){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await s(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var xt=class s{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"?So(t.fsPath):No(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 r=s.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...r?{filters:r}:{}})}async save(e,t,n){let r=this.host??await this.defaultHost();try{let o=await s.ask(r,e,n);return o?(await r.writeFile(o,new TextEncoder().encode(t)),{status:"saved",path:o.fsPath}):{status:"cancelled"}}catch(o){return{status:"error",message:o instanceof Error?o.message:String(o)}}}async saveStream(e,t,n){let r=this.host??await this.defaultHost(),o;try{let a=await s.ask(r,e,n);if(!a)return{status:"cancelled"};let i=await r.openFile(a);o=i;let d=await t(c=>i.write(c));return await i.close(),o=void 0,{status:"saved",path:a.fsPath,result:d}}catch(a){return await o?.abort().catch(()=>{}),{status:"error",message:a instanceof Error?a.message:String(a)}}}};function Bt(s,e,t,n,r=0){s?.register(e,t,n,r);let o=!1,a=i=>{o||(o=!0,i())};return{progress:(i,d,c,p)=>{o||s?.updateProgress(e,i,d,c,p)},complete:()=>a(()=>s?.complete(e)),partial:()=>a(()=>s?.partial(e)),fail:i=>a(()=>s?.fail(e,i)),cancel:()=>a(()=>s?.cancel(e))}}var ve={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 Fe(s,e){return Object.assign(new Error(e),{code:s})}function Fr(s,e,t){let n=Gn(s);if(n==="refused")return Fe(ve.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 Fe(ve.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 _r(s,e){if(s.retries!==void 0&&s.retries>0)return{refusal:Fe(ve.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=s.where?.trim();if(t&&s.object===void 0)return{refusal:Fe(ve.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=Et.safeParse({orgId:s.orgId,templateId:s.templateId,...s.object!==void 0?{objects:[s.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let r=n.error.issues[0];return{refusal:Fe(ve.invalid,`The masking step is not one the DataOps page would run (${r.path.join(".")}: ${r.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:Fe(ve.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}function ao(s){let e=s.fields;return{name:s.name,label:s.label,labelPlural:s.labelPlural??"",keyPrefix:s.keyPrefix??null,custom:s.custom??!1,createable:s.createable,updateable:s.updateable,deletable:s.deletable,queryable:s.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:s.recordTypeInfos??[],childRelationships:s.childRelationships??[]}}var $o=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"]),Co=6e4,jo=10,Mo=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Eo(s,e){return s.slice(0,15)===e.slice(0,15)}var Wr="ORG_REPLACED_SINCE_BACKUP",zo="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",it=class extends Error{constructor(){super(zo),this.name="BackupCancelledError"}},Rt=class extends Error{constructor(e){super(`The backup could not be written to disk: ${R(e)}`),this.name="BackupWriteError"}},dt=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},jn="IsDeleted = false",Lo="SystemModstamp",io=5e4,Do=100,At=_n;function xo(s){return typeof s!="number"||!Number.isFinite(s)?io:Math.min(At,Math.max(Do,Math.floor(s)))}var at=200,Bo=1440*6e4,Fo=1440*6e4,Ur="backupRetention:since",_o="BACKUP_BUSY";function Wo(s,e){return e===0?"success":s===0?"failure":"partial"}function On(s){return Jt(s)}function Hr(s,e,t){s.length>=jo||s.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Ft(s,e,t=!1){let n=(e?.rules??[]).map(o=>o.fieldPattern.split(".")[0]).filter((o,a,i)=>i.findIndex(d=>Sn(d,o))===a);if(s.objects)return s.objects.map(o=>n.find(a=>Sn(a,o))??(Sn(o,W)?W:o));if(!e)return[];let r=[...n];return t&&vt(s,e,W)&&r.push(W),r}function Sn(s,e){return s.toLowerCase()===e.toLowerCase()}var Uo=`${ot} = true`;function vt(s,e,t){return s.objects===void 0&&t.toLowerCase()===W.toLowerCase()&&_t(e,W).length===0&&An(e.rules).length>0}function Nn(s,e,t){return vt(s,e,t)?Uo:zn(s)}async function Pn(s,e){try{return(await s.describe(W)).fields.some(t=>t.name===ot)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${R(t)}`),!1}}function _t(s,e){let t=`${e.toLowerCase()}.`;return s.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function Mn(s,e){return e.toLowerCase()===W.toLowerCase()?An(s.rules):[]}function Kr(s){let e=new Map;return{describe:t=>{let n=e.get(t)??s.describe(t);return e.set(t,n),n}}}async function Gr(s,e){return new sn(async n=>ao(await s.describe(n))).deniedOf(e.map(({objectApiName:n,rules:r})=>({objectApiName:n,operation:"update",fieldNames:r.map(o=>o.fieldPattern.includes(".")?o.fieldPattern.split(".")[1]:o.fieldPattern).filter(o=>o!=="*")})))}function qr(s,e){return _t(s,e).length>0||Mn(s,e).length>0}function $n(s){return{objectApiName:s.objectApiName,recordCount:s.recordCount,truncated:s.truncated===!0,...s.orgCount!==void 0?{orgCount:s.orgCount}:{},...s.stoppedAt?{stoppedAt:s.stoppedAt}:{},...s.notKept&&s.notKept.length>0?{notKept:[...s.notKept]}:{}}}function Cn(s,e){return s.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 r=t.orgCount!==void 0?` of ${t.orgCount}`:"",o=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${r}${o}`]}).join(", ")}var Xe=200,Ho=95,Wt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ko="NOTHING_TO_RESUME",Xr="TEMPLATE_NOT_FOUND";function Qr(s){return new Error(`Template "${s}" not found.`)}function Go(s){let e=s.Id;if(typeof e!="string"||!Wt.test(e))return[];let t=Object.keys(s).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:In(s,t)}]:[]}var qo="COUNT_FAILED",Vr="SNAPSHOT_NOT_TAKEN",Xo=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE"]),Qo=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Jr(s){if(typeof s=="object"&&s!==null){let{errorCode:e,code:t}=s;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return Qo.exec(R(s))?.[1]??"UNKNOWN"}var Yr=5;function Zr(s){return s==null?null:typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:JSON.stringify(s)}function co(s){return s.done?0:Math.max(0,s.total-s.masked-s.nothingToMask-s.refused-s.unanswered)}function Ut(s){return s.refused+s.unanswered+co(s)}function Tt(s){return s.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Ut(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function Vo(s,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:r}=Tt(s);return r===0?"success":t>0||e&&n===0?"partial":"failure"}function Jo(s,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:r}=Tt(s);return n+r>0?{outcome:"cancelled"}:{outcome:"stopped",code:rn}}function eo(s){return s.filter(e=>Ut(e)>0).map(e=>`${e.objectApiName} ${Ut(e)}`).join(", ")}function to(s){return s.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Ut(e)}))}function no(s){return s.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=co(e);return{...Ct(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function ro(s,e,t,n,r,o){return Yn(s,`SELECT ${t} FROM ${e}${En(o,r)} ORDER BY Id LIMIT ${n}`,n)}function En(s,e){let t=s?.trim(),n=[...t?[`(${Yt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function zn(s){let e=s.where?.trim();return e||void 0}function Yo(s){let e=s?.trim();return e?`(${Yt(e)}) AND ${jn}`:jn}function Zo(s){let e=new Map;for(let[t,n]of s){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(r=>Nt(r)).join(", "))}return e}function oo(s,e,t){let n=e===void 0?"more records":`${e} records`;return new dt(`${s} 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 po(s,e){return`The org stopped answering the read of ${s} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function es(s,e,t,n){let r={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},o=await s.query(e,r),a=[...o.records];for(;!o.done;){if(!o.nextRecordsUrl)throw new dt(po(n,a.length),!0);o=await s.queryMore(o.nextRecordsUrl,r),a.push(...o.records)}return a}function ts(s,e,t){let n=s[s.length-1]?.Id;if(typeof n!="string"||!Wt.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}var so=class{constructor(e,t){this.deps=e;this.saveDialog=t??new xt}deps;activeOrgOperations=new Set;writing=new Rr;dmlTracker=new zt;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Po(32).toString("hex");saveDialog;get savedTemplates(){return new Lt(this.deps.configStore)}findTemplate(e){return yt.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e){let t={...e.config};return e.ruleType==="hash"&&(t.hashSalt=this.maskingKey),t}maskingRules(e,t){return t.map(n=>({objectApiName:e,fieldApiName:n.fieldPattern.includes(".")?n.fieldPattern.split(".")[1]:n.fieldPattern,method:n.ruleType,config:this.ruleConfig(n)}))}refuseUnknownTemplate(e,t,n){M(this.deps,e,"dataops:error",t,Qr(n),{code:Xr})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}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(!Xo.has(Jr(e)))return e;let n=this.onCommandLine?"narrow --where to an indexed field, such as a range of CreatedDate, and mask the rest in other runs":`mask them in slices from the command line, each a run of its own (sandforge dataops anonymize --object ${t} --where) on an indexed field, such as a range of CreatedDate`;return new Error(`${R(e)} The org gave up counting the ${t} records the run would mask: ${n}. Nothing was masked.`)}duplicatesSettleMs=Tr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return Ir({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-7YDNUBO5.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>Re(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return nt(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,r,o,a){let i=this.targetAutomation;return Pr({act:n,target:this.orgNameOf(t),objects:r,org:Nr(e,d=>new Or(Co).withTimeout("dataops automation",()=>i.read(t,d)),Jt(this.deps.orgManager.getOrg(t))==="production"),accord:o,mayMute:this.muteOffered,muteLeases:this.muteLeases,...a?{voice:a}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let r of Sr(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${r}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(sr,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await this.readAct(n,t.orgId,t.act,t.objects,t,kt(t)),o=se(this.deps,e,"dataops:automation:response",{...r.answer});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} refusals=${r.answer.refusals.length}`)}catch(n){M(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 o of this.deps.configStore.getKeysByPrefix("backup:"))n.add(o.slice(7).split(":")[0]);let r=await t.sweep(n,Bo,e);r.length>0&&this.deps.log(`[INFO] Removed ${r.length} backup file(s) whose backup never saved its metadata: `+r.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+R(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!$o.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(fn(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(fn(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 r=await e.describe(t),o=r.fields.filter(d=>d.type===hr).map(d=>d.name),a=o.length>0&&n&&!await n()?o:[];return{select:r.fields.filter(d=>!a.includes(d.name)).map(d=>d.name).join(", "),notKept:a}}async maskedFields(e,t,n,r=[]){let o=(await e.describe(t)).fields,a=new Map(o.map(l=>[l.name.toLowerCase(),l.name])),i=[],d=[];for(let l of n){let f=a.get(l.fieldApiName.toLowerCase());f!==void 0?i.push({...l,fieldApiName:f}):l.fieldApiName!=="*"&&!d.includes(l.fieldApiName)&&d.push(l.fieldApiName)}let c=$r({objectApiName:t,fields:o,kept:i,derived:r,detector:this.deps.infraServices?.piiDetector??new wr});if(c&&c.unseen.length>0){let l=await e.describe(ft).then(f=>f.fields,()=>{});for(let f of Cr(c.unseen,l))d.includes(f)||d.push(f)}let p=c?[...i,...c.rules]:i,u=p.map(l=>l.fieldApiName).filter((l,f,h)=>l!=="Id"&&h.indexOf(l)===f),b=c&&u.length>0&&!u.includes(ot);return{rules:p,select:["Id",...u,...b?[ot]:[]].join(", "),missing:d,rulesOf:c?l=>Mr(t,l,p,c.personOnly):()=>p}}async countRows(e,t,n,r){let a=(await e.query(`SELECT COUNT() FROM ${t}${En(r,n)}`)).totalSize;if(typeof a!="number"||!Number.isInteger(a)||a<0)throw new Error(`The org did not say how many records ${t} holds.`);return a}async organizationIdOf(e){try{let n=(await gt(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&Mo.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${R(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Zn,e,"dataops:error",this.deps);if(!t)return;let n=e.id,r=await this.takeBackup(n,t,e.type);if("error"in r){M(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=se(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map($n),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 backupForPipeline(e,t){let n=e.fields?Zo(e.fields):void 0,r=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 r){let o=R(r.error);throw this.endBackupNotTaken(e.operationId,r),r.cancelled?new cn(o):r.error instanceof Error?r.error:new Error(o)}return r}endBackupNotTaken(e,t){if(t.cancelled){xe(this.deps,e,{aborted:!0});return}de(this.deps,e,R(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,r){let o={module:"dataops",operation:n},a=`backup:${t.orgId}`;if(this.activeOrgOperations.has(a)){let m=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${m}`),{error:new Error(m),retryable:!1,context:o}}this.activeOrgOperations.add(a);let i=()=>{},d,c=new AbortController,p=()=>c.abort();r?.aborted&&c.abort(),r?.addEventListener("abort",p,{once:!0});let u=this.backupCap(),b=this.backupWriter(e);this.backupsWriting.add(e);let l=[],f,h,w,T=(m,$,O,B)=>{Mt(this.deps,e,m,$,O,B),w?.progress(m,$,O,B)};try{if(this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:o};this.dmlTracker.register(e,"backup","insert",t.objects.length);let m=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager);h=m,t.onConnection?.(m);let $=br(async E=>(await m.query(E)).records),O=this.deps.orgManager.getOrg(t.orgId),B=wn(O?.orgType==="Sandbox"||O?.orgType==="Scratch"),Z=yn(B).defaultQueryLimit,K=`Backup ${t.objects.length} object(s)`;jt(this.deps,e,"dataops",K),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",K,new Promise((E,S)=>{i=C=>{C===void 0?E():S(C instanceof Error?C:new Error(String(C)))}}),c),w=Bt(this.liveTracker,e,"dataops",K,t.objects.length);for(let E of t.objects){if(c.signal.aborted)throw new it;let S=De(E);o.objectName=S;let C={objectApiName:E,recordCount:0,truncated:!1};f=C,await this.readIntoBackup(m,S,C,b,{pageSize:Z,cap:u,select:t.fields?.get(S),where:t.wheres?.get(S),scanAll:t.scanAll?.has(S)===!0,...t.origin==="checkpoint"?{stamp:Lo}:{},whole:t.failWhenTruncated===!0,viewsEncrypted:$},c.signal,()=>{let q=Math.max(1,Math.min(C.orgCount??u,u));T(Math.round((l.length+C.recordCount/q)/t.objects.length*100),l.length,t.objects.length,`Reading ${E} (${C.recordCount} of ${q} records)`)}),f=void 0,l.push(C),C.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${S} stopped at the cap of ${u} record(s): the object holds ${C.orgCount??"more"}.`),T(Math.round(l.length/t.objects.length*100),l.length,t.objects.length,`Exported ${E} (${C.recordCount} records)`)}let F=await this.organizationIdOf(m);if(c.signal.aborted)throw new it;let P=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:F,cap:u,...t.origin?{origin:t.origin}:{}},l,b,!1);return this.pruneAfterBackup(t.orgId),xe(this.deps,e,{objects:l.map(E=>({objectApiName:E.objectApiName,recordCount:E.recordCount})),totalRecords:P.totalRecords,...P.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),P.partial?w?.partial():w?.complete(),{operationId:e,objects:l,totalRecords:P.totalRecords,partial:P.partial,timestamp:P.timestamp}}catch(m){this.dmlTracker.markFailed(e);let $=m instanceof it,O=$||m instanceof Rt||t.failWhenTruncated===!0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:u,...t.origin?{origin:t.origin}:{}},h,{taken:l,reading:f,planned:t.objects},b);O===void 0&&await b.discard().catch(K=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+R(K))});let B=O===void 0?m:new Error(`${R(m)} \u2014 the backup keeps the ${O.totalRecords} record(s) read before it stopped, listed as partial: ${Cn(O.objects)}.`);d=B,$&&this.deps.infraServices?.backgroundRegistry?.abort(e),$?w?.cancel():w?.fail(R(B));let Z=!(m instanceof dt)||m.retryable;return{error:B,retryable:Z,context:o,cancelled:$}}finally{r?.removeEventListener("abort",p),i(d),this.activeOrgOperations.delete(a),this.backupsWriting.delete(e)}}backupCap(){return xo(this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",io))}snapshotCapWay(e){let t=this.backupCap(),n=e.filter(r=>r.tally.total>At).map(r=>r.tally.objectApiName);if(n.length>0||t>=At){let r=n.length>0?n.join(", "):"the object";return this.onCommandLine?`No snapshot holds more than ${At} records of one object, and nothing raises that: mask ${r} in slices, each a run of its own with --object and a --where that selects fewer (a range of CreatedDate, say), each taking its own snapshot.`:`No snapshot holds more than 1,000,000 records of one object, and nothing raises that: mask ${r} in slices from the command line, each a run of its own (sandforge dataops anonymize --object and --where), each taking its own snapshot.`}return this.onCommandLine?`Give --max-records up to ${At} (this run held ${t}), or narrow the run with --object and --where.`:`Raise sandforge.backup.maxRecordsPerObject in Settings (this run held ${t}, 1,000,000 at most), then apply again.`}backupWriter(e){let t=this.backupRecords;if(t){let r=new Set;return{begin:async o=>{r.add(o),await t.begin(e,o).catch(a=>{throw new Rt(a)})},append:async(o,a)=>{await t.append(e,o,a).catch(i=>{throw new Rt(i)})},keep:()=>{},discard:async()=>{for(let o of r)await t.delete(e,o)}}}let n=new Map;return{begin:async r=>{n.set(r,[])},append:async(r,o)=>{n.get(r)?.push(...o)},keep:()=>{for(let[r,o]of n)this.deps.configStore.set(`backup:${e}:${r}`,o,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,r,o,a,i){let d=o.scanAll===!0,c={headers:{"Sforce-Query-Options":`batchSize=${o.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=o.select;if(p===void 0){let T=await this.selectAllFields(e,t,o.viewsEncrypted);p=T.select,T.notKept.length>0&&(n.notKept=T.notKept)}let u=d?Yo(o.where):o.where,b=`SELECT ${p} FROM ${t}${En(u,void 0)}`,l=o.stamp??Xn(b)?.stamp,f=Qn(b,l===void 0?void 0:["Id",l]),h=d||o.whole===!0?T=>es(e,T,d,t):T=>gt(e,T),w=await e.query(f?.first??b,c);if(Be(e.limitInfo,`dataops:backup query ${t}`),typeof w.totalSize=="number"&&Number.isInteger(w.totalSize)&&(n.orgCount=w.totalSize),o.whole===!0&&n.orgCount!==void 0&&n.orgCount>o.cap)throw oo(t,n.orgCount,o.cap);for(await r.begin(n.objectApiName);;){let T=o.cap-n.recordCount,m=w.records.length>T,$=m?w.records.slice(0,T):w.records,O=$;f&&l!==void 0?O=await Jn($,f,h,{stamp:l,...d?{idsWhere:jn}:{}}):f&&await Vn($,f,h);let B=w.done?void 0:w.nextRecordsUrl;if(o.whole===!0&&!w.done&&B===void 0)throw new dt(po(t,n.recordCount+O.length),!0);let Z=m||B!==void 0&&n.recordCount+O.length>=o.cap;if(Z&&o.whole===!0)throw oo(t,n.orgCount,o.cap);if(await r.append(n.objectApiName,O),n.recordCount+=O.length,Z){n.truncated=!0,n.stoppedAt="cap";return}if(B===void 0)return;if(i(),a.aborted)throw new it;w=await e.queryMore(B,c),Be(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,r){let o={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},objects:t.map($n),partial:t.some(a=>a.truncated),...r?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((a,i)=>a+i.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,o,"backups"),n.keep(),o}async keepFailedBackup(e,t,n,r){let{taken:o,reading:a}=n,i=a?[...o,{...a,truncated:!0,stoppedAt:"failure"}]:[...o],d=new Set(i.map(u=>u.objectApiName.toLowerCase())),c=n.planned.filter(u=>!d.has(u.toLowerCase())).map(u=>({objectApiName:u,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),p=[...i,...c];if(!p.every(u=>u.recordCount===0))try{let u=t?await this.organizationIdOf(t):void 0,b=this.saveBackupMeta({...e,organizationId:u},p,r,!0);return this.pruneAfterBackup(e.orgId),{...b,objects:p}}catch(u){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+R(u));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=vr(this.deps.services);if(t<=0)return;let n=e-t*Fo;try{let r=this.retentionSince(e);for(let o of this.backupMetaKeys()){let a=this.deps.configStore.get(o),i=Date.parse(a?.timestamp??"");if(!Number.isFinite(i)||i>=n||i<r||a?.origin==="checkpoint"||a?.orgId!==void 0&&this.backupBusy(a.orgId))continue;await this.removeBackup(o);let d=a?.origin==="sync"?` \u2014 the values the Sync run ${a.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${o}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:o.slice(7),days:t,...a?.timestamp!==void 0?{takenAt:a.timestamp}:{},...a?.origin==="sync"?{syncRunId:a.runId??""}:{}})}}catch(r){this.deps.log(`[WARN] the backups past their age were not removed: ${R(r)}`)}}retentionSince(e){let t=Date.parse(this.deps.configStore.get(Ur)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(Ur,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 o of n)this.deps.configStore.delete(`${e}:${o.objectApiName}`);this.deps.configStore.delete(e);let r=e.slice(7);for(let o of n)await this.backupRecords?.delete(r,o.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(rr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){M(this.deps,"backup:delete","dataops:error",e,new Error(`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`),{code:_o});return}let n=t.operationIds?new Set(t.operationIds):void 0,r=[];try{for(let a of this.backupMetaKeys()){let i=this.deps.configStore.get(a);if(i?.orgId!==t.orgId)continue;let d=i.operationId??a.slice(7);n&&!n.has(d)||(await this.removeBackup(a),r.push(d))}}catch(a){M(this.deps,"backup:delete","dataops:error",e,a);return}this.deps.log(`[INFO] Deleted ${r.length} backup(s) of org ${t.orgId}`);let o=se(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} deleted=${r.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${R(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(er,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||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($n),...a.partial?{partial:!0}:{},...a.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,a)=>a.timestamp.localeCompare(o.timestamp));let r=se(this.deps,e,"backup:list:result",{backups:n});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=le(nr,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,r=this.deps.configStore.get(n);if(!r||r.orgId!==t.orgId){M(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let o=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,i=>this.writeBackupDocument(t,r,i),["json"]);if(o.status==="error"){M(this.deps,"backup:export","dataops:error",e,new Error(o.message));return}let a=se(this.deps,e,"backup:export:result",o.status==="saved"?{operationId:t.operationId,status:"saved",path:o.path,objects:o.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} ${o.status}`)}async writeBackupDocument(e,t,n){let{operationId:r}=e,a=[["sandforgeBackupVersion",1],["operationId",r],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
8
- `);await n(`{
9
- ${a.join("")} "objects": {`);let i=[];for(let{objectApiName:d}of t.objects??[]){if(i.some(p=>p.objectApiName===d))continue;await n(`${i.length>0?",":""}
10
- ${JSON.stringify(d)}: [`);let c=0;for await(let p of await this.backupBatches(r,d))p.length!==0&&(await n(p.map((u,b)=>`${c+b>0?",":""}
11
- ${JSON.stringify(u)}`).join("")),c+=p.length);await n(c>0?`
12
- ]`:"]"),i.push({objectApiName:d,records:c})}return await n(`${i.length>0?`
13
- `:""}}
14
- }
15
- `),i}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,at);if(n)return n;let r=this.deps.configStore.get(`backup:${e}:${t}`),o=Array.isArray(r)?r:[];return{async*[Symbol.asyncIterator](){for(let a=0;a<o.length;a+=at)yield o.slice(a,a+at)}}}async firstBackupRecord(e,t,n){let r=await this.backupBatches(e,t),o=n.origin==="sync"?Rn(r,at).batches:r;for await(let a of o)if(a[0]!==void 0)return a[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let r of this.deps.configStore.getKeysByPrefix("backup:")){if(r.slice(7).includes(":"))continue;let a=this.deps.configStore.get(r);a?.orgId===e&&a.origin!=="sync"&&a.origin!=="checkpoint"&&n.push({key:r,timestamp:a.timestamp??""})}if(!(n.length<=t)){n.sort((r,o)=>r.timestamp.localeCompare(o.timestamp));for(let{key:r}of n.slice(0,n.length-t))this.removeBackup(r),this.deps.log(`[INFO] Pruned backup ${r} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let r=[];for await(let a of n){let i=a.map(c=>c.Id).filter(c=>typeof c=="string");if(i.length===0)continue;let d=i.map(c=>`'${qn(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});r.push(...c.records.map(p=>p.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${R(c)}`),{undeleted:0}}}let o=0;for(let a=0;a<r.length;a+=200){let i=await e.soap.undelete(r.slice(a,a+200));o+=i.filter(d=>d.success).length}return{undeleted:o}}refuseWithoutGuard(e,t,n,r){oe(this.deps,{...r,outcome:"stopped",source:void 0,code:mt.code}),e(new Error(mt.message),{code:mt.code}),de(this.deps,t,mt.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(or,e,"dataops:error",this.deps);if(!t)return;let n=t,r=e.id,o={module:"dataops",operation:e.type},a=`backup:${n.orgId}`;if(this.activeOrgOperations.has(a)){let h=`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`;this.deps.log(`[WARN] ${h}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(h)),de(this.deps,r,h,!1,{context:o,authored:!0});return}this.activeOrgOperations.add(a);let i,d=[],c=!1,p=new AbortController,u=()=>{},b,l,f;try{if(this.dmlTracker.isDuplicate(r)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${r}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${r}`)),de(this.deps,r,`Duplicate operation: ${r}`,!1,{context:o,authored:!0});return}this.dmlTracker.register(r,"rollback","upsert",0);let h=await Re(n.orgId,this.deps.orgRegistry,this.deps.orgManager),w=new sn(async k=>{let A=await h.describe(k);return ao(A)}),T=`backup:${n.operationId}`,m=this.deps.configStore.get(T);if(!m)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);if(m.orgId!==n.orgId){let k=nt(this.deps.orgManager.getOrg(m.orgId),m.orgId),A=nt(this.deps.orgManager.getOrg(n.orgId),n.orgId);throw new Error(`Backup ${n.operationId} was taken from org ${m.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 ${k} into ${A}, copy them with Forge or Sync.`)}i={action:"backup_restore",module:"dataops",operationId:r,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:m.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let $=this.deps.infraServices?.productionGuard;if(!$){this.refuseWithoutGuard((k,A)=>M(this.deps,"dataops:rollback","dataops:error",e,k,A),r,o,i);return}let O=[];for(let k of m.objects){let A=await this.firstBackupRecord(n.operationId,k.objectApiName,m);if(A===void 0)continue;let y=De(k.objectApiName);if(!(await w.checkCrudPermission(y,"upsert")).allowed){O.push({objectApiName:y,operation:"upsert",deniedFields:[]});continue}let{denied:be}=await w.partitionWritableFields(y,"upsert",Object.keys(A).filter(me=>me!=="attributes"));be.length>0&&O.push({objectApiName:y,operation:"upsert",deniedFields:be})}if(O.length>0){let k=on(O);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${r}: ${k}`),oe(this.deps,{...i,outcome:"stopped",source:void 0,code:ht}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:ht}),de(this.deps,r,k,!1,{context:o,authored:!0});return}let B=(k,A,y,je=[])=>{oe(this.deps,{...y,outcome:"stopped",source:void 0,code:k}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(A),{code:k,...kn({alsoRefused:je})}),de(this.deps,r,A,!1,{context:o,authored:!0})},Z=await this.readAct(h,n.orgId,"restore",m.objects.map(k=>({objectApiName:k.objectApiName,records:k.recordCount})),n,kt(n)),K=bn(Z.answer);if(K){B(K.code,K.message,i,K.alsoRefused);return}f=this.duplicatesWatchOf(h,mn(Z.answer.automation,m.objects.filter(k=>k.recordCount>0).map(k=>k.objectApiName)));let F=this.deps.orgManager.getOrg(n.orgId),P={orgId:n.orgId,orgTier:On(F),operation:"upsert",objectName:m.objects.map(k=>k.objectApiName).join(", ")||"RollbackData",recordCount:m.totalRecords??0,module:"dataops"},{check:E,decision:S}=await un($,P);if(i.guard=S,(S==="refused"||S==="declined")&&oe(this.deps,{...i,outcome:"stopped",source:void 0}),S==="refused")throw en(E.blockedReason??E.impactSummary);if(S==="declined"){let k="Operation cancelled by user (confirmation declined).";M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:Zt.declined}),de(this.deps,r,k,!1,{context:o,authored:!0});return}if(m.organizationId!==void 0){let k=await this.organizationIdOf(h);if(k!==void 0&&!Eo(m.organizationId,k)){let A=nt(F,n.orgId),y=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(y?await y({alias:A,backedUpFrom:m.organizationId,now:k}):!1)){oe(this.deps,{...i,outcome:"stopped",source:void 0,code:Wr});let be=`Restore not run: ${A} answers as org ${k}, not as org ${m.organizationId}, which backup ${n.operationId} was taken from, `+(y?"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.");M(this.deps,"dataops:rollback","dataops:error",e,new Error(be),{code:Wr}),de(this.deps,r,be,!1,{context:o,authored:!0});return}}}let C=await hn(Z,r,n.acceptEmails===!0,kt(n));if("refused"in C){B(C.refused.code,C.refused.message,i);return}l=C.held,jt(this.deps,r,"dataops",`Rollback ${m.objects.length} object(s)`),c=!0,this.deps.infraServices?.backgroundRegistry?.register(r,"dataops",`Rollback ${m.objects.length} object(s)`,new Promise((k,A)=>{u=y=>{y===void 0?k():A(y instanceof Error?y:new Error(String(y)))}}),p),b=Bt(this.liveTracker,r,"dataops",`Rollback ${m.objects.length} object(s)`,m.objects.length);let q=!1,L=0,fe=0,Te=0,Qe=[],Ve=new Map,I=m.origin==="sync"&&n.includeChanged!==!0,D=Number.NEGATIVE_INFINITY,ee=!1;if(I){let k=m.runId!==void 0?await this.syncRuns?.get(m.runId).catch(y=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${R(y)}`)}):void 0,A=k?gr(k):void 0;ee=A===void 0,D=await mr({serverTime:async()=>(await h.soap.getServerTimestamp()).timestamp},A)}let X=[];for(let k=0;k<m.objects.length;k++){if(p.signal.aborted){q=!0;break}let A=m.objects[k],y=De(A.objectApiName);o.objectName=y;let je=await this.backupBatches(n.operationId,A.objectApiName),be=m.origin==="sync"?Rn(je,at):void 0,me=be?.batches??je,Ie;for await(let _ of me)if(Ie=_[0],Ie!==void 0)break;if(I&&Ie!==void 0){let _=[];for await(let ae of me)for(let te of ae)typeof te.Id=="string"&&_.push(te.Id);let ue=await zr({query:async(ae,te)=>({records:(await h.query(ae,te)).records})},y,_,D);ue.size>0&&(X.push({objectApiName:y,count:ue.size}),me=Lr(me,ue))}if(Ie===void 0){Ve.set(A.objectApiName,0),this.deps.log(`[WARN] No backup records for ${A.objectApiName}, skipping.`);continue}let Ht=Object.keys(Ie).filter(_=>_!=="attributes"),{skipped:Kt}=await w.partitionWritableFields(y,"upsert",Ht),Me=new Set(Kt.filter(_=>_.toLowerCase()!=="id").map(_=>_.toLowerCase()));Me.size>0&&this.deps.log(`[INFO] Rollback on ${y}: ${Me.size} non-writable field(s) excluded from the payload \u2014 ${[...Me].sort().join(", ")}`);let It=await this.undeleteFromRecycleBin(h,y,me);It.undeleted>0&&this.deps.log(`[INFO] Rollback on ${y}: ${It.undeleted} record(s) brought back from the recycle bin`),o.batchSize=at;let Ee=0,Ze=0,G=0,We=0;for await(let _ of me){if(p.signal.aborted){q=!0;break}We+=_.length;let ue=_.map(J=>{let we=y===W?Pt(J,!1):void 0,ze={};for(let[tt,Gt]of Object.entries(J))tt!=="attributes"&&(Me.has(tt.toLowerCase())||we!==void 0&&St(W,tt,we)||(ze[tt]=Gt));return ze}),ae=ue;if(n.rewriteAll!==!0){let J=await Er({query:async we=>{let ze=await h.query(we);return{totalSize:ze.totalSize,records:ze.records}}},y,ue);J.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${y}: the org's values could not be read, so ${ue.length} row(s) are written back without comparing \u2014 ${J.unread}`),ae=J.write,G+=J.unchanged}if(ae.length===0)continue;f.beforeWrite(y);let te;try{te=await h.sobject(y).upsert(ae,"Id",{headers:Vt()})}catch(J){throw ln(J)==="may-have-written"&&f.wrote(y,ae.map(we=>we.Id)),J}let et=Array.isArray(te)?te:[te];f.wrote(y,et.flatMap((J,we)=>J.success?[ae[we]?.Id]:[]));for(let J of et){if(J.success){Ee++;continue}Ze++,Hr(Qe,y,J.errors)}}if(Be(h.limitInfo,`dataops:rollback upsert ${y}`),Ve.set(A.objectApiName,be&&!q?be.lines():We),L+=Ee,fe+=Ze,Te+=G,d.push({...Ct(y),updated:Ee,failed:Ze}),q)break;let pt=`Restored ${y} (${Ee}/${We}${G>0?`, ${G} unchanged`:""})`,Oe=Math.round((k+1)/m.objects.length*100);Mt(this.deps,r,Oe,k+1,m.objects.length,pt),b.progress(Oe,k+1,m.objects.length,pt)}let N=X.reduce((k,A)=>k+A.count,0),ce=Wo(L,fe),V=q&&fe===0||N>0&&ce==="success"?"partial":ce;i&&(c=!1,oe(this.deps,{...i,...q?L+fe>0?{outcome:"cancelled"}:{outcome:"stopped",code:rn}:{outcome:V},objects:d}));let Ce=await this.releaseMute(l,n.orgId);l=void 0;let he=await f.read();q?(this.deps.infraServices?.backgroundRegistry?.abort(r),xe(this.deps,r,{aborted:!0,totalRestored:L,totalFailed:fe,totalUnchanged:Te})):xe(this.deps,r,{status:V,totalRestored:L,totalFailed:fe,totalUnchanged:Te}),this.dmlTracker.markCompleted(r),q?b.cancel():V==="failure"?b.fail(`The org refused the ${fe} record(s)`):V==="partial"?b.partial():b.complete();let pe=Cn(m.objects,Ve),Je=(q?`Rollback cancelled: ${L} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:fe>0?`Rollback ${V}: ${L} restored, ${fe} rejected by the org`:N>0?`Rollback partial: ${L} records restored`:`Rollback completed: ${L} records restored`)+(Te>0?`; ${Te} already held the backup's values and were not written`:"")+(N>0?`; ${N} changed or deleted since the Sync run were left as they are `+(ee?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),Ne=bt(he,this.orgNameOf(n.orgId),"restore"),Ye=pe===""?Je:`${Je}. The backup held only part of the org's records, and the rest were left as they are: ${pe}`,ct=Ne?`${Ye}. ${Ne}`:pe===""?Ye:`${Ye}.`,_e=se(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:V,message:ct,totalRestored:L,totalFailed:fe,totalUnchanged:Te,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...N>0?{keptChanged:{total:N,objects:X,...ee?{runNotKept:!0}:{}}}:{},errors:Qe,...pe!==""?{partial:!0}:{},...q?{cancelled:!0}:{},...Ce?{mutedAutomation:Ce}:{},...he?{duplicates:he}:{}});this.deps.broker.postToWebview(_e),this.deps.log(`[TX] ${_e.type} id=${_e.id} status=${V}`),(fe>0||pe!==""||q||N>0||gn(he))&&nn(this.deps,V==="failure"?"error":"warning","Restore",`${ct}${Qe[0]?` \u2014 e.g. ${Qe[0].message}`:""}`)}catch(h){this.dmlTracker.markFailed(r),await this.releaseMute(l,n.orgId),l=void 0;let w=await f?.read(),T=bt(w,this.orgNameOf(n.orgId),"restore");M(this.deps,"dataops:rollback","dataops:error",e,T?new Error(`${R(h)} ${T}`):h,{code:tn(h),...w?{extraPayload:{duplicates:w}}:{}}),de(this.deps,r,R(h),!0,{context:o}),b?.fail(R(h))}finally{await this.releaseMute(l,n.orgId),this.activeOrgOperations.delete(a),u(),c&&i&&oe(this.deps,{...i,outcome:"failure",objects:d})}}async snapshotBeforeMasking(e,t,n,r,o){let a=new Map,i=new Map;try{for(let p of r){if(p.tally.total===0)continue;p.where!==void 0&&i.set(p.tally.objectApiName,p.where);let{select:u}=await this.maskedFields(e,p.tally.objectApiName,this.maskingRules(p.objectName,p.objectRules),this.maskingRules(p.objectName,p.personRules));u!=="Id"&&a.set(p.tally.objectApiName,u)}}catch(p){return{refused:`No snapshot was taken, so nothing was masked: ${R(p)}`,retryable:!0}}if(a.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...a.keys()],...i.size>0?{wheres:i}:{},fields:a},o.origin,o.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${R(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 (${Cn(c.objects)}). `+this.snapshotCapWay(r),retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,r){if(r.length===0)return{code:ve.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 o=[],a=[];for(let d of r){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:p,missing:u}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));o.push(...u.map(b=>({objectApiName:c,fieldApiName:b}))),p.length===0&&a.push(c)}let i={fieldsNotFound:o,objectsNotCovered:a};if(o.length>0){let d=o.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:ve.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. `+(a.length>0?`No field of ${a.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:i}}if(a.length>0)return{code:ve.masksNothing,message:`The template "${t.name}" masks no field of ${a.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:i}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw Fe(ve.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=Fr(On(n),e.answer,nt(n,e.orgId));if(r)throw r;let o=_r(e,f=>this.findTemplate(f)!==void 0);if("refusal"in o)throw o.refusal;let a=crypto.randomUUID(),i,d,c,p={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,h)=>{i??={err:f,...h},this.deps.log(`[ERR] dataops:anonymize ${a} for the pipeline "${e.pipeline.name}": `+R(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>Ar(e.answer,()=>this.mask(o.asked,a,p,t)));let u=i,b=c;if(u){let f=R(u.err),h=u.err,w=u.code??(typeof h?.code=="string"?h.code:void 0),T=u.extraPayload?.snapshot,m={...w!==void 0?{code:w}:{},...T!==void 0?{snapshot:T}:{},...b?{mutedAutomation:b}:{}};throw Object.assign(w===$t?new cn(f):new Error(f),m)}let l=d;if(l===void 0)throw new Error("The masking run ended without a result.");return{operationId:a,result:b?{...l,mutedAutomation:b}:l}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Et,e,"dataops:error",this.deps);if(!t)return;let n=kt(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)=>M(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=se(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||gn(t.duplicates))&&nn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}async mask(e,t,n,r){let o,a={},i,d=async()=>(i??={released:await this.releaseMute(o,e.orgId)},i.released),c={...n,refused:(I,D)=>{if(!o){n.refused(I,D);return}a.answer??=ee=>n.refused(I,ee?{...D,extraPayload:{...D.extraPayload,mutedAutomation:ee}}:D)},ended:I=>{if(!o){n.ended(I);return}a.answer??=D=>n.ended(D?{...I,mutedAutomation:D}:I)}},p={module:"dataops",operation:c.origin},u=this.findTemplate(e.templateId),b=Ft(e,u),l={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],h=[],w=zn(e),T=u?Dt(u.rules,b,w):"",m=!1,$=!1,O=!1,B=!1,Z,K,F=new AbortController,P=()=>{},E,S,C,q=async()=>C?.read(),L=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);L?.signal.addEventListener("abort",()=>F.abort(),{once:!0});let fe=()=>F.abort();r?.aborted&&F.abort(),r?.addEventListener("abort",fe,{once:!0});let Te=async()=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:$t});let I="The masking run was cancelled before it wrote anything.";c.refused(new Error(I),{code:$t,...K?{extraPayload:{snapshot:K}}:{}}),await d(),xe(this.deps,t,{aborted:!0})},Qe=(I,D,ee)=>{E=I;let X=R(I),N=Tt(f),ce=m&&N.recordsNotMasked>0,V=bt(ee,this.orgNameOf(e.orgId)),Ce={...m?{...N,objects:to(f)}:{},...K?{snapshot:K}:{},...ee?{duplicates:ee}:{}},he=ce?`${X} \u2014 ${N.recordsProcessed} masked before it stopped; ${N.recordsNotMasked} still hold their original values (${eo(f)}).`:X;c.refused(ce||V?new Error(V?`${he} ${V}`:he):I,{code:tn(I),extraPayload:Ce}),de(this.deps,t,X,D,{context:p,extraPayload:Ce}),S?.fail(X)},Ve=()=>{B=!0;let I=new st(this.deps.configStore),{recordsNotMasked:D}=Tt(f),ee=f.reduce((X,N)=>X+N.masked+N.nothingToMask+N.refused+N.unanswered,0);try{if(D===0)return I.clear(e.orgId,e.templateId),!1;if(ee===0)return I.load(e.orgId,e.templateId,T)!==void 0;let X=h.map(N=>N.progress);return wt(X)>qe?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${wt(X)} record(s), more than a resume retries (${qe}): only a full run masks them.`),I.clear(e.orgId,e.templateId),!1):(I.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:T,savedAt:new Date().toISOString(),objects:X,...Z?{namesGiven:Z.namesGiven()}:{}}),!0)}catch(X){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+R(X)),!1}};try{let I=this.deps.infraServices?.productionGuard;if(!I){this.refuseWithoutGuard((g,j)=>c.refused(g,j),t,p,l);return}if(!u){c.refused(Qr(e.templateId),{code:Xr});return}let D=vt(e,u,W)?Ft(e,u,!0):void 0,ee=D?[T,Dt(u.rules,D,w)]:[T],X=()=>c.refused(new Error("There is nothing to resume: the run has finished since, another run of this template has stopped since, or its rules have changed. Apply masks every record of its objects."),{code:Ko}),N;if(e.resumeFrom!==void 0){let g=new st(this.deps.configStore);if(N=ee.map(j=>g.load(e.orgId,e.templateId,j)).find(j=>j?.id===e.resumeFrom),!N){X();return}}let ce=await Re(e.orgId,this.deps.orgRegistry,this.deps.orgManager),V=Kr(ce);if(D&&await Pn(V,this.deps.log)&&(b=D,T=ee[1]),N&&N.fingerprint!==T){X();return}let Ce,he=g=>{let j=Be(ce.limitInfo,g);j&&j.usagePercent>=Ho&&(Ce??=j)},pe=()=>Ce;for(let g of b){let j=_t(u,g),ie=Mn(u,g);if(j.length===0&&ie.length===0)continue;let ge=De(g),U=Nn(e,u,g);p.objectName=ge;let v=N?.objects.find(Ue=>Ue.objectApiName===ge),x={objectApiName:ge,done:v?.done??!1,...v?.afterId!==void 0?{afterId:v.afterId}:{},refused:[...v?.refused??[]],...v?.unconfirmed?.length?{unconfirmed:[...v.unconfirmed]}:{}},Pe=0;if(!x.done){try{Pe=await this.countRows(ce,ge,x.afterId,U)}catch(Ue){throw oe(this.deps,{...l,outcome:"failure",source:void 0,objects:[Ct(ge)],code:qo,details:{reason:Jr(Ue)}}),this.countGaveUp(Ue,ge)}he(`dataops:anonymize count ${ge}`),Pe===0&&(x.done=!0)}let Ot=Pe+x.refused.length+(x.unconfirmed?.length??0),ut={objectApiName:ge,total:Ot,masked:0,nothingToMask:0,refused:0,unanswered:0,done:Ot===0};f.push(ut),h.push({objectName:g,...U!==void 0?{where:U}:{},objectRules:j,personRules:ie,tally:ut,progress:x})}let Je=f.reduce((g,j)=>g+j.total,0),Ne=await this.maskingNotCovered(V,u,b,h);if(Ne){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Ne.code}),c.refused(new Error(Ne.message),{code:Ne.code,extraPayload:{...Ne.gaps}}),de(this.deps,t,Ne.message,!1,{context:p,authored:!0});return}let Ye=await Gr(V,h.filter(g=>g.tally.total>0).map(g=>({objectApiName:g.tally.objectApiName,rules:[...g.objectRules,...g.personRules]})));if(Ye.length>0){let g=on(Ye);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${g}`),oe(this.deps,{...l,outcome:"stopped",source:void 0,code:ht}),c.refused(new Error(g),{code:ht}),de(this.deps,t,g,!1,{context:p,authored:!0});return}let ct=(g,j,ie=[])=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:g}),c.refused(new Error(j),{code:g,...kn({alsoRefused:ie})}),de(this.deps,t,j,!1,{context:p,authored:!0})},_e=await this.readAct(ce,e.orgId,"masking",f.map(g=>({objectApiName:g.objectApiName,records:g.total})),c.accord,c.voice),k=bn(_e.answer);if(k){ct(k.code,k.message,k.alsoRefused);return}let A=this.duplicatesWatchOf(ce,mn(_e.answer.automation,f.filter(g=>g.total>0).map(g=>g.objectApiName)));C=A;let y=this.deps.orgManager.getOrg(e.orgId),je={orgId:e.orgId,orgTier:On(y),operation:"update",objectName:b.join(", ")||"AnonymizeData",recordCount:Je,module:"dataops"},{check:be,decision:me}=await un(I,je);if(l.guard=me,(me==="refused"||me==="declined")&&oe(this.deps,{...l,outcome:"stopped",source:void 0}),me==="refused")throw en(be.blockedReason??be.impactSummary);if(me==="declined"){let g="Operation cancelled by user (confirmation declined).";c.refused(new Error(g),{code:Zt.declined}),de(this.deps,t,g,!1,{context:p,authored:!0});return}for(let g of be.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${g}`);if(F.signal.aborted){await Te();return}let Ie=await hn(_e,t,c.accord.acceptEmails===!0,c.voice);if("refused"in Ie){ct(Ie.refused.code,Ie.refused.message);return}o=Ie.held,m=!0;let Ht=wn(y?.orgType==="Sandbox"||y?.orgType==="Scratch"),Kt=yn(Ht).defaultQueryLimit;if(e.snapshot===!0){let g=await this.snapshotBeforeMasking(V,t,e.orgId,h,{origin:c.origin,stop:F.signal});if("refused"in g&&F.signal.aborted){await Te();return}if("refused"in g){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Vr}),c.refused(new Error(g.refused),{code:Vr}),await d(),de(this.deps,t,g.refused,g.retryable,{context:p,authored:!0});return}if(K=g.taken,F.signal.aborted){await Te();return}}let Me=c.pipeline?`Pipeline anonymization with ${u.name}`:`Anonymizing with ${u.name}`;jt(this.deps,t,"dataops",Me),$=!0,O=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Me,new Promise((g,j)=>{P=ie=>{ie===void 0?g():j(ie instanceof Error?ie:new Error(String(ie)))}}),F),S=Bt(this.liveTracker,t,"dataops",Me,Je);let{AnonymizationEngine:It}=await import("./chunk-TLH7AD35.mjs"),Ee=new It(void 0,this.maskingKey);Z=Ee,N&&!(N.namesGiven!==void 0&&Ee.continueFrom(N.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 Ze=[],G=!1,We=g=>g.masked+g.nothingToMask+g.refused,pt=(g,j)=>{let ie=f.reduce((x,Pe)=>x+We(Pe),0),ge=Math.max(Je,ie),U=Math.round(ie/ge*100),v=`Anonymized ${g} (${We(j)}/${Math.max(j.total,We(j))})`;Mt(this.deps,t,U,ie,ge,v),S?.progress(U,ie,ge,v)};for(let{objectName:g,where:j,objectRules:ie,personRules:ge,tally:U,progress:v}of h){if(U.total===0)continue;if(F.signal.aborted){G=!0;break}if(pe())break;let x=U.objectApiName;p.objectName=x;let{select:Pe,rulesOf:Ot}=await this.maskedFields(V,x,this.maskingRules(g,ie),this.maskingRules(g,ge));p.batchSize=Xe;let ut=async(Y,ke,$e)=>{let Le=Y.map(Ot),Ae=Y.map((re,H)=>Ee.anonymize([re],Le[H])[0]),ne=[];Y.forEach((re,H)=>{let z={Id:re.Id};for(let ye of Le[H])pn(re[ye.fieldApiName])&&(z[ye.fieldApiName]=Ae[H][ye.fieldApiName]);Object.keys(z).length>1?ne.push(z):U.nothingToMask++});for(let re=0;re<ne.length;re+=Xe){if(F.signal.aborted)return G=!0,!0;if(pe())return!0;let H=ne.slice(re,re+Xe),z;A.beforeWrite(x);try{z=await ce.sobject(g).update(H,{headers:Vt()})}catch(He){throw ln(He)==="may-have-written"&&(U.unanswered+=H.length,$e(H,H.flatMap(Go)),A.wrote(x,H.map(lt=>lt.Id))),He}he(`dataops:anonymize update ${x}`);let ye=[],xn=Array.isArray(z)?z:[z];A.wrote(x,xn.flatMap((He,lt)=>He.success?[H[lt]?.Id]:[])),xn.forEach((He,lt)=>{if(He.success){U.masked++;return}U.refused++;let Xt=H[lt]?.Id;typeof Xt=="string"&&Wt.test(Xt)&&ye.push(Xt),Hr(Ze,x,He.errors)}),ke(H,ye),pt(g,U)}return ne.length===0&&pt(g,U),!1},Ue=v.unconfirmed??[];for(let Y=0;Y<Ue.length;Y+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Ue.slice(Y,Y+Xe),$e=ke.map(z=>`'${z.id}'`).join(", "),Le=await gt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${$e})`);he(`dataops:anonymize query ${x}`);let Ae=new Map(Le.map(z=>[String(z.Id),z])),ne=[];for(let z of ke){let ye=Ae.get(z.id);ye===void 0?U.total-=1:In(ye,z.fields)===z.digest?U.nothingToMask++:ne.push(z.id)}let re=new Set(ke.map(z=>z.id)),H=(v.unconfirmed??[]).filter(z=>!re.has(z.id));H.length>0?v.unconfirmed=H:delete v.unconfirmed,v.refused.push(...ne)}if(G||pe())break;let Dn=[...v.refused];for(let Y=0;Y<Dn.length;Y+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Dn.slice(Y,Y+Xe),$e=await gt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${ke.map(re=>`'${re}'`).join(", ")})`);he(`dataops:anonymize query ${x}`),U.total-=ke.length-$e.length;let Le=[];if(await ut($e,(re,H)=>Le.push(...H),(re,H)=>{let z=new Set(H.map(ye=>ye.id));v.refused=v.refused.filter(ye=>!z.has(ye)),v.unconfirmed=[...v.unconfirmed??[],...H]}))break;let ne=new Set(ke);v.refused=[...v.refused.filter(re=>!ne.has(re)),...Le]}if(G||pe())break;if(v.done){U.done=!0;continue}let qt=v.afterId;for(;;){if(F.signal.aborted){G=!0;break}if(pe())break;let Y=await ro(ce,x,Pe,Kt,qt,j);if(he(`dataops:anonymize query ${x}`),Y.records.length===0){U.done=!0,v.done=!0;break}let ke=Y.truncated?ts(Y.records,qt,x):void 0;if(F.signal.aborted){G=!0;break}let $e=Ae=>{let ne=Ae[Ae.length-1]?.Id;typeof ne=="string"&&Wt.test(ne)&&(v.afterId=ne)};if(await ut(Y.records,(Ae,ne)=>{v.refused.push(...ne),$e(Ae)},(Ae,ne)=>{v.unconfirmed=[...v.unconfirmed??[],...ne],$e(Ae)}))break;if(ke===void 0){U.done=!0,v.done=!0;break}qt=ke,v.afterId=ke}if(G||pe())break}let Oe=pe(),_=Vo(f,G),{recordsProcessed:ue,recordsFailed:ae,recordsNotMasked:te}=Tt(f),et=eo(f);$=!1,oe(this.deps,{...l,...Jo(f,_,G),objects:no(f)});let J=Ve();if(te>0){let g=G?"cancelled":Oe?`stopped at ${Oe.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${g}: ${te} record(s) not masked \u2014 ${et}`)}await d();let we=await q();G?(this.deps.infraServices?.backgroundRegistry?.abort(t),xe(this.deps,t,{aborted:!0,totalProcessed:ue,totalFailed:ae,totalNotMasked:te}),S?.cancel()):(xe(this.deps,t,{status:_,totalProcessed:ue,totalFailed:ae,totalNotMasked:te}),_==="failure"?S?.fail(`The org refused the ${ae} record(s)`):_==="partial"?S?.partial():S?.complete());let ze=`${te} still hold their original values (${et})`,tt=G?`Anonymization cancelled: ${ue} masked before the cancel \u2014 ${ze}.`:Oe?`Anonymization stopped at ${Oe.usagePercent}% of the org's daily API requests (${Oe.apiUsage} of ${Oe.apiLimit}): ${ue} masked \u2014 ${ze}. ${J?"Resume it":"Run it again"} once the org has requests to spare.`:ae===0?`Anonymization ${_==="success"?"completed":_}: ${ue} records processed.`:`Anonymization ${_}: ${ue} masked, ${ae} rejected by the org \u2014 those records still hold their original values.`,Gt=J&&te>0?" Resume masks only what this run left.":"",Ln=bt(we,this.orgNameOf(e.orgId)),uo=tt+Gt+(Ln?` ${Ln}`:"");c.ended({templateId:e.templateId,status:_,recordsProcessed:ue,recordsFailed:ae,recordsNotMasked:te,objects:to(f),message:uo,errors:Ze,...G?{cancelled:!0}:{},...Oe?{stoppedAtApiLimit:!0}:{},...K?{snapshot:K}:{},...o?{mutedAutomation:o.outcome}:{},...we?{duplicates:we}:{}})}catch(I){await d();let D=await q().catch(()=>{});Qe(I,!0,D)}finally{let I=await d();if(I&&c.muted?.(I),$){let D=f.some(ee=>ee.masked>0);oe(this.deps,{...l,outcome:D?"partial":"failure",objects:m?no(f):[]})}O&&!B&&Ve(),P(E),L?.release(),r?.removeEventListener("abort",fe),a.answer?.(I)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=se(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...yt,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(tr,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 r,o=()=>r??=Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Pn(d,this.deps.log)),a=[];for(let d of n?[n]:this.listedTemplates()){let c=vt({},d,W)&&await o();for(let p of Ft({},d,c))p!==""&&p!=="*"&&!a.includes(p)&&a.push(p)}let i=se(this.deps,e,"backup:objects:response",{objects:a});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} objects=${a.length}`)}catch(r){M(this.deps,"backup:objects","dataops:error",e,r)}}async plannedObjectsIn(e,t,n){let r=vt(t,n,W)&&await Pn(e,this.deps.log);return Ft(t,n,r)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(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 r=this.latestBackup(t.orgId),o=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),a=[],i=await this.plannedObjectsIn(o,t,n);for(let p of i){if(!qr(n,p))continue;let u=De(p),b=null;try{b=await this.countRows(o,u,void 0,Nn(t,n,p))}catch(f){this.deps.log(`[WARN] dataops:anonymize:coverage: ${u} not counted: ${R(f)}`)}let l=r?.objects.find(f=>f.objectApiName.toLowerCase()===u.toLowerCase());a.push({objectApiName:u,count:b,backedUp:l?.recordCount??0,truncated:l?.truncated===!0,...l?.stoppedAt?{stoppedAt:l.stoppedAt}:{}})}let d=new st(this.deps.configStore).load(t.orgId,t.templateId,Dt(n.rules,i,zn(t))),c=se(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...r?{backup:{operationId:r.operationId,timestamp:r.timestamp}}:{},objects:a,...d?{checkpoint:{id:d.id,savedAt:d.savedAt}}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} objects=${a.length}`)}catch(r){M(this.deps,"dataops:anonymize:coverage","dataops:error",e,r)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ir,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 r=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:o}=await import("./chunk-TLH7AD35.mjs"),a=new o(void 0,this.maskingKey),i=[],d=[],c=Kr(r);for(let u of await this.plannedObjectsIn(r,t,n)){if(!qr(n,u))continue;let b=De(u);try{let l=_t(n,u),f=Mn(n,u),{rules:h,select:w,missing:T,rulesOf:m}=await this.maskedFields(c,b,this.maskingRules(u,l),this.maskingRules(u,f)),$=await ro(r,b,w,Yr,void 0,Nn(t,n,u));Be(r.limitInfo,`dataops:anonymize:preview ${b}`);let O=$.records.length>0;O&&d.push(...T.map(P=>({objectApiName:b,fieldApiName:P})));let[B]=O?await Gr(c,[{objectApiName:b,rules:[...l,...f]}]):[],Z=$.records.map(m),K=$.records.map((P,E)=>a.anonymize([P],Z[E])[0]),F=h.map(P=>P.fieldApiName).filter((P,E,S)=>P!=="Id"&&S.indexOf(P)===E);i.push({objectApiName:b,fields:F,...O&&h.length===0?{notCovered:!0}:{},...B?{writeDenied:{deniedFields:[...B.deniedFields]}}:{},methods:Object.fromEntries(h.map(P=>[P.fieldApiName,P.method])),rows:$.records.slice(0,Yr).map((P,E)=>{let S={},C={},q=new Set(Z[E].map(L=>L.fieldApiName));for(let L of F)S[L]=Zr(P[L]),C[L]=pn(P[L])&&q.has(L)?Zr(K[E][L]):S[L];return{id:String(P.Id??""),before:S,after:C}})})}catch(l){let f=R(l);this.deps.log(`[WARN] dataops:anonymize:preview: ${b} not read: ${f}`),i.push({objectApiName:b,fields:[],rows:[],error:f})}}let p=se(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:i,fieldsNotFound:d});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id} objects=${i.length}`)}catch(r){M(this.deps,"dataops:anonymize:preview","dataops:error",e,r)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let r=n.slice(7);if(r.includes(":"))continue;let o=this.deps.configStore.get(n);if(o?.orgId!==e)continue;let a=o.timestamp??"";t&&t.timestamp.localeCompare(a)>=0||(t={operationId:r,timestamp:a,objects:o.objects??[]})}return t}async handleQualityScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ur,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await lr({describe:a=>n.describe(a),query:async a=>{let i=await n.query(a);return Be(n.limitInfo,"dataops:quality-scan"),{totalSize:i.totalSize,records:i.records}}},t),o=se(this.deps,e,"dataops:quality-scan:response",{...r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${r.objects.length}`)}catch(n){M(this.deps,"dataops:quality-scan","dataops:error",e,n)}}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(dr,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...yt,...this.savedTemplates.list()].some(i=>i.name.trim().toLowerCase()===n.toLowerCase())){M(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 o={id:`tpl-saved-${crypto.randomUUID()}`,name:n,description:"",complianceFramework:"custom",rules:t.rules.map(i=>({...i,description:""})),saved:!0,createdAt:new Date().toISOString()};this.savedTemplates.save(o);let a=se(this.deps,e,"dataops:anonymization-template:save:response",{template:o});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(cr,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(yt.some(r=>r.id===n)){M(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 r=this.savedTemplates.delete(n),o=se(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,r)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(pr,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:r}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let o=await Re(n,this.deps.orgRegistry,this.deps.orgManager),a=await Promise.all(r.map(async d=>{let c=De(d),p=await o.describe(c);Be(o.limitInfo,`precheck:pii-scan describe ${c}`);let u=p.fields.map(l=>({apiName:l.name,label:l.label,type:l.type,length:l.length})),b=this.deps.infraServices.piiDetector.detectPII(d,u);return{objectName:d,piiFields:b.piiFields.map(l=>({fieldName:l.fieldApiName,piiType:l.classification,confidence:l.confidence}))}})),i=se(this.deps,e,"precheck:pii-scan:response",{success:!0,results:a});this.deps.broker.postToWebview(i)}catch(o){this.deps.log(`[ERR] precheck:pii-scan: ${R(o)}`);let a=se(this.deps,e,"precheck:pii-scan:response",{success:!1,error:R(o)});this.deps.broker.postToWebview(a)}}};export{yt as a,zt as b,yn as c,wn as d,Lt as e,An as f,xt as g,Bt as h,_r as i,Do as j,At as k,xo as l,so as m};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as P,b as $}from"./chunk-JEERQRLW.mjs";import{b as O,c as b,e as E,f as D}from"./chunk-HS4YRX4J.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";import{ac as R,y as f}from"./chunk-TTFDUKUS.mjs";var y=[{field:"PermissionsViewAllData",label:"View All Data"},{field:"PermissionsModifyAllData",label:"Modify All Data"}],I="PermissionsQueryAllFiles",T="PermissionsCustomizeApplication",d="No record was read or written.";function c(e,t){return{allowed:!1,refusal:{code:e,message:t}}}function w(e,t){return c("PRODUCTION",`${e} is a production org, or cannot be told from one: ${t}. Checkpoints are for sandboxes, scratch orgs and Developer Edition orgs: SandForge never takes a checkpoint of, or rewinds, a production org. ${d}`)}function N(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function j(e,t){return e.slice(0,15)===t.slice(0,15)}function V(e,t){return e.orgType==="Scratch"?"scratch":t.sandbox?"sandbox":"developer"}var z={take:"A checkpoint needs a user with View All Data and Modify All Data: a rewind to it must",preview:"A preview needs a user with View All Data and Modify All Data: a record the user cannot see would read as deleted since, and the rewind it shows must",rewind:"Rewind needs a user with View All Data and Modify All Data: it must",undo:"Undo needs a user with View All Data and Modify All Data: it must",import:"An import needs a user with View All Data and Modify All Data: SandForge never keeps on this machine records its user could not see in the org, and a rewind to it must"},F={take:"Leave the custom settings out of the checkpoint, or give the user Customize Application.",preview:"This checkpoint holds custom settings: give the user Customize Application.",rewind:"This checkpoint holds custom settings: give the user Customize Application.",undo:"This checkpoint holds custom settings: give the user Customize Application.",import:"This checkpoint holds custom settings: give the user Customize Application."};function x(e){return c("PERMISSIONS",`${e.username} needs Customize Application to keep and rewind custom settings, and doesn't have it: View All Custom Settings lets a user read them, never write them. ${F[e.act]} ${d}`)}async function _(e,t){let r=[...y.map(n=>n.field),...t?[T]:[]],i=async n=>(await e.query(`SELECT ${n.join(", ")} FROM UserPermissionAccess`)).records[0],o;try{o=await i([...r,I])}catch{try{o=await i(r)}catch(n){return{unread:n instanceof Error?n.message:String(n)}}}return{missing:y.filter(n=>o?.[n.field]!==!0).map(n=>n.label),viewAllData:o?.PermissionsViewAllData===!0,modifyAllData:o?.PermissionsModifyAllData===!0,queryAllFiles:o?.[I]===!0,customizeApplication:o?.[T]===!0}}var q=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,L=/^0PG[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,M="SobjectType, PermissionsViewAllRecords, PermissionsModifyAllRecords";async function A(e,t){let r=await e.query(t),i=1,o=[...r.records];for(;!r.done;){let n=r.nextRecordsUrl;if(n===void 0||e.queryMore===void 0)throw new Error(`the org answered ${o.length} rows of ${r.totalSize}, and no next page`);r=await e.queryMore(n),i++,o.push(...r.records)}return{rows:o,requests:i}}async function U(e,t){let r=0;try{let i=await t();if(r++,!q.test(i))throw new Error(`the org named the user ${JSON.stringify(i)}`);let o=await A(e,`SELECT ${M} FROM ObjectPermissions WHERE ParentId IN (SELECT PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${i}' AND PermissionSetGroupId = null)`);r+=o.requests;let n=await A(e,`SELECT PermissionSetGroupId FROM PermissionSetAssignment WHERE AssigneeId = '${i}' AND PermissionSetGroupId != null`);r+=n.requests;let l=[...new Set(n.rows.map(a=>a.PermissionSetGroupId).filter(a=>typeof a=="string"&&L.test(a)))],s=[...o.rows];if(l.length>0){let a=await A(e,`SELECT ${M} FROM ObjectPermissions WHERE Parent.PermissionSetGroupId IN (${l.map(u=>`'${u}'`).join(", ")})`);r+=a.requests,s.push(...a.rows)}return{grants:P(s),requests:r}}catch(i){return{unread:S(i)}}}var v={take:"A checkpoint needs a user with View All Data and Modify All Data, or with View All and Modify All on each object it holds: a rewind to it must see and put back what everyone changed there.",preview:"A preview needs a user with View All Data and Modify All Data, or with View All and Modify All on each object it reads: a record the user cannot see would read as deleted since.",rewind:"Rewind needs a user with View All Data and Modify All Data, or with View All and Modify All on each object it puts back: it must see and put back what everyone changed there.",undo:"Undo needs a user with View All Data and Modify All Data, or with View All and Modify All on each object it takes back: it must see and put back what everyone changed there."};async function J(e,t,r={}){let{orgName:i,registered:o}=t;if(o===void 0)return w(i,"SandForge has no record of what kind of org it is");if(!R(o))return w(i,"SandForge has it registered as a production org");let n;try{n=await O(e)}catch(p){let C=E(p);if(C!==void 0)return c("ORG_UNTYPED",`${D(i,p,C)} SandForge takes a checkpoint of no org it cannot tell from a production one. ${d}`);let G=p instanceof Error?p.message:String(p);return w(i,`it did not say what org it is (${G})`)}if(b(n))return w(i,N(n));if(t.act!=="take"&&!j(n.id,t.organizationId))return c("OTHER_ORG",t.act==="import"?`${i} is another org than the one this file holds a checkpoint of: it is imported for the org it was taken of alone, under any alias of it. ${f} Nothing was imported.`:`${i} is another org than the one this checkpoint was taken of: its Organization Id has changed, as a sandbox's does when it is refreshed. This checkpoint is of the org before it, and can only be deleted. ${f} ${d}`);let l=t.customSettings===!0,s=await _(e,l),a=`${z[t.act]} see and put back what everyone changed.`;if("unread"in s)return c("PERMISSIONS",`${a} SandForge could not read whether ${t.username} has them (${s.unread}), and takes an org that will not say for a user who has neither. `+d);let u=s.missing.length===y.length?"them":s.missing.join(" and "),g=t.act,m=g==="import"?void 0:r.userId;if(s.missing.length>0&&m===void 0)return c("PERMISSIONS",`${a} ${t.username} doesn't have ${u}. ${d}`);if(l&&!s.customizeApplication)return x(t);let k={allowed:!0,org:n,tier:V(o,n),queryAllFiles:s.queryAllFiles};if(s.missing.length===0||m===void 0||g==="import")return{...k,grants:{kind:"org"}};let h=await U(e,m);return"unread"in h?c("PERMISSIONS",`${v[g]} ${t.username} doesn't have ${u}, and SandForge could not read which objects they have View All and Modify All on (${h.unread}). View Setup and Configuration lets a user read their own permissions; with View All Data and Modify All Data, nothing needs reading. `+d):$(h.grants)?{...k,grants:{kind:"perObject",viewAllData:s.viewAllData,modifyAllData:s.modifyAllData,objects:h.grants,requests:h.requests}}:c("PERMISSIONS",`${v[g]} ${t.username} doesn't have ${u}, nor View All and Modify All on any object. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. ${d}`)}export{U as a,J as b};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ge}from"./chunk-DYFALGRT.mjs";import{a as xe,b as je,c as Te,d as Oe,f as Pe}from"./chunk-M6P5ZZLE.mjs";import{Q as Me,_ as Le,aa as De,ca as qe,ga as B,na as Ie,oa as Ve,sa as Be,ua as U,va as Ue,xa as Qe}from"./chunk-CION3VMZ.mjs";import{b as E}from"./chunk-CA5NAXSU.mjs";import{$c as Se,L as Fe,N as ve,O as Ne,P as _e,Q as Ae,R as Ce,S as $e,T as Ee}from"./chunk-TTFDUKUS.mjs";import{e as X,l as ee}from"./chunk-7EANH5PY.mjs";var v=class extends Error{};function lt(e){let r=[],n=0;for(;n<e.length;){let t=e.slice(n),i=/^\s+/.exec(t);if(i){n+=i[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 We=[new Set(["||"]),new Set(["&&"]),new Set(["=","==","<>","!=","<",">","<=",">="]),new Set(["+","-","&"]),new Set(["*","/"]),new Set(["^"])];function ut(e){let r=lt(e),n=0,t=()=>r[n],i=u=>{if(r[n]!==u)throw new v(`${u} expected`);n++},l=u=>{if(u>=We.length)return f();let o=l(u+1);for(let a=t();a!==void 0&&We[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 i(")"),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 i(")"),{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 S(e){switch(e.kind){case"call":return e.name==="PRIORVALUE"&&e.args.length===1?S(e.args[0]):{...e,args:e.args.map(S)};case"binary":return{...e,left:S(e.left),right:S(e.right)};case"not":case"negative":return{...e,arg:S(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 Ke=e=>e==="true"?"false":e==="false"?"true":"unknown";function P(e){return e.kind==="call"&&e.name==="AND"?e.args.flatMap(P):e.kind==="binary"&&e.op==="&&"?[...P(e.left),...P(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 k(e){let r=ne(e);if(r)return r;if(e.kind==="not")return Ke(k(e.arg));if(e.kind==="call")switch(e.name){case"ISCHANGED":return"false";case"ISNEW":return"true";case"NOT":return e.args.length===1?Ke(k(e.args[0])):"unknown";case"AND":return ze(P(e));case"OR":return He(M(e));case"IF":{if(e.args.length!==3)return"unknown";let[n,t,i]=e.args,l=k(n);if(l==="true")return k(t);if(l==="false")return k(i);let f=k(t);return f===k(i)?f:"unknown"}default:return"unknown"}return e.kind==="binary"?e.op==="&&"?ze(P(e)):e.op==="||"?He(M(e)):ct(e):"unknown"}function ze(e){let r=e.map(k);if(r.includes("false"))return"false";let n=new Map;for(let t of e){let{condition:i,holds:l}=te(t),f=n.get(i);if(f!==void 0&&f!==l)return"false";n.set(i,l)}return r.every(t=>t==="true")?"true":"unknown"}function He(e){let r=e.map(k);return r.includes("true")?"true":r.every(n=>n==="false")?"false":"unknown"}function ct(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)??k(e.left),i=ne(e.right)??k(e.right);return t==="unknown"||i==="unknown"?"unknown":t===i===r?"true":"false"}function Ze(e){try{return k(S(ut(e)))==="false"}catch(r){if(r instanceof v)return!1;throw r}}var et=25,W=20,ie=W*Me,G=4,Ye=10,dt=2e3,ft=.8;function pt(e){return typeof e!="object"||e===null?null:{optional:e.optionalFilter===!0}}function It(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:pt(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 gt(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 mt="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}$/,ht=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 D(e){return typeof e=="string"?[e]:Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function yt(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(i=>i.name.toLowerCase()===t.toLowerCase())?.name:t}function tt(e){let r=Ie({filterFormula:e}).filter(t=>t.bypass).map(t=>t.name),n=Ve(e).map(t=>t.value===void 0?t.reference:`${t.reference} = '${t.value}'`);return{bypasses:[...r.map(t=>`$Permission.${t}`),...n],permissions:r}}function wt(e,r={}){let n=r.maxRecordsPerObject,t=e.nodes.filter(d=>d.included),i=r.inputMode==="record"&&typeof r.recordId=="string"?"atMost":"exact",l=t.map(d=>d.recordCountUnknown===!0?(n===void 0?i="unknown":i==="exact"&&(i="atMost"),{...d,recordCount:n??0}):{...d,recordCount:n===void 0?d.recordCount:Math.min(d.recordCount,n)}),f=new Ge().generate({...e,nodes:l}).totalApiCalls,p=l.reduce((d,u)=>d+Math.max(1,Math.ceil(u.recordCount/dt)),0);return{writes:f,reads:p,bound:i}}function j(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 Vt(e){return async r=>qe(await e.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(De(`/services/data/v${e.version}`,r)),headers:{"Content-Type":"application/json"}}),r.length)}async function bt(e,r,n){let t=e.filter(({id:i})=>ae.test(i));t.length!==0&&await B(r,[{queries:t.map(({id:i,rule:l})=>({soql:q(i),retrieve:{sobject:"ValidationRule",id:i},take:f=>{let p=f[0]?.Metadata,d=typeof p=="object"&&p!==null?p.errorConditionFormula:void 0;typeof d=="string"&&Ze(d)&&(l.onChangeOnly=!0)},refused:()=>{}})),requests:W}],G,n)}async function kt(e,r,n,t,i){let l=[...new Set(r)].filter(g=>x.test(g));if(l.length===0)return[];let f=new Map(l.map(g=>[g.toLowerCase(),g])),p=new Map(l.map((g,b)=>[g,b])),d=await e(oe(l)),u=new Map,o=async(g,b)=>{let R=se(b,void 0);if(!n)return R;let F=u.get(g);F||(F=n(g).catch(()=>[]),u.set(g,F));let C=y(b).trim().toLowerCase();if(!C)return;let _=R?.toLowerCase(),$=await F;return $.length===0?R:$.find(A=>A.name.toLowerCase()===_)?.name??$.find(A=>A.label?.trim().toLowerCase()===C)?.name},h=(await Promise.all(d.map(async g=>{let b=le(g.EntityDefinition),R=b===void 0?void 0:f.get(b.toLowerCase()),F=y(g.ValidationName);return!R||!F?[]:[{id:y(g.Id),rule:{objectApiName:R,name:Q(y(g.NamespacePrefix),F),message:y(g.ErrorMessage),...ue(await o(R,g.ErrorDisplayField))}}]}))).flat().sort((g,b)=>(p.get(g.rule.objectApiName)??0)-(p.get(b.rule.objectApiName)??0)||g.rule.name.localeCompare(b.rule.name));return t&&await bt(h,t,i),h.map(({rule:g})=>g)}async function Bt(e,r,n,t){let i=[...new Set(r)].filter(a=>x.test(a));if(i.length===0)return{rules:[],notRead:0,requests:0};let l=new Map(i.map(a=>[a.toLowerCase(),a])),f=await e(oe(i)),p=f.requests,d=f.records.flatMap(a=>{let h=le(a.EntityDefinition),g=h===void 0?void 0:l.get(h.toLowerCase()),b=y(a.ValidationName);return!g||!b?[]:[{id:y(a.Id),objectApiName:g,name:Q(y(a.NamespacePrefix),b),read:!1,permissions:[]}]}),u=d.filter(a=>ae.test(a.id)),o=(a,h)=>{let g=typeof h=="object"&&h!==null?h.errorConditionFormula:void 0;typeof g=="string"&&(a.read=!0,a.permissions=tt(g).permissions)};return n?p+=await B(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 U(u.slice(0,et).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:g})=>({objectApiName:a,name:h,permissions:g})),notRead:d.filter(a=>!a.read).length,requests:p}}function Ut(e,r,n){let t=async i=>(await e(gt(i))).flatMap(l=>typeof l.QualifiedApiName=="string"?[{name:l.QualifiedApiName,...typeof l.Label=="string"?{label:l.Label}:{}}]:[]);return i=>kt(e,i,t,r,n)}var Je=class{deps;constructor(r){this.deps=r}async read(r,n,t,i={}){let l=new Set(i.excludedObjects??[]),f=Ue(yt(t),l),p=[];if(f.length===0)return{gaps:[],unread:p,requests:0};let d=0,u=(s,c)=>{p.push({part:s,reason:c})},o=new Map(f.map(s=>[s.toLowerCase(),s])),a=s=>s===void 0?void 0:o.get(s.toLowerCase()),h=new Map(f.map((s,c)=>[s,c])),g=f.filter(s=>x.test(s)),b=[],R=[],F,C,_=new Map,$=new Map,A=new Set,I=(s,c,m)=>async()=>{try{let w=await c();d+=w.requests,m(w.records)}catch(w){d++,u(s,E(w))}},ce=(s,c,m,w)=>async()=>{try{let{fields:J,sent:ot,createable:at}=await this.deps.describeFields(s,c);ot&&d++,w.set(c,J),w===_&&at===!1&&A.add(c)}catch(J){d++,u(m,`${c}: ${E(J)}`)}};await U([...g.length>0?[I("validationRules",()=>this.deps.toolingQuery(n,oe(g)),s=>{b=s})]:[],I("duplicateRules",()=>this.deps.query(n,mt),s=>{R=s}),async()=>{try{d++,F=await this.deps.readLimits(n)}catch(s){C=E(s)}},...f.flatMap(s=>[ce(n,s,"targetFields",_),ce(r,s,"sourceFields",$)])],G);let T=b.flatMap(s=>{let c=a(le(s.EntityDefinition)),m=y(s.ValidationName);if(!c||!m)return[];let w=y(s.Id);return[{id:ae.test(w)?w:null,name:Q(y(s.NamespacePrefix),m),objectApiName:c,...ue(se(s.ErrorDisplayField,_.get(c))),message:y(s.ErrorMessage),formula:"notRead",bypasses:[],permissions:[]}]}).sort((s,c)=>(h.get(s.objectApiName)??0)-(h.get(c.objectApiName)??0)||s.name.localeCompare(c.name)),{toolingQueries:O,toolingRetrieves:de}=this.deps,K=T.filter(s=>s.id!==null).slice(0,O?ie:et);for(let s of T)s.id===null&&(s.formula="unreadable");let z=R.flatMap(s=>{let c=a(y(s.SobjectType)),m=Q(y(s.NamespacePrefix),y(s.DeveloperName));return!c||!y(s.DeveloperName)?[]:[{objectApiName:c,developerName:m,label:y(s.MasterLabel)||m,fullName:`${y(s.SobjectType)}.${m}`}]}),fe=new Map,pe=[];for(let s=0;s<z.length;s+=Ye)pe.push(z.slice(s,s+Ye).map(c=>c.fullName));let V,H,ge=(s,c)=>{let m=typeof c=="object"&&c!==null?c.errorConditionFormula:void 0;if(typeof m!="string"){s.formula="unreadable";return}s.formula="read",Object.assign(s,tt(m));let w=se(c.errorDisplayField,_.get(s.objectApiName));w&&(s.field=w)},rt=async()=>{if(!O||K.length===0)return;let s=await B(c=>O(n,c),[{queries:K.map(c=>({soql:q(c.id),retrieve:{sobject:"ValidationRule",id:c.id},take:m=>ge(c,m[0]?.Metadata),refused:m=>{c.formula="unreadable",V??=m}})),requests:W}],G,de&&(c=>de(n,c)));d+=s},me=new Map,Z={},he=[...A].filter(s=>x.test(s)),st=async()=>{let[s,c]=await Promise.all([Oe((m,w)=>this.deps.toolingQuery(m,w),n,he),this.deps.createFacts?this.deps.createFacts(n).then(m=>({facts:m,requests:0})).catch(()=>({facts:{},requests:0})):Te(this.deps,n)]);d+=s.requests+c.requests;for(let[m,w]of s.answered)me.set(m,w);Z=c.facts};await U([...he.length>0?[st]:[],...O?[rt]:[],...(O?[]:K).map(s=>async()=>{try{let c=await this.deps.toolingQuery(n,q(s.id));d+=c.requests,ge(s,c.records[0]?.Metadata)}catch(c){d++,s.formula="unreadable",V??=E(c)}}),...pe.map(s=>async()=>{try{d++;for(let c of await this.deps.readDuplicateRules(n,s)){if(typeof c!="object"||c===null)continue;let m=c,w=y(m.fullName);w&&fe.set(w.toLowerCase(),m)}}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(s=>s.permissions.length>0)&&await I("userPermissions",()=>this.deps.query(n,Le),s=>{ye=!0;for(let c of s)Y.add(Be(y(c.NamespacePrefix),y(c.DeveloperName)))})();let we=[...new Set(T.flatMap(s=>s.permissions.filter(c=>!Y.has(c.toLowerCase()))))],it=we.length>0?await Qe(we,async s=>{let c=[];return await I("permissionSets",()=>this.deps.query(n,s),m=>{c=m})(),c},()=>p.some(s=>s.part==="permissionSets")):void 0,be=[...T.map(s=>vt(s,ye?Y:void 0,it)),...z.map(s=>Nt(s,fe.get(s.fullName.toLowerCase()))),...f.flatMap(s=>{if(A.has(s))return[Ft(s,xe(s,Z,me.get(s.toLowerCase())),_.get(s)??[],Z)];let c=_.get(s),m=$.get(s);return c&&m?_t(s,c,m,i):[]})],ke=ht.safeParse(F),Re=C===void 0&&ke.success?ke.data.DailyApiRequests:void 0;return Re||u("apiBudget",C??"the limits the org answered hold no DailyApiRequests"),be.push(At(t,i,f[0],Re)),{gaps:Ae(be),unread:p,requests:d}}},Rt={platform:"object_platform_only",setup:"object_setup_only",feature:"object_feature_off",parent:"object_through_parent",user:"object_not_createable"};function Ft(e,r,n,t){let i=r==="parent"?Pe(n,t):[];return j({kind:Rt[r],severity:je(r)?"info":"blocking",objectApiName:e,...i.length>0?{detail:{editOn:i}}:{},decisions:["exclude_object"]})}function vt(e,r,n){let t=r?e.permissions.filter(f=>r.has(f.toLowerCase())):[],i=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 j({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}:{},...i.length>0?{assign:i}:{}},decisions:l,...e.field?{defaultDecision:"leave_empty"}:{}})}function Nt(e,r){let n=y(r?.actionOnInsert).toLowerCase(),t=n==="block"||n==="allow"?n:"unknown",i=D(r?.operationsOnInsert).map(f=>f.toLowerCase());return j({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:i.includes("alert")}:{},...t==="allow"?{report:i.includes("report")}:{}},decisions:t==="allow"?["ignore"]:["ignore","exclude_object"],...t==="allow"?{defaultDecision:"ignore"}:{}})}function _t(e,r,n,t){let i=o=>o.toLowerCase(),l=new Set((t.fieldExclusions?.[e]??[]).map(i)),f=new Map(Object.entries(t.fieldMappings?.[e]??{}).map(([o,a])=>[i(o),i(a)])),p=new Set([...f].filter(([o])=>!l.has(o)).map(([,o])=>o)),d=new Map(n.map(o=>[i(o.name),o])),u=o=>{let a=i(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[j({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[j({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 At(e,r,n,t){let i=e.nodes[0]?.objectApiName??n,l=wt(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>ft*t.Max;p=d&&l.bound==="exact"?"blocking":d||u?"warning":"info"}return j({kind:"api_budget",severity:p,objectApiName:i,detail:{calls:f,writes:l.writes,reads:l.reads,estimate:l.bound,...t?{max:t.Max,remaining:t.Remaining}:{budgetRead:!1}},decisions:["ignore"]})}var Ct={blocking:"BLOCKING",warning:"warning",info:"info"},$t=new Set(["picklist_value_refused","dependent_value_invalid","picklist_value_absent","currency_inactive"]),Et=new Set(["record_type_unmapped","record_type_unavailable"]);function nt(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 i=new Set(e.decisions),{field:l,value:f}=e;if(i.has("skip_rows")&&Ne((r.skippedRows??[]).filter(o=>o.object===t),e.id,n))return"these rows held back";if($t.has(e.kind)&&l!==void 0&&f!==void 0&&(i.has("map_value")||i.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&&i.has("leave_empty"))return"the field left empty in these rows";if(a&&a.to!==null&&i.has("map_value"))return`written as "${a.to}"`}let p=Et.has(e.kind)?e.value??e.recordType:void 0;if(p!==void 0&&i.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=i.has("set_default")?r.defaultValues?.find(d):void 0;if(u)return`default "${String(u.value)}"`;if(i.has("truncate")&&r.truncateFields?.some(d))return"cut to the field's length";if(i.has("leave_empty")&&r.fieldExclusions?.[t]?.includes(l))return"the field left out of the rows"}function Qt(e,r){let n=e.gaps.map(t=>t.id);return{...e,gaps:e.gaps.map(t=>{let i=nt(t,r,n);return i===void 0?t:{...t,answeredBy:i}})}}function Xe(e,r,n,t){if(t)return`the mute lifts it (${t.permission}, in ${t.permissionSet}): ${re(e,!0)}`;let i=r?nt(e,r,n):void 0;return i===void 0?`${Ct[e.severity]}: ${re(e)}`:`answered by the run's decision: ${i} \u2014 ${re(e)}`}var St={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"},Gt={notInSource:"the source has no such field",notCreateableInSource:"the source cannot give it",excluded:"the run leaves it out"},L=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 (${Gt[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}`:"",i=[...D(n.bypasses).map(f=>`not when ${f}`),...D(n.heldBypasses).length>0?[`kept quiet for this run: the user it writes as holds ${D(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}${i.length>0?` (${i.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 i=[n.alert===!0?"an alert":"",n.report===!0?"a report":""].filter(Boolean).join(" and ");return`${t}: allows an insert it matches${i?`, with ${i}`:""}: 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=D(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 ${L(n.calls)} call(s) (${L(n.writes)} write(s) of 200 rows, ${L(n.reads)} read(s))`,i=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":`${L(n.remaining)} of ${L(n.max)} daily requests left`;return`API budget: the run takes ${i}; ${l}`}default:return e.kind}}function xt(e,r,n){return $e(e).map(({permission:t,permissionSet:i,others:l})=>{if(!i)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?`: ${Se(i.name,r,n)}`:"";return` ${t}: held by permission set ${i.name}, the smallest${f}${p}`})}function Wt(e,r,n={}){let t=[`target gaps: what ${r} holds against the rows, read from its metadata`],i=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(` ${Xe(o,n.decisions,i,a)}`),a||t.push(...xt(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(` ${Xe(u,n.decisions,i)}`);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(` ${St[u]??u} could not be read: ${o}`);return t.push(` read in ${e.requests} request(s) to ${r}`),t}export{et as a,W as b,ie as c,It as d,oe as e,gt as f,q as g,mt as h,tt as i,wt as j,Vt as k,kt as l,Bt as m,Ut as n,Je as o,nt as p,Qt as q,Wt as r};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-XLXIPIEW.mjs";import"./chunk-TTKXMDBN.mjs";import"./chunk-5TC3QB4U.mjs";import"./chunk-2BA2XKAY.mjs";import"./chunk-JEERQRLW.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-SIHORWVK.mjs";import"./chunk-NZC67CGR.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-JPUR2CFX.mjs";import"./chunk-LPBMBW3O.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VYXMVJL5.mjs";import"./chunk-AEKONPF4.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-CION3VMZ.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{h as REWIND_MUTING_STEP_WORDS,g as REWIND_STEP_WORDS,i as acceptanceRefusal,j as boundsRefusal,k as boundsRefusals,e as firedCount,m as notConfirmedRefusal,a as objectsWrittenBy,b as previewTotals,f as remakeUnasked,d as rewindStepsOf,c as selectionDiff,l as undeletableUnattendedRefusal};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{ib as o,ic as c}from"./chunk-TTFDUKUS.mjs";var u=new Set(["picklist","multipicklist"]);function d(s){return(s.picklistValues??[]).filter(n=>n.active!==!1&&typeof n.value=="string"&&n.value!=="").map(n=>n.value)}function b(s){let n=new Map,r=t=>{let i=n.get(t);return i||(i=s(t),n.set(t,i)),i};return{async createable(t){let{fields:i}=await r(t);return new Set(i.filter(e=>e.createable===!0).map(e=>e.name))},async visible(t){let{fields:i}=await r(t);return new Set(i.map(e=>e.name))},async computed(t){let{fields:i}=await r(t);return new Set(i.filter(e=>e.calculated===!0||e.autoNumber===!0).map(e=>e.name))},async picklistValues(t){let{fields:i}=await r(t),e=new Map;for(let a of i){if(!u.has(a.type??""))continue;let l=d(a);l.length>0&&e.set(a.name,l)}return e},async keyPrefix(t){let{keyPrefix:i}=await r(t);return typeof i=="string"&&i.length===3?i:void 0},async lengths(t){let{fields:i}=await r(t);return new Map(i.flatMap(e=>typeof e.length=="number"&&e.length>0?[[e.name,e.length]]:[]))},async required(t){let{fields:i}=await r(t);return i.filter(e=>e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0&&(e.referenceTo??[]).length===0).map(e=>({fieldApiName:e.name,type:e.type??"string",picklistValues:d(e),referenceTo:[],length:e.length??0,integerDigits:o({...e,type:e.type??"string"}),objectApiName:t,required:!0}))}}}function m(s,n){return async r=>(await s.required(r)).filter(t=>!c(r,t.fieldApiName,n.includes(r)?"person":"business"))}export{b as a,m as b};
@@ -1,11 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{u as Q,w as q}from"./chunk-LPBMBW3O.mjs";import{F as W,H as Z,d as K,k as I,r as b,s as L,t as F,u as J,x as D,z as U}from"./chunk-IFETCRWE.mjs";import{Ca as Y,Da as G,Ea as N}from"./chunk-TTFDUKUS.mjs";import{b as H,e as _,m as $,v as X}from"./chunk-7EANH5PY.mjs";import{createCipheriv as be,createDecipheriv as Be,createHash as y,hkdfSync as Ae,randomBytes as S,timingSafeEqual as Ee}from"node:crypto";import{createReadStream as Oe}from"node:fs";import{lstat as ee,open as T,rename as xe,rm as Ie,statfs as Se}from"node:fs/promises";import{basename as ie,dirname as oe,join as ve}from"node:path";import{Readable as ae}from"node:stream";import{pipeline as se}from"node:stream/promises";import{createGunzip as Re,createGzip as Ce}from"node:zlib";var ct=".sfcheckpoint",Te=1024*1024,Pe=new Set([1]),He=new Set([1]),P=32,A=16,_e=4096,$e=1024,Ne=64*1024*1024,ce=2**32,he="sandforge-checkpoint/1 block key",fe="sandforge-checkpoint/1 key check",M="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",Ke=Math.ceil(P*8/5),w="Nothing was imported.";function ht(){return S(P)}function ft(n){if(n.length!==P)throw new RangeError("Not a key of a checkpoint file");let e="",t=0,r=0;for(let i of n)for(t=(t<<8|i)&65535,r+=8;r>=5;)e+=M[t>>>r-5&31],r-=5;return r>0&&(e+=M[t<<5-r&31]),(e.match(/.{1,4}/g)??[]).join("-")}function dt(n){let e=n.replace(/[\s-]/g,"").toUpperCase();if(e.length!==Ke||!/^[A-Z2-7]+$/.test(e))return;let t=Buffer.alloc(P),r=0,i=0,o=0;for(let a of e)r=(r<<5|M.indexOf(a))&65535,i+=5,i>=8&&(t[o++]=r>>>i-8&255,i-=8);if((r&(1<<i)-1)===0)return t}function v(n,e,t,r){return Buffer.from(Ae("sha256",n,e,t,r))}function de(n,e){let t=Buffer.alloc(12);return n.copy(t,0),t.writeUInt32BE(e,8),t}function le(n,e,t){let r=Buffer.alloc(37);return n.copy(r,0),r.writeUInt32BE(e,32),r[36]=t?1:0,r}function Fe(n,e,t,r){let i=be("aes-256-gcm",n.blockKey,de(n.prefix,e),{authTagLength:A});return i.setAAD(le(n.headerHash,e,t)),Buffer.concat([i.update(r),i.final(),i.getAuthTag()])}function De(n,e,t,r){let i=Be("aes-256-gcm",n.blockKey,de(n.prefix,e),{authTagLength:A});i.setAAD(le(n.headerHash,e,t)),i.setAuthTag(r.subarray(r.length-A));try{let o=i.update(r.subarray(0,r.length-A));return Buffer.concat([o,i.final()])}catch{return}}var R=class extends Error{constructor(t){super(t.message);this.refusal=t;this.name="ImportRefused"}refusal};function f(n){return new R({code:"IMPORT_DAMAGED",message:`This checkpoint file ${n}: it was changed or damaged after it was exported. ${w}`})}var E=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointExportError"}code};function Me(n){return{...C(n,ue),org:C(n.org,pe)}}var ue=["lastRewind","takenOn","expiresAt","bytes","importedFrom"],pe=["alias"];function C(n,e){return Object.fromEntries(Object.entries(n).filter(([t])=>!e.includes(t)))}async function*ye(n,e){if(e===0)return;let t=0;for await(let r of Oe(n,{start:0,end:e-1})){let i=r;t+=i.length,yield i}if(t!==e)throw new E("EXPORT_CHANGED",`${ie(n)} of the checkpoint shrank while it was exported: export it again.`)}async function me(n,e){let t=y("sha256");for await(let r of ye(n,e))t.update(r);return t.digest("hex")}async function lt(n){let{folder:e,checkpoint:t,out:r,key:i}=n,o=n.chunkBytes??Te;if(await ee(r).catch(()=>{}))throw new E("EXPORT_EXISTS",`${r} is there already: name another file, or move that one away first.`);let a=Buffer.from(`${JSON.stringify(Me(t))}
8
- `,"utf8"),s=[{path:b,bytes:a.length,sha256:y("sha256").update(a).digest("hex"),content:a}];for(let l of await F(e))l.path!==b&&s.push({...l,sha256:await me(l.file,l.bytes)});let h=S(32),c=S(8),d={format:"sandforge-checkpoint",formatVersion:1,checkpointFormat:1,sandforgeVersion:n.sandforgeVersion,organizationId:I(t.org.organizationId),orgTier:t.org.tier,checkpointId:t.checkpointId,takenAt:t.takenAt,records:we(t),objects:t.objects.length,files:s.length,bytes:s.reduce((l,p)=>l+p.bytes,0),cipher:"aes-256-gcm",kdf:"hkdf-sha256",salt:h.toString("hex"),noncePrefix:c.toString("hex"),keyCheck:v(i,h,fe,16).toString("hex"),chunkBytes:o},u=Buffer.from(`${JSON.stringify(N.parse(d))}
9
- `),m={blockKey:v(i,h,he,32),prefix:c,headerHash:y("sha256").update(u).digest()},k=ve(oe(r),`.${ie(r)}.${process.pid}-${S(4).toString("hex")}.tmp`),O=y("sha256"),g=0,x=await T(k,"wx",K);try{try{let l=async p=>{O.update(p),g+=p.length,await ge(x,p)};await l(u),await se(ae.from(ze(s)),Ce({level:6}),async p=>{await je(p,o,m,l)}),await x.sync()}finally{await x.close()}if(await ee(r).catch(()=>{}))throw new E("EXPORT_EXISTS",`${r} appeared while the checkpoint was exported: name another file.`);await xe(k,r)}catch(l){throw await Ie(k,{force:!0}),l}return{header:d,bytes:g,sha256:O.digest("hex")}}async function ge(n,e){for(let t=0;t<e.length;){let{bytesWritten:r}=await n.write(e,t,e.length-t);t+=r}}function we(n){return n.objects.reduce((e,t)=>e+t.records,0)}async function*ze(n){for(let e of n){let{path:t,bytes:r,sha256:i}=e;if(yield Buffer.from(`${JSON.stringify({path:t,bytes:r,sha256:i})}
10
- `,"utf8"),e.content!==void 0){yield e.content;continue}let o=y("sha256");for await(let a of ye(e.file??"",r))o.update(a),yield a;if(o.digest("hex")!==i)throw new E("EXPORT_CHANGED",`${t} of the checkpoint changed while it was exported: export it again.`)}yield Buffer.from(`${JSON.stringify({end:!0,files:n.length})}
11
- `,"utf8")}async function je(n,e,t,r){let i=0,o,a=[],s=0,h=async c=>{if(o!==void 0){if(i>=ce)throw new RangeError("The checkpoint is too large for one file");await r(Fe(t,i,c,o)),i++,o=void 0}};for await(let c of n)for(a.push(c),s+=c.length;s>=e;){let d=Buffer.concat(a);await h(!1),o=d.subarray(0,e),a=[d.subarray(e)],s=d.length-e}s>0&&(await h(!1),o=Buffer.concat(a)),await h(!0)}async function z(n,e,t){let r=Buffer.alloc(t),i=0;for(;i<t;){let{bytesRead:o}=await n.read(r,i,t-i,e+i);if(o===0)break;i+=o}return i===t?r:r.subarray(0,i)}function B(n){return{refusal:{code:"IMPORT_NOT_ARCHIVE",message:`This is not a checkpoint file SandForge exported: ${n}. ${w}`}}}async function Ve(n){let e;try{e=await T(n,"r")}catch(t){let r=t.code;return B(r==="ENOENT"?"there is no such file":"it cannot be read")}try{let t=await e.stat();if(!t.isFile())return B("it is not a file");let r=await z(e,0,Math.min(t.size,_e)),i=r.indexOf(10);if(i<0)return B("it does not start with a checkpoint file\u2019s header");let o=r.subarray(0,i+1),a;try{a=JSON.parse(o.toString("utf8"))}catch{return B("it does not start with a checkpoint file\u2019s header")}let s=G.safeParse(a);if(!s.success)return B("it does not start with a checkpoint file\u2019s header");let{formatVersion:h,checkpointFormat:c,sandforgeVersion:d}=s.data;if(!He.has(h)||!Pe.has(c))return{refusal:{code:"IMPORT_VERSION",message:`This file was made by SandForge ${d}, with checkpoint format ${c} in file format ${h}, which this SandForge does not read: update SandForge, then import it. ${w}`}};let u=N.safeParse(a);return u.success?{read:{header:u.data,headerBytes:o.length,headerHash:y("sha256").update(o).digest(),size:t.size}}:B("its header does not read")}finally{await e.close()}}async function Xe(n){try{let e=await Se(n);return Number(e.bavail)*Number(e.bsize)}catch{return}}async function ut(n){try{return await Ye(n)}catch(e){if(e instanceof R)return{imported:!1,refusal:e.refusal};if(e instanceof W&&e.code==="damaged")return{imported:!1,refusal:{code:"IMPORT_DAMAGED",message:`${e.message} ${w}`}};throw e}}async function Ye(n){let{store:e,file:t,key:r}=n,i=n.now??new Date,o=await Ve(t);if("refusal"in o)return{imported:!1,refusal:o.refusal};if(!o.read.headerHash.equals(n.read.headerHash))throw f("changed since its header was read");let a=o.read,{header:s}=a,h=Buffer.from(s.salt,"hex");if(!Ee(v(r,h,fe,16),Buffer.from(s.keyCheck,"hex")))return{imported:!1,refusal:{code:"IMPORT_KEY",message:`This key is not the one the file was exported with. ${w}`}};let c={blockKey:v(r,h,he,32),prefix:Buffer.from(s.noncePrefix,"hex"),headerHash:a.headerHash},d=await e.read(s.checkpointId);if(d!==void 0)return ne(d,t,a,c);let u=await(n.freeBytes??Xe)(e.root),m=s.bytes+Q(s.records,2)+s.objects*8;if(u!==void 0&&u<m)return{imported:!1,refusal:{code:"IMPORT_DISK",message:`The checkpoint takes about ${te(m)} on this machine, and its disk has ${te(u)} free: make room, then import it. ${w}`}};let k=await e.importInto(s.organizationId,s.checkpointId,async g=>{let x=await ke(t,a,c,g.dir),l=We(x,a,{...n.alias!==void 0?{alias:n.alias}:{},keepDays:n.keepDays,takenOn:n.takenOn,now:i});await D(g.indexDir);for(let p of l.objects){let V=await q(g,l.snapshotId,p.objectApiName);if(V.rows!==p.records)throw f(`holds ${V.rows} records of ${p.objectApiName} where its checkpoint counts ${p.records}`)}return await Z(g,l.objects),l});if(k.outcome==="imported")return{imported:!0,outcome:"imported",checkpoint:k.checkpoint};let O=await e.read(s.checkpointId);if(O===void 0)throw f("could not be kept");return ne(O,t,a,c)}function te(n){return`${(n/(1024*1024)).toFixed(1)} MB`}async function ne(n,e,t,r){let i=c=>({imported:!1,refusal:{code:"IMPORT_KEPT_OTHER",message:`A checkpoint ${t.header.checkpointId} is kept on this machine already, ${c}: delete it first to import this file. ${w}`}});if(n.folder.organizationId!==I(t.header.organizationId))return i("of another org");if(n.checkpoint===void 0)return i("damaged");let o=i("and differs from this one"),a=await ke(e,t,r),s=new Map(a.hashes.filter(([c])=>c!==b).map(([c,d])=>[c,d])),h=(await F(n.folder)).filter(c=>c.path!==b);if(h.length!==s.size)return o;for(let c of h)if(s.get(c.path)!==await me(c.file,c.bytes))return o;return{imported:!0,outcome:"alreadyKept",checkpoint:n.checkpoint}}var Ge=$({path:H().min(1).max(300),bytes:_().int().nonnegative(),sha256:H().regex(/^[0-9a-f]{64}$/)}),Le=$({end:X(!0),files:_().int().positive()});async function ke(n,e,t,r){let i=await T(n,"r"),o=y("sha256");try{let a=new j(e.header,r);try{await se(ae.from(Je(i,e,t,o)),Re(),async h=>{for await(let c of h)await a.take(c)})}catch(h){throw String(h.code??"").startsWith("Z_")?f("does not inflate"):h}finally{await a.close()}return{...a.ended(),sha256:o.digest("hex")}}finally{await i.close()}}async function*Je(n,e,t,r){r.update(await z(n,0,e.headerBytes));let i=e.header.chunkBytes+A,o=e.size-e.headerBytes;if(o<=0)throw f("holds nothing after its header");let a=Math.ceil(o/i),s=o-(a-1)*i;if(s<=A)throw f("ends inside a block");if(a>ce)throw f("holds more blocks than a file can");for(let h=0;h<a;h++){let c=h===a-1,d=c?s:i,u=await z(n,e.headerBytes+h*i,d);if(u.length<d)throw f("is cut short");r.update(u);let m=De(t,h,c,u);if(m===void 0)throw f(`holds a block, the ${Ue(h+1)} of ${a}, that does not decrypt`);yield m}}function Ue(n){let e=n%100,t=e>=11&&e<=13?"th":["th","st","nd","rd"][n%10]??"th";return`${n}${t}`}var j=class{constructor(e,t){this.header=e;this.into=t}header;into;line=[];lineBytes=0;current;seen=new Set;hashes=[];portable;bytes=0;end=!1;async take(e){let t=0;for(;t<e.length;){if(this.end)throw f("holds bytes after its last entry");let r=this.current;if(r!==void 0){let s=e.subarray(t,t+Math.min(r.left,e.length-t));t+=s.length,r.left-=s.length,r.hash.update(s),r.handle!==void 0&&await ge(r.handle,s),r.held?.push(Buffer.from(s)),r.left===0&&await this.endEntry();continue}let i=e.indexOf(10,t),o=i<0?e.length:i;if(this.lineBytes+=o-t,this.lineBytes>$e)throw f("holds a line too long for an entry");if(this.line.push(e.subarray(t,o)),t=o,i<0)continue;t++;let a=Buffer.concat(this.line).toString("utf8");this.line=[],this.lineBytes=0,await this.startEntry(a)}}async startEntry(e){let t;try{t=JSON.parse(e)}catch{throw f("holds an entry that does not read")}let r=Le.safeParse(t);if(r.success){if(r.data.files!==this.hashes.length||r.data.files!==this.header.files)throw f("counts other files than it holds");this.end=!0;return}let i=Ge.safeParse(t);if(!i.success)throw f("holds an entry that does not read");let{path:o,bytes:a,sha256:s}=i.data;if(!L(o))throw f(`names a file no checkpoint holds, ${JSON.stringify(o)}`);if(this.seen.has(o))throw f(`holds ${o} twice`);if(this.seen.add(o),this.bytes+=a,this.bytes>this.header.bytes||this.seen.size>this.header.files)throw f("holds more than its header says");let h=o===b;if(h&&a>Ne)throw f("holds a checkpoint.json larger than any checkpoint\u2019s");let c;if(!h&&this.into!==void 0){let d=J(this.into,o);await D(oe(d)),c=await T(d,"wx",K)}this.current={path:o,left:a,sha256:s,hash:y("sha256"),...c!==void 0?{handle:c}:{},...h?{held:[]}:{}},a===0&&await this.endEntry()}async endEntry(){let e=this.current;if(e!==void 0){if(this.current=void 0,e.handle!==void 0)try{await e.handle.sync()}finally{await e.handle.close()}if(e.hash.digest("hex")!==e.sha256)throw f(`holds ${e.path} with other bytes than its sha256 says`);e.held!==void 0&&(this.portable=Buffer.concat(e.held)),this.hashes.push([e.path,e.sha256])}}async close(){await this.current?.handle?.close().catch(()=>{})}ended(){if(!this.end||this.current!==void 0)throw f("is cut short");if(this.bytes!==this.header.bytes)throw f("holds other bytes than its header says");if(this.portable===void 0)throw f("holds no checkpoint.json");return{portable:this.portable,hashes:this.hashes}}};function We(n,e,t){let r;try{r=JSON.parse(n.portable.toString("utf8"))}catch{throw f("holds a checkpoint.json that does not read")}if(!re(r)||!re(r.org))throw f("holds a checkpoint.json that does not read");let i=Y.safeParse({...C(r,ue),org:{...C(r.org,pe),...t.alias!==void 0?{alias:t.alias}:{}},takenOn:t.takenOn,expiresAt:U(t.now,t.keepDays),bytes:0,importedFrom:{at:t.now.toISOString(),sandforgeVersion:e.header.sandforgeVersion,sha256:n.sha256}});if(!i.success)throw f("holds a checkpoint.json that does not parse");let o=i.data,{header:a}=e;if(o.checkpointId!==a.checkpointId||I(o.org.organizationId)!==I(a.organizationId)||o.takenAt!==a.takenAt||o.status!=="ready"||we(o)!==a.records||o.objects.length!==a.objects)throw f("holds another checkpoint than its header says");return o}function re(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}export{ct as a,Te as b,ht as c,ft as d,dt as e,E as f,Me as g,lt as h,Ve as i,ut as j};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c}from"./chunk-WA7EYLAQ.mjs";import"./chunk-LKQ5RKIV.mjs";import"./chunk-XAMBCQPU.mjs";import"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DX_PROJECT_FILE,b as scenarioProjectOf,c as writeRunTestFile};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w}from"./chunk-ZUTYVST5.mjs";import"./chunk-NTOVCTRS.mjs";export{a as CURRENCY_FIELD,q as CURRENCY_FOLLOWS,c as CURRENCY_SETTINGS_SOQL,b as CURRENCY_TYPES_SOQL,u as CurrencyReplacementTally,d as DATED_RATES_ON_SOQL,e as DATED_RATES_SOQL,j as DATED_RATE_FIELDS,l as conversionFactor,n as currencyFieldsOf,w as currencyReplacementsNote,k as datedRateOf,g as datedRatesOf,v as describeCurrencyReplaced,t as followParentCurrency,r as followsItsParentsCurrency,f as orgCurrenciesOf,s as parentCurrencyChange,h as readOrgCurrencies,i as readRunCurrencies,p as replaceRowCurrency,o as replacementCurrency,m as roundToScale};
@@ -1,14 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{f as ce}from"./chunk-A527W53V.mjs";import{wc as de}from"./chunk-TTFDUKUS.mjs";import{b as u,e as f,i as ie,k as w,l as m,r as se,s as N,u as ae,v as D}from"./chunk-7EANH5PY.mjs";import{createHash as fe}from"node:crypto";import*as C from"node:fs/promises";import*as M from"node:path";import*as I from"node:fs/promises";import*as O from"node:path";import*as U from"node:fs";import*as b from"node:path";function Oe(t){let e=b.resolve(t);for(;;){if(U.existsSync(b.join(e,".git"))||U.existsSync(b.join(e,"pnpm-workspace.yaml")))return e;let r=b.dirname(e);if(r===e)throw new Error(`No repository root found above ${t}`);e=r}}function le(t){let e=b.resolve(t);return process.platform==="win32"?e.toLowerCase():e}function _(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t))throw new Error(`Not an org id a file of the sas can be named after: "${t}"`);return t}var q=class extends Error{constructor(r,n){super(`Refusing output path inside the repository: ${r} (repo root: ${n}). Frozen-dataset exports, retained-ID lists and working manifests must live in a sas directory OUTSIDE the repo \u2014 versioning them would create a real\u2194anonymized correspondence table.`);this.resolvedPath=r;this.repoRoot=n;this.name="InsideRepoPathError"}resolvedPath;repoRoot},k=class{repoRoot;constructor(e){this.repoRoot=e?b.resolve(e):Oe(process.cwd())}isInsideRepo(e){let r=le(this.repoRoot),n=le(e);if(n===r)return!0;let i=b.relative(r,n);return i!==""&&!i.startsWith("..")&&!b.isAbsolute(i)}assertOutsideRepo(e){if(this.isInsideRepo(e))throw new q(b.resolve(e),this.repoRoot);return b.resolve(e)}};function ot(t){return t.map(({objectApiName:e,why:r,count:n})=>({objectApiName:e,count:n,note:ce(n,r)}))}var ue=/^\d+\.\d+\.\d+$/,Se=/^[0-9a-f]{12}$/,P=class extends Error{constructor(e){super(e),this.name="ManifestError"}};function it(t){let e=(t.now?.()??new Date).toISOString(),r={version:t.version,status:"frozen",frozenAt:e,source:t.source,saltFingerprint:t.saltFingerprint,rulesVersion:t.rulesVersion,volumetry:t.volumetry,controls:{nonReidentification:t.nonReidentification,dryRunLoad:null,author:t.author,date:e},...t.coverage?{coverage:t.coverage}:{}};return W(r),r}function W(t){if(!ue.test(t.version))throw new P(`version must be semver, got ${JSON.stringify(t.version)}`);if(t.status!=="frozen")throw new P(`status must be "frozen", got ${JSON.stringify(t.status)}`);if(!t.frozenAt)throw new P("frozenAt is required");if(!t.source?.orgId||!t.source.decisionDate)throw new P("source.orgId and source.decisionDate are required");if(!Se.test(t.saltFingerprint))throw new P("saltFingerprint must be 12 lowercase hex chars of the salt SHA-256");if(!ue.test(t.rulesVersion))throw new P(`rulesVersion must be semver, got ${JSON.stringify(t.rulesVersion)}`);if(typeof t.volumetry?.budgetMax!="number"||!t.volumetry.measured)throw new P("volumetry.budgetMax and volumetry.measured are required");if(!t.controls?.nonReidentification)throw new P("controls.nonReidentification is required");if(!t.controls.author||!t.controls.date)throw new P("controls.author and controls.date are required");let e=t.coverage;if(e!==void 0&&(typeof e.objects!="number"||typeof e.truncated!="boolean"||typeof e.maxNodes!="number"||!Array.isArray(e.unboundedObjects)||!Array.isArray(e.filesLeftOut)||e.leftToThePlatform!==void 0&&!Array.isArray(e.leftToThePlatform)||e.exclusionCosts!==void 0&&!Array.isArray(e.exclusionCosts)||e.requiredLeftEmpty!==void 0&&!Array.isArray(e.requiredLeftEmpty)||e.keptWithoutARule!==void 0&&!Array.isArray(e.keptWithoutARule)||e.encryptedNotKept!==void 0&&!Array.isArray(e.encryptedNotKept)))throw new P("coverage, when present, needs objects, truncated, maxNodes, unboundedObjects and filesLeftOut, and a list of what it left to the platform, of what its exclusions cost, of the required fields the rules leave empty, of the fields kept without a rule, or of the encrypted fields not kept, if it names any")}function pe(t){return W(t),`${JSON.stringify(t,null,2)}
8
- `}function st(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new P("Manifest must be a JSON object");let e=t;return W(e),e}var V="platform-records.json",G=class extends Error{constructor(e){let r=e.checks.filter(n=>!n.passed).map(n=>`${n.name} (${n.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${r}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},ge=class{guard;constructor(e){this.guard=e??new k}async write(e,r,n,i){if(!i.passed)throw new G(i);let o=this.guard.assertOutsideRepo(e),s=this.guard.assertOutsideRepo(O.join(o,"data"));await I.mkdir(s,{recursive:!0});for(let l of await I.readdir(s))l.endsWith(".json")&&await I.rm(this.guard.assertOutsideRepo(O.join(s,l)));let a=[],d=async(l,p)=>{let g=this.guard.assertOutsideRepo(l);await I.writeFile(g,`${JSON.stringify(p)}
9
- `,"utf8"),a.push(g)},c=this.guard.assertOutsideRepo(O.join(o,"manifest.json"));await I.writeFile(c,pe(n),"utf8"),a.push(c);for(let l of r.objects)await d(O.join(s,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await d(O.join(o,"record-types.json"),r.recordTypes),await d(O.join(o,"personcontact-sidecar.json"),r.personContactSidecar),await d(O.join(o,V),{...r.standardPricebook?{standardPricebook:r.standardPricebook}:{}}),{dir:o,files:a}}};var K="manifest.json",Fe=["record-types.json","personcontact-sidecar.json",V],Z="data",Ee="sha256:";async function gt(t){let e=await H(M.join(t,K));if(e===void 0)throw new Error(`No frozen dataset at ${t}: it holds no ${K}.`);let r=[{name:K,content:ke(e)}];for(let i of Fe){let o=await H(M.join(t,i));o!==void 0&&r.push({name:i,content:o})}for(let i of await xe(M.join(t,Z))){let o=await H(M.join(t,Z,i));o!==void 0&&r.push({name:`${Z}/${i}`,content:o})}let n=fe("sha256");for(let{name:i,content:o}of r.sort((s,a)=>me(s.name,a.name)))n.update(`${i}\0${fe("sha256").update(o).digest("hex")}
10
- `);return`${Ee}${n.digest("hex")}`}async function xe(t){let e;try{e=await C.readdir(t)}catch(r){if(r.code==="ENOENT")return[];throw r}return e.filter(r=>r.endsWith(".json"))}async function H(t){try{return await C.readFile(t)}catch(e){if(e.code==="ENOENT")return;throw e}}function ke(t){let e;try{e=JSON.parse(t.toString("utf8"))}catch{return t}if(Y(e)&&Y(e.controls)){let r={...e.controls};delete r.dryRunLoad,e={...e,controls:r}}return Buffer.from(X(e),"utf8")}function X(t){return Array.isArray(t)?`[${t.map(X).join(",")}]`:Y(t)?`{${Object.keys(t).sort(me).map(r=>`${JSON.stringify(r)}:${X(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function me(t,e){return t===e?0:t<e?-1:1}import*as h from"node:fs/promises";import*as z from"node:path";var yt=4*1024*1024,wt=64*1024*1024;var he=1e4,L=u().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),S=u().min(1).max(40),bt=m({forgeId:u().min(1).max(200),targetOrgId:u().min(1).max(128),timestamp:S,duration:f().nonnegative(),status:ae(["success","partial","failure"]),cancelled:D(!0).optional(),writtenBetween:m({first:S,last:S}).optional(),retryOf:u().min(1).max(200).optional(),objects:w(m({objectApiName:u().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:w(L)})),linked:f().int().nonnegative(),mayHaveBeenWritten:f().int().nonnegative().optional(),undo:m({removedAt:S,deleted:f().int().nonnegative(),alreadyGone:f().int().nonnegative(),kept:f().int().nonnegative(),refused:f().int().nonnegative(),notReached:f().int().nonnegative().optional(),notVisible:f().int().nonnegative().optional()}).optional(),removalStamps:N(L,S).optional(),removalSpans:w(m({first:S,last:S,userId:L})).optional(),removalLeft:w(L).optional(),sweep:m({sweptAt:S,deleted:f().int().nonnegative(),keptChanged:f().int().nonnegative(),refused:f().int().nonnegative()}).optional(),inJournal:m({journalId:u().min(1).max(200),part:f().int().nonnegative(),left:w(m({objectApiName:u().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:f().int().nonnegative()}))}).optional()}),Rt=m({version:D(1),plans:w(ie())}),Pt=m({version:D(1),runs:w(m({forgeId:u().min(1).max(300),ids:w(L),late:w(L).optional()}))});var J="referenceid-mapping.json",Ne=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,Me=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,T=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=new Set;function De(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var _e=m({at:u().min(1).max(40),object:u().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:w(se([u().min(1).max(400),u().regex(T)])).max(1e4)}),Ce=m({journal:m({startedAt:u().min(1).max(40),pid:f().int().positive(),runUserId:u().regex(T).optional()})});function Be(t){let e,r={},n=new Map,i;for(let o of t.split(`
11
- `)){if(o.trim()==="")continue;let s;try{s=JSON.parse(o)}catch{continue}if(!e){let c=Ce.safeParse(s);c.success&&(e=c.data.journal);continue}let a=_e.safeParse(s);if(!a.success)continue;let d=n.get(a.data.object)??[];for(let[c,l]of a.data.created)Object.prototype.hasOwnProperty.call(r,c)||d.push(c),r[c]=l;n.set(a.data.object,d),i=a.data.at}if(!(!e||i===void 0||Object.keys(r).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:i,mapping:r,created:[...n].filter(([,o])=>o.length>0).map(([o,s])=>({objectApiName:o,referenceIds:s})),load:{startedAt:e.startedAt,endedAt:i},...e.runUserId?{runUserId:e.runUserId}:{}}}}function Je(t){return`referenceid-mapping.${_(t)}.json`}async function B(t){let e;try{e=await h.readFile(t,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}return JSON.parse(e)}async function At(t,e){let r=e.assertOutsideRepo(t),n;try{n=await h.readdir(r)}catch(o){if(o.code==="ENOENT")return[];throw o}let i=new Set(n.flatMap(o=>Ne.exec(o)?.[1]??Me.exec(o)?.[1]??[]));if(n.includes(J)){let s=(await B(e.assertOutsideRepo(z.join(r,J))))?.orgId;typeof s=="string"&&$e(s)&&i.add(s)}return[...i].sort()}function $e(t){try{return _(t),!0}catch{return!1}}var Ue=w(m({objectApiName:u(),referenceIds:w(u())})),qe=m({startedAt:u(),endedAt:u()}),We=m({first:u(),last:u()}),Ge=m({removedAt:u(),deleted:f(),alreadyGone:f(),kept:f(),refused:f(),notReached:f().optional()}),Ve=N(u(),u()),Ke=w(m({first:u(),last:u(),userId:u()})),ye=N(u(),u()),ee=u().regex(T);function v(t,e){let r=t.safeParse(e);return r.success?r.data:void 0}function A(t){if(typeof t!="object"||t===null)return;let e=t,r=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(y=>typeof y[1]=="string")):{},n=v(Ue,e.created),i=v(qe,e.load),o=v(We,e.writtenBetween),s=v(Ge,e.removal),a=v(Ve,e.removalStamps),d=v(Ke,e.removalSpans),c=v(ye,e.personContacts),l=v(ye,e.withTheirRecord),p=v(ee,e.runUserId),g=v(w(ee),e.madeEarlier),R=v(w(ee),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:r,...n?{created:n}:{},...i?{load:i}:{},...o?{writtenBetween:o}:{},...s?{removal:s}:{},...a?{removalStamps:a}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...l?{withTheirRecord:l}:{},...p?{runUserId:p}:{},...g?{madeEarlier:g}:{},...R?{lateEarlier:R}:{}}}function F(t){return Array.isArray(t.earlier)?t.earlier.flatMap(e=>A(e)??[]):[]}function E(t){return t.load?.endedAt??t.updatedAt}function Ze(t,e){return t.slice(0,15)===e.slice(0,15)}function j(t){return t.slice(0,15)}function we(t,e){let r={};for(let[n,i]of Object.entries(t??{}))Object.prototype.hasOwnProperty.call(e,i)?Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=i):delete e[n];return r}function be(t,e){if(e.size===0)return t;let r=Object.fromEntries(Object.entries(t.mapping).filter(([,d])=>!e.has(j(d)))),n=we(t.personContacts,r),i=we(t.withTheirRecord,r),o=t.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(l=>Object.prototype.hasOwnProperty.call(r,l))})).filter(d=>d.referenceIds.length>0),s=Object.fromEntries(Object.entries(t.removalStamps??{}).filter(([d])=>!e.has(j(d)))),a={...t,mapping:r};return delete a.removalStamps,delete a.personContacts,delete a.withTheirRecord,{...a,...o?{created:o}:{},...Object.keys(s).length>0?{removalStamps:s}:{},...Object.keys(n).length>0?{personContacts:n}:{},...Object.keys(i).length>0?{withTheirRecord:i}:{}}}function Re(t){return t.created?t.created.some(e=>e.referenceIds.length>0):Object.keys(t.mapping).length>0}var Pe=class{constructor(e,r){this.sasDir=e;this.guard=r?.guard??new k,this.orgId=r?.orgId??"";let n=r?.organizationId;this.askOrganizationId=typeof n=="function"?n:async()=>n,this.now=r?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(z.join(this.sasDir,this.orgId===""?J:Je(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(z.join(this.sasDir,J))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${_(this.orgId)}`}journalPath(e){let r=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(z.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(r))}.ndjson`))}retiring=new Map;journal(e){let r=this.journalPath(e),n=!1,i=!1,o=!1,s,a=Promise.resolve(),d;Q.add(r);let c=p=>{a=a.then(async()=>{if(!(d!==void 0||i))try{if(!n){n=!0,await h.mkdir(z.dirname(r),{recursive:!0});let g={journal:{startedAt:e.toISOString(),pid:process.pid,...s?{runUserId:s}:{}}};await h.appendFile(r,`${JSON.stringify(g)}
12
- `,"utf8")}await h.appendFile(r,`${JSON.stringify(p)}
13
- `,"utf8")}catch(g){d=g instanceof Error?g.message:String(g)}})},l=async()=>{await a,i=!0,await h.rm(r,{force:!0})};return this.retiring.set(r,l),{writtenAs:p=>{T.test(p)&&(s=p)},created:(p,g)=>{let R=g.filter(([y,x])=>y!==""&&T.test(x));if(R.length!==0){o=!0;for(let y=0;y<R.length;y+=1e4)c({at:this.now().toISOString(),object:p,created:R.slice(y,y+1e4)})}},flush:async()=>(await a,d),close:async()=>{await a,this.retiring.delete(r),(i||!o)&&await h.rm(r,{force:!0}),i=!0,Q.delete(r)}}}async stoppedLoads(e){let r;try{r=await h.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(s){if(s.code==="ENOENT")return[];throw s}let n=`${this.journalStem}.load-`,i=new Set(e.flatMap(s=>s.load?[s.load.startedAt]:[])),o=[];for(let s of r){if(!s.startsWith(n)||!/^\d{1,16}\.ndjson$/.test(s.slice(n.length)))continue;let a=this.guard.assertOutsideRepo(z.join(this.sasDir,s));if(Q.has(a))continue;let d;try{d=await h.readFile(a,"utf8")}catch{continue}let c=Be(d);!c||i.has(c.startedAt)||c.pid!==process.pid&&De(c.pid)||o.push({file:a,load:c.load})}return o}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let r=A(e);return[...r?[r]:[],...F(e)].map(n=>({mapping:new Map(Object.entries(n.mapping)),...n.created?{created:n.created}:{},...n.writtenBetween?{writtenBetween:n.writtenBetween}:{},endedAt:E(n),...n.removalStamps?{removalStamps:n.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let r=typeof e.orgId=="string"?e.orgId:"",n=A(e);return[...n?[this.recordedOf(n,r)]:[],...F(e).map(i=>({...this.recordedOf(i,r),earlier:!0}))]}recordedOf(e,r){return{orgId:r,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:E(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let r=e.organizationId;if(r===void 0)return!1;let n=await this.currentOrganizationId();return n!==void 0&&!Ze(r,n)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await B(this.filePath);if(e!==void 0)return e;let r=this.singleFilePath;if(r===void 0)return;let n=await B(r);return n?.orgId===this.orgId?n:void 0}async readWithJournals(){let e=await this.readFile(),r=e?[A(e),...F(e)]:[],n=await this.stoppedLoads(r.filter(a=>a!==void 0));if(n.length===0)return{payload:e,journals:[]};let i=[...r.filter(a=>a!==void 0),...n.map(({load:a})=>a)].sort((a,d)=>Date.parse(E(d))-Date.parse(E(a))),[o,...s]=i;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...o,...s.length>0?{earlier:s}:{}},journals:n.map(({file:a})=>a)}}async dropJournals(e){for(let r of e)await h.rm(r,{force:!0}).catch(()=>{})}async write(e){let r=this.filePath;await h.mkdir(z.dirname(r),{recursive:!0}),await h.writeFile(r,`${JSON.stringify(e,null,2)}
14
- `,"utf8");let n=this.singleFilePath;if(n!==void 0)try{(await B(n))?.orgId===this.orgId&&await h.rm(n)}catch{}}async keptLoads(e,r,n=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let i=new Set(r.map(j)),o=new Set(n),s=A(e);return[...s?[s]:[],...F(e)].map(a=>be(a,i)).filter(a=>Re(a)||o.has(E(a)))}async persist(e,r){let{payload:n,journals:i}=await this.readWithJournals(),o=r?.earlier?await this.keptLoads(n,r.earlier.settled,r.earlier.stillToSweep):[],s=await this.currentOrganizationId(),a=this.now().toISOString(),d=p=>Object.fromEntries(Object.entries(p??{}).filter(([g,R])=>e.has(g)&&e.has(R))),c=d(r?.personContacts),l=d(r?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...s!==void 0?{organizationId:s}:{},updatedAt:a,mapping:Object.fromEntries([...e.entries()].sort(([p],[g])=>p.localeCompare(g))),...r?{created:r.created.map(({objectApiName:p,referenceIds:g})=>({objectApiName:p,referenceIds:g.filter(R=>e.has(R))})).filter(p=>p.referenceIds.length>0),load:{startedAt:r.startedAt.toISOString(),endedAt:a},...r.writtenBetween?{writtenBetween:{...r.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(l).length>0?{withTheirRecord:l}:{},...r.runUserId?{runUserId:r.runUserId}:{}}:{},...o.length>0?{earlier:o}:{}}),r?.earlier&&await this.dropJournals(i),r){let p=this.journalPath(r.startedAt),g=this.retiring.get(p);g?await g():await h.rm(p,{force:!0}).catch(()=>{})}}async recordRemoval(e,r){let{payload:n,journals:i}=await this.readWithJournals(),o=A(n);if(n===void 0||o===void 0)return!1;let s=[o,...F(n)],a=s.findIndex(p=>E(p)===e);if(a<0)return!1;let d=new Set(r.gone.map(j)),[c,...l]=s.map((p,g)=>be(g===a?Xe(p,r):p,d));return await this.write({version:1,orgId:typeof n.orgId=="string"?n.orgId:"",...n.organizationId!==void 0?{organizationId:n.organizationId}:{},...c,updatedAt:this.now().toISOString(),...l.length>0?{earlier:l}:{}}),await this.dropJournals(i),!0}async recordMade(e,r,n=[],i=[]){let{payload:o,journals:s}=await this.readWithJournals(),a=A(o);if(o===void 0||a===void 0)return!1;let d=[a,...F(o)],c=d.findIndex(y=>E(y)===e);if(c<0)return!1;let l=[...i],p=y=>{let x=ve(y.madeEarlier,r,l),oe=ve(y.lateEarlier,n,l),$={...y};return delete $.madeEarlier,delete $.lateEarlier,{...$,...x.length>0?{madeEarlier:x}:{},...oe.length>0?{lateEarlier:oe}:{}}},[g,...R]=d.map((y,x)=>x===c?p(y):y);return await this.write({version:1,orgId:typeof o.orgId=="string"?o.orgId:"",...o.organizationId!==void 0?{organizationId:o.organizationId}:{},...g,...R.length>0?{earlier:R}:{}}),await this.dropJournals(s),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:r,journals:n}=await this.readWithJournals(),i=A(r);if(r===void 0||i===void 0)return!1;let o=new Set(e),s=F(r),a=s.filter(d=>Re(d)||!o.has(E(d)));return a.length===s.length?!1:(await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...i,...a.length>0?{earlier:a}:{}}),await this.dropJournals(n),!0)}async recordStamps(e){let{payload:r,journals:n}=await this.readWithJournals(),i=A(r);if(r===void 0||i===void 0)return!1;let o=[i,...F(r)],s=o.map(c=>He(c,e));if(s.every((c,l)=>c===o[l]))return!1;let[a,...d]=s;return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...a,...d.length>0?{earlier:d}:{}}),await this.dropJournals(n),!0}};function ve(t,e,r=[]){let n=new Map,i=new Set(r.map(j)),o=[];for(let s of[...t??[],...e]){let a=j(s),d=a.slice(0,3),c=n.get(d)??0;!T.test(s)||i.has(a)||c>=he||(i.add(a),n.set(d,c+1),o.push(s))}return o}function He(t,e){let r=new Set(Object.values(t.mapping).map(j)),n=Object.entries(e).filter(([o])=>r.has(j(o)));if(n.length===0)return t;let i=new Set(n.map(([o])=>j(o)));return{...t,removalStamps:{...Object.fromEntries(Object.entries(t.removalStamps??{}).filter(([o])=>!i.has(j(o)))),...Object.fromEntries(n)}}}function Xe(t,e){let r={...t.removalStamps,...e.stamps},n=[...t.removalSpans??[],...e.span?[e.span]:[]],i=e.mark??t.removal;return{...t,...i?{removal:i}:{},...Object.keys(r).length>0?{removalStamps:r}:{},...n.length>0?{removalSpans:n}:{}}}var je={BusinessHours:["Name"]},Ot=["DUPLICATE_VALUE","DUPLICATES_DETECTED","duplicate value found"];var Ye=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Qe=/^[A-Za-z][A-Za-z0-9_]*$/;function te(t){return t.slice(0,15)}function re(t,e){let r=t.mapping.get(e);return typeof r=="string"&&Ye.test(r)?r:void 0}function Ie(t){let e=new Set((t.created??[]).flatMap(n=>n.referenceIds)),r=new Set;for(let n of t.mapping.keys()){if(e.has(n))continue;let i=re(t,n);i&&r.add(te(i))}return r}function et(t){let e=new Set((t.created??[]).flatMap(i=>i.referenceIds)),r=[...Object.entries(t.personContacts??{}),...Object.entries(t.withTheirRecord??{})];for(let i=!0;i;){i=!1;for(let[o,s]of r)e.has(o)||!e.has(s)||(e.add(o),i=!0)}let n=new Set;for(let[i]of r){let o=e.has(i)?re(t,i):void 0;o&&n.add(te(o))}return n}function Ae(t){let e=Ie(t),r=new Map;for(let{objectApiName:o,referenceIds:s}of t.created??[])Qe.test(o)&&r.set(o,[...r.get(o)??[],...s]);let n=new Set,i=[];for(let[o,s]of[...r].reverse()){let a=[];for(let d of[...s].reverse()){let c=re(t,d);if(!c)continue;let l=te(c);e.has(l)||n.has(l)||(n.add(l),a.push(c))}a.length>0&&i.push({objectApiName:o,ids:a})}return i}function ne(t){return de(t.removal)?[]:Ae(t).filter(e=>!ze(e.objectApiName))}function ze(t){return Object.prototype.hasOwnProperty.call(je,t)}function tt(t){return Ae(t).filter(e=>ze(e.objectApiName)).map(({objectApiName:e,ids:r})=>({objectApiName:e,count:r.length}))}function xt(t){return t.find(e=>ne(e).length>0)??t[0]}function kt(t,e){return t.filter(r=>r.endedAt!==e.endedAt&&r.created!==void 0&&ne(r).length===0)}function Lt(t){let e=t.created!==void 0,r=et(t),n=[...Ie(t)].filter(o=>!r.has(o)),i=tt(t);return{orgId:t.orgId,loadedAt:t.endedAt,created:ne(t).map(({objectApiName:o,ids:s})=>({objectApiName:o,count:s.length})),linked:e?n.length:0,recorded:e,...t.removal?{removed:t.removal}:{},...t.earlier?{earlier:!0}:{},...i.length>0?{keptByThePlatform:i}:{}}}export{Oe as a,_ as b,q as c,k as d,ot as e,it as f,pe as g,st as h,V as i,ge as j,gt as k,je as l,Ot as m,Je as n,At as o,Pe as p,Ae as q,ne as r,tt as s,xt as t,kt as u,Lt as v};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-NZC67CGR.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-VYXMVJL5.mjs";import"./chunk-AEKONPF4.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-CION3VMZ.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{p as actDeliverability,o as actEmailsGate,n as actSendersOf,q as afterLeaseEmailsRefusal,l as checkpointEmails,j as checkpointEmailsUncounted,c as draftedByDiff,d as draftedByPlan,a as emailsOfLimit,m as emailsRefusal,k as emailsUncountedWords,r as pageEmailsRefusal,e as statusBackByDiff,f as statusBackByPlan,b as updatedByDiff,g as writtenByDiff,h as writtenByPlan,i as writtenByUndo};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{J as H}from"./chunk-JPUR2CFX.mjs";import{b as k,c as ie,d as $}from"./chunk-GSKCGQIP.mjs";import{i as oe}from"./chunk-INIT2UKJ.mjs";import{h as Y}from"./chunk-TZE3Y7IQ.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";var ye=5,pe=100;function y(t){return t.slice(0,15)}function L(t){return t==null||t===""}var ae=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function he(t,n){if(L(t)||L(n))return L(t)&&L(n);if(typeof t=="number"||typeof n=="number")return Number(t)===Number(n);if(typeof t=="string"&&typeof n=="string"){if(t===n)return!0;if(ae.test(t)&&ae.test(n)){let a=Date.parse(t);return Number.isFinite(a)&&a===Date.parse(n)}return!1}return JSON.stringify(t)===JSON.stringify(n)}function me(t){let n;return()=>(n??=(async()=>{try{let a=await t.userId?.();return typeof a=="string"&&a!==""?y(a):void 0}catch{return}})(),n)}async function de(t){let n=Date.now();try{let a=Date.parse(await t.serverTime());return Number.isFinite(a)?a-(n+Date.now())/2:0}catch{return 0}}async function Ie(t,n){let a=Date.parse(n??"");return Number.isFinite(a)?a+await de(t)+H:Number.NEGATIVE_INFINITY}var be=1e3;function Re(t){let n=Date.parse(t);return Number.isFinite(n)?n-be:Number.NEGATIVE_INFINITY}function ke(t,n){let a=Object.hasOwn(t,n)?t[n]:[];return new Map(a.filter(c=>c.toLowerCase()!=="id").map(c=>[c.toLowerCase(),c]))}var Ae={INACTIVE_OWNER_OR_USER:"OwnerId"};function Oe(t,n){let a=new Set;for(let s of t.errors??[]){if(typeof s=="string")continue;if(Array.isArray(s.fields))for(let p of s.fields)typeof p=="string"&&a.add(p);let f=s.statusCode!==void 0?Ae[s.statusCode]:void 0;f!==void 0&&(!Array.isArray(s.fields)||s.fields.length===0)&&a.add(f)}let c=new Map(Object.keys(n).map(s=>[s.toLowerCase(),s]));return[...a].flatMap(s=>{let f=c.get(s.toLowerCase());return f!==void 0&&f!=="Id"?[f]:[]})}function ve(t,n){let a=Array.isArray(t)?t:[t];return Array.from({length:n},(c,s)=>a[s]??{success:!1})}function J(t){let n=t.errors?.[0];if(n===void 0)return{words:"The org gave no reason."};if(typeof n=="string")return{words:n};let a=n.statusCode,c=n.message??"";return{...a?{code:a}:{},words:a&&c?`${a}: ${c}`:a||c}}function P(t,{fields:n,why:a}){return`${n.map(c=>`${t}.${c}`).join(", ")}: the value from before is no longer taken (${a}) \u2014 left as the run wrote it`}async function je(t,n,a){let c=new Set;try{for(let s of $(a)){let f=await t.query(`SELECT Id FROM ${n} WHERE Id IN (${s})`);for(let p of f.records)typeof p.Id=="string"&&c.add(y(p.Id))}}catch(s){return{unread:S(s)}}return{live:c}}var Q=class{result;said=new Set;constructor(n,a){this.result={objectApiName:n,planned:a,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}without(){this.result.restoredWithout=(this.result.restoredWithout??0)+1}reason(n){this.said.has(n)||this.said.size>=ye||(this.said.add(n),this.result.reasons.push(n))}};async function De(t){let{org:n,plan:a}=t,c=[],s=[],f={},p=!1,I=!1;if(a.length===0)return{objects:c,left:s,wrote:p,cancelled:I,stamps:f};let M=t.changedAfter!==void 0?Re(t.changedAfter):await Ie(n,t.lastWriteAt),R=new Map(Object.entries(t.stamps??{}).map(([h,_])=>[y(h),Date.parse(_)])),F=t.ownWriters&&t.ownWriters.length>0?new Set(t.ownWriters.map(y)):void 0,W=t.stampsFor,ce=me(n);for(let{objectApiName:h,backup:_,ids:C}of a){let u=new Q(h,C.length);c.push(u.result);let B=t.unkept?.find(e=>e.objectApiName===h);if(B&&B.fields.length>0&&u.reason(`${B.fields.map(e=>`${h}.${e}`).join(", ")}: not kept, encrypted \u2014 the run's user cannot view encrypted data, and read their values from before masked; left as the run wrote them`),I||t.signal?.aborted){I=!0,u.result.notReached=C.length,s.push(...C);continue}let x=Y(h),m=new Map(C.map(e=>[y(e),e])),U=t.fields?ke(t.fields,h):void 0,O=new Map,G=new Set;try{let e=await t.backups.batches(_,h,k);for await(let r of e??[])for(let o of r){if(typeof o.Id!="string"||!m.has(y(o.Id)))continue;let i=O.get(y(o.Id))??{};for(let[l,d]of Object.entries(o)){if(l==="Id")continue;let g=U?U.get(l.toLowerCase()):l;g!==void 0&&!(g in i)&&(i[g]=d)}if(U&&Object.keys(i).length===0){G.add(y(o.Id));continue}O.set(y(o.Id),i)}}catch(e){u.reason(`The values from before the run could not be read: ${S(e)}`),O.clear(),G.clear()}let X=[...G].filter(e=>!O.has(e)).length;X>0&&u.reason(`${X} ${h} record(s) hold no value of a field that may be written back now: left as they are`);for(let e of[...m.keys()])O.has(e)||(u.result.notKept++,m.delete(e));if(m.size===0)continue;let Z=new Set;for(let e of O.values())for(let r of Object.keys(e))Z.add(Y(r));let ee=["Id","LastModifiedDate",...F?["LastModifiedById"]:[],...Z],ue=ee.length>pe?k/4:k,q=new Map,fe=async e=>{if(t.signal?.aborted)throw new T;return(await n.query(e)).records};try{for(let e of $([...m.values()],ue)){let r=await oe(`SELECT ${ee.join(", ")} FROM ${x} WHERE Id IN (${e})`,fe,{stamp:"LastModifiedDate"});for(let o of r)typeof o.Id=="string"&&q.set(y(o.Id),o)}}catch(e){if(e instanceof T){I=!0,u.result.notReached=m.size,s.push(...m.values());continue}u.result.refused+=m.size,u.reason(S(e)),s.push(...m.values());continue}let D=[],te=new Set,le=W?Date.now()+await de(n)-H:0;for(let[e,r]of m){let o=q.get(e);if(!o){u.result.alreadyGone++,t.counted?.(r,"alreadyGone");continue}let i=Date.parse(String(o.LastModifiedDate??"")),l=o.LastModifiedById,d=i<=M||i<=(R.get(e)??Number.NaN)||F!==void 0&&typeof l=="string"&&F.has(y(l));if(!d&&!t.includeChanged){u.result.keptChanged++,s.push(r);continue}let g=O.get(e)??{},w={Id:o.Id};for(let[b,A]of Object.entries(g))he(A,o[b])||(w[b]=L(A)?null:A);if(Object.keys(w).length===1){u.result.restored++,t.counted?.(r,"restored"),d&&W?.(r)&&typeof o.LastModifiedDate=="string"&&(f[o.Id]=o.LastModifiedDate);continue}D.push(w),d&&W?.(r)&&te.add(r)}let j=[],v=[],E=(e,r)=>{u.result.refused++,u.reason(r),s.push(m.get(y(e.Id))??e.Id)},z=e=>{u.result.restored++,t.counted?.(m.get(y(e.Id))??e.Id,"restored")},ge=e=>{u.result.alreadyGone++,t.counted?.(m.get(y(e.Id))??e.Id,"alreadyGone")},ne=e=>{I=!0,u.result.notReached=(u.result.notReached??0)+e.length,s.push(...e.map(r=>m.get(y(r.Id))??r.Id))},re=(e,r,o,i)=>{let l=Object.keys(e).filter(w=>w!=="Id"&&!r.includes(w));if(l.length>0){let w={Id:e.Id};for(let b of l)w[b]=e[b];j.push({record:w,leftOut:o});return}if(o.length===0){z(e);return}let[d,...g]=o;i?(u.without(),u.reason(P(h,d))):E(e,P(h,d));for(let w of g)u.reason(P(h,w))},K=async e=>{try{return p=!0,ve(await n.update(h,[...e]),e.length)}catch(r){let o=S(r);return e.map(()=>({success:!1,errors:[o]}))}},we=async e=>{let r=t.keep;if(!r)return!0;let o=e.map(i=>{let l=q.get(y(i.Id))??{},d={Id:i.Id};for(let g of Object.keys(i))g!=="Id"&&(d[g]=l[g]??null);return d});try{return await r(h,o),!0}catch(i){let l=`What these ${e.length} ${h} record(s) hold now could not be kept before they were written (${S(i)}), so none of them was written: nothing is written over that cannot be put back.`;for(let d of e)E(d,l);return!1}};for(let e=0;e<D.length;e+=k){let r=D.slice(e,e+k);if(t.signal?.aborted){I=!0;let i=D.slice(e);u.result.notReached=(u.result.notReached??0)+i.length,s.push(...i.map(l=>m.get(y(l.Id))??l.Id));break}if(!await we(r))continue;(await K(r)).forEach((i,l)=>{let d=r[l];if(i.success===!0){z(d);return}let g=J(i),w=Oe(i,d);if(g.code==="ENTITY_IS_DELETED"&&w.length===0){v.push({record:d,why:g.words});return}let b=Object.keys(d).filter(A=>A!=="Id"&&!w.includes(A));if(w.length>0&&b.length>0){let A={Id:d.Id};for(let se of b)A[se]=d[se];j.push({record:A,leftOut:[{fields:w,why:g.words}]});return}E(d,g.words)})}let N=[];if(v.length>0&&t.signal?.aborted)ne(v.map(({record:e})=>e));else if(v.length>0){let e=await je(n,x,v.map(({record:r})=>r.Id));e.unread!==void 0&&u.reason(`Whether ${v.length} ${h} record(s) refused as deleted are still in the org could not be read (${e.unread}): left to be given back again`);for(let{record:r,why:o}of v){if(e.unread!==void 0){E(r,o);continue}if(!e.live.has(y(r.Id))){ge(r);continue}let i=Object.keys(r).filter(l=>l!=="Id"&&ie(r[l]));i.length===0?E(r,o):i.length===1?re(r,i,[{fields:i,why:o}],!1):N.push({record:r,lookups:i,given:[],refusedAlone:[]})}}let V=N.length>0;for(let e=0;V&&N.some(({lookups:r})=>r.length>e);e++){let r=N.filter(({lookups:o})=>o.length>e);for(let o=0;o<r.length;o+=k){if(t.signal?.aborted){ne(N.map(({record:d})=>d)),V=!1;break}let i=r.slice(o,o+k);(await K(i.map(({record:d,lookups:g})=>({Id:d.Id,[g[e]]:d[g[e]]})))).forEach((d,g)=>{let w=i[g],b=w.lookups[e];d.success===!0?w.given.push(b):w.refusedAlone.push({field:b,why:J(d).words})})}}for(let e of V?N:[]){let r=new Map;for(let{field:o,why:i}of e.refusedAlone)r.set(i,[...r.get(i)??[],o]);re(e.record,e.lookups,[...r].map(([o,i])=>({fields:i,why:o})),e.given.length>0)}for(let e=0;e<j.length;e+=k){let r=j.slice(e,e+k);if(t.signal?.aborted){I=!0,u.result.notReached=(u.result.notReached??0)+j.length-e,s.push(...j.slice(e).map(({record:i})=>m.get(y(i.Id))??i.Id));break}(await K(r.map(({record:i})=>i))).forEach((i,l)=>{let{record:d,leftOut:g}=r[l];if(i.success===!0){if(g.length===0){z(d);return}u.without();for(let w of g)u.reason(P(h,w));return}E(d,J(i).words)})}Object.assign(f,await Ee(n,x,[...te],le,ce))}return{objects:c,left:s,wrote:p,cancelled:I,stamps:f}}async function Ee(t,n,a,c,s){let f={};if(a.length===0)return f;let p=await s();if(p===void 0)return f;for(let I of $(a)){let M;try{M=(await t.query(`SELECT Id, LastModifiedDate, LastModifiedById FROM ${n} WHERE Id IN (${I})`)).records}catch{continue}for(let R of M)typeof R.Id=="string"&&typeof R.LastModifiedDate=="string"&&typeof R.LastModifiedById=="string"&&y(R.LastModifiedById)===p&&Date.parse(R.LastModifiedDate)>=c&&(f[R.Id]=R.LastModifiedDate)}return f}var T=class extends Error{};function $e(t,n,a=[]){let c=t.map(s=>({...s}));for(let s of a){if(s.undeleted+s.refused===0)continue;let f=c.find(p=>p.objectApiName===s.objectApiName);f?(f.created+=s.undeleted,f.failed+=s.refused):c.push({objectApiName:s.objectApiName,created:s.undeleted,updated:0,deleted:0,failed:s.refused})}for(let s of n){let f=s.restored+(s.restoredWithout??0);if(f+s.refused===0)continue;let p=c.find(I=>I.objectApiName===s.objectApiName);p?(p.updated+=f,p.failed+=s.refused):c.push({objectApiName:s.objectApiName,created:0,updated:f,deleted:0,failed:s.refused})}return c}export{he as a,me as b,de as c,Ie as d,De as e,Ee as f,$e as g};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as b}from"./chunk-74Q6DORA.mjs";import"./chunk-UNJA4J37.mjs";import{a}from"./chunk-XLXIPIEW.mjs";import"./chunk-TTKXMDBN.mjs";import"./chunk-TSLJUSLW.mjs";import"./chunk-KRCA6IPH.mjs";import"./chunk-5TC3QB4U.mjs";import"./chunk-2BA2XKAY.mjs";import"./chunk-OAZRPP4I.mjs";import"./chunk-JEERQRLW.mjs";import"./chunk-MHMH6MTP.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-MJU2PGZQ.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-LWW4U276.mjs";import"./chunk-MJVTDA5Q.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-2CNCDM56.mjs";import"./chunk-SIHORWVK.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-B5QQJ4SI.mjs";import"./chunk-NZC67CGR.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-F43REJDZ.mjs";import"./chunk-JPUR2CFX.mjs";import"./chunk-LPBMBW3O.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-DBFJB2B6.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-MFG4MUIO.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-HS4YRX4J.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VYXMVJL5.mjs";import"./chunk-AEKONPF4.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-CION3VMZ.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as objectsWrittenBy,b as previewCheckpoint};