sandforge 1.81.0 → 1.83.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 (240) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-users.mjs +12 -0
  3. package/lib/{chunk-J6G23RUI.mjs → chunk-262TP6UU.mjs} +1 -1
  4. package/lib/{chunk-NWVVCZUK.mjs → chunk-27BBEGUD.mjs} +1 -1
  5. package/lib/{chunk-Y5ZCPY36.mjs → chunk-2ADSD5WK.mjs} +1 -1
  6. package/lib/{chunk-55LQD3Y3.mjs → chunk-2GSMHGIV.mjs} +1 -1
  7. package/lib/chunk-2K5BYZQM.mjs +8 -0
  8. package/lib/{chunk-GK7VEYFM.mjs → chunk-2KTGDYUH.mjs} +1 -1
  9. package/lib/{chunk-T3PLRQ2T.mjs → chunk-2N73W63D.mjs} +1 -1
  10. package/lib/{chunk-7PK5QDQI.mjs → chunk-2R6GFNKF.mjs} +1 -1
  11. package/lib/{chunk-2OIRJEYE.mjs → chunk-2WMKJVD2.mjs} +1 -1
  12. package/lib/{chunk-D62KWDDT.mjs → chunk-36Y225OM.mjs} +1 -1
  13. package/lib/{chunk-HYOOJVR6.mjs → chunk-3CM7LAPE.mjs} +1 -1
  14. package/lib/{chunk-OIIL4NVI.mjs → chunk-3OVTKRS4.mjs} +1 -1
  15. package/lib/{chunk-UT27HXE7.mjs → chunk-3V4YH5KO.mjs} +1 -1
  16. package/lib/{chunk-OZNLOV4U.mjs → chunk-446GBKAC.mjs} +1 -1
  17. package/lib/{chunk-SQGP46QS.mjs → chunk-4GCYGQXD.mjs} +1 -1
  18. package/lib/{chunk-2NAIUKVL.mjs → chunk-4V3QO7HF.mjs} +1 -1
  19. package/lib/{chunk-GWRKS3AL.mjs → chunk-4X5D3MSV.mjs} +1 -1
  20. package/lib/{chunk-KGYXLSQ5.mjs → chunk-5OGNK3JP.mjs} +1 -1
  21. package/lib/{chunk-D7P7DTWL.mjs → chunk-6KOUYHEY.mjs} +1 -1
  22. package/lib/chunk-6QSHWIZI.mjs +48 -0
  23. package/lib/chunk-6VOQFISN.mjs +7 -0
  24. package/lib/{chunk-742SSN7I.mjs → chunk-6YC2ELCU.mjs} +1 -1
  25. package/lib/chunk-77IVKH7R.mjs +7 -0
  26. package/lib/{chunk-KNIRA333.mjs → chunk-77MZRBWX.mjs} +1 -1
  27. package/lib/{chunk-ZUA5BNAO.mjs → chunk-7BQMBXKX.mjs} +1 -1
  28. package/lib/{chunk-OQQHNYR7.mjs → chunk-7DPHZWA4.mjs} +2 -2
  29. package/lib/chunk-7V2UYZ6S.mjs +7 -0
  30. package/lib/chunk-7WSQ65WG.mjs +9 -0
  31. package/lib/{chunk-HVC5CYIB.mjs → chunk-7ZBDACVG.mjs} +1 -1
  32. package/lib/chunk-A32ISQ6M.mjs +28 -0
  33. package/lib/{chunk-XC2QKQT5.mjs → chunk-AG24QMSY.mjs} +1 -1
  34. package/lib/{chunk-K77NR3UK.mjs → chunk-AHUGG3WU.mjs} +1 -1
  35. package/lib/{chunk-K55LH4ZQ.mjs → chunk-ALBY5SOH.mjs} +1 -1
  36. package/lib/chunk-AXFD2OH6.mjs +7 -0
  37. package/lib/{chunk-YCSFP6ER.mjs → chunk-BH76USTQ.mjs} +1 -1
  38. package/lib/chunk-BNKT3R3F.mjs +7 -0
  39. package/lib/{chunk-YIGFYZQY.mjs → chunk-BPHTA6KP.mjs} +1 -1
  40. package/lib/{chunk-MNITSYI2.mjs → chunk-BT43WSOS.mjs} +1 -1
  41. package/lib/{chunk-ZWZXQTAK.mjs → chunk-BVZ5H3N4.mjs} +14 -14
  42. package/lib/{chunk-43K2C6H2.mjs → chunk-C6RKM4BB.mjs} +1 -1
  43. package/lib/{chunk-C4YGSK6W.mjs → chunk-CDWZGQAJ.mjs} +1 -1
  44. package/lib/chunk-CGZGL6VT.mjs +7 -0
  45. package/lib/{chunk-KE2PGD6C.mjs → chunk-CN5HGFG4.mjs} +1 -1
  46. package/lib/chunk-CQAFVEKP.mjs +13 -0
  47. package/lib/{chunk-XIZ5LMQM.mjs → chunk-CTPLYUXA.mjs} +1 -1
  48. package/lib/chunk-CXKZ6TYV.mjs +9 -0
  49. package/lib/{chunk-DHIW4IO5.mjs → chunk-D6JT4PAB.mjs} +1 -1
  50. package/lib/{chunk-AELFEK3G.mjs → chunk-D7XUNWWU.mjs} +1 -1
  51. package/lib/{chunk-GR3NGDVM.mjs → chunk-DB5RVDC5.mjs} +1 -1
  52. package/lib/{chunk-MO3N5XVV.mjs → chunk-DIGUC7S4.mjs} +2 -2
  53. package/lib/{chunk-2OZG6GRW.mjs → chunk-DKDKCGXV.mjs} +1 -1
  54. package/lib/chunk-DMT5SCO3.mjs +7 -0
  55. package/lib/chunk-DNQKVCUV.mjs +475 -0
  56. package/lib/{chunk-MAHZMPMZ.mjs → chunk-DSR2MSBH.mjs} +1 -1
  57. package/lib/{chunk-O6ADMP36.mjs → chunk-E3RQ575Y.mjs} +1 -1
  58. package/lib/{chunk-ETT5GP4P.mjs → chunk-EOQON3E5.mjs} +1 -1
  59. package/lib/{chunk-TKQQVB2D.mjs → chunk-ETNQHIDI.mjs} +1 -1
  60. package/lib/chunk-F5SBGJWW.mjs +7 -0
  61. package/lib/chunk-FBXH4VRQ.mjs +7 -0
  62. package/lib/chunk-FKCIGJOI.mjs +15 -0
  63. package/lib/{chunk-OVOLG3AL.mjs → chunk-FVLFO2S6.mjs} +1 -1
  64. package/lib/{chunk-YOGMP72T.mjs → chunk-FYWNSMOZ.mjs} +1 -1
  65. package/lib/{chunk-DHGPDSXS.mjs → chunk-GEEWPTV5.mjs} +1 -1
  66. package/lib/{chunk-FSDO4DJA.mjs → chunk-GLN4PI5P.mjs} +1 -1
  67. package/lib/{chunk-PYUEHBA6.mjs → chunk-GT5ZKU6V.mjs} +1 -1
  68. package/lib/chunk-GTRU5AV5.mjs +7 -0
  69. package/lib/chunk-H33DVU3D.mjs +7 -0
  70. package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
  71. package/lib/{chunk-4L7FBOJS.mjs → chunk-HQZUQXDC.mjs} +1 -1
  72. package/lib/{chunk-VSU74RQ3.mjs → chunk-HVX2AFYW.mjs} +1 -1
  73. package/lib/chunk-I3ZO76LL.mjs +21 -0
  74. package/lib/{chunk-V4RKM4QZ.mjs → chunk-I5C4O3VA.mjs} +1 -1
  75. package/lib/{chunk-FSZTXLNW.mjs → chunk-IHGYJZZ2.mjs} +1 -1
  76. package/lib/chunk-ISA2NYJV.mjs +7 -0
  77. package/lib/{chunk-2IB7I3IQ.mjs → chunk-ISAUCWYK.mjs} +1 -1
  78. package/lib/{chunk-3B5H24ZG.mjs → chunk-ISOSTAJR.mjs} +1 -1
  79. package/lib/chunk-IXIY6Q4M.mjs +7 -0
  80. package/lib/{chunk-TPHXRHOA.mjs → chunk-J3TIHLWG.mjs} +1 -1
  81. package/lib/{chunk-TQM2XJ27.mjs → chunk-JAV6F6OA.mjs} +1 -1
  82. package/lib/chunk-JBWJ6UEZ.mjs +7 -0
  83. package/lib/{chunk-WM5JI4JI.mjs → chunk-JH4ZTVQN.mjs} +1 -1
  84. package/lib/{chunk-BZFIOZS3.mjs → chunk-JIPT5FUD.mjs} +1 -1
  85. package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
  86. package/lib/{chunk-67CC7RAE.mjs → chunk-JREKJO3D.mjs} +1 -1
  87. package/lib/{chunk-3AOKLIVE.mjs → chunk-JUOQUG7U.mjs} +1 -1
  88. package/lib/chunk-JYUMD357.mjs +7 -0
  89. package/lib/{chunk-56MPPWLA.mjs → chunk-K7G3W7XH.mjs} +1 -1
  90. package/lib/{chunk-OU5W7SCB.mjs → chunk-KKS2KFBT.mjs} +1 -1
  91. package/lib/{chunk-RKALOKAU.mjs → chunk-KWAVSZ2B.mjs} +1 -1
  92. package/lib/{chunk-WI4HYWV6.mjs → chunk-KXUOHACP.mjs} +1 -1
  93. package/lib/{chunk-GTIXJCGS.mjs → chunk-L3I6DAHX.mjs} +1 -1
  94. package/lib/{chunk-FLNLG43R.mjs → chunk-L47JCNP3.mjs} +1 -1
  95. package/lib/{chunk-5344TZBT.mjs → chunk-L4MSL4U7.mjs} +1 -1
  96. package/lib/chunk-L4RJX7DG.mjs +7 -0
  97. package/lib/chunk-L6CLN664.mjs +7 -0
  98. package/lib/chunk-LI2XNV7F.mjs +7 -0
  99. package/lib/chunk-LP2D3JJP.mjs +7 -0
  100. package/lib/{chunk-EH5YUA5W.mjs → chunk-LWES2KZE.mjs} +1 -1
  101. package/lib/{chunk-YJEXE6HZ.mjs → chunk-LYOGCIYD.mjs} +2 -2
  102. package/lib/{chunk-BNO5GIJ6.mjs → chunk-MJD6CPZZ.mjs} +1 -1
  103. package/lib/{chunk-33ZX3A56.mjs → chunk-MTM4KG3T.mjs} +1 -1
  104. package/lib/{chunk-E2YJVSX6.mjs → chunk-N2HYG3BL.mjs} +1 -1
  105. package/lib/chunk-N5UIE4IR.mjs +7 -0
  106. package/lib/{chunk-R6TF26V4.mjs → chunk-NDFFIJL5.mjs} +1 -1
  107. package/lib/{chunk-FDGFUEK3.mjs → chunk-NFEBX75O.mjs} +1 -1
  108. package/lib/{chunk-QXLZINZB.mjs → chunk-NNV7IGM7.mjs} +1 -1
  109. package/lib/{chunk-OXKZ4Y3B.mjs → chunk-NS6ONPWL.mjs} +1 -1
  110. package/lib/{chunk-OEHVAJAB.mjs → chunk-O7GCCRPW.mjs} +1 -1
  111. package/lib/chunk-OO24ZYYJ.mjs +7 -0
  112. package/lib/chunk-OOIDCHBQ.mjs +9 -0
  113. package/lib/{chunk-MWLFFVQV.mjs → chunk-OS5GE52G.mjs} +1 -1
  114. package/lib/chunk-OS6HFJ7L.mjs +7 -0
  115. package/lib/{chunk-HYBH5PFM.mjs → chunk-OTJH6AEA.mjs} +1 -1
  116. package/lib/chunk-OUU47Y7A.mjs +7 -0
  117. package/lib/{chunk-FTA5LOVX.mjs → chunk-P6WRYJN3.mjs} +1 -1
  118. package/lib/{chunk-DXOXLUZA.mjs → chunk-PDRXM5WN.mjs} +1 -1
  119. package/lib/chunk-PGRY365W.mjs +7 -0
  120. package/lib/chunk-Q4PPI3KG.mjs +7 -0
  121. package/lib/chunk-QFTF2PGS.mjs +21 -0
  122. package/lib/chunk-QKJXIY6L.mjs +7 -0
  123. package/lib/{chunk-DMBR24CK.mjs → chunk-QLRWU3MB.mjs} +1 -1
  124. package/lib/chunk-QO4MPHZD.mjs +7 -0
  125. package/lib/chunk-QP3JLFIO.mjs +7 -0
  126. package/lib/{chunk-UCHAZ4ZU.mjs → chunk-QQDZQCO2.mjs} +1 -1
  127. package/lib/chunk-QROPNEGY.mjs +14 -0
  128. package/lib/{chunk-6NADW3OI.mjs → chunk-QXB6U3ZP.mjs} +1 -1
  129. package/lib/chunk-R3OM3X4L.mjs +8 -0
  130. package/lib/chunk-R7GKMAT4.mjs +7 -0
  131. package/lib/{chunk-JU2XEKEO.mjs → chunk-RVCPQVKM.mjs} +1 -1
  132. package/lib/{chunk-WEZLXE34.mjs → chunk-RZKJQOOC.mjs} +1 -1
  133. package/lib/chunk-S4PRKKGC.mjs +8 -0
  134. package/lib/{chunk-NJ3EOEHS.mjs → chunk-SX6QWYCQ.mjs} +1 -1
  135. package/lib/{chunk-ONMBSACW.mjs → chunk-T36DZJPH.mjs} +1 -1
  136. package/lib/{chunk-AJPSGVMD.mjs → chunk-T7DDS4UQ.mjs} +1 -1
  137. package/lib/chunk-TCEXCHXR.mjs +7 -0
  138. package/lib/chunk-TMIESDE5.mjs +7 -0
  139. package/lib/chunk-TQJ5NPRC.mjs +7 -0
  140. package/lib/chunk-TUPZY2QJ.mjs +7 -0
  141. package/lib/{chunk-2Z54GB6X.mjs → chunk-U2CTKIPE.mjs} +1 -1
  142. package/lib/{chunk-DQR5NDMI.mjs → chunk-U4YFYSF3.mjs} +1 -1
  143. package/lib/{chunk-EOSEMFPU.mjs → chunk-UIR77ZJD.mjs} +1 -1
  144. package/lib/{chunk-UUSLTW5V.mjs → chunk-UOHZW2L4.mjs} +1 -1
  145. package/lib/chunk-UV74P4H2.mjs +7 -0
  146. package/lib/{chunk-CULAOP3U.mjs → chunk-VXZ5PTOM.mjs} +1 -1
  147. package/lib/{chunk-IBURU7T7.mjs → chunk-VZLJZEV2.mjs} +1 -1
  148. package/lib/chunk-W3BQGMTR.mjs +7 -0
  149. package/lib/{chunk-WWTXRWNZ.mjs → chunk-WABXKL4N.mjs} +1 -1
  150. package/lib/{chunk-E2OBAWSH.mjs → chunk-WAYQLQAD.mjs} +1 -1
  151. package/lib/{chunk-6CDIIFNX.mjs → chunk-WBELLGNE.mjs} +1 -1
  152. package/lib/{chunk-LO527YLT.mjs → chunk-WJAZ5LHL.mjs} +1 -1
  153. package/lib/{chunk-6IGEASOF.mjs → chunk-WXU6ZJIV.mjs} +1 -1
  154. package/lib/{chunk-YHIOS2PU.mjs → chunk-WZN36ACK.mjs} +1 -1
  155. package/lib/{chunk-AITNZWLB.mjs → chunk-X2XZQ434.mjs} +1 -1
  156. package/lib/chunk-X4HZD5U2.mjs +7 -0
  157. package/lib/chunk-X6XNTOGO.mjs +7 -0
  158. package/lib/{chunk-5VQNKDFU.mjs → chunk-XAMMIPZ4.mjs} +1 -1
  159. package/lib/{chunk-MHW6DV6T.mjs → chunk-XAUQXYPW.mjs} +1 -1
  160. package/lib/{chunk-5UT2ZBGF.mjs → chunk-XCJUNX63.mjs} +1 -1
  161. package/lib/chunk-XJICAOAQ.mjs +7 -0
  162. package/lib/{chunk-GYKNCYES.mjs → chunk-XKFHTBAB.mjs} +1 -1
  163. package/lib/{chunk-6SEDOIO3.mjs → chunk-XMQ5R6TC.mjs} +1 -1
  164. package/lib/chunk-XPXEQKLR.mjs +7 -0
  165. package/lib/{chunk-SW2NUKQL.mjs → chunk-Y7YUNRKK.mjs} +1 -1
  166. package/lib/{chunk-UIUPPEFB.mjs → chunk-YBZIDW6W.mjs} +1 -1
  167. package/lib/{chunk-X2ZVSQ54.mjs → chunk-YEVB7LVK.mjs} +1 -1
  168. package/lib/{chunk-EAFLDSQ2.mjs → chunk-Z3MGN42K.mjs} +1 -1
  169. package/lib/{chunk-MKNAZPOT.mjs → chunk-ZB5E7NHU.mjs} +1 -1
  170. package/lib/chunk-ZCOSME6P.mjs +7 -0
  171. package/lib/{chunk-KRNFVAGC.mjs → chunk-ZOSESZ22.mjs} +1 -1
  172. package/lib/chunk-ZTHC42X6.mjs +7 -0
  173. package/lib/{chunk-XEB6HZ34.mjs → chunk-ZXOUWHYE.mjs} +1 -1
  174. package/lib/sandforge-autopilot.mjs +1 -1
  175. package/lib/sandforge-backup.mjs +1 -1
  176. package/lib/sandforge-checkpoint.mjs +1 -1
  177. package/lib/sandforge-cleanup.mjs +1 -1
  178. package/lib/sandforge-clone.mjs +1 -1
  179. package/lib/sandforge-compare.mjs +1 -1
  180. package/lib/sandforge-dataops.mjs +1 -1
  181. package/lib/sandforge-empty.mjs +4 -4
  182. package/lib/sandforge-env.mjs +184 -139
  183. package/lib/sandforge-frozen.mjs +1 -1
  184. package/lib/sandforge-mcp.mjs +14 -14
  185. package/lib/sandforge-monitor.mjs +1 -1
  186. package/lib/sandforge-pipeline.mjs +1 -1
  187. package/lib/sandforge-seed.mjs +1 -1
  188. package/lib/sandforge-sync.mjs +1 -1
  189. package/lib/sandforge-users.mjs +155 -0
  190. package/lib/sandforge.mjs +1 -22
  191. package/lib/sf/sandforge/autopilot.mjs +20 -0
  192. package/lib/sf/sandforge/backup.mjs +20 -0
  193. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  194. package/lib/sf/sandforge/cleanup.mjs +20 -0
  195. package/lib/sf/sandforge/clone.mjs +20 -0
  196. package/lib/sf/sandforge/compare.mjs +20 -0
  197. package/lib/sf/sandforge/dataops.mjs +20 -0
  198. package/lib/sf/sandforge/empty.mjs +20 -0
  199. package/lib/sf/sandforge/env.mjs +20 -0
  200. package/lib/sf/sandforge/frozen.mjs +20 -0
  201. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  202. package/lib/sf/sandforge/index.mjs +20 -0
  203. package/lib/sf/sandforge/mcp.mjs +20 -0
  204. package/lib/sf/sandforge/monitor.mjs +20 -0
  205. package/lib/sf/sandforge/pipeline.mjs +20 -0
  206. package/lib/sf/sandforge/seed.mjs +20 -0
  207. package/lib/sf/sandforge/sync.mjs +20 -0
  208. package/lib/sf/sandforge/users.mjs +20 -0
  209. package/lib/sfHelpHook.mjs +7 -0
  210. package/lib/sfPlugin.mjs +11 -0
  211. package/oclif.manifest.json +1 -0
  212. package/package.json +17 -3
  213. package/lib/chunk-2ZMGVBLW.mjs +0 -7
  214. package/lib/chunk-5C5XEVZN.mjs +0 -11
  215. package/lib/chunk-5CKWGZX4.mjs +0 -9
  216. package/lib/chunk-5ZKCLBTN.mjs +0 -474
  217. package/lib/chunk-7DALDJMO.mjs +0 -7
  218. package/lib/chunk-CAFUNR6D.mjs +0 -7
  219. package/lib/chunk-DPYTG6DM.mjs +0 -48
  220. package/lib/chunk-G4VXPS3A.mjs +0 -7
  221. package/lib/chunk-GF247DA7.mjs +0 -7
  222. package/lib/chunk-IKGHRYCN.mjs +0 -7
  223. package/lib/chunk-IM2XA6JI.mjs +0 -7
  224. package/lib/chunk-K5HV4YRO.mjs +0 -7
  225. package/lib/chunk-KOQV4WXC.mjs +0 -8
  226. package/lib/chunk-N6HHNR6J.mjs +0 -7
  227. package/lib/chunk-N7J6NJQ6.mjs +0 -7
  228. package/lib/chunk-NWPQF5XR.mjs +0 -7
  229. package/lib/chunk-O7DAFE6M.mjs +0 -14
  230. package/lib/chunk-OMZJ37JI.mjs +0 -15
  231. package/lib/chunk-R2BJWO5N.mjs +0 -20
  232. package/lib/chunk-T26C576X.mjs +0 -9
  233. package/lib/chunk-T5VAULLQ.mjs +0 -7
  234. package/lib/chunk-V2QO6KOE.mjs +0 -19
  235. package/lib/chunk-V473C7LY.mjs +0 -7
  236. package/lib/chunk-W2AAGIZF.mjs +0 -7
  237. package/lib/chunk-WD47PGUS.mjs +0 -10
  238. package/lib/chunk-XC54KKKC.mjs +0 -7
  239. package/lib/chunk-XGKSSCW7.mjs +0 -7
  240. package/lib/chunk-ZWCRWF7E.mjs +0 -7
@@ -1,19 +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 Nn,b as fd,c as Cn,d as pd,f as yd,g as wd}from"./chunk-5CKWGZX4.mjs";import{l as ki}from"./chunk-R6TF26V4.mjs";import{a as Mn,b as bd,c as Rd,d as or,e as kd,f as Id}from"./chunk-WD47PGUS.mjs";import{c as ud,d as fe,f as md,g as Dn}from"./chunk-5C5XEVZN.mjs";import{a as Tr,b as gd,c as Mo,d as ot,e as zn,f as nr,g as xo,h as hd}from"./chunk-DXOXLUZA.mjs";import{k as ld}from"./chunk-5344TZBT.mjs";import{i as Ii}from"./chunk-V4RKM4QZ.mjs";import{e as Ri,f as To}from"./chunk-JU2XEKEO.mjs";import{G as dd,N as Do,O as cd,i as td,l as Ln,m as rd,n as nd,o as od,p as sd,v as ad}from"./chunk-IM2XA6JI.mjs";import{l as id}from"./chunk-DHGPDSXS.mjs";import{a as ei,b as Sn}from"./chunk-XCA5AONB.mjs";import{$a as Io,Dc as On,Ec as Oo,Xa as ja,Ya as Ea,Za as Fa,_a as La,a as Ra,ab as Na,b as Ot,bb as Ca,cb as za,db as Da,eb as Ma,g as yo,h as ka,j as Oe,k as Ia,l as Ir,m as va,n as wt,o as re,s as wo,wc as nt}from"./chunk-CAFUNR6D.mjs";import{a as wn}from"./chunk-CE6ZDGBB.mjs";import{a as si,b as ai}from"./chunk-BOGNK4LV.mjs";import{Ha as Ji,Na as Xi,Q as Yi,Ua as Zi,Wa as zo,Za as Qi,_a as ed,a as Ys,b as Js,h as qi,i as Gi,n as No,ua as Co}from"./chunk-KGYXLSQ5.mjs";import{a as Wi,b as Lo,c as Pr,d as En,h as Ui,i as Fn,j as Ki,l as Vi,m as Hi}from"./chunk-TEIBWMJM.mjs";import{e as yi,h as wi,j as bi}from"./chunk-4L7FBOJS.mjs";import{f as mi,i as Po,j as Tn}from"./chunk-UIUPPEFB.mjs";import{a as Ua,b as vo,c as Ka,d as Va,e as Ha,k as Za,l as Qa}from"./chunk-6SEDOIO3.mjs";import{B as _a,C as Ba,J as qa,N as zt,O as Ga,P as kn,Q as Wa}from"./chunk-ZWCRWF7E.mjs";import{c as In,d as vn}from"./chunk-T63U4OZJ.mjs";import{a as Ya,c as Ja,d as Xa,r as Ao}from"./chunk-ETT5GP4P.mjs";import{H as So,L as di,i as ii,k as Pn}from"./chunk-E2YJVSX6.mjs";import{r as Ae,s as vr,t as An,x as oi,z as Or}from"./chunk-T26C576X.mjs";import{a as vt}from"./chunk-4TLYUZD5.mjs";import{a as Us,b as Ks,d as Vs,e as Hs}from"./chunk-SQGP46QS.mjs";import{b as ti,c as ri,g as ni}from"./chunk-6IGEASOF.mjs";import{$a as vi,Ec as Bi,Pb as ji,Ra as jo,Vb as Ei,Xb as Fi,Yb as Li,_a as Eo,ac as Ni,b as ya,bc as Ci,c as wa,db as Oi,e as Xe,eb as Fo,ec as zi,f as ba,fb as Si,fc as Di,gc as Mi,hb as Ar,ib as Ai,jb as Pi,lb as Ti,sc as xi,tc as $i,uc as _i}from"./chunk-KOQV4WXC.mjs";import{a as lt,b as St}from"./chunk-VV3B6IC3.mjs";import{b as ci,d as li,f as Sr,g as ui,h as fi,i as pi,j as gi,p as hi}from"./chunk-CULAOP3U.mjs";import{i as Oa}from"./chunk-INIT2UKJ.mjs";import{h as $a}from"./chunk-KRNFVAGC.mjs";import{q as jn}from"./chunk-2OIRJEYE.mjs";import{b as bn}from"./chunk-HFSBDM7B.mjs";import{b as Aa,c as ct,e as bo,g as Pa,h as Ro,i as Ta,j as ko}from"./chunk-OHEOJISY.mjs";import{a as Sa}from"./chunk-EADHKH3A.mjs";import{$ as da,E as na,F as Nt,G as yt,I as ho,L as oa,M as sa,N as aa,Y as mo,Z as ia,a as Rr,b as Je,c as Xt,d as gn,da as Ct,ea as ca,f as Zt,fa as la,g as Xs,ga as ua,ha as fa,ia as pa,ja as er,k as Zs,ka as tr,l as go,m as Qs,n as ea,o as ta,p as ra,q as Ve,r as Ue,s as hn,t as kr,u as mn,v as Qt,z as yn}from"./chunk-55LQD3Y3.mjs";import{a as De,h as ge}from"./chunk-TZE3Y7IQ.mjs";import{a as xa}from"./chunk-3B5H24ZG.mjs";import{b as Rn}from"./chunk-UNDIBZWG.mjs";import{g as ga,h as rr,i as ha,j as ma}from"./chunk-EAFLDSQ2.mjs";import{b as X}from"./chunk-CA5NAXSU.mjs";import{$b as xs,Ac as ln,B as Ms,Bc as Bs,Gc as qs,Hd as Lt,Id as pn,Lc as un,Mc as fn,ac as Yt,dc as on,fc as qe,gc as sn,hc as mt,ic as Ft,jc as an,mc as We,nc as Ye,oc as dn,pc as ze,qc as Jt,qd as Gs,rc as $s,s as Ds,tc as _s,uc as cn,xd as Ws,zd as br}from"./chunk-DPYTG6DM.mjs";import{b as Ce,e as rn,f as nn,k as ht,l as Ge,s as Ns,u as Cs,v as zs,z as po}from"./chunk-WZQEK4WT.mjs";var He=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function sr(o){return o.objects.reduce((e,t)=>e+t.records.length,0)}async function vd(o){if($o(o),o.protectedOrgIds?.includes(o.orgId))throw new He("protected-environment",`Refusing frozen-dataset load on protected environment ${o.orgId}: it is listed in the protectedOrgIds configuration. Remediation: pick an unprotected sandbox, or review the protected-environment configuration if this org was retired.`,{orgId:o.orgId});if(o.manifest&&o.manifest.source.orgId===o.orgId)throw new He("source-is-target",`Refusing frozen-dataset load on ${o.orgId}: this org is the dataset SOURCE (manifest source.orgId). Loading would mix pseudonymized records with their origin. Remediation: target a fresh dev sandbox instead.`,{orgId:o.orgId});if(!await o.mockDetector.areCalloutsMocked(o.orgId))throw new He("unmocked-callouts",`Refusing frozen-dataset load on ${o.orgId}: unmocked callouts detected. Records under load would trigger real external calls. Remediation: deploy the mock configuration to the TARGET org (e.g. the custom metadata flag read by CustomMetadataCalloutMockDetector), then retry \u2014 never edit data on the source org.`,{orgId:o.orgId});if(sr(o.dataset)===0)throw new He("empty-dataset","Refusing frozen-dataset load: the dataset contains zero records. Remediation: re-run the selection/extraction with a coverage matrix that matches the source data, then freeze a new dataset version.")}function $o(o){if(o.orgTier==="staging")throw new He("non-sandbox",`Refusing frozen-dataset load on ${o.orgId}: it is a sandbox marked Staging, which holds real data, and a load never goes into one. Remediation: pick another sandbox, or, if this one holds no real data, untick Staging in its Edit dialog on the Organizations page.`,{orgId:o.orgId,tier:o.orgTier});if(o.orgTier!=="development"&&o.orgTier!=="scratch")throw new He("non-sandbox",`Refusing frozen-dataset load on ${o.orgTier} org ${o.orgId}: loads go into sandboxes and Developer Edition orgs only. Remediation: target a Developer/Scratch sandbox or a Developer Edition org \u2014 deploy the required configuration THERE; never run DML against a shared or source org.`,{orgId:o.orgId,tier:o.orgTier})}var jr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${ge(this.config.metadataTypeApiName)} WHERE ${ge(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var xn=class{constructor(e){this.orgAccess=e}orgAccess;uiApiCache=new Map;async alignObject(e){let t=new Map(e.describe.fields.map(d=>[d.name,d])),r=new Map,n=[],s=[],a=[];for(let d of e.records){let i={},u=e.accountKindOf?.(d.referenceId);for(let[l,c]of Object.entries(d.fields)){if(u!==void 0&&un(Ve,l,u))continue;let f=t.get(l);if(!f){this.countRemoval(r,l,"not-in-target");continue}if(!f.createable){this.countRemoval(r,l,"not-createable");continue}if(e.leaveOutEncrypted===!0&&f.type===Ya){c!=null&&c!==""&&this.countRemoval(r,l,"may-hold-masks");continue}let p=c;typeof p=="string"&&p!==""&&f.restrictedPicklist===!0&&(f.type==="picklist"||f.type==="multipicklist")&&(p=await this.alignPicklistValue(e,f.name,f.type,d,p,n,s)),i[l]=p}a.push(i)}return{objectApiName:e.objectApiName,alignedRecords:a,removals:[...r.entries()].map(([d,i])=>({objectApiName:e.objectApiName,field:d,reason:i.reason,affectedRecords:i.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,a),uiApiWarnings:s}}detectMissingRequired(e,t){let r=t.filter((i,u)=>!e.linked?.has(e.records[u].referenceId));if(r.length===0)return[];let n=[],s=e.accountKindOf,a=s?e.records.filter(i=>!e.linked?.has(i.referenceId)).map(i=>s(i.referenceId)):[];for(let i of e.describe.fields){let u=s?fn(Ve,i.name):void 0;if(!i.createable||i.nillable&&u===void 0||i.defaultedOnCreate)continue;let l=r.filter((f,p)=>u===void 0||Qt(u,a[p]));if(l.length===0)continue;if(!l.some(f=>{let p=f[i.name];return p!=null&&p!==""})){let f=i.unique?"unique":i.nameField?"name":void 0,p=(i.referenceTo?.length??0)>0,g=(i.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:i.name,isLookup:p,referenceTo:i.referenceTo??[],...f?{distinct:f}:{},...u?{accountKind:u}:{},...!p&&i.type?{fieldType:i.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=cn(e.objectApiName,i=>e.describe.fields.some(u=>u.name===i&&u.createable),i=>r.some(u=>u[i]!==void 0&&u[i]!==null&&u[i]!==""));if(d!==void 0&&!n.some(i=>i.field===d)){let i=e.describe.fields.find(u=>u.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...i?{fieldType:i}:{}})}return n}async alignPicklistValue(e,t,r,n,s,a,d){let i=r==="multipicklist",u=i?s.split(";"):[s],l=e.describe.fields.find(y=>y.name===t),c=new Set((l?.picklistValues??[]).filter(y=>y.active).map(y=>y.value)),f=u.filter(y=>!c.has(y));if(f.length>0){let y=e.ruleFor(e.objectApiName,t);return a.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:y,scope:"global"}),this.applyRule(y,u,f,i)}let p=e.resolvedRecordTypes.get(n.referenceId);if(!p)return s;let g=await this.uiApiValues(e,p,t,d);if(g===null)return s;let h=u.filter(y=>!g.includes(y));if(h.length===0)return s;let m=e.ruleFor(e.objectApiName,t);return a.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:m,scope:"record-type"}),this.applyRule(m,u,h,i)}async uiApiValues(e,t,r,n){let s=`${e.orgId}|${e.objectApiName}|${t}|${r}`,a=this.uiApiCache.get(s);if(a!==void 0)return a;try{let d=await this.orgAccess.picklistValues(e.orgId,e.objectApiName,t,r);return this.uiApiCache.set(s,d),d}catch(d){return this.uiApiCache.set(s,null),n.push(`UI API picklist-values read failed for ${e.objectApiName}.${r} (recordType ${t}): ${d instanceof Error?d.message:String(d)}. Record-type assignment gap check skipped for this field.`),null}}applyRule(e,t,r,n){return e.action==="replace"?e.value:n?t.filter(s=>!r.includes(s)).join(";"):""}countRemoval(e,t,r){let n=e.get(t);n?n.count++:e.set(t,{reason:r,count:1})}};var Er="Opportunity",Fr="SyncedQuoteId",yl="OpportunityLineItem",_o="QuoteLineItem";function Bo(o,e){let t=(d,i)=>{let u=new Map;for(let{referenceId:l,fields:c}of o.get(d)??[]){let f=c[i];typeof f!="string"||f===""||!e(l)||u.set(f,(u.get(f)??0)+1)}return u},r=t(yl,"OpportunityId"),n=t(_o,"QuoteId"),s=new Set((o.get("Quote")??[]).map(d=>d.referenceId)),a=[];for(let{referenceId:d,fields:i}of o.get(Er)??[]){let u=i[Fr];if(typeof u!="string"||!s.has(u)||!e(d)||!e(u))continue;let l=r.get(d)??0,c=n.get(u)??0;l>c&&a.push({opportunity:d,quote:u,products:l,lines:c})}return a}function Od(o,e,t=!1){if(o.length===0)return;let r=o.length===1,n=o.reduce((l,c)=>l+c.products,0),s=o.reduce((l,c)=>l+c.lines,0),a=r?"its":"their",d=r?"the quote's":"the quotes'",i=s===0?`none of ${d} lines`:`${s} of ${d} lines`,u=e&&s===0?", which excludedObjects leaves out":"";return{objectApiName:Er,count:o.length,note:`${o.length} ${t?"would be ":""}left unsynced with ${a} quote: the load ${t?"would write":"wrote"} ${n} of ${a} products and ${i}${u} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${Fr} left empty, the products kept`}}var Ze=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold;refusedBeside},Nr=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},ar=class extends Error{constructor(t){let r=t.reduce((n,s)=>n+s.count,0);super(`This reload finds in the target ${r} record(s) that its purge would delete along with what the loads before it created \u2014 ${t.map(n=>`${n.objectApiName} (${n.count}, under ${n.under.join(", ")})`).join("; ")}: the target deletes them with the record they hang from, which the reload does not find again, and the load would then write against records no longer there. Nothing was written. Give the records they hang from identity keys too, so that the reload finds them again, or take the load back first with a removal, then load the dataset again.`);this.found=t;this.name="ReloadTakesAlongError"}found};function wl(o){return o.perObject.reduce((e,t)=>e+t.toInsert,0)}function bl(o,e){if(!(e===void 0||o<=e))return`This load would insert ${o} record(s), more than the ${e} it may: nothing was written. The dataset or the target changed since that count was taken: preview the load again, and load with the count it gives.`}var st=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${Md(t,void 0)}`:"The load was cancelled before it created or purged a record: the mapping is left as it was.");this.written=t;this.name="FrozenLoadCancelledError"}written},Mt=class extends Error{constructor(t,r,n){super(Rl(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function Rl(o,e,t){return`${X(o)}
8
- The load failed ${Md(e,t)}`}function Md(o,e){let t=new Map,r=(i,u)=>{u!==0&&t.set(i,(t.get(i)??0)+u)};for(let i of o.placeholders)r(i.placeholderObjectApiName,1);for(let i of o.perObject)r(i.objectApiName,i.inserted);let n=[...t.values()].reduce((i,u)=>i+u,0),s=[...Object.values(o.purge.deleted),...Object.values(o.purge.deactivated)].reduce((i,u)=>i+u,0),a=[...n>0?[`created ${n} record(s) (`+[...t].map(([i,u])=>`${i}: ${u}`).join(", ")+")"]:[],...s>0?[`purged ${s} record(s) that earlier loads created`]:[]].join(" and "),d;return e!==void 0?d=n>0?`The mapping could not be written, and nothing names what it created \u2014 no removal or reload will find it: ${e}`:`The mapping could not be written: ${e}`:d=n>0?"What it created is kept in the mapping: a removal takes it back, and a reload purges it or finds it again.":"What the earlier loads created and it did not purge is still named in the mapping, for a removal or the next reload.",a===""?`before it had written the whole dataset. ${d}`:`after it had ${a}. ${d}`}function xd(o,e){let t=[];for(let[r,n]of o.givenRules){let s=[],a={};for(let{referenceId:i,fields:u}of o.alignedByObject.get(r)??[]){if(!gt(u.RecordTypeId)||!e(i))continue;s.push(i);let l=o.withoutRecordType.get(i)??"notRead";a[l]=(a[l]??0)+1}if(s.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:s.length,why:a,...d?{predicted:d}:{}},rule:n,keys:s})}return t}function $d(o){return{namespacePrefix:o.namespacePrefix,developerName:o.developerName}}function kl(o){if(!o)return"the user's default record type applies";if(o.kind==="master")return"the target leaves it on Master for that user";let{developerName:e}=o.info;return o.basis==="userDefault"?`the target gives it ${e}, the user's default record type`:`the target gives it ${e}, the only other record type open to the user`}async function Il(o,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new Mt(o,e.written,X(t))}return new Mt(o,e.written)}function _d(o,e,t){let r=t.map(n=>ct(n.namespacePrefix,n.developerName));return new Ze(`The dataset's ${o} records name record type "${e}" by its label, which ${r.join(" and ")} share in the source: which one each record had cannot be told, the dataset having been extracted before SandForge kept each record's record type by its name. Extract the dataset again. Nothing was written.`,void 0,{reason:"label",objectApiName:o,name:e,recordTypes:r})}function vl(o){for(let{objectApiName:e,records:t}of o.objects){let r=o.recordTypes[e]??[];if(!(r.length<2))for(let n of t){let s=n.fields.RecordTypeId;if(typeof s!="string"||s==="")continue;if(n.recordTypeDeveloperName!==void 0){let d=Ro(n.recordTypeDeveloperName,r,$d);if(d&&"found"in d)continue}let a=r.filter(d=>d.name===s);if(a.length>1)return _d(e,s,a)}}}var Bd="Opportunity",_n="placeholder:",Go=class{byObject=new Map;auditDated=new Set;add(e,t,r=!1){let n=this.byObject.get(e)??[];n.push(t),this.byObject.set(e,n),r&&this.auditDated.add(e)}sentAuditDates(e){return this.auditDated.has(e)}list(e=[]){let t=new Map,r=(n,s)=>{t.set(n,[...t.get(n)??[],...s])};for(let{objectApiName:n,referenceIds:s}of e)r(n,s);for(let[n,s]of this.byObject)r(n,s);return[...t].map(([n,s])=>({objectApiName:n,referenceIds:s}))}};function Ol(o){if(o.startsWith(_n))return o.split(":")[1]??"Unknown";let e=o.lastIndexOf("-");return e>0?o.slice(0,e):"Unknown"}function Sl(o){return typeof o=="number"?String(o):typeof o=="boolean"?o?"TRUE":"FALSE":`'${De(String(o))}'`}var At=200;function pe(o){return o.slice(0,15)}var Al=["CreatedDate","LastModifiedDate"],Pl=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function Dt(o){return typeof o=="string"?Date.parse(o):Number.NaN}function Sd(o){return o.success||o.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Ad(o){if(o.tried===0)return"";let e=o.tried-o.went,t=[o.went>0?`${o.went} went`:"",e>0?`${e} refused again`:""].filter(Boolean);return` \u2014 ${o.tried} refused at first, sent again once the rest had gone: ${t.join(", ")}`}function Pd(o,e,t){let r=`Status set to ${e.draft} for the purge, and left there: ${e.status} could not be given back \u2014 ${t}`,n=o.failures.find(s=>s.objectApiName===e.objectApiName&&pe(s.recordId)===pe(e.id));n?n.errors=[...n.errors,r]:o.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function qo(o,e){let t=(o.notInserted??0)+(e.notInserted??0),r=[o.writtenWithoutFields,e.writtenWithoutFields].reduce((n,s)=>s?Po(n,s):n,void 0);return{objectApiName:e.objectApiName,fromFiles:o.fromFiles+e.fromFiles,inserted:o.inserted+e.inserted,reused:o.reused+e.reused,skippedDuplicates:[...o.skippedDuplicates,...e.skippedDuplicates],failed:[...o.failed,...e.failed],...r?{writtenWithoutFields:r}:{},...t>0?{notInserted:t}:{}}}function Td(o){let e=o.filter(r=>r.replacedWith===void 0).map(r=>r.field),t=o.filter(r=>r.replacedWith!==void 0).map(r=>`${r.field} set to "${r.replacedWith}"`);return[...e.length>0?[`without ${e.join(", ")}`]:[],...t.length>0?[`with ${t.join(", ")}`]:[]].join(" and ")}function Bn(o,e="inserted"){return o>0?`, ${o} not ${e}: the load was cancelled first`:""}function Wo(o,e="inserted"){return o>0?`, ${o} not ${e}: the load failed`:""}function Tl(o,e){return o>0?"error":e>0?"stopped":"done"}function pt(o,e,t,r){return{phase:o,status:"error",progress:e,message:`${t} \u2014 ${X(r)}`}}var jd={phase:"guards",status:"started",progress:0,message:"Evaluating entry guards"};function $n(o,e){let{phase:t,progress:r,did:n,refused:s,notDone:a,done:d,notes:i=""}=o;return e?{phase:t,status:"error",progress:r,message:`${n}${Wo(a,d)}${i} \u2014 ${X(e.cause)}`}:{phase:t,status:Tl(s,a),progress:r,message:`${n}${Bn(a,d)}${i}`}}var Lr={accountNotInDataset:"its person account is not in the dataset",accountNotLoaded:"person account was not loaded (see perObject failures/skips)",noPersonAccounts:"the target org has no person accounts: it holds the account as a business account, which takes the contact as one of its own",businessAccount:"the target holds the account as a business account, which takes the contact as one of its own"};function jl(o){return o.accountReferenceId===""?"Not written: a person account's contact goes in with its account, which the dataset does not hold":"Not written: a person account's contact goes in with its account, which the load did not write"}function qd(o,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of o.personContactSidecar??[])e.get(n)===Ue&&t.set(n,r);for(let r of o.objects.find(n=>n.objectApiName===Ue)?.records??[]){if(t.has(r.referenceId)||!kr(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ve?n:"")}return t}function El(o){let e=new Set;for(let{accountReferenceId:t}of o.personContactSidecar??[])t!==""&&e.add(t);for(let t of o.objects.find(r=>r.objectApiName===Ve)?.records??[]){let r=t.fields.LastName;(kr(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function qn(o,e,t){let r=o.accountKind;return r===void 0?[...e]:e.filter(n=>Qt(r,t(n.referenceId)))}var Cr=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new fe}deps;config;sasGuard;journal;async gateLoad(e){try{await this.passEntryGuards(e)}catch(s){throw e.onProgress?.(jd),e.onProgress?.(pt("guards",2,"Entry guards not passed",s)),s}let t=e.dataset;if(e.pilot)try{t=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(s){throw e.onProgress?.({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"}),e.onProgress?.(pt("pilot",4,"Root folder not selected",s)),s}let r=vl(t);if(r)throw e.onProgress?.({phase:"align",status:"started",progress:12,message:"Resolving record types"}),e.onProgress?.(pt("align",20,"Schema not aligned",r)),r;let n=e.reload===!0&&!e.pilot;return this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:n?"delete":"insert",objectName:e.dataset.objects.filter(s=>s.records.length>0).map(s=>s.objectApiName).join(", "),recordCount:{atMost:sr(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return vd({orgId:e.orgId,orgTier:e.orgTier,dataset:e.dataset,manifest:e.manifest,mockDetector:this.deps.mockDetector,protectedOrgIds:this.config.protectedOrgIds})}async load(e){let t={};try{return await this.loadKeeping(e,t)}finally{await this.journal?.close().catch(()=>{}),this.journal=void 0}}async loadKeeping(e,t){try{return await this.loadInto(e,t)}catch(r){t.endOpenLine?.(r);let n=t.load;throw r instanceof st||!n?.wroteSome()?r:await Il(r,n)}}async planLoad(e){let t=e.now??(()=>new Date),r=d=>e.onProgress?.(d),n=await this.prepare(e,r,{}),s=e.reload&&!e.pilot?await this.planPurge(e.orgId,n.previousLoads,n.mapping):void 0;if(s){let d=await this.foundUnderThePurge(e.orgId,s.residuals,n.mapping,n.refIndex);if(d.length>0)throw new ar(d)}let a=Fd(n,s,{orgId:e.orgId,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:t().toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]});return this.withValidationRules(a)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(i=>i.toInsert>0).map(i=>i.objectApiName),n=[...new Set([...r,...e.placeholders.map(i=>i.placeholderObjectApiName)])];if(!t||n.length===0)return e;let s=new Map,a=new Map;try{for(let{objectApiName:i,onChangeOnly:u,...l}of await t(n))u?a.set(i,[...a.get(i)??[],l.name]):s.set(i,[...s.get(i)??[],l])}catch(i){return{...e,validationRulesUnread:X(i)}}let d=new Set(r);return{...e,perObject:e.perObject.map(i=>{if(i.toInsert===0)return i;let u=s.get(i.objectApiName)??[],l=a.get(i.objectApiName)??[];return{...i,...u.length>0?{validationRules:u}:{},...l.length>0?{validationRulesOnChange:l}:{}}}),placeholders:e.placeholders.map(i=>{let u=d.has(i.placeholderObjectApiName)?[]:s.get(i.placeholderObjectApiName)??[];return u.length>0?{...i,validationRules:u}:i})}}async prepare(e,t,r){let{orgId:n}=e;t(jd);try{await this.passEntryGuards(e)}catch($){throw t(pt("guards",2,"Entry guards not passed",$)),$}t({phase:"guards",status:"done",progress:2,message:"Entry guards passed"}),t({phase:"mapping",status:"started",progress:2,message:"Reading the mapping of earlier loads"});let s=await this.deps.mappingStore.previousLoads().catch($=>{throw t(pt("mapping",3,"Mapping not read",$)),$});t({phase:"mapping",status:"done",progress:3,message:`Mapping read: ${s.length} earlier load(s)`});let a=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{a=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(K){throw t(pt("pilot",4,"Root folder not selected",K)),K}let $=a.objects.reduce((K,Z)=>K+Z.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${$} record(s)`})}let d=Vo(a),i=Cl(e.dataset),u=qd(a,d),l=Bl(a,d,u),c=Ys(l),f=c.flat(),p=new Zt,g=new Zt(_l),h={...a,objects:a.objects.map($=>({...$,records:$.records.filter(K=>!p.leaveOut($.objectApiName,K.referenceId,Zs($.objectApiName,K.fields,typeof K.fields.RelationId=="string"?d.get(K.fields.RelationId):void 0))&&!g.leaveOut($.objectApiName,K.referenceId,K.fields))}))},m=new Map,y=new Set,R=new Set;if(e.reload||e.linkByKeys){t({phase:"reload",status:"started",progress:5,message:"Reusing reference data"}),r.endOpenLine=$=>t(pt("reload",10,"Reference data not reused",$)),await this.reuseByIdentityKeys(e,h,m,y);for(let $ of y)R.add($);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||Cd(h).length>0){t({phase:"catalog",status:"started",progress:10,message:"Looking up the catalog the target already holds"});let $;try{$=await this.lookUpTheCatalog(n,h,m,y)}catch(K){throw t(pt("catalog",11,"Catalog not looked up",K)),K}t({phase:"catalog",status:"done",progress:11,message:`Catalog looked up: ${$.join("; ")}`})}t({phase:"align",status:"started",progress:12,message:"Resolving record types"}),r.endOpenLine=$=>t(pt("align",20,"Schema not aligned",$));let L=[],T=new Map,j=new Map,x=new Map;for(let $ of h.objects){let K=[];for(let Z of $.records)K.push(await this.resolveRecordType(e,a,$.objectApiName,Z,j,L,x));T.set($.objectApiName,K)}let U=new xn(this.deps.orgAccess),S={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:L},w=new Map,I=new Map,A=new Map,N=new Map,v=new Map,P,C=El(a),G=$=>C.has($)?P===!1?"personAsBusiness":"person":"business",M=new Map,W=new Map,V=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let $ of h.objects){let K=$.objectApiName;if($.records.length===0)continue;let Z=$.records.filter(O=>!y.has(O.referenceId)),ne=(O,J)=>{S.excludedObjects.push({objectApiName:K,reason:O}),v.set(K,{objectApiName:K,fromFiles:a.objects.find(ee=>ee.objectApiName===K)?.records.length??$.records.length,inserted:0,reused:$.records.length-Z.length,skippedDuplicates:[],failed:Z.map(ee=>({objectApiName:K,referenceId:ee.referenceId,errors:[J]}))}),Z.length!==0&&t({phase:"align",objectName:K,status:"error",progress:12,message:`Skipped ${K} \u2014 ${O}`})},he;try{he=await this.deps.orgAccess.describe(n,K)}catch(O){let J=`Not present in target org: ${O instanceof Error?O.message:String(O)}. Deploy it to the target, or give the loading user Read on it, then load again; or leave it out of the configuration (excludedObjects) and extract again`;ne(J,J);continue}if(K===Ve&&(P=he.fields.some(O=>O.name===hn)),he.createable===!1&&Z.length>0){ne(`Not createable in target org: ${Z.length} record${Z.length===1?"":"s"} of the dataset not loaded. Give the loading user Create on it in a permission set, where the platform lets a user create it; otherwise leave it out of the configuration (excludedObjects) and extract again`,"Not createable in target org: the running user may not insert it");continue}A.set(K,new Set(he.fields.filter(O=>O.updateable===!1).map(O=>O.name)));let _e=he.fields.filter(O=>O.lookupFilter!==void 0&&O.createable&&(O.referenceTo?.length??0)>0).map(O=>({field:O.name,referenceTo:[...O.referenceTo??[]]}));_e.length>0&&N.set(K,_e);let Me=bn(he.recordTypeInfos);if(Me.some(O=>!O.master)){let O=Ki(Fn(Me));W.set(K,{types:Me,...O?{predicted:O}:{}})}let k=Ml(K,he,this.config);k.length>0&&M.set(K,k),I.set(K,new Set(he.fields.filter(O=>O.createable&&!O.nillable&&!O.defaultedOnCreate&&(O.referenceTo?.length??0)>0).map(O=>O.name)));let F=await U.alignObject({orgId:n,objectApiName:K,records:T.get(K)??[],describe:he,resolvedRecordTypes:j,ruleFor:(O,J)=>this.picklistRuleFor(O,J),linked:y,...K===Ve?{accountKindOf:G}:{},...V?{leaveOutEncrypted:V}:{}});S.objectResults.push(F),S.removals.push(...F.removals),S.adjustments.push(...F.adjustments),w.set(K,F.alignedRecords.map((O,J)=>({referenceId:(T.get(K)??[])[J].referenceId,fields:O})))}let H=await this.linkWhatThePlatformKeeps(n,S.objectResults,w,i,m,y,G),E=e.reload||e.linkByKeys?await this.reuseByKeysAsWritten(n,h,S.objectResults,w,i,m,y,G):{linked:[],said:[],leftEmpty:[]};for(let $ of[...H.linked,...E.linked])R.add($);let q=[...H.said,...E.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${q.length>0?` \u2014 ${q.join("; ")}`:""}`}),r.endOpenLine=void 0;let Y=new Zt(xl(M));Dl(w,I,[p,g,Y]);for(let $ of S.objectResults){let K=(w.get($.objectApiName)??[]).filter(Z=>!y.has(Z.referenceId));$.missingRequired=$.missingRequired.filter(Z=>qn(Z,K,G).some(ne=>gt(ne.fields[Z.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let ae=await this.planRequiredFields(e,S.objectResults).catch($=>{throw t(pt("placeholders",22,"Required fields not covered",$)),$});return t({phase:"placeholders",status:"done",progress:22,message:"Required fields checked"}),{previousLoads:s,working:a,refIndex:d,personContacts:u,groups:c,groupOrder:f,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:Y,loading:h,mapping:m,reused:y,reusedByKeys:R,ranks:i,recordTypeIssues:L,alignment:S,alignedByObject:w,requiredLookups:I,fixedAtInsert:A,filteredLookups:N,lostObjects:v,targetHasPersonAccounts:P,accountKindOf:G,plans:ae,givenRules:W,withoutRecordType:x,keysLeftEmpty:[...H.leftEmpty,...E.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),s=b=>e.onProgress?.(b),{orgId:a}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=await this.prepare(e,s,t),{previousLoads:i,working:u,refIndex:l,personContacts:c,groups:f,groupOrder:p,leftToThePlatform:g,untypedFeedItems:h,heldForExclusions:m,mapping:y,reused:R,ranks:L,recordTypeIssues:T,alignment:j,alignedByObject:x,requiredLookups:U,fixedAtInsert:S,lostObjects:w,targetHasPersonAccounts:I,accountKindOf:A,plans:N}=d,v=bl(wl(Fd(d,void 0,{orgId:a,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:n.toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]})),e.maxRecords);if(v)throw new Nr(v);let P=await this.runUserIdOf(a);P&&this.journal?.writtenAs(P);let C={deleted:{},deactivated:{},failures:[]},G=[],M=[],W=new Go,V=new Map,H=[],E=new Set,q,Y=new Map,ae=!1,$=async()=>{let b=await this.readWrittenBetween(a,W,y),_=q?.linked??new Map,z=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(y,{created:W.list(H),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...E],...z&&z.length>0?{stillToSweep:[...z]}:{}},..._.size>0?{personContacts:Object.fromEntries(_)}:{},...Y.size>0?{withTheirRecord:Object.fromEntries(Y)}:{},...P?{runUserId:P}:{}}),ae=!0},K=()=>W.list().length>0||Object.keys(C.deleted).length>0||Object.keys(C.deactivated).length>0,Z=async()=>{if(!e.signal?.aborted)return;let b=K();throw b&&await $(),new st({perObject:M,placeholders:G,purge:C},b)};t.load={keepMapping:$,mappingKept:()=>ae,wroteSome:K,written:{perObject:M,placeholders:G,purge:C}};let ne=[];if(e.reload){let b="",_={residuals:0},z={tried:0,went:0},se=be=>{let Te=Fe=>Object.values(Fe).reduce((Re,ce)=>Re+ce,0);return $n({phase:"reload",progress:24,did:`Purge: ${Te(C.deleted)} deleted, ${Te(C.deactivated)} deactivated, ${C.failures.length} failed`,refused:C.failures.length,notDone:_.residuals,done:"purged",notes:`${Ad(z)}${b}`},be)};if(!e.pilot){s({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let be=await this.planPurge(a,i,y),Te=await this.foundUnderThePurge(a,be.residuals,y,l);if(Te.length>0){let ce=new ar(Te);throw s(se({cause:ce})),ce}H=be.carried;for(let ce of H.flatMap(oe=>oe.referenceIds)){let oe=y.get(ce);oe&&E.add(pe(oe))}let Fe=Object.values(be.leftUnrecorded).reduce((ce,oe)=>ce+oe,0);Fe>0&&(C.leftUnrecorded=be.leftUnrecorded,b=` \u2014 ${Fe} record(s) left in place of a load recorded before loads kept what they created: it may have linked them`);let Re=Object.entries(be.keptByThePlatform);Re.length>0&&(C.keptByThePlatform=be.keptByThePlatform,b+=" \u2014 kept, the platform does not delete them: "+Re.map(([ce,oe])=>`${ce} (${oe})`).join(", "));try{e.purgeSweep&&(await Z(),await e.purgeSweep.first()),await this.purgeResiduals(e,be,[...p].reverse(),C,Z,E,_,z),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(ce){throw s(se(ce instanceof st?void 0:{cause:ce})),ce}for(let ce of i)if(!ce.created)for(let oe of ce.mapping.values())E.add(pe(oe));s(_.residuals>0||C.failures.length>0?se():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Ad(z)}${b}`})}}let he=b=>(x.get(b)??[]).filter(_=>!R.has(_.referenceId)),_e=N.filter(b=>b.kind==="placeholder").length,Me=b=>$n({phase:"placeholders",progress:25,did:`Placeholders: ${G.length} created`,refused:0,notDone:_e-G.length,done:"created"},b);_e>0&&(await Z(),s({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of N)b.kind==="placeholder"?(await Z(),await this.createPlaceholder(e,b,he(b.missing.objectApiName),y,G,W)):this.applyScalarDefault(b.missing,qn(b.missing,he(b.missing.objectApiName),A),ne,L)}catch(b){throw s(Me(b instanceof st?void 0:{cause:b})),b}_e>0&&s(Me());let k=f.flatMap(b=>b.length>1?Js(b,ql(x,U,l,c)):b),F=[],O=[],J=this.config.duplicateErrorPatterns??gd,ee=new Set(k.includes(Xt)?(x.get(Xt)??[]).map(b=>b.referenceId):[]),Q=[],me=null,te=0,Be=!1,D=b=>b===Je&&Q.length>0?`, ${Q.length} on a case waiting for ${Q.length===1?"its task":"their tasks"}`:"",we=new Set,et=async()=>{if(q)return q;let b=await this.linkPersonContacts(a,c,y,R,I,T);for(let _ of b.linked.keys())R.add(_);return we=new Set(b.unlinked.map(_=>_.contactReferenceId).filter(_=>!R.has(_))),q=b,b},tt=b=>{if(b.objectApiName!==Ue||!q)return b;let _=q.unlinked.filter(z=>we.has(z.contactReferenceId));return _.length===0?b:{...b,failed:[...b.failed,..._.map(z=>({objectApiName:Ue,referenceId:z.contactReferenceId,errors:[jl(z)]}))]}},B=()=>{if(q)for(let[b,_]of q.own)y.has(b)||(q.own.delete(b),q.unlinked.push({accountReferenceId:_.accountReferenceId,contactReferenceId:b,cause:"target-not-loaded",detail:`contact ${b} was not loaded (skipped, failed or excluded)`}))},ie=()=>{let b=q?.linked.size??0,_=q?.own.size??0,z=we.size;return[...b>0?[`${b} linked to the contact the platform wrote with ${b===1?"its":"their"} person account`]:[],..._>0?[`${_} sent as ${_===1?"a contact of its own":"contacts of their own"}: the target holds ${_===1?"its":"their"} account as a business account`]:[],...z>0?[`${z} not written: a person account's contact goes in with its account`]:[]]},bt=(b,_)=>[...b===Ue?ie():[],..._?[_]:[],...g.counts(b).map(({why:z,count:se})=>Xs(se,z)),...h.counts(b).map(({why:z,count:se})=>Nd(se,z)),...m.counts(b).map(({why:z,count:se})=>Yd(se,z))].map(z=>`, ${z}`).join(""),ue=(b,_,z,se,be)=>{let Te=M.findIndex(It=>It.objectApiName===b),Fe=Te>=0?M[Te]:void 0,Re=z.filter(It=>R.has(It.referenceId)).length,ce=Fe?.inserted??0,oe=Fe?.skippedDuplicates??[],Le=Fe?.failed??[],dt=Fe?.writtenWithoutFields,Ie=z.length-Re-ce-oe.length-Le.length,Et=tt({objectApiName:b,fromFiles:_,inserted:ce,reused:Re,skippedDuplicates:oe,failed:Le,...dt?{writtenWithoutFields:dt}:{},...Ie>0?{notInserted:Ie}:{}});Fe?M[Te]=Et:M.push(Et),s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*te/Math.max(k.length,1)),message:`${b}: ${ce} inserted, ${Et.reused} reused, ${oe.length} duplicates skipped, ${Et.failed.length} failed${D(b)}${Wo(Ie)}${Tn(dt)}${bt(b,se)} \u2014 ${X(be)}`})},ft,rt=(b,_,z)=>{if(b.waiting>0){let Re=M.find(ce=>ce.objectApiName===Je);Re&&(Re.notInserted=(Re.notInserted??0)+b.waiting)}let se=_==="cancel"&&b.waiting>0,be="";se?be=Bn(b.waiting):b.waiting>0&&(be=Wo(b.waiting));let Te=b.status;z?Te="error":se&&b.status!=="error"&&(Te="stopped");let Fe=z?` \u2014 ${X(z.cause)}`:"";s({phase:"insert",objectName:Je,status:Te,progress:25+Math.round(55*te/Math.max(k.length,1)),message:`${b.message}${be}${b.notes}${Fe}`})},xe=async()=>{let b=me;b&&e.signal?.aborted&&(me=null,rt(b,"cancel")),await Z()};t.endOpenLine=b=>{let _=ft;ft=void 0,_&&!(b instanceof st)&&_(b);let z=me;me=null,z&&rt(z,b instanceof st?"cancel":"failure")};let ye=async()=>{Be=!0;let b=Q.splice(0,Q.length),_=me;if(me=null,b.length===0)return;let z=25+Math.round(55*te/Math.max(k.length,1)),se;try{await Z()}catch(oe){throw _&&rt(_,oe instanceof st?"cancel":"failure"),oe}let be=oe=>`${oe.inserted} inserted, ${oe.reused} reused, ${oe.skippedDuplicates.length} duplicates skipped, ${oe.failed.length} failed${Bn(oe.notInserted??0)}${Tn(oe.writtenWithoutFields)}`,Te=oe=>{let Le=M.findIndex(dt=>dt.objectApiName===Je);Le>=0?M[Le]=qo(M[Le],oe):M.push(oe)},Fe={};try{se=await this.insertObject(e,Je,0,b,l,y,R,F,J,W,V,Ed(M),oe=>{Fe.result=oe})}catch(oe){let Le=Fe.result;if(Le&&Te(Le),_&&Le){let dt=Le.inserted+Le.skippedDuplicates.length+Le.failed.length;rt({..._,waiting:Math.max(_.waiting-dt,0),message:`${_.message}; after their task: ${be(Le)}`},"failure",{cause:oe})}else _&&rt(_,"failure",{cause:oe});throw oe}Te(se);let Re=be(se),ce="done";se.failed.length>0||_?.status==="error"?ce="error":(se.notInserted??0)>0&&(ce="stopped"),s({phase:"insert",objectName:Je,status:ce,progress:z,message:_?`${_.message}; after their task: ${Re}${_.notes}`:`${Je} after their task: ${Re}`})};for(let b of k){await xe();let _=x.get(b);if(!_){let le=w.get(b);if(le&&b===Ue&&c.size>0){try{await et()}catch(Ne){throw s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*te/Math.max(k.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${X(Ne)}`}),Ne}B();let je=q?.linked??new Map,Ee=le.failed.filter(Ne=>!je.has(Ne.referenceId));M.push({...le,reused:le.reused+le.failed.length-Ee.length,failed:Ee})}else le&&M.push(le);continue}te++,s({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*te/Math.max(k.length,1)),message:`Inserting ${b}`});let z,se=u.objects.find(le=>le.objectApiName===b)?.records.length??_.length,be=_;if(ft=le=>ue(b,se,be,z,le),b===Ue&&c.size>0){let le=await et();be=_.filter(je=>!we.has(je.referenceId));for(let je of be){let Ee=le.own.get(je.referenceId),Ne=je.fields.AccountId;Ee&&(Ne==null||Ne==="")&&(je.fields.AccountId=Ee.accountReferenceId)}}b===Rr&&await this.matchDirectRelations(a,u,_,y,R,Y),b===Xt&&await this.matchTasksWrittenWithEmails(a,u,_,y,R,Y),mo[b]!==void 0&&(z=await this.matchActivityRelations(e,b,_,y,R,S.get(b)??new Set));let Te=0;if(b===Nt){let le=await this.matchContactRolesWrittenWithOpportunities(e,{working:u,aligned:_,refIndex:l,mapping:y,reused:R,withTheirRecord:Y,pendingFk:F,fixedAtInsert:S.get(b)??new Set});Te=le.linked,z=le.note}let Fe=Ct[b],Re=Fe?await this.startAsDrafts(a,b,Fe,be,O):be;if(b===Je&&!Be&&ee.size>0){let le=je=>ta(je,Ee=>l.get(Ee))&&ee.has(String(je.ActivityId));Q.push(...Re.filter(je=>le(je.fields))),Re=Re.filter(je=>!le(je.fields))}let ce=Re.filter(le=>!R.has(le.referenceId)).length,oe=e.signal?.aborted===!0&&ce>0,Le=(le,je,Ee=Ne=>M.push(Ne))=>this.insertObject(e,b,je,le,l,y,R,F,J,W,V,Ed(M),Ee),dt=u.standardPricebook,Ie;if(oe)Ie={objectApiName:b,fromFiles:se,inserted:0,reused:Re.length-ce,skippedDuplicates:[],failed:[],notInserted:ce};else if(an(b)&&dt){let le=await Le(Re.filter(Ee=>Ee.fields[mt]===dt),0),je=Re.filter(Ee=>Ee.fields[mt]!==dt);if(e.signal?.aborted){let Ee=je.filter(ml=>R.has(ml.referenceId)).length,Ne={...le,fromFiles:se,reused:le.reused+Ee},Ht=Re.length-Ne.inserted-Ne.reused-Ne.skippedDuplicates.length-Ne.failed.length;Ie={...Ne,...Ht>0?{notInserted:Ht}:{}}}else{let Ee={},Ne=await Le(je,se,Ht=>{Ee.result=Ht}).catch(Ht=>{throw M.push(Ee.result?qo(le,Ee.result):{...le,fromFiles:se}),Ht});Ie=qo(le,Ne)}}else Ie=await Le(Re,se);ft=void 0,b===Ue&&B(),Ie=tt(Ie),Te>0&&(Ie={...Ie,writtenByThePlatform:Te});let Et=b===Je?Q.filter(le=>!R.has(le.referenceId)).length:0;(Ie.notInserted??0)>0&&(Ie.notInserted=(Ie.notInserted??0)+Et);let It=Ie.notInserted??0;M.push(Ie);let js=bt(b,z),Es=D(b),uo=Ie.failed.length>0,Fs=uo?"error":"done";!uo&&It>0&&(Fs="stopped");let Ls=25+Math.round(55*te/Math.max(k.length,1)),fo=`${b}: ${Ie.inserted} inserted, ${Ie.reused} reused, ${Ie.skippedDuplicates.length} duplicates skipped, ${Ie.failed.length} failed${Es}${Bn(It)}${Tn(Ie.writtenWithoutFields)}`;Es&&It===0?(me={status:uo?"error":"done",message:fo,notes:js,waiting:Et},s({phase:"insert",objectName:b,status:"started",progress:Ls,message:fo})):s({phase:"insert",objectName:b,status:Fs,progress:Ls,message:`${fo}${js}`}),b===Xt&&await ye(),It>0&&await xe()}await ye(),await Z(),s({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let ve={report:{resolved:0,unresolved:[]},unanswered:0},Rt=Bo(x,b=>y.has(b)),en=new Set(Rt.map(b=>b.opportunity)),lo=F.filter(b=>b.objectApiName!==Er||b.field!==Fr||!en.has(b.referenceId)),tn=Rt.length>0?`, ${Rt.length} synced quote${Rt.length===1?"":"s"} left unset`:"",Wt=b=>$n({phase:"pass2",progress:88,did:`Pass 2: ${ve.report.resolved} resolved, ${ve.report.unresolved.length} unresolved${tn}`,refused:ve.report.unresolved.length,notDone:ve.unanswered,done:"resolved"},b);try{await this.patchCycleFks(e,lo,y,ve)}catch(b){throw s(Wt({cause:b})),b}s(Wt());let Ke=ve.report;await Z();let it={report:{restored:0,refused:[]},unanswered:0},gr=b=>$n({phase:"pass2",progress:89,did:`Statuses: ${it.report.restored} applied, ${it.report.refused.length} refused`,refused:it.report.refused.length,notDone:it.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,O,y,it)}catch(b){throw s(gr({cause:b})),b}let hr=it.report;hr.restored+hr.refused.length+it.unanswered>0&&s(gr()),await Z();let $e=await et(),Ut={restored:$e.linked.size,sent:[...$e.own.values()],unresolved:$e.unlinked};c.size>0&&s({phase:"personcontact",status:$e.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${$e.linked.size} linked to the contact the platform wrote with their account, ${$e.own.size} sent as contacts of their own, ${$e.unlinked.length} not linked`}),await Z(),await e.lease?.giveBack().catch(()=>{}),s({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await $();let mr=g.counts(),kt=h.counts(),Tt=m.counts(),yr=this.writeContract(e,u,M,G,{now:r,startedAt:n},new Set(w.keys()),[...mr.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"left-to-the-platform"})),...kt.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"untyped-feed-item"})),...Tt.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"excluded-parent"}))],we.size,V,Ke.unresolved.filter(b=>b.cause==="target-not-loaded"));s({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Kt=M.some(b=>b.failed.length>0)||Ke.unresolved.length>0||Ut.unresolved.length>0||hr.refused.length>0||C.failures.length>0,Vt=new Set(W.list().flatMap(({referenceIds:b})=>b)),wr=await this.readBackRecordTypes(a,xd(d,b=>Vt.has(b)),y),jt={status:Kt?"completed-with-errors":"completed",orgId:a,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:j,placeholders:G,requiredDefaults:ne,perObject:M,pass2:Ke,personContact:Ut,statuses:hr,purge:C,...mr.length>0?{leftToThePlatform:Mn(mr)}:{},...kt.length>0?{untypedFeedItems:kt.map(({objectApiName:b,why:_,count:z})=>({objectApiName:b,count:z,note:Nd(z,_)}))}:{},...Tt.length>0?{heldForExcludedParents:Jd(Tt)}:{},...Hd(Rt,this.config),...Wd(d.keysLeftEmpty),...wr.length>0?{recordTypesGiven:wr}:{},...P?{runUserId:P}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:yr};return s({phase:"done",status:jt.status==="completed"?"done":"error",progress:100,message:`Load ${jt.status}`}),jt}async checkGuard(e,t,r,n){await this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:t,objectName:r,recordCount:n,module:"frozendataset"})}async consultGuard(e,t){let{check:r,decision:n}=await On(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new He("guard-refused",`Production guard refused ${t.operation} on ${t.objectName}: ${r.blockedReason??"confirmation declined"}`,{decision:n,...n==="refused"&&r.blockedReason!==void 0?{reason:r.blockedReason}:{}});return n}filterPilotScope(e,t){return Ho(e,this.config.rootObjectApiName,t)}async reuseByIdentityKeys(e,t,r,n){for(let[s,a]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(i=>i.objectApiName===s)?.records??[];for(let[i,u]of await this.findByKeys(e.orgId,s,a,d))r.set(i,u),n.add(i)}}async findByKeys(e,t,r,n){let s=new Map,a=n.filter(l=>r.every(c=>!gt(l.fields[c])));if(a.length===0)return s;let d=["Id",...r].map(ge).join(", "),i=new Map,u=100;for(let l=0;l<a.length;l+=u){let c=a.slice(l,l+u).map(p=>`(${r.map(g=>`${ge(g)} = ${Sl(p.fields[g])}`).join(" AND ")})`).join(" OR "),f=`SELECT ${d} FROM ${ge(t)} WHERE ${c}`;for(let p of await this.deps.orgAccess.query(e,f))typeof p.Id=="string"&&i.set(zd(r.map(g=>p[g])),p.Id)}for(let l of a){let c=i.get(zd(r.map(f=>l.fields[f])));c&&s.set(l.referenceId,c)}return s}async linkWhatThePlatformKeeps(e,t,r,n,s,a,d){let i={linked:[],said:[],leftEmpty:[]};for(let[u,l]of Object.entries(Tr)){let c=this.config.identityKeys?.[u]??l,f=(r.get(u)??[]).filter(g=>!a.has(g.referenceId));if(f.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:u,keyFields:c,records:f,missingRequired:t.find(g=>g.objectApiName===u)?.missingRequired??[],ranks:n,accountKindOf:d},s,a,i);p>0&&i.said.push(`${u}: ${p} found by ${c.join(", ")}, which the platform does not delete`)}return i}async reuseByKeysAsWritten(e,t,r,n,s,a,d,i){let u={linked:[],said:[],leftEmpty:[]};for(let[l,c]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(Tr,l))continue;let f=new Set((t.objects.find(h=>h.objectApiName===l)?.records??[]).filter(h=>c.some(m=>gt(h.fields[m]))).map(h=>h.referenceId)),p=(n.get(l)??[]).filter(h=>f.has(h.referenceId)&&!d.has(h.referenceId));if(p.length===0)continue;let g=await this.linkByKeysAsWritten(e,{objectApiName:l,keyFields:c,records:p,missingRequired:r.find(h=>h.objectApiName===l)?.missingRequired??[],ranks:s,accountKindOf:i},a,d,u);g>0&&u.said.push(`${l}: ${g} found by ${c.join(", ")}, as the load writes `+(g===1?"it":"them"))}return u}async linkByKeysAsWritten(e,t,r,n,s){let{objectApiName:a,keyFields:d}=t,i=Nl(t,this.config.requiredFieldDefaults??{}),u=i.flatMap(c=>{let f=d.filter(p=>gt(c.fields[p]));return f.length>0?[f]:[]});if(u.length>0){let c=d.filter(f=>u.some(p=>p.includes(f)));s.leftEmpty.push({objectApiName:a,fields:c,count:u.length}),s.said.push(`${a}: ${u.length} not looked up, ${c.join(", ")} left empty`)}let l=await this.findByKeys(e,a,d,i);for(let[c,f]of l)r.set(c,f),n.add(c),s.linked.push(c);return l.size}async lookUpTheCatalog(e,t,r,n){let s=[],a=t.standardPricebook;if(a){let[u]=await this.deps.orgAccess.query(e,Ft);typeof u?.Id=="string"?(r.set(a,u.Id),n.add(a),s.push("standard price book linked")):s.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),i=await this.matchSellingModelOptions(e,t,r,n);Cd(t).includes(ze)&&d.push({objectApiName:ze,linked:i});for(let{objectApiName:u,linked:l,notAsked:c}of d)c===void 0&&s.push(`${u}: ${l} linked`);for(let{objectApiName:u,notAsked:l}of d)l!==void 0&&s.push(`${u} not looked up \u2014 ${l}`);return s}async matchByNaturalKey(e,t,r,n){let s=[];for(let[a,d]of Object.entries(gn)){let i=t.objects.find(f=>f.objectApiName===a)?.records??[];if(i.length===0)continue;let u=i.filter(f=>!r.has(f.referenceId)&&d.every(p=>f.fields[p]!==void 0&&f.fields[p]!=="")),l=[];if(u.length>0)try{l=await pa(f=>this.deps.orgAccess.query(e,f),a,d,u.map(f=>f.fields))}catch(f){s.push({objectApiName:a,linked:0,notAsked:X(f)});continue}let c=0;u.forEach((f,p)=>{let g=l[p];g!==void 0&&(r.set(f.referenceId,g),n.add(f.referenceId),c++)}),s.push({objectApiName:a,linked:c})}return s}async matchSellingModelOptions(e,t,r,n){let s=[];for(let d of t.objects.find(i=>i.objectApiName===ze)?.records??[]){if(r.has(d.referenceId))continue;let i=d.fields[We],u=d.fields[Ye],l=typeof i=="string"?r.get(i):void 0,c=typeof u=="string"?r.get(u):void 0;l===void 0||c===void 0||s.push({referenceId:d.referenceId,pair:{[We]:l,[Ye]:c}})}if(s.length===0)return 0;let a=await fa(d=>this.deps.orgAccess.query(e,d),s.map(d=>d.pair));for(let[d,i]of a)r.set(s[d].referenceId,i),n.add(s[d].referenceId);return a.size}async planPurge(e,t,r){let n={residuals:new Map,datedBy:new Map,carried:[],leftUnrecorded:{},keptByThePlatform:{}},s=new Map;for(let[g,h]of r)s.has(pe(h))||s.set(pe(h),g);let a=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},i=(g,h)=>{let m=n.carried.at(-1);m?.objectApiName===g?m.referenceIds.push(h):n.carried.push({objectApiName:g,referenceIds:[h]})},u=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},l=[],c=t.some(g=>g.created&&!g.writtenBetween)?await this.targetClockAheadMs():Number.NaN,f=t.map(g=>{let h=new Set;if(!g.created)return h;let m=new Set(g.created.flatMap(y=>y.referenceIds));for(let[y,R]of g.mapping)m.has(y)||h.add(pe(R));return h}),p=new Set(f.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[R,L]of g.mapping){let T=pe(L);if(s.has(T)||a.has(T))continue;a.add(T);let j=Ol(R);this.mayHaveLinked(j,R)||p.has(T)?u(j):j==="Pricebook2"&&!R.startsWith(_n)?l.push(L):d(j,L)}return}let m=g.writtenBetween?Dt(g.writtenBetween.last):Dt(g.endedAt)+c+qa,y=new Map(Object.entries(g.removalStamps??{}).map(([R,L])=>[pe(R),Dt(L)]));for(let{objectApiName:R,referenceIds:L}of g.created)for(let T of L){let j=g.mapping.get(T);if(j===void 0)continue;let x=pe(j);if(f[h].has(x)||a.has(x))continue;a.add(x);let U=s.get(x);if(U!==void 0){i(R,U);continue}if(this.keptByThePlatform(R)){n.keptByThePlatform[R]=(n.keptByThePlatform[R]??0)+1;continue}d(R,j);let S=[m,y.get(x)??Number.NaN].filter(Number.isFinite);S.length>0&&n.datedBy.set(x,Math.max(...S))}}),l.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,Ft);g=typeof h?.Id=="string"?pe(h.Id):""}catch{g=void 0}for(let h of l)g===void 0||pe(h)===g?u("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return Dt(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let s=new Set([...t.values()].flat().map(pe)),a=new Map;for(let[u,l]of r){let c=n.get(u);c===void 0||s.has(pe(l))||a.set(c,[...a.get(c)??[],l])}if(s.size===0||a.size===0)return[];let d=new Map,i=(u,l,c)=>{let f=d.get(u)??{keys:new Set,under:new Set};f.keys.add(pe(l)),f.under.add(c),d.set(u,f)};for(let u of t.keys()){let l;try{l=(await this.deps.orgAccess.describe(e,u)).cascadeChildren??[]}catch{continue}for(let{childSObject:c,field:f}of l){let p=a.get(c);if(!p)continue;let g;try{g=await this.readRecords(e,c,[f],p)}catch{for(let h of p)i(c,h,u);continue}for(let h of g){let m=h[f];typeof h.Id!="string"||typeof m!="string"||s.has(pe(m))&&i(c,h.Id,u)}}}return[...d].map(([u,{keys:l,under:c}])=>({objectApiName:u,count:l.size,under:[...c]}))}mayHaveLinked(e,t){return t.startsWith(_n)?!1:e==="Unknown"||e===ze||Object.prototype.hasOwnProperty.call(gn,e)||Object.prototype.hasOwnProperty.call(Tr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(Tr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,s,a,d,i){let u=t.residuals,l=[],c=[...u.values()].reduce((T,j)=>T+j.length,0),f=0,p=()=>{d.residuals=c-f},g=async()=>{let T=l.splice(0);T.length>0&&await this.giveStatusesBack(e,T,n)},h=async()=>{e.signal?.aborted&&await g(),await s()},m=r.filter(T=>u.has(T)),y=[...u.keys()].filter(T=>!r.includes(T)).sort(),R=[...m,...y],L=new Set;try{L=await this.residualsInSight(e.orgId,u),await this.draftResiduals(e,t,l,h);for(let T of R){let j=u.get(T)??[],x=this.config.undeletableObjects?.[T];if(x!==void 0){await h(),await this.checkGuard(e,"update",T,j.length);let U=await this.deps.writer.update(e.orgId,T,j.map(S=>({Id:S,[x]:!1})));U.forEach((S,w)=>{S.success?(n.deactivated[T]=(n.deactivated[T]??0)+1,a.add(pe(j[w]))):n.failures.push({objectApiName:T,recordId:j[w],errors:S.errors})}),f+=U.length}else{let U=an(T)?await this.customPricesFirst(e.orgId,j):T===Rr?[await this.withoutDirectRelations(e.orgId,j)]:[j];f+=j.length-U.reduce((S,w)=>S+w.length,0);for(let S of U){if(S.length===0)continue;await h(),await this.checkGuard(e,"delete",T,S.length);let w=await this.deps.writer.delete(e.orgId,T,S);w.forEach((I,A)=>{Sd(I)?(n.deleted[T]=(n.deleted[T]??0)+1,a.add(pe(S[A]))):n.failures.push({objectApiName:T,recordId:S[A],errors:I.errors})}),f+=w.length}}}await this.purgeAgain(e,R,n,a,h,i)}catch(T){throw await g(),p(),T}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,a,L),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,s]of t)try{for(let a of await this.readRecords(e,n,[],s))typeof a.Id=="string"&&r.add(pe(a.Id))}catch{}return r}async purgeAgain(e,t,r,n,s,a){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let i=r.failures.filter(l=>l.objectApiName===d).map(l=>l.recordId);if(i.length===0)continue;let u=an(d)?await this.customPricesFirst(e.orgId,i).catch(()=>[i]):[i];for(let l of u){if(l.length===0)continue;await s(),await this.checkGuard(e,"delete",d,l.length),(await this.deps.writer.delete(e.orgId,d,l)).forEach((f,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===l[p]);g<0||(a.tried++,Sd(f)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(pe(l[p])),a.went++):r.failures[g]={objectApiName:d,recordId:l[p],errors:f.errors})})}}}async settleTakenAlong(e,t,r,n){for(let s of new Set(t.failures.map(a=>a.objectApiName))){let a=t.failures.filter(h=>h.objectApiName===s).map(h=>h.recordId),d=h=>this.readRecords(e,s,[],h),{gone:i,unchecked:u,failure:l}=await _a(a,d,h=>n.has(pe(h))),c=l?`Not checked: not read back once the purge was through, to tell whether a parent deleted after it took it along \u2014 ${l}`:"Not checked: the purge could not read it before its delete, nor after \u2014 gone, or out of the session's sight",f=new Set(u.map(pe));for(let h of t.failures)h.objectApiName!==s||!f.has(pe(h.recordId))||h.errors.includes(c)||(h.errors=[...h.errors,c]);let p=new Set(i.map(pe));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==s||!p.has(pe(h.recordId)));t.failures.splice(0,t.failures.length,...g),t.deleted[s]=(t.deleted[s]??0)+p.size;for(let h of p)r.add(h)}}async draftResiduals(e,t,r,n){for(let[s,a]of Object.entries(Ct)){if(ca.has(s))continue;let d=t.residuals.get(s);if(!d||d.length===0)continue;let i=await this.statusCategories(e.orgId,a),u=i?.draft;if(!i||!u)continue;let l;try{l=await this.readRecords(e.orgId,s,["Status","LastModifiedDate"],d)}catch{continue}let c=l.flatMap(f=>{let p=i.categoryOf.get(String(f.Status));if(typeof f.Id!="string"||p===void 0||p==="Draft")return[];let g=t.datedBy.get(pe(f.Id))??Number.NaN;return[{objectApiName:s,id:f.Id,draft:u,status:String(f.Status),unchanged:Dt(f.LastModifiedDate)<=g}]});c.length!==0&&(await n(),await this.checkGuard(e,"update",s,c.length),r.push(...c),await this.deps.writer.update(e.orgId,s,c.map(({id:f})=>({Id:f,Status:u}))))}}async giveStatusesBack(e,t,r){let n=this.deps.restoringWriter??this.deps.writer,s=await this.runningUser(e.orgId),a={};for(let d of new Set(t.map(i=>i.objectApiName))){let i=t.filter(p=>p.objectApiName===d),u=new Map(i.map(p=>[pe(p.id),p])),l;try{l=await this.readRecords(e.orgId,d,["Status"],i.map(p=>p.id))}catch(p){for(let g of i)Pd(r,g,`its status was not read back: ${X(p)}`);continue}let c=l.flatMap(p=>{let g=typeof p.Id=="string"?u.get(pe(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<c.length;p+=At){let g=c.slice(p,p+At),h;try{await this.checkGuard(e,"update",d,g.length),h=await n.update(e.orgId,d,g.map(({id:m,status:y})=>({Id:m,Status:y})))}catch(m){let y=X(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let R=h[y];R?.success||Pd(r,m,R?.errors.join("; ")||"the org gave no reason")})}let f=c.filter(p=>p.unchanged);if(!(f.length===0||s===void 0))try{let p=await this.readRecords(e.orgId,d,["LastModifiedDate","LastModifiedById"],f.map(g=>g.id));for(let g of p)typeof g.Id=="string"&&typeof g.LastModifiedDate=="string"&&typeof g.LastModifiedById=="string"&&pe(g.LastModifiedById)===s&&(a[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(a).length!==0)try{await this.deps.mappingStore.recordStamps(a)}catch{}}async runningUser(e){let t=await this.runUserIdOf(e);return t?pe(t):void 0}async runUserIdOf(e){let t=this.deps.orgAccess.userId;if(t)try{return await t.call(this.deps.orgAccess,e)||void 0}catch{return}}async readBackRecordTypes(e,t,r){let n=[];for(let{given:s,rule:a,keys:d}of t){let i=d.flatMap(u=>r.get(u)??[]);try{let u=await this.deps.orgAccess.query(e,Vi(s.objectApiName,i));n.push({...s,readBack:Hi(u,a.types)})}catch(u){let l=X(u);n.push({...s,readBack:{read:0,types:[],unread:l}})}}return n}async readRecords(e,t,r,n){let s=["Id",...r].map(ge).join(", "),a=[];for(let d=0;d<n.length;d+=At){let i=n.slice(d,d+At).map(u=>`'${De(u)}'`).join(", ");a.push(...await this.deps.orgAccess.query(e,`SELECT ${s} FROM ${ge(t)} WHERE Id IN (${i})`))}return a}async resolveRecordType(e,t,r,n,s,a,d){let i={...n.fields};r===Ve&&delete i[hn];let u=i.RecordTypeId;if(typeof u!="string"||u==="")return"RecordTypeId"in i&&d.set(n.referenceId,"masterInSource"),delete i.RecordTypeId,{referenceId:n.referenceId,fields:i};let l=t.recordTypes[r]??[],c=n.recordTypeDeveloperName===void 0?void 0:Ro(n.recordTypeDeveloperName,l,$d),f=c&&"found"in c?[c.found]:l.filter(m=>m.name===u),p=f[0];if(!p)return delete i.RecordTypeId,d.set(n.referenceId,"dropped"),a.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:i};if(f.length>1)throw _d(r,u,f);let g=ct(p.namespacePrefix,p.developerName),h=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,r,p.developerName,...p.namespacePrefix!==void 0?[p.namespacePrefix]:[]);if(h!==null&&typeof h=="object"&&"ambiguous"in h)throw new Ze(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${ko(r,p.developerName,"the target org",h.carriers)}. Extract the dataset again: a dataset extracted now names each record type with its namespace. Nothing was written.`,void 0,{reason:"namespace",objectApiName:r,name:p.developerName,recordTypes:h.carriers.map(m=>ct(m.namespacePrefix,m.developerName))});if(h!==null&&typeof h=="object"){let m=await this.deps.recordTypeResolver.givenRecordType?.(e.orgId,r).catch(()=>{});return delete i.RecordTypeId,d.set(n.referenceId,"dropped"),a.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${kl(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:i}}return h?(i.RecordTypeId=h,s.set(n.referenceId,h),{referenceId:n.referenceId,fields:i}):(delete i.RecordTypeId,d.set(n.referenceId,"dropped"),a.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:i})}async planRequiredFields(e,t){let r=[],n=[];for(let s of t)for(let a of s.missingRequired){let d=`${a.objectApiName}.${a.field}`;if(!a.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let c=a.accountKind?` of a ${a.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${zl(a)} for this required field${c}`)}else r.push({kind:"default",missing:a});continue}let i=this.config.requiredLookupPlaceholders?.[d];if(!i){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${a.referenceTo.join(" or ")||"its parent"}`);continue}let u=i.targetObjectApiName??a.referenceTo[0];if(!u){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let l;if(i.recordTypeDeveloperName){let c=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,u,i.recordTypeDeveloperName);if(c!==null&&typeof c=="object"&&"ambiguous"in c){let f=c.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+ko(u,i.recordTypeDeveloperName,"the target org",c.carriers)+(f?" \u2014 a package's is named with its namespace: "+ct(f.namespacePrefix,f.developerName):""));continue}if(c!==null&&typeof c=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${i.recordTypeDeveloperName} on ${u} is not available to the running user`);continue}if(l=c??void 0,!l){n.push(`requiredLookupPlaceholders["${d}"]: record type ${i.recordTypeDeveloperName} is not on ${u} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:a,key:d,name:i.name,targetObject:u,recordTypeId:l})}if(n.length>0)throw new Ze(`The dataset leaves ${n.length} required field(s) empty that the configuration does not cover. Nothing was written. Declare them all, then load again \u2014 records are never silently excluded:
9
- - ${n.join(`
10
- - `)}`,n);return r}async createPlaceholder(e,t,r,n,s,a){let{missing:d,key:i,targetObject:u}=t,l={Name:t.name};t.recordTypeId&&(l.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",u,1);let[c]=await this.deps.writer.insert(e.orgId,u,[l]);if(c===void 0&&e.signal?.aborted)return;if(!c?.success||!c.id)throw new Ze(`Placeholder insert failed for required lookup ${i} on ${u}: ${c?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let f=`${_n}${u}:${i}`;n.set(f,c.id),a.add(u,f),this.journal?.created(u,[[f,c.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=c.id,p++)}s.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:u,placeholderName:t.name,placeholderId:c.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let s=`${e.objectApiName}.${e.field}`,a=this.config.requiredFieldDefaults?.[s],d=Uo(a,e.distinct),i=0;for(let u of t)gt(u.fields[e.field])&&(u.fields[e.field]=Ko(a,d,{referenceId:u.referenceId,rank:n.get(u.referenceId)??0}),i++);r.push({objectApiName:e.objectApiName,field:e.field,value:a,affectedRecords:i,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,s,a,d,i,u,l,c,f,p){let g={objectApiName:t,fromFiles:r,inserted:0,reused:0,skippedDuplicates:[],failed:[]},h=n.filter(S=>!d.has(S.referenceId));g.reused=n.length-h.length;let m=[];for(let S of h){let w=Fl(t,S.fields,s,f);w?g.failed.push({objectApiName:t,referenceId:S.referenceId,errors:[w]}):m.push(S)}if(m.length===0)return g;let y=m.map(S=>{let w={},I=[];for(let[N,v]of Object.entries(S.fields))if(!(v===""||v===null||v===void 0))if(typeof v=="string"&&s.has(v)){let P=a.get(v);P&&!(t===Er&&N===Fr)?w[N]=P:I.push({objectApiName:t,referenceId:S.referenceId,field:N,targetReferenceId:v})}else w[N]=v;let A=Qs(t,w);for(let N of A)delete w[N];i.push(...I.filter(N=>!A.includes(N.field)));for(let N of _s(t,w))delete w[N];return w}),R=(S,w,I)=>{a.set(S,w),l.add(t,S,Al.some(A=>A in I)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let L=await this.deps.writer.insert(e.orgId,t,y,(S,w)=>this.journalBatch(t,m,S,w)),T=[];L.forEach((S,w)=>{let I=m[w].referenceId;if(S.success&&S.id){R(I,S.id,y[w]);return}if(Dd(S.errors,u)){g.skippedDuplicates.push({objectApiName:t,referenceId:I,errors:S.errors});return}let A=this.sentAgain(t,y[w],S);A?T.push({...A,referenceId:I,errors:S.errors}):g.failed.push({objectApiName:t,referenceId:I,errors:S.errors})});let j=m.length-L.length;if(j>0&&e.signal?.aborted&&(g.notInserted=j),T.length===0)return g;let x=(S,w)=>{for(let I of S)g.failed.push({objectApiName:t,referenceId:I.referenceId,errors:[...I.errors,`Not written again ${Td(I.fields)}: ${w}`]})};if(e.signal?.aborted)return x(T,"the load was cancelled first"),g;let U;try{await this.checkGuard(e,"insert",t,T.length),U=await this.deps.writer.insert(e.orgId,t,T.map(S=>S.payload),(S,w)=>this.journalBatch(t,T,S,w))}catch(S){throw x(T,X(S)),p?.(g),S}return T.forEach((S,w)=>{let I=U[w];if(!I){x([S],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if(I.success&&I.id){R(S.referenceId,I.id,S.payload),g.writtenWithoutFields=Po(g.writtenWithoutFields,{rows:1,fields:S.fields.map(N=>({...N,rows:1}))});for(let{field:N,replacedWith:v}of S.fields){if(v!==void 0)continue;let P=c.get(t)??new Map;P.set(N,[...P.get(N)??[],S.referenceId]),c.set(t,P)}return}let A=[...I.errors,`Sent again ${Td(S.fields)} after the first refusal: ${S.errors.join("; ")}`];Dd(I.errors,u)?g.skippedDuplicates.push({objectApiName:t,referenceId:S.referenceId,errors:A}):g.failed.push({objectApiName:t,referenceId:S.referenceId,errors:A})}),g}journalBatch(e,t,r,n){let s=this.journal;s&&s.created(e,n.flatMap((a,d)=>{let i=t[r+d];return a.success&&a.id&&i?[[i.referenceId,a.id]]:[]}))}sentAgain(e,t,r){let n=mi(r.errorDetails,t,void 0);if(!n)return;let s={...t},a=n.map(d=>{let i=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return i?.action==="replace"&&i.value!==""&&i.value!==t[d.field]?(s[d.field]=i.value,{...d,replacedWith:i.value}):(delete s[d.field],{...d})});return{payload:s,fields:a}}async matchDirectRelations(e,t,r,n,s,a){let d=new Map;for(let l of t.objects.find(c=>c.objectApiName==="Contact")?.records??[])d.set(l.referenceId,l.fields.AccountId);let i=r.filter(l=>{let c=l.fields.ContactId;return typeof c=="string"&&l.fields.AccountId!==void 0&&d.get(c)===l.fields.AccountId&&n.has(c)&&typeof l.fields.AccountId=="string"&&n.has(l.fields.AccountId)});if(i.length===0)return;let u=await la(l=>this.deps.orgAccess.query(e,l),i.map(l=>({AccountId:n.get(l.fields.AccountId),ContactId:n.get(l.fields.ContactId)})));for(let[l,c]of i.entries()){let f=u.get(l);typeof f=="string"&&(n.set(c.referenceId,f),s.add(c.referenceId),a.set(c.referenceId,c.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,s,a){let d=new Set(r.map(l=>l.referenceId)),i=new Map;for(let l of t.objects.find(c=>c.objectApiName===Je)?.records??[]){let c=l.fields.ActivityId;if(typeof c!="string"||!d.has(c)||s.has(l.referenceId))continue;let f=n.get(l.referenceId);f&&i.set(c,{id:f,key:l.referenceId})}if(i.size===0)return;let u=await ra(l=>this.deps.orgAccess.query(e,l),[...new Set([...i.values()].map(l=>l.id))]);for(let[l,c]of i){let f=u.get(c.id);f!==void 0&&(n.set(l,f),s.add(l),a.set(l,c.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:s,reused:a}=t,d=w=>typeof w=="string"?s.get(w):void 0,i=new Map;for(let w of t.working.objects.find(I=>I.objectApiName===Bd)?.records??[]){let I=s.get(w.referenceId),A=d(w.fields[yt]);I&&A&&!a.has(w.referenceId)&&i.set(I,A)}if(i.size===0)return{linked:0};let u=r.map(w=>({OpportunityId:d(w.fields.OpportunityId),[yt]:d(w.fields[yt]),IsPrimary:w.fields.IsPrimary})),l=ho(u,w=>i.get(w)).filter(w=>!a.has(r[w].referenceId));if(l.length===0)return{linked:0};let c=w=>{let I={},A=[];for(let[N,v]of Object.entries(w.fields))if(!(N==="OpportunityId"||N===yt)&&!t.fixedAtInsert.has(N)&&!(v===""||v===null||v===void 0))if(typeof v=="string"&&n.has(v)){let P=s.get(v);P?I[N]=P:A.push({objectApiName:Nt,referenceId:w.referenceId,field:N,targetReferenceId:v})}else I[N]=v;return{fields:I,owed:A}},f=new Map(l.map(w=>[w,{opportunity:String(u[w].OpportunityId),contact:String(u[w][yt])}])),p=[...new Set(l.flatMap(w=>Object.keys(c(r[w]).fields)))],g=await oa(w=>this.deps.orgAccess.query(e.orgId,w),[...new Set([...f.values()].map(({opportunity:w})=>w))],p),{found:h,alike:m}=sa(f,g),y=m.length>0?aa(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let R=w=>y?`${w}; ${y}`:w,L=[];for(let[w,I]of h){let A=r[w],N=String(I.Id);s.set(A.referenceId,N),a.add(A.referenceId),t.withTheirRecord.set(A.referenceId,String(A.fields.OpportunityId));let{fields:v,owed:P}=c(A);t.pendingFk.push(...P);let C=Object.entries(v).filter(([G,M])=>String(I[G]??"")!==String(M));C.length>0&&L.push({Id:N,...Object.fromEntries(C)})}let T=h.size,j=`${T} written by the platform with ${na(Nt)}`;if(L.length===0)return{linked:T,note:R(j)};let x=(w,I)=>`${j}, ${w} of them left as it wrote ${w===1?"it":"them"}, without the fields of the source's role: ${I}`;if(e.signal?.aborted)return{linked:T,note:R(x(L.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",Nt,L.length);let U=await this.deps.writer.update(e.orgId,Nt,L),S=L.flatMap((w,I)=>{let A=U[I];return A?.success?[]:[A?A.errors.join("; ")||"refused":"no answer came for it"]});return S.length===0?{linked:T,note:R(j)}:{linked:T,note:R(x(S.length,S[0]))}}async matchActivityRelations(e,t,r,n,s,a){let{orgId:d}=e,i=mo[t],u=c=>typeof c=="string"?n.get(c):void 0,l=await ia(c=>this.deps.orgAccess.query(d,c),t,r.map(c=>({[i]:u(c.fields[i]),RelationId:u(c.fields.RelationId)})));for(let[c,f]of l)n.set(r[c].referenceId,f),s.add(r[c].referenceId);return da(t,[...l].map(([c,f])=>[r[c].fields,f]),c=>!a.has(c),async c=>(await this.checkGuard(e,"update",t,c.length),this.deps.writer.update(d,t,c)),()=>e.signal?.aborted===!0)}async startAsDrafts(e,t,r,n,s){let a=await this.statusCategories(e,r);return a?.draft?n.map(d=>{let i=tr(d.fields.Status,a);return i?(s.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:i}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=At){let s=t.slice(n,n+At).map(d=>`'${De(d)}'`).join(", "),a=await this.deps.orgAccess.query(e,`SELECT Id FROM ${Rr} WHERE Id IN (${s}) AND IsDirect = true`);for(let d of a)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await ua(n=>this.deps.orgAccess.query(e,n),t);return[t.filter(n=>!r.has(n)),t.filter(n=>r.has(n))]}async readWrittenBetween(e,t,r){let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:a,referenceIds:d}of t.list()){let i=[...new Set(d.flatMap(l=>{let c=r.get(l);return c?[c]:[]}))],u=t.sentAuditDates(a);for(let l=0;l<i.length;l+=At){let c=await this.writtenDatesOf(e,a,i.slice(l,l+At));if(!c)return;for(let f of c){let p=Dt(f.SystemModstamp),g=y=>{let R=u?Number.NaN:Dt(f[y]);return Number.isFinite(R)?R:p},h=g("CreatedDate"),m=g("LastModifiedDate");Number.isFinite(h)&&(n=Math.min(n,h)),Number.isFinite(m)&&(s=Math.max(s,m))}}}if(!(!Number.isFinite(n)||!Number.isFinite(s)))return{first:new Date(n).toISOString(),last:new Date(Math.max(n,s)).toISOString()}}async writtenDatesOf(e,t,r){let n=r.map(s=>`'${De(s)}'`).join(", ");for(let s of Pl)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${s.join(", ")} FROM ${ge(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return er(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:s}=n.report,a=new Map;for(let d of t){let i=r.get(d.referenceId);i&&a.set(d.objectApiName,[...a.get(d.objectApiName)??[],{...d,id:i}])}n.unanswered=[...a.values()].reduce((d,i)=>d+i.length,0);for(let[d,i]of a){if(e.signal?.aborted)continue;let u=i.map(c=>({Id:c.id,Status:c.status}));await this.checkGuard(e,"update",d,u.length);let l=await this.deps.writer.update(e.orgId,d,u);l.forEach((c,f)=>{c.success?n.report.restored++:s.push({objectApiName:d,referenceId:i[f].referenceId,status:i[f].status,detail:c.errors.join("; ")})}),n.unanswered-=l.length}}async patchCycleFks(e,t,r,n){let{unresolved:s}=n.report,a=new Map,d=new Map;for(let u of t){let l=r.get(u.referenceId),c=r.get(u.targetReferenceId);if(!l||!c){s.push({objectApiName:u.objectApiName,referenceId:u.referenceId,field:u.field,cause:l?"target-not-loaded":"record-not-loaded",detail:l?`referenced record ${u.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(l,u.referenceId);let f=a.get(u.objectApiName)??new Map,p=f.get(l)??{Id:l};p[u.field]=c,f.set(l,p),a.set(u.objectApiName,f)}let i=u=>u.reduce((l,c)=>l+Object.keys(c).length-1,0);n.unanswered=[...a.values()].reduce((u,l)=>u+i([...l.values()]),0);for(let[u,l]of a){let c=[...l.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",u,c.length);let f=await this.deps.writer.update(e.orgId,u,c);f.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(c[g]).length-1:s.push({objectApiName:u,referenceId:d.get(String(c[g].Id))??String(c[g].Id),field:Object.keys(c[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=i(c.slice(0,f.length))}}async linkPersonContacts(e,t,r,n,s,a){let d={linked:new Map,own:new Map,unlinked:[]},i=new Map,u=[...t].map(([f,p])=>({accountReferenceId:p,contactReferenceId:f}));for(let f of u){let p=f.accountReferenceId===""?void 0:r.get(f.accountReferenceId);p!==void 0&&i.set(p,[...i.get(p)??[],f])}let l=i.size===0||s===!1?new Map:await yn(f=>this.deps.orgAccess.query(e,f),[...i.keys()]),c=new Map;for(let[f,p]of i){let g=l.get(f);if(g!==void 0)for(let h of p)c.set(h.contactReferenceId,g)}for(let f of u){let p=c.get(f.contactReferenceId);if(p!==void 0){r.set(f.contactReferenceId,p),d.linked.set(f.contactReferenceId,f.accountReferenceId);continue}if(f.accountReferenceId===""||!r.has(f.accountReferenceId)){d.unlinked.push({...f,cause:"record-not-loaded",detail:f.accountReferenceId===""?Lr.accountNotInDataset:Lr.accountNotLoaded});continue}if(n.has(f.contactReferenceId))continue;let g=a.find(m=>m.objectApiName===Ve&&m.referenceId===f.accountReferenceId),h=Lr.noPersonAccounts;s!==!1&&(h=g?`${Lr.businessAccount}: ${g.detail}`:`${Lr.businessAccount}: its record type there is no person account's`),d.own.set(f.contactReferenceId,{...f,detail:h})}return d}writeContract(e,t,r,n,s,a,d,i=0,u=new Map,l=[]){let c=new Map;for(let{objectApiName:h,referenceId:m,field:y}of l){let R=c.get(h)??{};R[y]=[...R[y]??[],m],c.set(h,R)}let f=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let R=f.get(h)??{};R[y]=(R[y]??0)+m,f.set(h,R)}let p=[...r];for(let[h,m]of f)p.some(y=>y.objectApiName===h)||p.push({objectApiName:h,fromFiles:t.objects.find(y=>y.objectApiName===h)?.records.length??Object.values(m).reduce((y,R)=>y+R,0),inserted:0,reused:0,skippedDuplicates:[],failed:[]});let g={};for(let h of p){let m={};h.skippedDuplicates.length>0&&(m["duplicate-skipped"]=h.skippedDuplicates.length);let y=h.objectApiName===Ue?i:0,R=h.failed.filter(S=>Ll(S.errors)).length;if(R>0&&(m["parent-refused"]=R),h.failed.length-R>y){let S=a.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[S]=h.failed.length-R-y}y>0&&(m["person-contact-not-sent"]=y);let L=0;for(let[S,w]of Object.entries(f.get(h.objectApiName)??{}))m[S]=w,L+=w;let T=h.skippedDuplicates.length+h.failed.length+L,j=n.filter(S=>S.placeholderObjectApiName===h.objectApiName).length,x=u.get(h.objectApiName),U=c.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:T,added:j,expected:h.inserted+h.reused+j,...x&&x.size>0?{writtenWithout:Object.fromEntries(x)}:{},...U?{parentNotLoaded:U}:{}}}return fd(this.sasGuard,e.sasDir,{version:1,orgId:e.contractOrgId??e.orgId,datasetVersion:t.datasetVersion,writtenAt:s.now().toISOString(),loadStartedAt:s.startedAt.toISOString(),objects:g})}picklistRuleFor(e,t){return this.config.picklistRules?.[`${e}.${t}`]??this.config.defaultPicklistRule??{action:"clear"}}contractPath(e,t){return Nn(this.sasGuard,e,t)}};function Ed(o){let e=new Map;for(let t of o)for(let r of t.failed)e.set(r.referenceId,t.objectApiName);return e}function Fl(o,e,t,r){if(r.size===0)return;let n=new Set(o===Je&&!go(e,s=>t.get(s))?["ActivityId"]:[]);for(let[s,a]of Object.entries(e)){if(typeof a!="string"||n.has(s)||!t.has(a))continue;let d=r.get(a);if(d!==void 0)return`PARENT_REFUSED: the ${d} record its ${s} names was refused in this load, and written without it this record would stand without its ${d}.`}}function Ll(o){return o.length===1&&o[0].startsWith("PARENT_REFUSED:")}function gt(o){return o==null||o===""}var Gd=/\{(n|referenceId)\}/g;function Uo(o,e){if(typeof o=="string")return o.match(Gd)?"token":e}function Ko(o,e,t){return typeof o!="string"||e===void 0?o:e==="token"?o.replace(Gd,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${o} ${t.rank}`}function Nl(o,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:s}=o,a=o.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return o.records.map(d=>{let i={...d.fields};for(let u of a){let l=e[`${t}.${u.field}`];l===void 0||!gt(i[u.field])||qn(u,[d],s).length!==0&&(i[u.field]=Ko(l,Uo(l,u.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:i}})}function Wd(o,e=!1){return o.length===0?{}:{keysLeftEmpty:o.map(({objectApiName:t,fields:r,count:n})=>{let s=n===1?"its":"their",a=r.join(", "),d="the dataset holds no value, and no default fills it";return{objectApiName:t,fields:[...r],count:n,note:e?`${n} not looked up by ${s} identity keys: ${a} stays empty in what the load would write \u2014 ${d} \u2014 so ${n===1?"it":"they"} would be inserted, never matched`:`${n} not looked up by ${s} identity keys: ${a} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function Cl(o){let e=new Map;for(let t of o.objects)t.records.forEach((r,n)=>e.set(r.referenceId,n+1));return e}function Ud(o){let e=Vo(o),t=new Map(o.objects.map(n=>[n.objectApiName,n.records])),r=new Set;return new Set([...Kd(t,r),...Vd(t,r,qd(o,e),n=>e.get(n))])}function Kd(o,e){let t=(o.get(Nt)??[]).filter(i=>!e.has(i.referenceId));if(t.length===0)return new Set;let r=new Map,n=i=>{if(typeof i!="string"||i==="")return;let u=r.get(i);return u===void 0&&(u=String(r.size+1).padStart(15,"0"),r.set(i,u)),u},s=new Set((o.get(Ue)??[]).map(i=>i.referenceId)),a=new Map;for(let i of o.get(Bd)??[]){if(e.has(i.referenceId))continue;let u=i.fields[yt];typeof u!="string"||!s.has(u)||a.set(n(i.referenceId),n(u))}if(a.size===0)return new Set;let d=t.map(i=>({OpportunityId:n(i.fields.OpportunityId),[yt]:n(i.fields[yt]),IsPrimary:i.fields.IsPrimary}));return new Set(ho(d,i=>a.get(i)).map(i=>t[i].referenceId))}function Vd(o,e,t,r){let n=l=>(o.get(l)??[]).filter(c=>!e.has(c.referenceId)),s=new Set,a=new Map;for(let l of n(Ue))t.has(l.referenceId)||a.set(l.referenceId,l.fields.AccountId);let d=new Set((o.get("Account")??[]).map(l=>l.referenceId));for(let l of n(Rr)){let{AccountId:c,ContactId:f}=l.fields;typeof c!="string"||typeof f!="string"||a.get(f)===c&&d.has(c)&&s.add(l.referenceId)}let i=new Set([...o.values()].flatMap(l=>l.map(c=>c.referenceId))),u=new Set(n(Xt).map(l=>l.referenceId));for(let l of n(Je)){let c=l.fields.ActivityId,f=l.fields.RelatedToId;typeof c!="string"||!u.has(c)||typeof f!="string"||!i.has(f)||go(l.fields,r)||s.add(c)}return s}function Fd(o,e,t){let{working:r,loading:n,alignedByObject:s,reused:a,reusedByKeys:d,alignment:i,ranks:u}=o,l=o.targetHasPersonAccounts===!1?new Set:o.personContacts,c=w=>(s.get(w)??[]).filter(I=>!a.has(I.referenceId)),f=[...new Set([...o.groupOrder,...r.objects.map(w=>w.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=Kd(s,a),h=Vd(s,a,l,w=>o.refIndex.get(w)),m=[];for(let w of f){let I=r.objects.find(E=>E.objectApiName===w)?.records.length??0,A=e?.residuals.get(w)?.length??0;if(I===0&&A===0)continue;let N=s.get(w),P=(N??n.objects.find(E=>E.objectApiName===w)?.records??[]).filter(E=>a.has(E.referenceId)),C=P.filter(E=>d.has(E.referenceId)).length,G=N?c(w):[],M=G.filter(E=>l.has(E.referenceId)).length;p+=M;let W=G.filter(E=>g.has(E.referenceId)||h.has(E.referenceId)).length,V=(o.filteredLookups.get(w)??[]).flatMap(({field:E,referenceTo:q})=>{let Y=G.filter(ae=>!gt(ae.fields[E])).length;return Y>0?[{field:E,referenceTo:q,records:Y}]:[]}),H=t.undeletableObjects[w]!==void 0;m.push({objectApiName:w,fromFiles:I,toInsert:G.length-M-W,reusedByKeys:C,reusedFromCatalog:P.length-C,...W>0?{writtenByThePlatform:W}:{},fieldsDropped:i.removals.filter(E=>E.objectApiName===w).length,picklistsRewritten:i.adjustments.filter(E=>E.objectApiName===w).length,notSent:I-(N?N.length:P.length),toPurge:H?0:A,toDeactivate:H?A:0,...V.length>0?{lookupFilters:V}:{}})}let y=(w,I)=>c(w).filter(A=>gt(A.fields[I])),R=(w,I)=>y(w,I).length,L=w=>{let I=qn(w,y(w.objectApiName,w.field),o.accountKindOf),A=t.requiredFieldDefaults[`${w.objectApiName}.${w.field}`],N=Uo(A,w.distinct),v=I[0];return{objectApiName:w.objectApiName,field:w.field,affectedRecords:I.length,...N?{perRecord:N}:{},...N&&v?{example:String(Ko(A,N,{referenceId:v.referenceId,rank:u.get(v.referenceId)??0}))}:{}}},T=e?.leftUnrecorded??{},j=e?.keptByThePlatform??{},x=o.heldForExclusions.counts(),U=xd(o,w=>!a.has(w)&&!l.has(w)).map(({given:w})=>w),S=new Set([...s.values()].flatMap(w=>w.map(I=>I.referenceId)));return{orgId:t.orgId,mode:t.mode,plannedAt:t.plannedAt,perObject:m,excludedObjects:i.excludedObjects,removals:i.removals,placeholders:o.plans.flatMap(w=>w.kind==="placeholder"?[{objectApiName:w.missing.objectApiName,field:w.missing.field,placeholderObjectApiName:w.targetObject,placeholderName:w.name,affectedRecords:R(w.missing.objectApiName,w.missing.field)}]:[]),requiredDefaults:o.plans.flatMap(w=>w.kind==="default"?[L(w.missing)]:[]),recordTypeIssues:o.recordTypeIssues.length,personContacts:p,earlierLoads:o.previousLoads.length,...Object.keys(T).length>0?{leftUnrecorded:T}:{},...Object.keys(j).length>0?{keptByThePlatform:j}:{},...x.length>0?{heldForExcludedParents:Jd(x)}:{},...Hd(Bo(s,w=>S.has(w)),t,!0),...Wd(o.keysLeftEmpty,!0),...U.length>0?{recordTypesGiven:U}:{}}}var Ld=5;function zl(o){switch(o.fieldType){case"date":return'a date, as "2026-12-31",';case"datetime":return'a date and time, as "2026-12-31T09:00:00Z",';case"time":return'a time, as "09:00:00.000Z",';case"double":case"currency":case"percent":return"a number";case"int":case"long":return"a whole number";case"boolean":return"true or false";case"picklist":case"multipicklist":{let e=o.activeValues??[];return e.length===0?"one of its values":`one of its active values (${e.slice(0,Ld).join(", ")}${e.length>Ld?", \u2026":""})`}case"email":return"an email address";case"string":case"textarea":case"phone":case"url":case"encryptedstring":case"combobox":return"a string";default:return"a value"}}function Hd(o,e,t=!1){let r=Od(o,(e.excludedObjects??[]).includes(_o),t);return r?{quotesLeftUnsynced:[r]}:{}}function Dl(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let a=[...e.get(n)??[]],d=s.filter(i=>!t.some(u=>u.leaveOut(n,i.referenceId,i.fields,a)));d.length!==s.length&&(o.set(n,d),r=!0)}}}function Ml(o,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let s of e.fields){let a=s.referenceTo??[];a.length===0||!a.every(d=>r.has(d))||!s.createable||s.defaultedOnCreate||Yt(o,s.name,s.nillable)&&(t.requiredLookupPlaceholders?.[`${o}.${s.name}`]||n.push({field:s.name,excludedObject:a[0]}))}return n}function xl(o){return(e,t)=>{for(let{field:r,excludedObject:n}of o.get(e)??[])if(gt(t[r]))return{field:r,value:"",noun:n}}}function Yd(o,e){return e.through?`${o} left out: ${e.through} names a record left out for the ${e.rows.noun} excludedObjects leaves out`:`${o} left out: ${e.rows.field??"a lookup"} names ${/^[AEIOU]/i.test(e.rows.noun)?"an":"a"} ${e.rows.noun} record, which excludedObjects leaves out \u2014 declare a placeholder in requiredLookupPlaceholders to load them`}function Jd(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:Yd(r,t)}))}var $l={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function _l(o,e){if(o!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:$l}function Nd(o,e){let t="extract the dataset again, with rules that keep FeedItem.Type";return e.through?`${o} left out: ${e.through} names a feed item whose type the dataset does not carry \u2014 ${t}`:`${o} feed item${o===1?"":"s"} left out: the dataset does not carry ${o===1?"its":"their"} type, and a tracked change cannot be told from a post \u2014 ${t}`}function Vo(o){let e=new Map;for(let t of o.objects)for(let r of t.records)e.set(r.referenceId,t.objectApiName);return e}function Bl(o,e,t=new Map){let r=new Map;for(let n of o.objects){let s=r.get(n.objectApiName)??new Set;for(let a of n.records)for(let[d,i]of Object.entries(a.fields))if(!(n.objectApiName===Ve&&d===hn)&&typeof i=="string"){let u=e.get(i);u&&u!==n.objectApiName&&s.add(u)}r.set(n.objectApiName,s)}t.size>0&&r.has(Ve)&&r.get(Ue)?.add(Ve);for(let{sourceObject:n,targetObject:s}of hi(new Set(r.keys()),[]))r.get(s)?.add(n);for(let{sourceObject:n,targetObject:s}of ea(new Set(r.keys())))r.get(n)?.delete(s),r.get(s)?.add(n);return r}function ql(o,e,t,r=new Map){let n=new Map;for(let[s,a]of o){let d=e.get(s),i=new Set;if(d)for(let u of a)for(let l of d){let c=u.fields[l],f=typeof c=="string"?t.get(c):void 0;f&&f!==s&&i.add(f)}n.set(s,i)}return r.size>0&&n.set(Ue,new Set([...n.get(Ue)??[],Ve])),n}function Gl(o,e){let t=h=>o.objects.find(m=>m.objectApiName===h)?.records??[],r=(h,m)=>m.map(y=>String(h[y]??"")).join("|"),n=[We,Ye,Jt],s=[We,Ye],a=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(qe),i=d.filter(h=>e.has(h.referenceId)&&a(h.fields,We)),u=o.standardPricebook,l=h=>u!==void 0&&h.fields[mt]===u,c=new Set(i.filter(h=>!l(h)).map(h=>r(h.fields,n))),f=d.filter(h=>l(h)&&c.has(r(h.fields,n))),p=new Set([...i,...f].filter(h=>a(h.fields,Ye)).map(h=>r(h.fields,s))),g=t(ze).filter(h=>p.has(r(h.fields,s)));return[...f,...g].map(h=>h.referenceId)}function Cd(o){return[...Object.keys(gn),ze].filter(e=>o.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function Wl(o,e){for(let t of o.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function zd(o){return JSON.stringify(o.map(e=>e===void 0?null:e))}function Dd(o,e){return o.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}function Ho(o,e,t){if(!e)throw new Ze("Pilot mode requires config.rootObjectApiName (the business-folder root object).");let r=o.objects.find(l=>l.objectApiName===e)?.records??[],n=t??r[0]?.referenceId;if(!n||!r.some(l=>l.referenceId===n))throw new Ze(`Pilot root ${t??"<first>"} not found in ${e} records (${r.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let s=Vo(o),a=new Set([n]),d=!0;for(;d;){d=!1;for(let l of o.objects)for(let c of l.records)a.has(c.referenceId)||Object.values(c.fields).some(f=>typeof f=="string"&&a.has(f))&&(a.add(c.referenceId),d=!0)}let i=l=>{for(;l.length>0;){let c=l.pop(),f=Wl(o,c);if(f)for(let p of Object.values(f.fields))typeof p=="string"&&s.has(p)&&!a.has(p)&&(a.add(p),l.push(p))}};i([...a]);let u=Gl(o,a).filter(l=>!a.has(l));for(let l of u)a.add(l);return i(u),{...o,objects:o.objects.map(l=>({...l,records:l.records.filter(c=>a.has(c.referenceId))})).filter(l=>l.records.length>0)}}import{randomBytes as Ul}from"node:crypto";import{readFile as Kl}from"node:fs/promises";var Yo="frozen.salt";function Vl(){return Ul(32).toString("base64url")}function Xd(o){let e=o[Wi];return e?{salt:e,source:"environment"}:void 0}function vp(o,e=process.env){let t=async()=>{let r=Xd(e);if(r)return r;let n=await o.getSecret(Yo);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=Vl();if(await o.storeSecret(Yo,n),await o.getSecret(Yo)!==n)throw new Pr;return{salt:n,source:"secretStorage",created:!0}}}}function Zd(o=process.env,e){let t=async()=>{let r=Xd(o);if(r)return r;if(e===void 0)return;let n=(await Kl(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new Pr;return r}}}import{createHash as Hl}from"node:crypto";import{appendFileSync as Yl,mkdirSync as Jl,readFileSync as Xl}from"node:fs";import*as zr from"node:path";var Zl=15*6e4;function Gn(o){return`sha256:${Hl("sha256").update(zr.resolve(o)).digest("hex").slice(0,16)}`}function Qd(o,e){if(!o?.writtenBetween)return;let t=Date.parse(o.endedAt),r=Date.parse(e);if(!Number.isFinite(t)||!Number.isFinite(r)||t<r)return;let n=Date.parse(o.writtenBetween.first),s=Date.parse(o.writtenBetween.last);if(!(!Number.isFinite(n)||!Number.isFinite(s)))return new Date(Math.max(n,s)).toISOString()}function Ql(o,e){return e.some(t=>{let r=Date.parse(t.endedAt),n=Date.parse(t.startedAt??t.endedAt);return Number.isFinite(r)&&o>=(Number.isFinite(n)?n:r)-6e4&&o<=r+Zl})}function ec(o,e){let t=[];for(let r of o){let n=Date.parse(r.endedAt);if(!Number.isFinite(n)||(r.sas!==void 0?r.sas===e.sasMark:Ql(n,e.own)))continue;let s=Date.parse(r.lastWriteAt??""),a=Number.isFinite(s)?s:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,a):a,to:a})}return t}var tc="frozen-loads.ndjson";function Pp(o,e){Jl(o,{recursive:!0}),Yl(zr.join(o,tc),`${JSON.stringify(e)}
11
- `)}function eu(o,e){return o.slice(0,15)===e.slice(0,15)}function Tp(o,e){let t;try{t=Xl(zr.join(o,tc),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
12
- `)){if(n.trim()==="")continue;let s;try{s=JSON.parse(n)}catch{continue}let{organizationId:a,sas:d,startedAt:i,endedAt:u,lastWriteAt:l}=s??{};typeof a!="string"||typeof u!="string"||eu(a,e)&&r.push({endedAt:u,...typeof d=="string"?{sas:d}:{},...typeof i=="string"?{startedAt:i}:{},...typeof l=="string"?{lastWriteAt:l}:{}})}return r}function rc(o){return o.filter(e=>(e.action==="frozen_load"||e.action==="checkpoint_replay")&&e.outcome!=="stopped").map(e=>{let t=e.details?.sas,r=e.details?.startedAt,n=e.details?.lastWriteAt;return{endedAt:e.timestamp,...typeof t=="string"?{sas:t}:{},...typeof r=="string"?{startedAt:r}:{},...typeof n=="string"?{lastWriteAt:n}:{}}})}var tu="FROZEN_EMAILS_EXCEEDED";function Cp(o,e){return[...Ci(o.counted,e),...o.uncounted!==void 0?[` emails: not counted, ${o.uncounted} could not be read`]:[],...o.deliverability?[` ${Mi(o.deliverability.reading)}`]:[]]}function ru(o){return typeof o.unread=="string"}async function nc(o){let{read:e,plan:t,writes:r,target:n}=o,s=await ni({read:e,...t?{plan:t}:{},writes:r,readDeliverability:o.readDeliverability,accepted:o.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:o.mayMute}),a=[],d;if(ru(e))d=`the target's automation: ${e.unread}`;else{let c=Lt(e,t,r).automation,f={objects:o.inserts.map(g=>({...g,storageBytes:0}))};d=Li(c,Fi(f));let p=Gs(c);if(p.length>0){let g=await o.readLimits().catch(h=>({unread:X(h)}));a=Ei(f,p,g)}}let i=Ni(a,n),u=i?{code:tu,message:`${i} Nothing was written.`}:s.gate.stop,{deliverability:l}=s.gate;return{run:s,info:{counted:a.map(c=>({...c,objects:[...c.objects]})),...d!==void 0?{uncounted:d}:{},verdict:s.gate.verdict,...l?{deliverability:l}:{},accepted:o.accepted,...u?{refused:{code:u.code,message:u.message}}:{}},...u?{stop:u}:{}}}var nu="AUTOMATION_NOT_ACCEPTED";function ou(o){let e=new Set(o);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function su(o){return typeof o.unread=="string"}function au({kind:o,name:e}){return o==="flow"?`flow "${e}"`:o==="process"?`process "${e}"`:o==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var oc={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function sc(o){return`${o.objectApiName}: ${au(o)} (${o.writes.join(", ")})`}function iu(o,e,t){let r=[];o.firing.length>0&&r.push(`${e} runs automation as this load inserts its records and updates them: ${o.firing.map(sc).join("; ")}.`);for(let{part:n,reason:s}of o.unread??[]){let a=oc[n];r.push(`${a[0].toUpperCase()}${a.slice(1)} of ${e} could not be read (${s}), so what fires as the load writes is not known.`)}return r.push(...t),r.push(`Nothing was written. Add --accept-automation to load all the same, or turn that automation off in ${e} first.`),r.join(" ")}function Jo(o){let{read:e,target:t}=o,r=ou(o.written),n=[],s=[],a=[];if(su(e))s=[{part:"automation",reason:e.unread}];else{let u=Lt(e,o.plan,r),l=new Map;for(let p of u.firing){if(p.write!=="insert"&&p.write!=="update")continue;let g=`${p.objectApiName}\0${p.kind}\0${p.name}`,h=l.get(g);h?h.writes.includes(p.write)||h.writes.push(p.write):l.set(g,{objectApiName:p.objectApiName,kind:p.kind,name:p.name,writes:[p.write]})}n=[...l.values()].map(p=>({...p,writes:["insert","update"].filter(g=>p.writes.includes(g))})),s=_i(e);let c=$i(u.automation,xi(u.automation,[...o.written])),f=[...new Set(c.flatMap(p=>p.permissionSet??[]))];a=[...Bi(c,t,"the load"),...o.mayMute&&f.length>0?[`With --mute-automation, the load assigns ${f.join(", ")} to the user it writes as for the load alone, under a lease, and what ${f.length===1?"it keeps":"they keep"} quiet does not fire.`]:[]]}if(n.length===0&&s.length===0)return{};let d={firing:n,...s.length>0?{unread:s}:{},accepted:o.accepted};if(o.accepted)return{info:d};let i={code:nu,message:iu(d,t,a)};return{info:{...d,refused:i},stop:i}}function xp(o,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...o.firing.map(t=>` ${sc(t)}`),...(o.unread??[]).map(({part:t,reason:r})=>` ${oc[t]} could not be read: ${r}`),...o.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}var Mr="No record was read or deleted.",du="Nothing was deleted.";function Dr(o,e){return{allowed:!1,refusal:{code:"PRODUCTION",message:`${o} is a production org, or cannot be told from one: ${e}. Emptying is for sandboxes, scratch orgs and Developer Edition orgs: SandForge never empties objects of a production org, and nothing lifts this. ${Mr}`}}}async function Wp(o,e){let{orgName:t,registered:r}=e;if(r===void 0)return Dr(t,"SandForge has no record of what kind of org it is");if(!Bs(r))return Dr(t,"SandForge has it registered as a production org");let n;try{n=await Us(o)}catch(a){let d=Vs(a);return d!==void 0?{allowed:!1,refusal:{code:"ORG_UNTYPED",message:`${Hs(t,a,d)} SandForge empties no org it cannot tell from a production one. ${Mr}`}}:Dr(t,`it did not say what org it is (${X(a)})`)}if(Ks(n))return Dr(t,n.edition?`its Organization record says IsSandbox false, edition ${n.edition}`:"its Organization record says IsSandbox false, and no edition");let s=ln(r);return s==="production"?Dr(t,"SandForge has it registered as a production org"):s==="staging"&&e.mode==="org"?{allowed:!1,refusal:{code:"STAGING_ORG",message:`${t} is a sandbox marked Staging: it holds real data, and SandForge never empties the whole of it. Pick the objects to empty instead, which Production Guard asks about, or unmark it on the Organizations page if it holds nobody's work. ${Mr}`}}:{allowed:!0,org:n,tier:s}}var ac=["PermissionsViewAllData","PermissionsModifyAllData","PermissionsBulkApiHardDelete"];async function Up(o){let e=async n=>(await o.query(`SELECT ${n.join(", ")} FROM UserPermissionAccess`)).records[0]??{},t,r;try{t=await e(ac)}catch(n){try{t=await e(ac.slice(0,2)),r=`whether the user has Bulk API Hard Delete could not be read: ${X(n)}`}catch(s){return{viewAllData:!1,modifyAllData:!1,hardDelete:!1,unread:X(s)}}}return{viewAllData:t.PermissionsViewAllData===!0,modifyAllData:t.PermissionsModifyAllData===!0,hardDelete:t.PermissionsBulkApiHardDelete===!0,...r!==void 0?{unread:r}:{}}}function Kp(o){return{code:"HARD_DELETE_NOT_PERMITTED",message:"Deleting for good needs Bulk API Hard Delete, and the user SandForge deletes as "+(o.unread!==void 0?`could not be read to have it (${o.unread}). `:"doesn't have it: Salesforce refuses the job as it is opened. ")+"Give the user a permission set with Bulk API Hard Delete, or empty to the recycle bin, which Undo brings back. Nothing was deleted."}}var Vp=60*6e4,ic=2e3,dc=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;async function Hp(o,e,t,r){let n=t.filter(l=>dc.test(l)).map(l=>l.slice(0,15)),s=n.length>0?` AND LastModifiedById NOT IN (${n.map(l=>`'${l}'`).join(", ")})`:"",a=new Map,d=[],i=!1;for(let l of e){let c=ge(l);try{let f=await o.query(`SELECT LastModifiedById, LastModifiedDate FROM ${c} WHERE LastModifiedDate >= ${r}${s} LIMIT ${ic}`);f.records.length>=ic&&(i=!0);for(let p of f.records){let{LastModifiedById:g,LastModifiedDate:h}=p;if(typeof g!="string"||!dc.test(g))continue;let m=g.slice(0,15),y=typeof h=="string"&&!Number.isNaN(Date.parse(h))?h:"",R=a.get(m);if(!R){a.set(m,{userId:g,records:1,lastChangedAt:y});continue}R.records+=1,y!==""&&(R.lastChangedAt===""||Date.parse(y)>Date.parse(R.lastChangedAt))&&(R.lastChangedAt=y)}}catch(f){d.push(`${l}: ${X(f)}`)}}let u=[...a.keys()].sort();return{people:u.map(l=>a.get(l).userId),...i?{atLeast:!0}:{},who:u.map(l=>a.get(l)),unread:d}}var cu=200;async function Yp(o,e){let t=e.who.map(s=>s.userId).slice(0,cu);if(t.length===0)return e;let r;try{r=(await o.query(`SELECT Id, Name FROM User WHERE Id IN (${t.map(s=>`'${s}'`).join(", ")})`)).records}catch{return e}let n=new Map;for(let s of r){let{Id:a,Name:d}=s;typeof a=="string"&&typeof d=="string"&&d.trim()!==""&&n.set(a.slice(0,15),d.trim())}return{...e,who:e.who.map(s=>{let a=n.get(s.userId.slice(0,15));return a!==void 0?{...s,name:a}:s})}}function lu(o){let e;for(let t of o)t.lastChangedAt!==""&&(e===void 0||Date.parse(t.lastChangedAt)>Date.parse(e))&&(e=t.lastChangedAt);return e}function Jp(o,e,t={}){if(t.accepted===!0)return;let r=new Set((t.accepted??[]).map(l=>l.slice(0,15))),n=e.people.filter(l=>!r.has(l.slice(0,15)));if(n.length===0)return;let s=n.length,a=`${e.atLeast?"At least ":""}${s} ${s===1?"person":"people"}`,d=lu(e.who.filter(l=>n.includes(l.userId))),i=r.size>0?" the preview did not name":"",u=t.voice==="page"?"or tick the box that lets their work go, to empty all the same":"or add --accept-people-active to empty all the same";return{code:"PEOPLE_ACTIVE",message:`${a}${i} other than the user SandForge deletes as changed records of these objects in ${o} in the last hour${d!==void 0?`, the last at ${d}`:""}: emptying them would take their work. Empty once they have stopped, ${u}. `+du}}var xr=1024,cc="COPY_SANDBOX",uu=Ge({DataStorageMB:Ge({Max:rn()}).loose()}).loose();async function eg(o){if(o.orgType!=="Sandbox")return;let e="Empty it whole from DataOps Cleanup in the panel, which knows whether it is marked Staging, or pick the objects to empty with --objects, which Production Guard asks about. "+Mr,t;try{t=uu.parse(await o.limits()).DataStorageMB.Max}catch(r){return{code:cc,message:`${o.target} is a sandbox whose data storage could not be read (${X(r)}): this command cannot tell a Partial Copy or Full sandbox, which may hold real data, from a developer's. ${e}`}}if(!(t<=xr))return{code:cc,message:`${o.target} is a Partial Copy or Full sandbox, by its data storage (${t.toLocaleString("en-US")} MB, past the ${xr.toLocaleString("en-US")} MB of a Developer Pro): it may hold real data, and this command cannot see whether it is marked Staging in the extension, where such a sandbox is never emptied whole. ${e}`}}import{existsSync as If}from"node:fs";import*as Se from"node:fs/promises";import*as fl from"node:os";import*as Pe from"node:path";var ir=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
13
- - ${r.join(`
14
- - `)}`:t);this.violations=r;this.name="RulesFileError"}violations},fu=/^\d+\.\d+\.\d+$/,uc=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,pu=new Set(Lo);function Xo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Wn(o){let e=[];if(!Xo(o))throw new ir("Rules file must be a JSON object");let t=o.rulesVersion;(typeof t!="string"||!fu.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=o.rules;if(!Xo(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new ir("Invalid rules file",e);let n={};for(let[s,a]of Object.entries(r)){if(!uc.test(s)){e.push(`"${s}": key must match "ObjectApiName.FieldApiName"`);continue}if(!Xo(a)){e.push(`"${s}": rule must be an object with a "generator" property`);continue}let d=a.generator;if(typeof d!="string"||!pu.has(d)){e.push(`"${s}": unknown generator ${JSON.stringify(d)} (supported: ${Lo.join(", ")})`);continue}let i=a.approved===!0;if(d==="keep"&&!i){e.push(`"${s}": generator "keep" requires "approved": true (explicit human review)`);continue}let u={generator:d};a.approved!==void 0&&(u.approved=i),typeof a.comment=="string"&&(u.comment=a.comment),n[s]=u}if(e.length>0)throw new ir("Invalid rules file",e);return{rulesVersion:t,rules:n}}function fc(o){let e=Object.keys(o.rules).sort(),t={};for(let r of e)t[r]=o.rules[r];return`${JSON.stringify({rulesVersion:o.rulesVersion,rules:t},null,2)}
15
- `}var pc={rulesVersion:"1.0.0",rules:{}};function gc(o){if(o===null)return{found:!1};try{let e=Wn(JSON.parse(o));return{found:!0,rulesVersion:e.rulesVersion,ruleCount:Object.keys(e.rules).length}}catch(e){return{found:!0,invalid:e instanceof Error?e.message:String(e)}}}var gu=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],hu=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...gu.flatMap(o=>[`BusinessHours.${o}StartTime`,`BusinessHours.${o}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),mu=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function ut(o,e,t){let r=`${e}.${t}`,n=o.rules[r]?.generator;return n||(o.personalBySchema?.has(r)===!0?"clear":hu.has(r)||mu.has(t)||o.keptBySchema?.has(r)===!0?"keep":"clear")}function hc(o,e,t){let r=new Set(o.keptBySchema??[]),n=new Set(o.personalBySchema??[]);for(let[s,a]of e){let d=new Set(t.detectPII(s,a.map(i=>({apiName:i.name,label:i.label??i.name,type:i.type}))).piiFields.map(i=>i.fieldApiName));for(let i of a){let u=`${s}.${i.name}`;d.has(i.name)?n.add(u):i.type==="picklist"&&(i.restrictedPicklist===!0||i.nillable===!1)&&i.compoundFieldName===void 0&&r.add(u)}}return{...o,keptBySchema:r,personalBySchema:n}}function mc(o,e){let t=new Set;for(let r of o.objects)for(let n of r.records)for(let s of Object.keys(n.fields)){let a=`${r.objectApiName}.${s}`;e.rules[a]===void 0&&ut(e,r.objectApiName,s)==="keep"&&t.add(a)}return[...t].sort()}function yc(o,e,t){let r=[];for(let n of o.objects){let s=t.get(n.objectApiName)??[];for(let l of s){let c=fn(n.objectApiName,l.name);if(l.name==="Id"||l.createable===!1||l.nillable!==!1&&c===void 0||l.defaultedOnCreate===!0||l.type==="reference"||(l.referenceTo?.length??0)>0||ut(e,n.objectApiName,l.name)!=="clear")continue;n.records.some(p=>{if(c!==void 0&&!Qt(c,mn(p.fields,!1)))return!1;let g=p.fields[l.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${l.name}`)}let a=n.objectApiName,d=cn(a,l=>s.some(c=>c.name===l&&c.createable!==!1),l=>ut(e,a,l)!=="clear"),i=`${a}.${d}`;d!==void 0&&n.records.some(l=>{let c=l.fields[d];return c!=null&&c!==""})&&!r.includes(i)&&r.push(i)}return r.sort()}var yu="Cleared on review of the extraction result: kept in clear text without a rule before.";function wc(o,e){let t=Wn(o),r=e.filter(u=>!uc.test(u));if(r.length>0)throw new ir('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(u=>JSON.stringify(u)));let n=o,s={...n.rules},a=[],d=[];for(let u of[...new Set(e)].sort()){if(t.rules[u]!==void 0){d.push(u);continue}s[u]={generator:"clear",comment:yu},a.push(u)}let i=a.length>0?wu(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:i,rules:s},rulesVersion:i,cleared:a,alreadyRuled:d}}function wu(o){let[e,t]=o.split(".").map(Number);return`${e}.${t+1}.0`}import*as bc from"node:fs/promises";import*as Rc from"node:path";var Zo=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,kc=/^[A-Z][A-Z0-9_]*$/,Pt=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function $r(o,e){for(let a of Object.keys(e))if(!kc.test(a))throw new Pt(`Invalid token name ${JSON.stringify(a)}`);let t=new Set;for(let a of o.matchAll(Zo))t.add(a[1]);let r=[...t].filter(a=>!(a in e));if(r.length>0)throw new Pt(`Query template references token(s) without a value: ${r.join(", ")}. Token values (ID lists, date bounds) must be provided from the sas at execution time.`);let n=o.replace(Zo,(a,d)=>e[d]),s=n.match(Zo);if(s)throw new Pt(`Unresolved placeholder(s) after render: ${s.join(", ")}`);return n}async function Ic(o,e,t){let n=(t??new fe).assertOutsideRepo(Rc.join(o,e)),s=JSON.parse(await bc.readFile(n,"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))throw new Pt(`Token file ${n} must contain a JSON object`);let a={};for(let[d,i]of Object.entries(s)){if(!kc.test(d))throw new Pt(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof i!="string")throw new Pt(`Token ${d} in ${n} must be a string`);a[d]=i}return a}var _r=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function bu(o,e){return e?e.aborted?(o.catch(()=>{}),Promise.reject(new _r)):new Promise((t,r)=>{let n=()=>r(new _r);e.addEventListener("abort",n,{once:!0}),o.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),r(s)})}):o}var Ru=2500,ku=3,Iu=5;function vu(o,e){return Object.entries(o).filter(([t,r])=>t!==e&&r>0).sort(([t,r],[n,s])=>s-r||t.localeCompare(n)).slice(0,Iu).map(([t,r])=>({objectApiName:t,count:r}))}var xt=class extends Error{constructor(t,r,n,s){let a=vu(t,s),d=a.map(u=>`${u.objectApiName} ${u.count}`),i=a.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(a.map(u=>u.objectApiName))}), narrow the coverage axes/edge cases, or raise budgetMaxRecords explicitly. `:"Narrow the coverage axes/edge cases or raise budgetMaxRecords explicitly. ";super(`Volumetry budget exceeded: ${r} records measured for a budget of ${n}. ${i}Per-object counts: ${JSON.stringify(t)}`);this.measured=t;this.total=r;this.budgetMax=n;this.name="VolumetryBudgetExceededError",this.heaviest=d}measured;total;budgetMax;heaviest},Qo=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},Un=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??Ru,n=e.candidatesPerCombination??ku,s=ge(e.rootObject),{signal:a}=t,d=p=>t.onProgress?.(p),i=[],u=[],l=[],c={during:"axes",pending:[]},f=()=>{let p={};for(let h of l)for(let[m,y]of Object.entries(h))p[m]=(p[m]??0)+y;let g=Object.values(p).reduce((h,m)=>h+m,0);if(g>r)throw new xt(p,g,r,s);return{roots:i,uncovered:u,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:a?.reason==="timeout"?"timeout":"cancelled",during:c.during,...c.combinationKey!==void 0?{combinationKey:c.combinationKey}:{},...c.candidate!==void 0?{candidate:c.candidate,candidates:n}:{},notProbed:c.pending}}};try{return await this.run(e,{rootObject:s,budgetMax:r,candidateLimit:n,signal:a,tell:d},{roots:i,uncovered:u,ownMeasures:l,at:c})}catch(p){if(p instanceof _r)return f();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:s,candidateLimit:a,signal:d,tell:i}=t,{roots:u,uncovered:l,ownMeasures:c,at:f}=r,p=j=>bu(j,d),g=new Map,h=new Map;for(let j of e.axes)i({phase:"axis",axis:j.name}),g.set(j.name,await p(this.enumerateAxisValues(j,e.tokens))),h.set(j.name,await p(this.deps.fieldType?.(n,j.filterField).catch(()=>{})??Promise.resolve(void 0)));let m=e.axes.length===0?[[]]:Au(e.axes.map(j=>({axis:j.name,values:g.get(j.name)??[]}))),y=j=>j.length===0?"all":j.map(x=>`${x.axis}=${x.value??"NULL"}`).join("|");f.pending=[...m.map(y),...e.edgeCases.map(j=>`edge:${j.name}`)];let R=async(j,x)=>(f.during="combination",f.combinationKey=j,f.candidate=void 0,f.pending=f.pending.filter(U=>U!==j),this.pickHealthyRoot(n,x,a,e.tokens,{step:p,onCandidate:U=>{f.candidate=U,i({phase:"candidate",combinationKey:j,candidate:U,candidates:a})}}));for(let[j,x]of m.entries()){let U=y(x);i({phase:"combination",combinationKey:U,index:j+1,of:m.length});let S=x.map(A=>{let N=ge(e.axes.find(v=>v.name===A.axis)?.filterField??"");return A.value===null?`${N} = NULL`:`${N} = ${Su(A.value,h.get(A.axis))}`}).join(" AND "),w=await R(U,S),I={};for(let A of x)I[A.axis]=A.value;w.id?(u.push({rootRecordId:w.id,combinationKey:U,axisValues:I}),w.measured&&c.push(w.measured)):l.push({combinationKey:U,reason:vc(w,a)})}for(let[j,x]of e.edgeCases.entries()){let U=`edge:${x.name}`;i({phase:"combination",combinationKey:U,index:j+1,of:e.edgeCases.length});let S=await R(U,`(${x.whereFragment})`);S.id?(u.push({rootRecordId:S.id,combinationKey:U,axisValues:{},edgeCase:x.name}),S.measured&&c.push(S.measured)):l.push({combinationKey:`edge:${x.name}`,reason:S.probed===0?"no record matches the edge-case marker":vc(S,a)})}f.during="measure",f.combinationKey=void 0,f.candidate=void 0,u.length>0&&i({phase:"measure",roots:u.length});let L=u.length===0?{}:await p(this.deps.measureVolumetry(u.map(j=>j.rootRecordId))),T=Object.values(L).reduce((j,x)=>j+x,0);if(T>s)throw new xt(L,T,s,n);return{roots:u,uncovered:l,volumetry:{measured:L,total:T,budgetMax:s},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=$r(e.valuesSoql,t??{}),n=await this.deps.query(r),s=[];for(let a of n){if(!("axisValue"in a))throw new Qo(`Axis "${e.name}" query must alias its grouped value as axisValue (e.g. SELECT ${e.filterField} axisValue, COUNT(Id) cnt ... GROUP BY ${e.filterField})`);let d=a.axisValue;d==null?s.push(null):typeof d=="string"?s.push(d):s.push(String(d))}return[...new Set(s)].sort((a,d)=>(a??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,s){let a=t===""?`SELECT Id FROM ${e} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`:`SELECT Id FROM ${e} WHERE ${t} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`,d=await s.step(this.deps.query($r(a,n??{}))),i=0,u;for(let l of d){let c=l.Id;if(typeof c!="string"||c==="")continue;i++,s.onCandidate(i);let f=await s.step(this.deps.checkHealth.check(c));if(f.healthy)return{id:c,probed:i,...f.measured?{measured:f.measured}:{}};u=f.reason}return{id:null,probed:i,lastReason:u}}};function vc(o,e){if(o.probed===0)return"no candidate record";let t=`no healthy candidate among the ${o.probed} probed (limit ${e})`;return o.lastReason?`${t} \u2014 last: ${o.lastReason}`:t}var Ou=new Set(["int","long","double","currency","percent"]);function Su(o,e){let t=`'${De(o)}'`;switch(e){case"boolean":return/^(true|false)$/i.test(o)?o.toLowerCase():t;case"date":return/^\d{4}-\d{2}-\d{2}$/.test(o)?o:t;case"datetime":return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/.test(o)?o:t;default:return e!==void 0&&Ou.has(e)&&/^-?\d+(\.\d+)?$/.test(o)?o:t}}function Au(o){let e=[[]];for(let{axis:t,values:r}of o){let n=[];for(let s of e)for(let a of r)n.push([...s,{axis:t,value:a}]);e=n}return e}var Kn=class{constructor(e,t){this.measure=e;this.expectedObjects=t}measure;expectedObjects;async check(e){let t;try{t=await this.measure([e])}catch(r){return{healthy:!1,reason:`extraction failed: ${r instanceof Error?r.message:String(r)}`}}for(let r of this.expectedObjects)if((t[r]??0)===0)return{healthy:!1,reason:`no ${r} record in this dossier`};return{healthy:!0,measured:t}}};import*as dr from"node:fs/promises";import*as es from"node:path";var Br="selection.json";async function Oc(o,e,t){let r=t??new fe,n=r.assertOutsideRepo(o);await dr.mkdir(n,{recursive:!0});let s=r.assertOutsideRepo(es.join(n,Br));return await dr.writeFile(s,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
16
- `,"utf8"),s}async function ts(o,e){let r=(e??new fe).assertOutsideRepo(es.join(o,Br)),n=JSON.parse(await dr.readFile(r,"utf8"));if(typeof n!="object"||n===null||n.fileVersion!==1||typeof n.selection!="object")throw new Error(`Invalid selection file at ${r} (expected fileVersion 1)`);return n.selection}import*as cr from"node:fs/promises";import*as rs from"node:path";var Sc="discovery.json",Pu=1440*6e4,Tu=Ge({name:Ce(),fields:ht(Ge({name:Ce(),type:Ce(),referenceTo:ht(Ce())}).loose()),childRelationships:ht(Ge({childSObject:Ce(),field:Ce(),relationshipName:Ce()}).loose())}).loose(),ju=Ge({fileVersion:zs(1),sourceOrgId:Ce().min(1),rootObject:Ce().min(1),maxNodes:rn().int().positive(),step:Cs(["select","extract"]),discoveredAt:po.datetime(),schemaStamp:po.datetime().optional(),graph:Ge({nodes:ht(Ge({objectApiName:Ce(),included:nn()}).loose()),edges:ht(Ge({sourceObject:Ce(),targetObject:Ce()}).loose())}).loose(),describes:Ns(Ce(),Tu),objects:ht(Ge({name:Ce(),keyPrefix:Ce().nullable()}))});async function Ac(o,e,t=new fe){let r=t.assertOutsideRepo(o);await cr.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(rs.join(r,Sc));return await cr.writeFile(n,`${JSON.stringify(e)}
17
- `,"utf8"),n}async function Pc(o,e=new fe){let t=e.assertOutsideRepo(rs.join(o,Sc)),r;try{r=await cr.readFile(t,"utf8")}catch{return{none:"no graph kept in the sas"}}let n;try{n=JSON.parse(r)}catch{return{none:"the graph kept in the sas could not be read"}}let s=ju.safeParse(n);return s.success?{kept:s.data}:{none:"the graph kept in the sas could not be read"}}function Tc(o,e,t=new Date){if(o.sourceOrgId!==e.sourceOrgId)return"the graph kept is of another org";if(o.rootObject!==e.rootObject)return`the graph kept is of ${o.rootObject}, not ${e.rootObject}`;if(o.maxNodes!==e.maxNodes)return`the graph kept was discovered at a cap of ${o.maxNodes}, not ${e.maxNodes}`;let r=t.getTime()-Date.parse(o.discoveredAt);if(!(r>=0&&r<=Pu))return`the graph kept was discovered on ${o.discoveredAt}, more than a day ago`;if(!o.schemaStamp)return"the org did not give its clock when the graph kept was discovered"}function jc(o){let e=Date.parse(o);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as Hn from"node:fs/promises";import*as Ec from"node:path";var Eu="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Fu="rt-map.json",Lu=10;function Nu(o,e){return Sr.has(o)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>Sr.has(r))?{...t,nillable:!0}:t)}function $t(o){if(!("attributes"in o))return o;let e={...o};return delete e.attributes,e}var ns=class{constructor(e){this.keyPrefixes=e}keyPrefixes;prefixes=new Map;known=new Set;fromOrg;learnFrom(e){for(let[t,r]of e){let n=r.keys().next();n.done||this.note(t,n.value.slice(0,3))}}async objectsOf(e,t){return t.length<2?t:(!this.known.has(e.slice(0,3))&&this.keyPrefixes&&(this.fromOrg??=this.keyPrefixes().then(r=>{for(let[n,s]of r)this.prefixes.has(n)||this.note(n,s)},()=>{}),await this.fromOrg),gi(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function qr(o,e){return e.filter(t=>t.type==="reference"&&Yt(o,t.name,t.nillable)).map(t=>t.name)}function Cu(o,e,t){return{objectApiName:o,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}var zu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,Vn=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Gr=class{deps;soqlBuilder=new ci;constructor(e){this.deps=e}query(e){return Oa(e,t=>this.deps.query(t))}async extract(e){if(!zu.test(e.asOf))throw new Vn(`asOf must be a strict ISO instant (e.g. 2026-08-03T09:44:52Z), got ${JSON.stringify(e.asOf)}`);if(e.rootRecordIds.length===0)throw new Vn("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new fe,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,s=new No;s.add(e.rootObject,e.rootRecordIds),s.addReached(e.rootObject,e.rootRecordIds);let a=new Map,d=new Zt,i=new Set,u={},l=new ns(this.deps.keyPrefixes),c=new Map,f=async I=>{let A=c.get(I);if(A)return A;let N=await this.deps.describeFields(I);return c.set(I,N),N},p=async I=>{let A=await f(I);A.some(v=>v.name==="CreatedDate")||i.add(I);let N=A.filter(v=>v.type==="base64").map(v=>v.name);return N.length>0&&(u[I]=N),A},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(pi(e.graph,g),f,g),m=h.graph,y=[...m.nodes].filter(I=>I.included).sort((I,A)=>I.level-A.level),R=new Set(y.map(I=>I.objectApiName));for(let I of y){let A=await p(I.objectApiName),N=this.selectFields(I.objectApiName,A,e.excludedFields),v=A.some(E=>E.name==="CreatedDate"),P=this.soqlBuilder.build({node:I,fields:Nu(I.objectApiName,A),selectFields:N,edges:m.edges,cache:s,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:v?n:void 0,everyEdge:!Sr.has(I.objectApiName),readObjects:R,catalog:Sr,fromAboveOnly:!0});if(!P.scoped)continue;let C=[],G=[];for(let[E,q]of P.statements.entries()){let Y=await this.query(q);if(C.push(...Y),!(E<P.byIdCount))for(let ae of Y)typeof ae.Id=="string"&&G.push(ae.Id)}let M=d.keep(I.objectApiName,await this.keepWhatStatusesNeed(h.added.get(I.objectApiName),C,a),qr(I.objectApiName,A)),W=a.get(I.objectApiName);W||(W=new Map,a.set(I.objectApiName,W));let V=[];for(let E of M){let q=E.Id;typeof q!="string"||q===""||(V.push(q),W.has(q)||W.set(q,$t(E)))}s.addRead(I.objectApiName,V);let H=new Set(V);s.addReached(I.objectApiName,G.filter(E=>H.has(E))),l.learnFrom(a);for(let E of A)if(E.type==="reference")for(let q of M){let Y=q[E.name];if(!(typeof Y!="string"||Y===""))for(let ae of await l.objectsOf(Y,E.referenceTo))s.add(ae,[Y])}I.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:A,selectFields:N,bucket:W,cache:s,owners:l,recordsByObject:a,leftToThePlatform:d,extraWhere:v?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:y,edges:m.edges,cache:s,recordsByObject:a,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},a,p,n,l,d,g),await Du(a,p,d);let L=await this.addStandardPrices(e,a,n);await this.addSellingModelOptions({...e,graph:m},a,p,n,g);let T=(a.get(dn)?.size??0)>0,j=await this.exclusionCosts(a,p,g,T),x=await this.leaveOutWhatReadsMasked(a,f),U=[...a.entries()].sort(([I],[A])=>I.localeCompare(A)).map(([I,A])=>{let N=[...A.values()].sort((P,C)=>String(P.Id).localeCompare(String(C.Id)));I===qe&&(N=$s(N,{sellingModel:T}));let v=N.map((P,C)=>({referenceId:`${I}-${String(C+1).padStart(6,"0")}`,sourceId:String(P.Id),fields:P}));return{objectApiName:I,records:v}}),S=await this.pullRecordTypes(e);await Hn.mkdir(r,{recursive:!0});let w=t.assertOutsideRepo(Ec.join(r,Fu));return await Hn.writeFile(w,`${JSON.stringify(S,null,2)}
18
- `,"utf8"),{objects:U,asOf:e.asOf,recordTypeMap:S,unboundedObjects:[...i],fileFields:u,...L?{standardPricebookSourceId:L}:{},leftToThePlatform:d.counts(),...j.length>0?{exclusionCosts:j}:{},...x.length>0?{encryptedNotKept:x}:{}}}async leaveOutWhatReadsMasked(e,t){let r=Xa(Ja(s=>this.deps.query(s)),async s=>({fields:await t(s)})),n=[];for(let[s,a]of e)if(a.size!==0)for(let d of await r(s)){let i=!1;for(let u of a.values())d in u&&(i||=u[d]!==null&&u[d]!==void 0,delete u[d]);i&&n.push(`${s}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(i=>i.objectApiName)),s=new Map,a=[],d=[];for(let i of e.nodes){let u=on[i.objectApiName];if(!i.included||!u||n.has(u.object)||s.has(u.object)||r.has(u.object))continue;let l;try{l=await t(u.object)}catch{continue}let c=l.find(f=>f.name===u.lookup&&f.type==="reference"&&f.referenceTo.includes(i.objectApiName));c&&(s.set(u.object,{parent:i.objectApiName,lookup:c.name}),a.push(Cu(u.object,l,i.level+1)),d.push({sourceObject:i.objectApiName,targetObject:u.object,relationshipName:c.name,type:"lookup",required:Yt(u.object,c.name,c.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...a],edges:[...e.edges,...d]},added:s}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,s=new Set([...n.get(t)??[]].filter(i=>!r.has(i)));if(s.size===0)return;let a=[];for(let i of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:s,extraWhere:e.extraWhere}))a.push(...await this.query(i));let d=e.leftToThePlatform.keep(t,a,qr(t,e.fields));for(let i of d)typeof i.Id=="string"&&!r.has(i.Id)&&r.set(i.Id,$t(i));e.owners.learnFrom(e.recordsByObject);for(let i of e.fields)if(i.type==="reference")for(let u of d){let l=u[i.name];if(!(typeof l!="string"||l===""))for(let c of await e.owners.objectsOf(l,i.referenceTo))n.add(c,[l])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=Ct[e.parent],s=n?await er(d=>this.query(d),n):void 0,a=new Set;for(let[d,i]of r.get(e.parent)??[])s&&tr(i.Status,s)&&a.add(d);return t.filter(d=>{let i=d[e.lookup];return typeof i=="string"&&a.has(i)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(on)){let n=e.nodes.find(m=>m.objectApiName===r.object),s=e.recordsByObject.get(t),a=Ct[t];if(!n||!s||s.size===0||!a)continue;let d=e.cache.reachedOf(t),i=[...s].filter(([m])=>!d?.has(m));if(i.length===0)continue;let u=await er(m=>this.query(m),a);if(!u)continue;let l=i.filter(([,m])=>tr(m.Status,u)).map(([m])=>m);if(l.length===0)continue;let c=await e.describe(r.object),f=new No;f.addRead(t,l);let p=this.soqlBuilder.build({node:n,fields:c,selectFields:this.selectFields(r.object,c,e.excludedFields),edges:e.edges,cache:f,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:l[0],extraWhere:c.some(m=>m.name==="CreatedDate")?e.asOfWhere:void 0,under:new Set([t])});if(!p.scoped)continue;let g=e.recordsByObject.get(r.object);g||(g=new Map,e.recordsByObject.set(r.object,g));let h=qr(r.object,c);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let R of y)typeof R.Id=="string"&&!g.has(R.Id)&&g.set(R.Id,$t(R))}}}async completeRequiredParents(e,t,r,n,s,a,d){let i=new Set(e.graph.nodes.filter(f=>f.included).map(f=>f.objectApiName)),u=fi(e.graph,d),l=f=>i.has(f)||u.has(f),c=new Map;for(let f=0;f<Lu;f++){s.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&ui(g,y));for(let y of h.values())for(let R of m){let L=y[R.name];if(typeof L!="string"||L===""||a.has(L)||!R.referenceTo.some(l))continue;let T=(await s.objectsOf(L,R.referenceTo)).filter(l);for(let j of T)t.get(j)?.has(L)||c.get(j)?.has(L)||p.set(j,(p.get(j)??new Set).add(L))}}if(p.size===0)return;for(let[g,h]of p){c.set(g,new Set([...c.get(g)??[],...h]));let m=await r(g),y=t.get(g);y||(y=new Map,t.set(g,y));let R=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(T=>T.name==="CreatedDate")?n:void 0}),L=qr(g,m);for(let T of R)for(let j of a.keep(g,await this.query(T),L))typeof j.Id=="string"&&!y.has(j.Id)&&y.set(j.Id,$t(j))}}}async addStandardPrices(e,t,r){let n=t.get(qe);if(!n||n.size===0)return;let[s]=await this.query(Ft),a=typeof s?.Id=="string"?s.Id:void 0;if(!a)return;let d=g=>[We,Ye,Jt].map(h=>String(g[h]??"")).join("|"),i=new Set,u=new Set;for(let g of n.values()){if(g[mt]===a)continue;let h=g[We];typeof h=="string"&&h!==""&&(i.add(h),u.add(d(g)))}if(i.size===0)return;let l=async(g,h)=>{let m=await this.deps.describeFields(g),y=this.selectFields(g,m,e.excludedFields).map(L=>ge(L)).join(", "),R=m.some(L=>L.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${R}`)},c=t.get(sn);if(c||(c=new Map,t.set(sn,c)),!c.has(a))for(let g of await l(sn,`Id = '${De(a)}'`))c.set(a,$t(g));let f=await this.deps.describeFields(qe),p=this.soqlBuilder.buildJoining({objectApiName:qe,selectFields:this.selectFields(qe,f,e.excludedFields),split:{field:We,ids:i},whole:{field:mt,ids:new Set([a])},extraWhere:f.some(g=>g.name==="CreatedDate")?r:void 0});for(let g of p)for(let h of await this.query(g))typeof h.Id!="string"||n.has(h.Id)||u.has(d(h))&&n.set(h.Id,$t(h));return a}async addSellingModelOptions(e,t,r,n,s){if(s.has(ze)||e.graph.nodes.some(m=>m.objectApiName===ze&&!m.included))return;let a=t.get(qe),d=t.get(li),i=t.get(dn);if(!a||!d||!i)return;let u=m=>`${String(m[We]??"")}|${String(m[Ye]??"")}`,l=new Set,c=new Set,f=new Set;for(let m of a.values()){let y=m[We],R=m[Ye];typeof y!="string"||!d.has(y)||typeof R!="string"||!i.has(R)||(l.add(y),c.add(R),f.add(u(m)))}if(f.size===0)return;let p=await r(ze),g=this.soqlBuilder.buildJoining({objectApiName:ze,selectFields:this.selectFields(ze,p,e.excludedFields),split:{field:We,ids:l},whole:{field:Ye,ids:c},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(ze);h||(h=new Map,t.set(ze,h));for(let m of g)for(let y of await this.query(m))typeof y.Id!="string"||h.has(y.Id)||f.has(u(y))&&h.set(y.Id,$t(y))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let s=[],a=i=>`record${i===1?"":"s"}`,d=new Map;for(let[i,u]of e){if(u.size===0)continue;let l=(await t(i)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==i&&r.has(g.referenceTo[0])&&Yt(i,g.name,g.nillable)),c=i===qe&&n&&r.has(ze);if(l.length===0&&!c)continue;let f=new Map,p=new Map;for(let[g,h]of u){let m;for(let L of l){let T=h[L.name],j=L.referenceTo[0];if(!(typeof T!="string"||T==="")&&!e.get(j)?.has(T)){m={field:L.name,excluded:j};break}}let y=h[Ye];if(!m&&c&&typeof y=="string"&&e.get(dn)?.has(y)&&(m={field:Ye,excluded:ze}),!m)continue;f.set(g,m.excluded);let R=p.get(m.excluded)??{field:m.field,count:0};R.count++,p.set(m.excluded,R)}f.size>0&&d.set(i,f);for(let[g,{field:h,count:m}]of p)s.push({objectApiName:i,excludedObject:g,count:m,note:g===ze?`${m} ${i} ${a(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${i} ${a(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[i,u]of Object.entries(on)){let l=e.get(i),c=Ct[i];if(!l||l.size===0||!c)continue;let f=await er(y=>this.query(y),c);if(!f)continue;let p=new Set,g=new Map,h=d.get(u.object);for(let[y,R]of e.get(u.object)??[]){let L=R[u.lookup];if(typeof L!="string")continue;let T=h?.get(y);T?g.has(L)||g.set(L,T):p.add(L)}let m=new Map;for(let[y,R]of l){if(!tr(R.Status,f))continue;let L=r.has(u.object)?u.object:p.has(y)?void 0:g.get(y);L&&m.set(L,(m.get(L)??0)+1)}for(let[y,R]of m){let L=R===1;s.push({objectApiName:i,excludedObject:y,count:R,note:`${R} ${i} ${a(R)} past Draft will be loaded as ${L?"a draft":"drafts"} and stay so: `+(y===u.object?`the platform gives ${i} this status only with ${u.object} records under it, and excludedObjects leaves ${u.object} out`:`none of ${L?"its":"their"} ${u.object} records can be loaded without ${y}, which excludedObjects leaves out`)})}}return s}selectFields(e,t,r){let n=new Set(r?.[e]??[]),s=t.map(a=>a.name).filter(a=>!n.has(a));return s.includes("Id")||s.unshift("Id"),s}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??Eu,r=$r(t,e.tokens??{}),n=await this.query(r),s=[];for(let a of n)typeof a.Id=="string"&&typeof a.SobjectType=="string"&&typeof a.DeveloperName=="string"&&typeof a.Name=="string"&&s.push({id:a.Id,sobjectType:a.SobjectType,developerName:a.DeveloperName,..."NamespacePrefix"in a?{namespacePrefix:typeof a.NamespacePrefix=="string"&&a.NamespacePrefix!==""?a.NamespacePrefix:null}:{},name:a.Name});return s}};async function Du(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let a=[...s.values()],d=qr(n,await e(n)),i=t.keep(n,a,d);if(i.length===a.length)continue;r=!0;let u=new Set(i.map(l=>l.Id));for(let l of s.keys())u.has(l)||s.delete(l)}}}var Yn=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([c,f])=>f.some(p=>ut(t,c,p)!=="keep")).map(([c])=>c).filter(c=>e.extracted.objects.some(f=>f.objectApiName===c&&f.records.length>0)).sort(),s={...e.extracted,objects:e.extracted.objects.filter(c=>!n.includes(c.objectApiName))},a=new Map;for(let c of s.objects)for(let f of c.records)a.set(f.sourceId,f.referenceId);let d=new Map(s.recordTypeMap.map(c=>[c.id,c])),i={};for(let c of s.objects)i[c.objectApiName]=s.recordTypeMap.filter(f=>f.sobjectType===c.objectApiName).map(f=>({name:f.name,developerName:f.developerName,...f.namespacePrefix!==void 0?{namespacePrefix:f.namespacePrefix}:{}}));let u=[];for(let c of s.objects){let f=c.records.map(p=>{let g=this.anonymizeRecordFields(c.objectApiName,p.fields,a,d,t,r),h=p.fields.RecordTypeId,m=typeof h=="string"?d.get(h):void 0;return{referenceId:p.referenceId,fields:g,...m?{recordTypeDeveloperName:ct(m.namespacePrefix,m.developerName)}:{}}});u.push({objectApiName:c.objectApiName,records:f})}let l=s.standardPricebookSourceId?a.get(s.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:u,recordTypes:i,personContactSidecar:Mu(s,a),...l?{standardPricebook:l}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,s,a){let d={};for(let[i,u]of Object.entries(t)){if(i==="Id")continue;if(u==null){d[i]=u;continue}if(i==="RecordTypeId"&&typeof u=="string"){let c=n.get(u);d[i]=c?c.name:"";continue}if(typeof u=="string"){let c=r.get(u);if(c!==void 0){d[i]=c;continue}}let l=ut(s,e,i);d[i]=a.pseudonymize(l,u)}for(let[i,u]of Object.entries(d))typeof u=="string"&&Rn(u)&&(d[i]="");return d}};function Mu(o,e){let t=[],r=o.objects.find(n=>n.objectApiName==="Account");if(!r)return t;for(let n of r.records){let s=n.fields.PersonContactId;if(typeof s!="string"||s==="")continue;let a=e.get(s);a!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:a})}return t}var xu=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,$u=/^\+3363998\d{4}$/,_u=/^[a-z0-9-]+@example\.invalid$/,Bu=/^\d{2}0+$/,qu=3,Jn=class{run(e,t,r,n={}){let s=new Set,a=new Map;for(let c of t.objects)for(let f of c.records)s.add(f.referenceId),a.set(f.referenceId,{objectApiName:c.objectApiName,record:f});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},i=new Map(e.recordTypeMap.map(c=>[c.id,[c.name,c.developerName]])),u=new Set(t.filesLeftOut??[]);for(let c of e.objects)if(!u.has(c.objectApiName))for(let f of c.records){let p=a.get(f.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:c.objectApiName,referenceId:f.referenceId,detail:"record missing from the frozen dataset"});continue}let g=f.fields.RecordTypeId;this.checkSubstitution(c.objectApiName,f,p.record,r,d.substitution,new Set(typeof g=="string"?i.get(g)??[]:[]))}for(let c of t.objects)for(let f of c.records)this.checkClearEmpty(c.objectApiName,f,r,s,d["clear-empty"]),this.checkNoResidualId(c.objectApiName,f,s,d["no-residual-id"]);this.checkFormats(e,t,r,a,d.formats);let l=["substitution","clear-empty","formats","no-residual-id"].map(c=>({name:c,passed:d[c].length===0,violations:d[c]}));return{passed:l.every(c=>c.passed),checks:l,author:n.author??"frozen-dataset-engine",checkedAt:(n.now?.()??new Date).toISOString()}}checkSubstitution(e,t,r,n,s,a){for(let[d,i]of Object.entries(t.fields)){if(d==="Id"||i===null||i===void 0||i===""||ut(n,e,d)==="keep")continue;let l=r.fields[d];if(Gu(l,i)){s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof i=="string"&&i.length>=qu)for(let[c,f]of Object.entries(r.fields))c===d||typeof f!="string"||f!==i||ut(n,e,c)==="keep"||c==="RecordTypeId"&&a.has(f)||s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:c,detail:`transversal leak: original value of "${d}" found in "${c}"`})}}checkClearEmpty(e,t,r,n,s){for(let[a,d]of Object.entries(t.fields))a!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||ut(r,e,a)==="clear"&&d!==""&&d!==null&&d!==void 0&&s.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:a,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,s){let a={registrationSIV:d=>xu.test(d),phoneE164:d=>$u.test(d),email:d=>_u.test(d),postalCodeGeneralize:(d,i)=>Bu.test(d)&&d.length===i.trim().length};for(let d of e.objects)for(let i of d.records){let u=n.get(i.referenceId);if(u)for(let[l,c]of Object.entries(i.fields)){if(typeof c!="string"||c==="")continue;let f=ut(r,d.objectApiName,l),p=a[f];if(!p)continue;let g=u.record.fields[l];typeof g!="string"||g===""||p(g,c)||s.push({check:"formats",objectApiName:d.objectApiName,referenceId:i.referenceId,field:l,detail:`format not conserved for ${f}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[s,a]of Object.entries(t.fields))typeof a=="string"&&Rn(a)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:s,detail:"checksum-valid Salesforce ID survived the sweep"})}};function Gu(o,e){return o===e?!0:o==null||e===null||e===void 0?!1:String(o)===String(e)}var Wr=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let s=n===void 0?Pa(r):{namespacePrefix:n,developerName:r},a=`${e}|${t}|${String(s.namespacePrefix)}|${s.developerName}`,d=this.cache.get(a);if(d!==void 0)return d;let i=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${De(t)}' AND DeveloperName = '${De(s.developerName)}'`,u=Aa(await this.orgAccess.query(e,i)),l=Ta(s,u,bo),c;if("ambiguous"in l)c={ambiguous:!0,carriers:l.ambiguous.map(bo)};else if("found"in l){let f=l.found.id;c=await this.isUnavailable(e,t,f)?{unavailable:!0,id:f}:f}else c=null;return this.cache.set(a,c),c}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(a=>a.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return Fn(bn((await r).recordTypeInfos))}describeOf(e,t){let r=this.orgAccess.describe;if(!r)return;let n=`${e}|${t}`,s=this.describes.get(n);return s||(s=r(e,t),this.describes.set(n,s)),s}};import*as Qn from"node:fs";var Wu=2e3,Uu=3,Ku=10,Vu=o=>new Promise(e=>setTimeout(e,o)),Xn=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new fe}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??Vu,n=g=>e.onProgress?.(g),s=e.measurementIntervalMs??Wu,a=e.maxAttempts??Uu,d=Cn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let i=null,u=null,l=null,c=0;for(let g=1;g<=a;g++){c=g,l=await this.measure(e,d);let h=os(l);if(i!==null&&h===i){u=l;break}i=h,g<a&&await r(s)}let f=this.buildChecks(e,d,u??l,u!==null),p={status:Qu(f,d,u),checks:f,attempts:c,measuredAt:t().toISOString(),objects:ef(d,u??l)};return e.manifestPath&&(this.consignVerdict(e.manifestPath,p,e.author),p.manifestPath=this.sasGuard.assertOutsideRepo(e.manifestPath)),n({phase:"verify",status:p.status==="passed"?"done":"error",progress:100,message:`Post-load verification: ${p.status} (${c} measurement(s))`}),p}async measure(e,t){return{counts:await this.measureCounts(e,t),orphans:await this.measureOrphans(e,t),personContact:await this.measurePersonContacts(e),presence:await this.measurePresence(e,t)}}async measureCounts(e,t){let r=e.mapping?Lc(e.mapping):void 0,n={};for(let s of Object.keys(t.objects).sort()){let a=`SELECT COUNT() FROM ${ge(s)}`;if(!r){n[s]=await this.deps.orgAccess.count(e.orgId,a);continue}let d=0;for(let i of Nc(r.get(s)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${a} WHERE ${i}`);n[s]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??Ku,s=e.mapping?Lc(e.mapping):void 0;for(let[a,d]of Object.entries(e.mandatoryLookups??{}))for(let i of d){let u=new Set([...Fc(t,a,i),...ss(t.objects[a]?.parentNotLoaded,i)].flatMap(f=>{let p=e.mapping?.get(f);return p===void 0?[]:[p]})),l=s?Nc((s.get(a)??[]).filter(f=>!u.has(f))):[""],c=[];for(let f of l){let p=`SELECT Id FROM ${ge(a)} WHERE ${ge(i)} = null${f?` AND ${f}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);c.push(...g.map(h=>String(h.Id)))}r[`${a}.${i}`]=c.sort().slice(0,n)}return r}async measurePersonContacts(e){let t=e.dataset?.personContactSidecar??[];if(t.length===0||!e.mapping)return{checked:0,unrestored:[]};let r=t.filter(i=>e.mapping?.has(i.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let n=r.map(i=>e.mapping?.get(i.accountReferenceId)),s=await yn(i=>this.deps.orgAccess.query(e.orgId,i),n),a=[],d=0;for(let i of r){let u=e.mapping.get(i.accountReferenceId),l=s.get(u);l!==void 0&&(d++,e.mapping.get(i.contactReferenceId)!==l&&a.push(i.accountReferenceId))}return{checked:d,unrestored:a.sort()}}describesPersonAccounts(e){let t=this.personAccounts.get(e);if(!t){let r=this.deps.orgAccess.describe;t=r?r.call(this.deps.orgAccess,e,"Account").then(n=>n.fields.some(s=>s.name==="PersonContactId")).catch(()=>!0):Promise.resolve(!0),this.personAccounts.set(e,t)}return t}async measurePresence(e,t){let r={};if(!e.dataset)return r;for(let[n,s]of Object.entries(e.presenceKeys??{})){let a=new Set(Fc(t,n,s)),d=(e.dataset.objects.find(l=>l.objectApiName===n)?.records??[]).filter(l=>!a.has(l.referenceId)),i=[...new Set(d.map(l=>l.fields[s]).filter(l=>typeof l=="string"&&l!==""))].sort();if(i.length===0){r[n]=[];continue}let u=new Set;for(let l=0;l<i.length;l+=Zn){let c=i.slice(l,l+Zn).map(p=>`'${De(p)}'`).join(", "),f=await this.deps.orgAccess.query(e.orgId,`SELECT ${ge(s)} k FROM ${ge(n)} WHERE ${ge(s)} IN (${c})`);for(let p of f)u.add(String(p.k))}r[n]=i.filter(l=>!u.has(l))}return r}buildChecks(e,t,r,n){let s=[];if(s.push({name:"stability",passed:n,detail:n?"Two identical consecutive measurements \u2014 org reads are stable":"No two identical measurements within the attempt budget \u2014 org reads are transiently inconsistent"}),!r)return s;let a=Object.entries(t.objects).filter(([f,p])=>r.counts[f]!==p.expected).map(([f,p])=>`${f}: expected ${p.expected}, got ${r.counts[f]??0}`);s.push({name:"counts",passed:a.length===0,detail:a.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${a.join("; ")}`});let d=Cc(t),i=Hu(t,r);s.push({name:"load",passed:d.records===0&&i.length===0,detail:Ju(d,i)});let u=Object.entries(r.orphans).filter(([,f])=>f.length>0),l=Zu(t),c=[...u.length>0?[`Orphans \u2014 ${u.map(([f,p])=>`${f} (${p.length}: ${p.join(", ")})`).join("; ")}`]:[],...l.length>0?["Lookups the load left empty because the record they name was not loaded \u2014 "+l.map(({link:f,count:p})=>`${f} (${p})`).join("; ")]:[]];if(s.push({name:"orphans",passed:c.length===0,detail:c.length===0?"No orphans on the mandatory lookups of the graph":c.join("; ")}),(e.dataset?.personContactSidecar?.length??0)>0&&e.mapping&&s.push({name:"personcontact",passed:r.personContact.unrestored.length===0,detail:r.personContact.unrestored.length===0?`All ${r.personContact.checked} person account(s) hold the contact the load linked`:`Person accounts without the contact the load linked \u2014 accounts: ${r.personContact.unrestored.join(", ")}`}),e.dataset&&Object.keys(e.presenceKeys??{}).length>0){let f=Object.entries(r.presence).filter(([,p])=>p.length>0);s.push({name:"presence",passed:f.length===0,detail:f.length===0?"All referential keys present in the org":`Missing keys \u2014 ${f.map(([p,g])=>`${p}: ${g.join(", ")}`).join("; ")}`})}return s}consignVerdict(e,t,r){let n=this.sasGuard.assertOutsideRepo(e),s=or(JSON.parse(Qn.readFileSync(n,"utf8")));s.controls.dryRunLoad={status:t.status==="passed"?"passed":"failed",at:t.measuredAt,detail:`post-load check by ${r??"unknown"}: verdict=${t.status}; `+t.checks.map(a=>`${a.name}=${a.passed?"OK":"KO"}`).join(", ")},Qn.writeFileSync(n,Rd(s),"utf8")}};function os(o){return Array.isArray(o)?`[${o.map(os).join(",")}]`:typeof o=="object"&&o!==null?`{${Object.entries(o).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${os(r)}`).join(",")}}`:JSON.stringify(o)}function Fc(o,e,t){return ss(o.objects[e]?.writtenWithout,t)}function ss(o,e){let t=o?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Ur={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function Cc(o){let e={whole:[],part:[],refused:0,heldBack:0,notLoadable:[],records:0};for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s))){let n=u=>u.reduce((l,c)=>l+(r.exclusionReasons[c]??0),0),s=n(Ur.notLoadable);s>0&&e.notLoadable.push({objectApiName:t,records:s});let a=n(Ur.refused),d=n(Ur.heldBack),i=a+d;i!==0&&(e.refused+=a,e.heldBack+=d,e.records+=i,r.expected===0?e.whole.push({objectApiName:t,notLoaded:i}):e.part.push({objectApiName:t,notLoaded:i,of:i+r.expected}))}return e}function Hu(o,e){return Object.entries(o.objects).sort(([t],[r])=>t.localeCompare(r)).flatMap(([t,r])=>{let n=e.counts[t]??0;return n<r.expected?[{objectApiName:t,gone:r.expected-n,of:r.expected}]:[]})}function Yu(o){return o.length===0?"":`${o.reduce((t,r)=>t+r.gone,0)} record(s) it wrote or linked are no longer in the target \u2014 `+o.map(t=>`${t.objectApiName} (${t.gone} of ${t.of})`).join(", ")}function Ju(o,e=[]){let t=Xu(o),r=Yu(e);if(o.records===0)return r===""?`Every record the load had to write went in${t}`:`The load wrote every record it had to, and ${r}${t}`;let n=[...o.whole.length>0?["Objects the load wrote none of \u2014 "+o.whole.map(a=>`${a.objectApiName} (${a.notLoaded} not loaded)`).join(", ")]:[],...o.part.length>0?["Objects it wrote part of \u2014 "+o.part.map(a=>`${a.objectApiName} (${a.notLoaded} of ${a.of} not loaded)`).join(", ")]:[]],s=[...o.refused>0?[`${o.refused} refused by the target org`]:[],...o.heldBack>0?[`${o.heldBack} held back for a parent the target org refused`]:[]];return`${o.records} record(s) not loaded: ${s.join(", ")}. ${n.join("; ")}${r===""?"":`; ${r}`}${t}`}function Xu(o){return o.notLoadable.length===0?"":`; ${o.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the preview said \u2014 `+o.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function Zu(o){let e=[];for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s)))for(let n of Object.keys(r.parentNotLoaded??{}).sort()){let s=ss(r.parentNotLoaded,n).length;s>0&&e.push({link:`${t}.${n}`,count:s})}return e}function Qu(o,e,t){if(t===null)return"unstable";let r=o.filter(a=>!a.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(a=>a.length>0);return r.every(a=>a.name==="load"||a.name==="orphans")&&!n&&Cc(e).whole.length===0?"partial":"failed"}function ef(o,e){let t=r=>r.slice(0,r.indexOf("."));return Object.entries(o.objects).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let s=[...Ur.refused,...Ur.heldBack].reduce((c,f)=>c+(n.exclusionReasons[f]??0),0),a=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([c])=>t(c)===r).reduce((c,[,f])=>c+f.length,0),i=e?.presence[r]?.length??0,u=r==="Account"?e?.personContact.unrestored.length??0:0,l=e!==null&&a===n.expected&&s===0&&d===0&&i===0&&u===0;return{objectApiName:r,status:l?"passed":"failed",expected:n.expected,found:a,notLoaded:s,orphans:d,missingKeys:i,...u>0?{personContactsUnlinked:u}:{}}})}var Zn=200;function Lc(o){let e=new Map;for(let[t,r]of o){let n=t.startsWith("placeholder:")?t.split(":")[1]:t.slice(0,t.lastIndexOf("-"));if(!n)continue;let s=e.get(n)??[];s.push(r),e.set(n,s)}return e}function Nc(o){let e=[];for(let t=0;t<o.length;t+=Zn){let r=o.slice(t,t+Zn).map(n=>`'${De(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var is=200;function ds(o,e=is){return{insert:(t,r,n,s)=>as(o.insert(r,n,e,s?tf(s):void 0)),update:(t,r,n)=>as(o.update(r,n,e)),delete:(t,r,n)=>as(o.delete(r,n,e))}}function tf(o){let e=0,t=0;return{sending:(r,n,s)=>{t=s},answered:(r,n,s,a)=>{a?s.forEach((d,i)=>{let u=a[i];u!==void 0&&o(u,[d])}):(o(e,s),e+=t),t=0}}}async function as(o){try{return await o}catch(e){if(e instanceof id)return e.written;throw e}}var rf=200;function zc(o){let e={threshold:o.threshold,perCall:is,...o.duplicateRules?{duplicateRules:o.duplicateRules}:{}},t=o.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:s})=>n+Math.ceil(s/rf),0);return Do(t,e)+Do((o.purged??[]).filter(({rows:n})=>n>0),e)+cd(t.length,o.automationRead??0)+r}var nf="Nothing was read or written.",of=new Set([ga,ha,ma,"Document"].map(o=>o.toLowerCase()));function cs(o){return of.has(o.toLowerCase())}function ls(o,e){let t=new Map(o.objects.map(i=>[i.objectApiName.toLowerCase(),i])),r=new Set(e.objects.map(i=>i.toLowerCase())),n=new Set(e.excluded.map(i=>i.toLowerCase())),s=[...e.objects,...e.excluded].filter(i=>!t.has(i.toLowerCase())),a=[],d=[];for(let i of o.objects){let u=i.objectApiName.toLowerCase(),l=c=>{d.push({objectApiName:i.objectApiName,records:i.records,reason:c})};cs(i.objectApiName)?l("fileContentNotKept"):r.size>0&&!r.has(u)||n.has(u)||i.customSetting!==void 0&&!e.customSettings?l("excluded"):a.push(i)}return{replayed:a,leftOut:d,unknown:[...new Set(s)],records:a.reduce((i,u)=>i+u.records,0)}}function Mc(o){let e=o.dataStorageMaxMB!==void 0?{dataStorageMaxMB:o.dataStorageMaxMB}:{};return o.staging===!0?{kind:"real",why:"staging",...e}:o.tier==="scratch"?{kind:"free",why:"scratch",...e}:o.tier==="developer"?{kind:"free",why:"developer",...e}:o.dataStorageMaxMB===void 0?{kind:"unknown"}:o.dataStorageMaxMB>xr?{kind:"real",why:"storage",dataStorageMaxMB:o.dataStorageMaxMB}:{kind:"free",why:"developerSandbox",dataStorageMaxMB:o.dataStorageMaxMB}}function xc(o,e){return o!==void 0&&e!==void 0&&o.slice(0,15)===e.slice(0,15)}var sf=/\.my\.salesforce\.com$/;function Dc(o){if(o!==void 0)try{let e=new URL(o).hostname.toLowerCase();return sf.test(e)?e:void 0}catch{return}}function $c(o,e){if(o.tier!=="sandbox")return;if((e.formerOrganizationIds??[]).some(r=>xc(r,o.organizationId)))return"formerOrganizationId";if(e.username!==void 0&&e.username.trim().toLowerCase()===o.username.trim().toLowerCase())return"username";let t=Dc(e.instanceUrl);if(t!==void 0&&t===Dc(o.instanceUrl))return"myDomain"}var Kr={mask:"replay it masked (--mask)",noRealData:"declare that it holds no real data (--no-real-data), which the audit trail keeps",fewerObjects:"name the objects to replay (--objects A,B) or leave some out (--exclude-object X)",rewind:"rewind that org to the checkpoint instead"};function _t(o,e,t){return{code:o,message:`${e} ${nf}`,params:t}}function eo(o){return o.toLocaleString("en-US")}function _c(o){let e={...Kr,...o.words},{checkpoint:t,target:r}=o;if(t===void 0)return _t("REPLAY_CHECKPOINT_UNUSABLE",`Checkpoint ${o.checkpointId} does not read: its file is damaged, and what it holds cannot be told.`,{checkpoint:o.checkpointId,why:"damaged"});let n=t.name;if(t.status!=="ready")return _t("REPLAY_CHECKPOINT_UNUSABLE",t.status==="taking"?`Checkpoint '${n}' is still being taken, or its take stopped before its end: it holds part of its org at most.`:`The take of checkpoint '${n}' failed: it holds part of its org at most.`,{checkpoint:n,why:t.status});let s=df(t,r,e);if(s!==void 0)return s;let a=cf(t,o.choices,r,e);if(a!==void 0)return a;let d=ls(t,o.choices);if(d.records===0){let u=d.replayed.length===0?"every object it holds is left out":"the objects replayed hold no record";return _t("REPLAY_NOTHING",`Nothing of checkpoint '${n}' is left to replay into ${r.name}: ${u}${af(d)?", and a checkpoint keeps no file\u2019s content":""}.`,{checkpoint:n,target:r.name})}let i=o.maxRecords??Ms;if(d.records>i)return _t("REPLAY_TOO_MANY",`Checkpoint '${n}' would replay ${eo(d.records)} records into ${r.name}, past the ${eo(i)} a replay sets up at once: ${e.fewerObjects}.`,{checkpoint:n,target:r.name,records:d.records,max:i})}function af(o){return o.leftOut.length>0&&o.leftOut.every(e=>e.reason==="fileContentNotKept")}function df(o,e,t={}){if(!xc(e.organizationId,o.org.organizationId))return;let r=t.rewind??Kr.rewind;return _t("REPLAY_SAME_ORG",`${e.name} is the org checkpoint '${o.name}' was taken of: a replay creates copies of its records in another org, beside what that org holds. To bring ${e.name} back to that moment, ${r}.`,{checkpoint:o.name,target:e.name})}function cf(o,e,t,r={}){let n={...Kr,...r},s=Mc(o.org);if(s.kind==="free"||e.mask||$c(o.org,t)!==void 0)return;let a=o.name;if(s.kind==="unknown")return e.noRealData===!0?void 0:_t("REPLAY_COPY_UNKNOWN",`Checkpoint '${a}' is of a sandbox and does not say which: taken before SandForge 1.81, it keeps no data storage, and a Partial Copy or a Full sandbox holds production\u2019s records. To replay it into ${t.name}, ${n.mask}, or ${n.noRealData}.`,{checkpoint:a,target:t.name});let d=s.why==="staging"?"a sandbox marked Staging, which holds real data":`a Partial Copy or Full sandbox, by its data storage (${eo(s.dataStorageMaxMB??0)} MB, past the ${eo(xr)} MB of a Developer Pro), which may hold real data`;return _t("REPLAY_REAL_DATA",`Checkpoint '${a}' is of ${d}: it goes into another org masked only. To replay it into ${t.name}, ${n.mask}.`,{checkpoint:a,target:t.name,why:s.why,...s.dataStorageMaxMB!==void 0?{mb:s.dataStorageMaxMB}:{}})}function Bc(o,e,t){let r=Mc(o.org),n=$c(o.org,t),s=r.kind==="unknown"&&!e.mask&&e.noRealData===!0;return{replaySource:r.kind==="free"||r.kind==="real"?r.why:"unknown",...r.kind!=="unknown"&&r.dataStorageMaxMB!==void 0?{replaySourceStorageMB:r.dataStorageMaxMB}:{},replayMasked:e.mask,replayContactPoints:e.contactPoints,...s?{replayNoRealDataDeclared:!0}:{},...n!==void 0&&!e.mask&&r.kind!=="free"?{replayIntoSameSandbox:n}:{}}}function de(o){return o.slice(0,15)}var Wc=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ke(o){return xa(o)??o}function qc(o,e){return`${o}-${ke(e)}`}var us="005",fs="00G",Uc="00D",ps="00e",Kc="OwnerId",ys="RecordTypeId",gs="SetupOwnerId",Hr="CurrencyIsoCode",ro="Pricebook2",Bt=200,hs=new Set([...Ri,To]),lf=["Title","Name"];async function*ms(o,e){let t=await Ao.read(o.folder,o.checkpoint.snapshotId,e);for await(let r of t.records())typeof r.Id=="string"&&(yield r)}async function uf(o,e){let t=await Ao.read(o.folder,o.checkpoint.snapshotId,e),r=[];for(let n=0;n<t.size;n++)r.push(t.idAt(n));return r}function no(o,e){return o!==void 0&&!o.unread.some(t=>t.part===e)}async function ff(o){let e=ls(o.checkpoint,o.choices),t=new Map;for(let p of o.checkpoint.objects)for(let g of await uf(o,p.objectApiName))t.set(de(g),p.objectApiName);let r=new Set,n=new Set,s=new Set,a=new Set,d=new Map,i=new Set,u=[],l=new Set;for(let p of e.replayed)for await(let g of ms(o,p.objectApiName)){l.add(de(g.Id));for(let[h,m]of Object.entries(g)){if(hs.has(h)||typeof m!="string"||(h===Hr&&m!==""&&i.add(m),!Wc.test(m)))continue;let y=de(m);if(h===ys)s.add(y);else if(y.startsWith(us))r.add(y);else if(y.startsWith(fs)&&h===Kc)n.add(y);else if(y.startsWith(ps)&&h===gs)a.add(y);else if(!t.has(y)&&!y.startsWith(Uc)){let R=`${p.objectApiName}.${h}`,L=d.get(R)??new Set;L.add(y),d.set(R,L)}}if(p.objectApiName===qe){let h=g[mt],m=g[We];if(typeof h=="string"&&typeof m=="string"){let y=g[Jt];u.push({book:de(h),product:de(m),currency:typeof y=="string"?y:""})}}}let c=[];if((o.checkpoint.files?.links??0)>0)for await(let p of ki(o.folder))l.has(de(p.LinkedEntityId))&&c.push({ContentDocumentId:p.ContentDocumentId,LinkedEntityId:p.LinkedEntityId,ShareType:p.ShareType,Visibility:p.Visibility});let f=[];for(let p of e.leftOut)if(p.reason==="fileContentNotKept")for await(let g of ms(o,p.objectApiName)){let h=lf.map(m=>g[m]).find(m=>typeof m=="string"&&m!=="");f.push({objectApiName:p.objectApiName,id:ke(g.Id),...h!==void 0?{name:h}:{}})}return{objects:e,heldBy:t,users:r,queues:n,recordTypes:s,profiles:a,notHeld:d,currencies:i,standardPricebook:pf(o,u,t),fileLinks:c,filesLeft:f}}function pf(o,e,t){let r=o.checkpoint.objects.some(i=>i.objectApiName===ro||i.objectApiName===qe);if(no(o.annex,"standardPricebook")&&o.annex.standardPricebookId)return{id:ke(o.annex.standardPricebookId),how:"annex"};let n=e.filter(i=>t.has(i.product));if(n.length===0||!r)return{how:"none"};let s=new Set(n.map(i=>`${i.product}|${i.currency}`)),a=new Map;for(let i of n){let u=a.get(i.book)??new Set;u.add(`${i.product}|${i.currency}`),a.set(i.book,u)}let d=[...a].filter(([,i])=>i.size===s.size).map(([i])=>i);return d.length===1?{id:ke(d[0]),how:"deduced"}:{how:"ambiguous"}}function Vr(o,e){let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t}function to(o){return o.map(e=>`'${De(e)}'`).join(", ")}function Vc(o){let e=o.lastIndexOf("@"),t=o.lastIndexOf("."),r=o.slice(e+1);return e>=0&&t>e&&r.split(".").length>2?o.slice(0,t):o}function gf(o){if(o===void 0)return;let e=Vc(o);return e===o?void 0:o.slice(e.length)}async function hf(o){let{access:e,orgId:t,survey:r,source:n}=o,s=0,a=async v=>(s++,e.query(t,v)),d=new Map,i=new Map,u=async v=>{s++;try{d.set(v,await e.describe(t,v))}catch(P){i.set(v,X(P))}};for(let v of r.objects.replayed)await u(v.objectApiName);r.fileLinks.length>0&&await u(rr);let l=new Map,c=v=>typeof v.Id=="string"&&typeof v.Username=="string"?{id:ke(v.Id),username:v.Username,isActive:v.IsActive===!0,userType:typeof v.UserType=="string"?v.UserType:""}:void 0,f=[...new Set([...r.users,...Object.values(n.choices.ownerMap??{}).map(de)])].sort();for(let v of Vr(f,Bt))for(let P of await a(`SELECT Id, Username, IsActive, UserType FROM User WHERE Id IN (${to(v)})`)){let C=c(P);C&&l.set(de(C.id),C)}let p=new Map;if(no(n.annex,"users")){let v=o.tier==="sandbox"?gf(o.username):void 0,P=new Map;for(let M of n.annex.users){let W=de(M.id),V=l.get(W);if(V?.isActive===!0&&V.userType==="Standard")continue;let H=n.checkpoint.org.tier==="sandbox"?Vc(M.username):M.username,E=[M.username,H,...v!==void 0?[`${H}${v}`]:[]];P.set(W,[...new Set(E.map(q=>q.toLowerCase()))])}let C=[...new Set([...P.values()].flat())].sort(),G=new Map;for(let M of Vr(C,Bt)){let W=M.map(V=>`'${De(V)}'`).join(", ");for(let V of await a(`SELECT Id, Username, IsActive, UserType FROM User WHERE Username IN (${W})`)){let H=c(V);H&&G.set(H.username.toLowerCase(),H)}}for(let[M,W]of P){let V=W.map(H=>G.get(H)).find(H=>H!==void 0);V&&p.set(M,V)}}let g=[],h=[...d.keys()].filter(v=>d.get(v)?.fields.some(P=>P.name===ys));if(h.length>0){let v=Hc(d),P=await a(`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${v?", IsPersonType":""} FROM RecordType WHERE SobjectType IN (${h.map(C=>`'${ge(C)}'`).join(", ")})`);for(let C of P)typeof C.Id!="string"||typeof C.SobjectType!="string"||typeof C.DeveloperName!="string"||g.push({id:ke(C.Id),sobjectType:C.SobjectType,developerName:C.DeveloperName,...typeof C.NamespacePrefix=="string"&&C.NamespacePrefix!==""?{namespacePrefix:C.NamespacePrefix}:{},name:typeof C.Name=="string"?C.Name:C.DeveloperName,isActive:C.IsActive!==!1,...typeof C.IsPersonType=="boolean"?{isPersonType:C.IsPersonType}:{}})}let m=[];if(r.queues.size>0){let v=new Map;for(let P of await a("SELECT QueueId, SobjectType FROM QueueSobject"))typeof P.QueueId!="string"||typeof P.SobjectType!="string"||v.set(de(P.QueueId),[...v.get(de(P.QueueId))??[],P.SobjectType]);for(let P of await a("SELECT Id, DeveloperName FROM Group WHERE Type = 'Queue'"))typeof P.Id!="string"||typeof P.DeveloperName!="string"||m.push({id:ke(P.Id),developerName:P.DeveloperName,sobjectTypes:v.get(de(P.Id))??[]})}let y;if([...d.values()].some(v=>v.fields.some(P=>P.name===Hr))&&r.currencies.size>0){y=new Set;for(let v of await a("SELECT IsoCode, IsActive FROM CurrencyType"))typeof v.IsoCode=="string"&&v.IsActive===!0&&y.add(v.IsoCode)}let L;if(r.standardPricebook.id!==void 0){let[v]=await a(Ft);typeof v?.Id=="string"&&(L=ke(v.Id))}let T=new Set,j=new Map;for(let[v,P]of r.heldBy){let C=j.get(P);C?C.push(v):j.set(P,[v])}let x=async(v,P)=>{let C=0;for(let G of Vr(P,Bt))for(let M of await a(`SELECT Id FROM ${ge(v)} WHERE Id IN (${to(G)})`))typeof M.Id=="string"&&(T.add(de(M.Id)),C++);return C},U=new Set(r.objects.replayed.map(v=>v.objectApiName));for(let[v,P]of j){if(i.has(v)||cs(v))continue;let C=[...P].sort(),G=C.slice(0,Bt);try{await x(v,G)>0&&await x(v,C.slice(Bt))}catch(M){if(U.has(v))throw M}}let S=new Map;for(let[v,P]of r.notHeld){let[C,G]=v.split("."),M=d.get(C)?.fields.find(H=>H.name===G),W=M?.type==="reference"?M.referenceTo??[]:[];if(W.length!==1)continue;let V=S.get(W[0])??new Set;for(let H of P)V.add(H);S.set(W[0],V)}for(let[v,P]of S)try{await x(v,[...P].sort())}catch{}let w=new Map;for(let v of r.objects.replayed){if(v.customSetting===void 0||i.has(v.objectApiName))continue;let P={names:new Set,owners:new Set};for(let C of await a(`SELECT Id, Name, SetupOwnerId FROM ${ge(v.objectApiName)}`))typeof C.Name=="string"&&P.names.add(C.Name),typeof C.SetupOwnerId=="string"&&P.owners.add(de(C.SetupOwnerId));w.set(v.objectApiName,P)}let I=new Set;for(let v of Vr([...r.profiles].sort(),Bt))for(let P of await a(`SELECT Id FROM Profile WHERE Id IN (${to(v)})`))typeof P.Id=="string"&&I.add(de(P.Id));let A=new Set,N=[...new Set(r.fileLinks.map(v=>de(v.ContentDocumentId)))];if(!i.has(rr))for(let v of Vr(N.sort(),Bt))for(let P of await a(`SELECT Id FROM ContentDocument WHERE Id IN (${to(v)})`))typeof P.Id=="string"&&A.add(de(P.Id));return{organizationId:ke(o.organizationId),runningUserId:ke(o.runningUserId),describes:d,missing:i,usersById:l,usersByUsername:p,recordTypes:g,queues:m,...y!==void 0?{currencies:y}:{},...L!==void 0?{standardPricebookId:L}:{},sameIds:T,customSettings:w,profiles:I,files:A,requests:s}}function Hc(o){return o.get("Account")?.fields.some(e=>e.name===To)===!0}function mf(o,e,t){let r=[...new Set(Object.values(o.ownerMap??{}).map(de))].sort(),n=r.filter(a=>{let d=e.usersById.get(a);return d===void 0||d.userType!=="Standard"});if(n.length>0)return{code:"OWNER_MAP_UNKNOWN",users:n.map(ke),message:`The owners chosen give records to users ${t} does not hold as standard users: ${n.map(ke).join(", ")}. Choose users of ${t}. Nothing was written.`};let s=r.filter(a=>e.usersById.get(a)?.isActive!==!0);if(s.length>0)return{code:"OWNER_MAP_INACTIVE",users:s.map(ke),message:`The owners chosen give records to users ${t} holds inactive: ${s.map(ke).join(", ")}. It refuses a record owned by an inactive user: choose an active user, or reactivate them there. Nothing was written.`}}var qt=class{constructor(e){this.id=e}id;counts=new Map;add(e,t=1){let r=this.id(e),n=this.counts.get(r);n?n.n+=t:this.counts.set(r,{key:e,n:t})}entries(){return[...this.counts.values()]}};function yf(o,e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0||xs(o,e.name)}function wf(o){let e=o.length;return typeof e=="number"&&e>0?e:void 0}var bf=new Set(["id","reference","boolean","double","int","long","percent","currency","date","datetime","time","picklist","multipicklist"]);async function Rf(o){let{survey:e,target:t,choices:r,annex:n}=o,s=mf(r,t,o.targetName);if(s)return{refusal:s};let a=new qt(k=>`${k.object}|${k.reason}`);for(let k of e.objects.leftOut)a.add({object:k.objectApiName,reason:k.reason},k.records);let d=e.objects.replayed.filter(k=>t.missing.has(k.objectApiName)?(a.add({object:k.objectApiName,reason:"notInTarget"},k.records),!1):t.describes.get(k.objectApiName)?.createable===!1?(a.add({object:k.objectApiName,reason:"notCreateable"},k.records),!1):!0),i=new Set(d.map(k=>k.objectApiName)),u=new qt(k=>`${k.field}|${k.reason}`),l={kept:0,toRunningUser:0,reasons:{notInTarget:0,inactive:0,queueMissing:0}},c=new qt(k=>`${k.object}|${k.recordType}|${k.outcome}`),f=new qt(k=>k),p=new Map,g=!1,h={inserted:0,alreadyThere:0},m=new Map,y=new Map,R=Hc(t.describes),L=new Set,T=e.standardPricebook,j=T.id!==void 0?de(T.id):void 0,x=new Map(Object.entries(r.ownerMap??{}).map(([k,F])=>[de(k),ke(F)])),U=k=>{let F=t.usersById.get(k);if(F?.userType==="Standard"&&F.isActive)return{id:F.id};let O=t.usersByUsername.get(k);return O?.userType==="Standard"&&O.isActive?{id:O.id}:{why:F!==void 0||O!==void 0?"inactive":"notInTarget"}},S=(k,F)=>{let O=Q=>Q.sobjectTypes.includes(k),J=t.queues.find(Q=>de(Q.id)===F&&O(Q));if(J)return J.id;let ee=no(n,"queues")?n.queues.find(Q=>de(Q.id)===F):void 0;if(ee!==void 0)return t.queues.find(Q=>Q.developerName===ee.developerName&&O(Q))?.id},w=(k,F,O)=>{let J=de(F),ee=no(n,"recordTypes")?n.recordTypes.find(B=>de(B.id)===J):void 0,Q=t.recordTypes.filter(B=>B.sobjectType===k&&B.isActive),me,te="default";if(ee!==void 0&&(me=Q.find(B=>B.developerName===ee.developerName&&(B.namespacePrefix??null)===(ee.namespacePrefix??null)),me&&(te="byName")),me===void 0&&(me=Q.find(B=>de(B.id)===J),me&&(te="byId")),me===void 0&&O){let B=Q.filter(ie=>ie.isPersonType===!0);if(B.length!==1)return{refused:`the checkpoint does not say which of the person account record types of ${o.targetName} its person accounts had: take it again with SandForge 1.81 or later, or leave Account out`};me=B[0]}let Be={recordType:ee!==void 0?ct(ee.namespacePrefix,ee.developerName):ke(F),outcome:te};if(me===void 0)return{given:Be};let D=me,we=t.describes.get(k)?.recordTypeInfos?.find(B=>de(B.recordTypeId)===de(D.id));if(we!==void 0&&!we.available)return{refused:`${ct(D.namespacePrefix,D.developerName)} is not assigned to the user who replays in ${o.targetName}: assign it to them, or leave ${k} out`};let et={name:D.name,developerName:D.developerName,namespacePrefix:D.namespacePrefix??null},tt=y.get(k)??new Map;return tt.set(D.id,et),y.set(k,tt),{ref:et,given:Be}},I=[];for(let k of d){let F=k.objectApiName,O=t.describes.get(F);if(O===void 0)continue;let J=new Map(O.fields.map(te=>[te.name,te])),ee=k.fields.filter(te=>!hs.has(te)&&!J.has(te)&&!(te===Hr&&t.currencies===void 0));ee.length>0&&p.set(F,new Set(ee));let Q=k.customSetting,me=t.customSettings.get(F);for await(let te of ms(o,F)){let Be=de(te.Id);if(t.sameIds.has(Be)){m.set(qc(F,te.Id),ke(te.Id));continue}let D={objectApiName:F,key:Be,referenceId:qc(F,te.Id),fields:{},pointsAt:new Map,sourceId:ke(te.Id),emptied:[]},we=(B,ie)=>{D.refused??={reason:B,...ie!==void 0?{path:ie}:{}}},et=(F==="Account"||F==="Contact")&&kr(te);et&&!R&&we("personAccountsUnsupported",`turn person accounts on in ${o.targetName}, or leave ${F} out`),et&&F==="Contact"&&L.add(Be);let tt=F==="Account"?mn(te,!1):void 0;for(let[B,ie]of Object.entries(te)){if(hs.has(B)||tt!==void 0&&un(F,B,tt))continue;let bt=J.get(B);if(bt===void 0){B===Hr&&typeof ie=="string"&&ie!==""&&(g||=t.currencies===void 0);continue}if(ie==null||ie==="")continue;if(B===Hr&&typeof ie=="string"){t.currencies!==void 0&&!t.currencies.has(ie)&&(we("inactiveCurrency",`activate ${ie} in ${o.targetName}, or leave ${F} out`),f.add(ie)),D.fields[B]=ie;continue}if(B===ys&&typeof ie=="string"){let ye=w(F,ie,et);ye.given!==void 0&&(D.recordType=ye.given),ye.refused!==void 0?we("recordTypeUnavailable",ye.refused):ye.ref!==void 0&&(D.fields[B]=ye.ref.name,D.recordTypeDeveloperName=ct(ye.ref.namespacePrefix,ye.ref.developerName));continue}if(bt.type!=="reference"||typeof ie!="string"||!Wc.test(ie)){D.fields[B]=ie;continue}let ue=de(ie),ft=yf(F,bt),rt=(ye,ve)=>{ft?we("requiredLookupMissing",ve):D.emptied.push({field:`${F}.${B}`,reason:ye})};if(ue.startsWith(Uc)){D.fields[B]=t.organizationId;continue}if(B===gs){(ue.startsWith(ps)?t.profiles.has(ue):t.usersById.has(ue))?D.fields[B]=ke(ie):we("requiredLookupMissing",`the ${ue.startsWith(ps)?"profile":"user"} its row is of is not in ${o.targetName}`);continue}if(B===Kc&&(ue.startsWith(us)||ue.startsWith(fs))){let ye=x.get(ue);if(ye!==void 0)D.owner="kept",D.fields[B]=ye;else if(r.owners==="me")D.owner="toRunningUser";else if(ue.startsWith(fs)){let ve=S(F,ue);D.owner=ve!==void 0?"kept":"queueMissing",ve!==void 0&&(D.fields[B]=ve)}else{let ve=U(ue);D.owner=ve.id!==void 0?"kept":ve.why??"notInTarget",ve.id!==void 0&&(D.fields[B]=ve.id)}continue}if(ue.startsWith(us)){let ye=U(ue);ye.id!==void 0?D.fields[B]=ye.id:ft?D.fields[B]=t.runningUserId:D.emptied.push({field:`${F}.${B}`,reason:"userNotInTarget"});continue}if(j!==void 0&&ue===j){t.sameIds.has(ue)?D.fields[B]=ke(ie):i.has(ro)&&e.heldBy.has(ue)?D.pointsAt.set(B,ue):t.standardPricebookId!==void 0?D.fields[B]=t.standardPricebookId:rt("objectNotHeld",`${o.targetName} has no standard price book`);continue}let xe=e.heldBy.get(ue);xe!==void 0&&t.sameIds.has(ue)?D.fields[B]=ke(ie):xe!==void 0&&i.has(xe)?D.pointsAt.set(B,ue):xe!==void 0?rt("objectNotReplayed",`replay ${xe} too`):t.sameIds.has(ue)?D.fields[B]=ke(ie):rt("objectNotHeld",`the checkpoint holds no record it points at, and ${o.targetName} holds none under its Id`)}if(F===qe&&T.how==="ambiguous"&&we("requiredLookupMissing",`the checkpoint does not say which of its price books is the standard one, which every other price needs first: take it again with SandForge 1.81 or later, or leave ${qe} out`),Q!==void 0&&me!==void 0){let B=D.fields[gs];if(Q==="list"?typeof te.Name=="string"&&me.names.has(te.Name):typeof B=="string"&&me.owners.has(de(B))){h.alreadyThere++;continue}}I.push(D)}}let A=new Map(I.map(k=>[k.key,k])),N=new Map;for(let k of I)for(let F of k.pointsAt.values()){let O=N.get(F);O?O.push(k):N.set(F,[k])}let v=I.filter(k=>k.refused!==void 0);for(let k=0;k<v.length;k++){let F=v[k];for(let O of N.get(F.key)??[])O.refused===void 0&&(O.refused={reason:"parentRefused",path:`its ${F.objectApiName} is refused: lift that first`},v.push(O))}let P=new qt(k=>`${k.object}|${k.reason}`),C=new Map,G=[];for(let k of I){if(k.refused!==void 0){P.add({object:k.objectApiName,...k.refused});continue}for(let O of k.emptied)u.add(O);k.recordType!==void 0&&c.add({object:k.objectApiName,...k.recordType}),k.owner==="kept"?l.kept++:k.owner!==void 0&&(l.toRunningUser++,k.owner!=="toRunningUser"&&l.reasons[k.owner]++);for(let[O,J]of k.pointsAt){let ee=A.get(J);ee!==void 0&&ee.refused===void 0?k.fields[O]=ee.referenceId:u.add({field:`${k.objectApiName}.${O}`,reason:"objectNotReplayed"})}L.has(k.key)&&typeof k.fields.AccountId=="string"&&G.push({accountReferenceId:k.fields.AccountId,contactReferenceId:k.referenceId});let F=C.get(k.objectApiName)??[];F.push({referenceId:k.referenceId,fields:k.fields,...k.recordTypeDeveloperName!==void 0?{recordTypeDeveloperName:k.recordTypeDeveloperName}:{}}),C.set(k.objectApiName,F)}for(let k of d)k.customSetting!==void 0&&(h.inserted+=C.get(k.objectApiName)?.length??0);let M=t.describes.get(rr);if(M!==void 0&&M.createable!==!1){let k=[];for(let F of e.fileLinks){let O=A.get(de(F.LinkedEntityId));O===void 0||O.refused!==void 0||t.files.has(de(F.ContentDocumentId))&&k.push({referenceId:`${rr}-${ke(F.ContentDocumentId)}_${O.sourceId}`,fields:{ContentDocumentId:ke(F.ContentDocumentId),LinkedEntityId:O.referenceId,ShareType:F.ShareType,Visibility:F.Visibility}})}k.length>0&&C.set(rr,k)}let W=new Ui(o.salt),V=r.mask?new Yi(void 0,o.salt):void 0,H=r.mask?new vn:void 0,E=[],q=[];for(let[k,F]of C){let O=t.describes.get(k);if(O===void 0)continue;let J=new Set(F.flatMap(D=>Object.keys(D.fields))),ee=O.fields.filter(D=>J.has(D.name)).map(D=>{let we=wf(D);return{name:D.name,queryable:!0,createable:D.createable,isReference:D.type==="reference",type:D.type,...we!==void 0?{length:we}:{}}});if(r.contactPoints==="neutralized"){let D=W.forObject(k,ee);if(D)for(let we of F)D(we.fields)}if(V===void 0||H===void 0)continue;let Q=ee.filter(D=>!bf.has((D.type??"").toLowerCase())),me=new Set(In(H,Q.map(D=>({name:D.name,type:D.type??"string"})))),te=Q.filter(D=>me.has(D.name)).map(D=>({name:D.name,type:D.type??"string",...D.length!==void 0?{length:D.length}:{}}));for(let D of te)E.push(`${k}.${D.name}`);for(let D of Q)!me.has(D.name)&&(D.type??"").toLowerCase()==="textarea"&&q.push(`${k}.${D.name}`);if(te.length===0)continue;let Be=V.anonymize({objectApiName:k,records:F.map(D=>D.fields),sourceIds:F.map(D=>D.referenceId),fields:te,methods:{}});F.forEach((D,we)=>{D.fields=Be[we]??D.fields})}let Y={};for(let[k,F]of y)Y[k]=[...F.values()];let ae=[...C].map(([k,F])=>({objectApiName:k,records:F})),$=j!==void 0?A.get(j):void 0,K=$!==void 0&&$.refused===void 0&&$.objectApiName===ro?$.referenceId:void 0,Z={datasetVersion:"1.0.0",objects:ae,recordTypes:Y,personContactSidecar:G,...K!==void 0?{standardPricebook:K}:{}},ne=ae.reduce((k,F)=>k+F.records.length,0),he=e.objects.replayed.some(k=>k.objectApiName===ro||k.objectApiName===qe),_e=P.entries(),Me={records:{toCreate:ne-(K!==void 0?1:0),linkedById:m.size,linkedByKey:0,refusedBeforeWrite:_e.reduce((k,F)=>k+F.n,0)},owners:l,recordTypes:c.entries().map(({key:k,n:F})=>({...k,records:F})).sort((k,F)=>Gc(`${k.object}.${k.recordType}`,`${F.object}.${F.recordType}`)),notReplayed:a.entries().map(({key:k,n:F})=>({...k,records:F})),lookupsEmptied:u.entries().map(({key:k,n:F})=>({...k,records:F})).sort((k,F)=>Gc(k.field,F.field)),refused:_e.map(({key:k,n:F})=>({object:k.object,records:F,reason:k.reason,...k.path!==void 0?{path:k.path}:{}})),fieldsNotInTarget:[...p].map(([k,F])=>({object:k,fields:[...F].sort()})),...e.objects.replayed.some(k=>k.customSetting!==void 0)?{customSettings:h}:{},currencies:{refused:f.entries().map(({key:k,n:F})=>({code:k,records:F})),...g?{singleCurrencyTarget:!0}:{}},...he?{standardPricebook:T.how}:{},masked:{fields:E.sort(),...r.mask?{unmaskedFreeText:q.sort()}:{}},contactPoints:r.contactPoints,degraded:kf(n),auditDates:"new"};return{conversion:{dataset:Z,summary:Me,identityKeys:Object.fromEntries(r.link.map(k=>[k.objectApiName,[...k.fields]])),linkedById:m,filesLeft:e.filesLeft}}}function kf(o){return o===void 0?["recordTypes","users","queues","standardPricebook"]:[...new Set(o.unread.map(e=>e.part))]}function Gc(o,e){return o<e?-1:o>e?1:0}async function Yc(o){let e={folder:o.folder,checkpoint:o.checkpoint,annex:o.annex,choices:o.choices},t=await ff(e),r=await hf({...o,source:e,survey:t});return{...await Rf({...e,survey:t,target:r,targetName:o.targetName,...o.salt!==void 0?{salt:o.salt}:{}}),target:r,survey:t}}var vf={insert:async()=>{throw new Error("A preview writes nothing.")},update:async()=>{throw new Error("A preview writes nothing.")},delete:async()=>{throw new Error("A preview writes nothing.")}},Of=new Set(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:manifest:get","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"]),oo="REPLACE_LEAVES_RECORDS",ur=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},fr=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.emails=n;this.orgId=s;this.name="LoadEmailsStop"}code;emails;orgId},Xr=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.automation=n;this.orgId=s;this.name="LoadAutomationStop"}code;automation;orgId},Zr=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=Fo},pl="FROZEN_STORAGE_EXCEEDED",Qr=class extends Error{constructor(t,r,n){super(t);this.storage=r;this.orgId=n;this.name="LoadStorageStop"}storage;orgId;code=pl};function so(o){let e=o<10?100:10;return String(o<=0?0:Math.ceil(o*e-1e-9)/e)}function Jc(o){let e;return{request:t=>(e===void 0&&(e=Promise.resolve().then(()=>o.request(t)),e.catch(()=>{})),e)}}function Xc(o){if("unread"in o.storage)return;let e=Math.max(0,o.automationBytes??0),t=gl(o.dataset,o.sent)+e,r=(o.purged??[]).filter(l=>l.deletes).reduce((l,c)=>l+jo(c.objectApiName,{rows:c.rows}),0),n=1024*1024,{remainingMB:s,maxMB:a}=o.storage;if(t<=s*n+r)return;let d={estimateMB:t/n,...e>0?{automationMB:e/n}:{},remainingMB:s,maxMB:a,...r>0?{freedMB:r/n}:{}},i=d.freedMB!==void 0?`, and the reload's purge frees about ${so(d.freedMB)} MB first`:"",u=d.automationMB!==void 0?`, about ${so(d.automationMB)} MB of it for what the target's automation creates under them`:"";return o.replay===!0?{storage:d,message:`The replay was refused before it wrote anything: the checkpoint's records take about ${so(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${a} MB${i}. To replay part of it, ${Kr.fewerObjects}; or free data storage in ${o.target}. Nothing was written.`}:{storage:d,message:`The load was refused before it wrote anything: the dataset's records take about ${so(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${a} MB${i}. Load a pilot first, one root folder of it; or extract a smaller dataset, with a lower budget in the configuration, a new selection and a new extraction; or free data storage in ${o.target}. Nothing was written.`}}var Sf=Ge({sobjects:ht(Ge({name:Ce().min(1),createable:nn().optional()}).loose())}).loose();function gl(o,e){return o.objects.reduce((t,r)=>{if(e!==void 0&&!e.takes(r.objectApiName))return t;let n=e===void 0?r.records.length:r.records.filter(s=>!e.byThePlatform.has(s.referenceId)).length;return t+jo(r.objectApiName,{rows:n})},0)}function Zc(o,e,t,r){if(!("objects"in o))return 0;let n=qi(Lt(o,e,r),r),s=new Map(t.objects.map(a=>[a.objectApiName,a.records.length]));return Gi(n,a=>s.get(a)??0)}function Af(o){return{estimateMB:o.estimateMB,...o.automationMB!==void 0?{automationMB:o.automationMB}:{},remainingMB:o.remainingMB,maxMB:o.maxMB,...o.freedMB!==void 0?{freedMB:o.freedMB}:{}}}function Qc(o,e,t){if(t!==!0)return o;try{return Ho(o,e.rootObject)}catch{return o}}function el(o){return o?{replay:o}:{}}function Pf(o,e){let t=0;for(let r of o.perObject){let n=r.reused-(r.writtenByThePlatform??0),s=e.standardPricebook!==void 0&&r.objectApiName==="Pricebook2"&&n>0?1:0;t+=n-s}return t}function Tf(o,e){let t=Si(o,e);return{verdict:o.verdict,estimate:o.estimate,...o.verdict==="unread"?{unread:o.unread}:{remaining:o.remaining,max:o.max},...o.parts?{parts:{...o.parts}}:{},...t!==void 0?{refused:{code:Fo,message:t}}:{}}}function Yr(o,e){let t=[...new Set(o.map(r=>r.objectApiName))];return Ws({setToDraft:Ba(t),delete:Wa(t)},e)}function ws(o){return o.status==="success"&&(o.left??[]).length===0}function tl(o){return o.verdict!=="nothingSends"||o.counted.length>0||o.uncounted!==void 0}function jf(o,e){if(e.includeChanged||o.refusal!==void 0||o.status!=="partial"&&o.status!=="failure")return o;let t=o.objects.every(s=>s.refused===0&&s.deleted+s.alreadyGone+s.keptChanged===s.found),r=(o.left??[]).some(s=>s.class==="late"&&e.sweepLate||s.class==="untied"&&e.sweepUntied),n=o.objects.some(s=>s.keptChanged>0);return t&&!r&&n?{...o,status:"success"}:o}var Jr="frozen",rl="frozen:config",lr="frozen:lastRun",nl="frozen:lastRuns",bs="frozen:lastVerify",Rs="frozen:lastVerifies",ol="tokens.json",Ef="rules.json",pr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Ff=async o=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(o),{preview:!1})},Lf="0.1.0",Nf=10*6e4,ks=15*6e4,Cf="EXTRACT_TIMEOUT",sl=30*6e4,Is=6e4,al=12e4,zf=50;function Df(o,e){let t=0,r=null,n=null,s=d=>{o(...d),t=Date.now(),r=null},a=((...d)=>{r=d;let i=e-(Date.now()-t);i<=0?(n&&(clearTimeout(n),n=null),s(d)):n||(n=setTimeout(()=>{n=null,r&&s(r)},i))});return a.flush=()=>{n&&(clearTimeout(n),n=null),r&&s(r)},a}function il(o,e){let t=Df(o,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),o(n)},{flush:t.flush})}async function Qe(o){try{return await Se.access(o),!0}catch{return!1}}function Mf(o){return o.check==="clear-empty"?'residual value under "clear" generator (value redacted at the bridge)':o.detail.length>200?`${o.detail.slice(0,200)}\u2026`:o.detail}function hl(o){return{passed:o.passed,author:o.author,checkedAt:o.checkedAt,checks:o.checks.map(e=>({name:e.name,passed:e.passed,violations:e.violations.slice(0,zf).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:Mf(t)}))}))}}function vs(o){return{version:o.version,status:o.status,frozenAt:o.frozenAt,source:o.source,saltFingerprint:o.saltFingerprint,rulesVersion:o.rulesVersion,volumetry:o.volumetry,controls:{nonReidentification:hl(o.controls.nonReidentification),dryRunLoad:o.controls.dryRunLoad,author:o.controls.author,date:o.controls.date},...o.coverage?{coverage:o.coverage}:{}}}function xf(o,e,t){return{combinations:o.roots.map(r=>({combinationKey:r.combinationKey,axisValues:r.axisValues,edgeCase:r.edgeCase})),uncovered:o.uncovered,volumetry:o.volumetry,selectedAt:o.selectedAt,selectionPath:e,...t?{graph:t}:{},...o.stopped?{stopped:o.stopped}:{}}}function Os(o,e){if(!e||e.length===0)return o;let t=new Set(e);return{...o,nodes:o.nodes.map(r=>t.has(r.objectApiName)?{...r,included:!1}:r)}}function dl(o,e){return{objects:o.nodes.filter(wi).length,truncated:o.truncated===!0,maxNodes:e}}function $f(o){return o.length===0?"":` Kept in the org, the platform does not delete them: ${o.map(({objectApiName:t,count:r})=>`${t} (${r})`).join(", ")}.`}function Ss(o,e){if(!o)return{message:"No load into this org was recorded in this sas: there is nothing to remove.",code:"NO_LOAD"};if(o.orgId!==e.targetOrgId||o.endedAt!==e.loadedAt)return{message:"Another load was recorded since this one was shown, and nothing was removed: check what a removal takes now, then confirm it again.",code:"LOAD_CHANGED"};if(!o.created)return{message:"This load was recorded before loads kept what they created: its records cannot be told from the ones it linked, and cannot be removed from here, nor replaced by a reload, which would delete what someone changed since. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself.",code:"NOT_RECORDED"};if(ot(o).length>0)return;let t=$f(zn(o));return o.removal?{message:`The records this load created were already removed, on ${o.removal.removedAt}.${t}`,code:"ALREADY_REMOVED"}:t?{message:`This load created no record a removal takes.${t}`,code:"NOTHING_TO_REMOVE"}:{message:"This load created no record to remove.",code:"NOTHING_TO_REMOVE"}}function As(o){let e=o.writtenBetween,t=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),r=Date.parse(o.endedAt);return{...e?{runStartedAt:new Date(e.first),runEndedAt:new Date(e.last)}:{...Number.isFinite(t)&&Number.isFinite(r)?{runDurationMs:Math.max(0,r-t)}:{},...Number.isFinite(r)?{runRecordedAt:new Date(r),endedByItsWrites:!0}:{}},removalStamps:o.removalStamps,removalSpans:o.removalSpans,...o.runUserId?{runUserId:o.runUserId}:{}}}function _f(o,e=!1){let t=new Map;for(let{objects:r}of o)for(let n of r){let s=n.heldByAutomation??0,a=(n.keptDependents??0)-(e?s:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",i=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",a>0?(d?`${a} kept for records that stay under them (${d})`:`${a} kept as what hangs from them could not be read`)+(!e&&s>0?`, ${s} of them for what the target's automation likely made for the load, which a sweep takes first`:""):"",n.undeletable>0?`${n.undeletable} the user may not delete`:"",n.notVisible>0?`${n.notVisible} out of the user's sight`:"",n.unread>0?`${n.unread} that could not be read`:""].filter(Boolean),u=n.keptChanged+Math.max(0,a)+n.undeletable+n.notVisible+n.unread;if(u===0)continue;let l=t.get(n.objectApiName)??{left:0,why:new Set};l.left+=u;for(let c of i)l.why.add(c);t.set(n.objectApiName,l)}return[...t].map(([r,{left:n,why:s}])=>({objectApiName:r,left:n,why:[...s]}))}function Bf(o){return{status:o.status,orgId:o.orgId,mode:o.mode,startedAt:o.startedAt,durationMs:o.durationMs,alignment:{excludedObjects:o.alignment.excludedObjects,removals:o.alignment.removals,adjustments:o.alignment.adjustments,recordTypeIssues:o.alignment.recordTypeIssues},placeholders:o.placeholders,requiredDefaults:o.requiredDefaults,perObject:o.perObject,pass2:o.pass2,personContact:o.personContact,statuses:o.statuses,purge:o.purge,...o.leftToThePlatform?{leftToThePlatform:o.leftToThePlatform}:{},...o.untypedFeedItems?{untypedFeedItems:o.untypedFeedItems}:{},...o.heldForExcludedParents?{heldForExcludedParents:o.heldForExcludedParents}:{},...o.quotesLeftUnsynced?{quotesLeftUnsynced:o.quotesLeftUnsynced}:{},...o.keysLeftEmpty?{keysLeftEmpty:o.keysLeftEmpty}:{},...o.recordTypesGiven?{recordTypesGiven:o.recordTypesGiven}:{},...o.runUserId?{runUserId:o.runUserId}:{},mappingPath:o.mappingPath,contractPath:o.contractPath}}function qf(o){return o.status==="completed"?"success":o.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Gf(o){let e=o.perObject.reduce((t,r)=>t+r.failed.length,0)+o.purge.failures.length;return co(o)===0&&e===0?"stopped":"cancelled"}function co(o){let e=t=>Object.values(t).reduce((r,n)=>r+n,0);return o.perObject.reduce((t,r)=>t+r.inserted,0)+o.placeholders.length+e(o.purge.deleted)+e(o.purge.deactivated)}function cl(o){return`frozen:${o}`}var ao=(o,e)=>e==="insert"||e==="update",Gt=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function Ps(o){let e=new Map,t=r=>{let n=e.get(r)??ba(r);return e.set(r,n),n};for(let r of o.perObject){let n=t(r.objectApiName);n.created+=r.inserted,n.failed+=r.failed.length+r.skippedDuplicates.length,r.notInserted&&(n.notSent=(n.notSent??0)+r.notInserted),r.writtenWithoutFields&&(n.writtenWithoutFields=(n.writtenWithoutFields??0)+r.writtenWithoutFields.rows)}for(let r of o.placeholders)t(r.placeholderObjectApiName).created+=1;for(let[r,n]of Object.entries(o.purge.deleted))t(r).deleted+=n;for(let[r,n]of Object.entries(o.purge.deactivated))t(r).updated+=n;for(let r of o.purge.failures)t(r.objectApiName).failed+=1;return[...e.values()]}async function Wf(o,e){try{let t=await e.load();return Object.fromEntries(o.objects.map(r=>[r.objectApiName,r.records.filter(n=>t.has(n.referenceId)).length]))}catch{return}}var at=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="ReplayRefused"}code;params},Ts=class extends Dn{constructor(t,r,n){super(t,r);this.registeredAs=n}registeredAs;async recorded(){let t=await super.recorded();return t&&{...t,orgId:this.registeredAs}}async recordedLoads(){return(await super.recordedLoads()).map(t=>({...t,orgId:this.registeredAs}))}};function Uf(){let o=ii();return{checkpoints:()=>[o,ld(o)].flatMap(e=>{if(!If(e))return[];let t=di({root:e});return"store"in t?[t.store]:[]}),replays:new wd({root:yd()})}}function ll(o,e){let t=Object.fromEntries((e?.link??[]).map(n=>[n.objectApiName,[...n.fields]])),r={...o?.identityKeys,...t};return{rootObject:"",axes:[],edgeCases:[],...o,...Object.keys(r).length>0?{identityKeys:r}:{}}}function io(o){return o.replay?{module:"checkpoint",sasMark:Gn(o.replay.folder.dir)}:{module:"frozen"}}function Kf(o){return o.replay?{action:"checkpoint_replay",module:"checkpoint"}:{action:"frozen_load",module:"frozen"}}var ul=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=Zd();openInEditor=Ff;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new ei;loading=new Map;beforeRunCheckpoints;describeCache=new Co({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new Co({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});forgetOrg(e){this.describeCache.invalidateByPrefix(`${e}::`),this.describeGlobalCache.invalidate(e)}setRegistry(e){this.registry=e}setRulesEditor(e){this.openInEditor=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setRemovalAsker(e){this.removalAsker=e}removalAsker;ownReader(){return this.reader??=import("./chunk-T5VAULLQ.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>Ae(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setSaltKeeper(e){this.saltKeeper=e}isWritingTo(e,t){if(this.writing.has(e))return!0;for(let[r,n]of this.loading)if(n===e&&(t===void 0||t!==cl(r)))return!0;return!1}async loadingDuring(e,t){let r=Sn(e,"targetOrgId");if(r===void 0)return t();this.loading.set(e.id,r);try{await t()}finally{this.loading.delete(e.id)}}async handle(e){if(!Of.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"frozen:config:get":return this.handleConfigGet(e),!0;case"frozen:config:save":return this.handleConfigSave(e),!0;case"frozen:select":return await this.handleSelect(e),!0;case"frozen:extract":return await this.handleExtract(e),!0;case"frozen:manifest:get":return await this.handleManifestGet(e),!0;case"frozen:load":return await this.loadingDuring(e,()=>this.handleLoad(e)),!0;case"frozen:load:preview":return await this.handlePreview(e),!0;case"frozen:verify":return await this.handleVerify(e),!0;case"frozen:remove":return await this.writing.during(Sn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(Sn(e,"targetOrgId"),()=>this.handleRemoveSweep(e)),!0;case"frozen:remove:automation":return await this.handleRemoveAutomation(e),!0;case"frozen:remove:preview":return await this.handleRemovePreview(e),!0;case"frozen:status":return await this.handleStatus(e),!0;case"frozen:rules:clear":return await this.handleRulesClear(e),!0;case"frozen:rules:create":return await this.handleRulesCreate(e),!0;default:return!1}}loadConfig(){return this.deps.configStore.get(rl)??null}handleConfigGet(e){let t=this.loadConfig(),r=Oe(this.deps,e,"frozen:config:get:response",{config:t,sasDir:this.resolveSasDir(t),datasetDir:this.resolveDatasetDir(t)});this.deps.broker.postToWebview(r)}handleConfigSave(e){let t=nt(ja,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(rl,t.config,Jr);let r=Oe(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??Pe.join(fl.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??Pe.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return Pe.resolve(e?.rulesFilePath??Pe.join(this.resolveSasDir(e),Ef))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await Qe(t)?await Se.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:X(n)}}return{path:t,...gc(r)}}async loadTokens(e,t){return await Qe(Pe.join(e,ol))?Ic(e,ol,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let s=await new St(3e4).withTimeout(`frozen:describe:${t}`,async()=>{let d=await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:d.name,fields:d.fields.map(i=>({name:i.name,label:i.label,type:i.type,referenceTo:i.referenceTo??[],relationshipName:i.relationshipName??null,isMasterDetail:i.cascadeDelete===!0,nillable:i.nillable!==!1,createable:i.createable!==!1,updateable:i.updateable!==!1,restrictedPicklist:i.restrictedPicklist===!0,defaultedOnCreate:i.defaultedOnCreate===!0,...i.compoundFieldName?{compoundFieldName:i.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(i=>({childSObject:i.childSObject,field:i.field,relationshipName:i.relationshipName??i.field,isCascadeDelete:i.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,s),s}buildDiscoveryService(){return new bi({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,detectPII:e=>{let t=this.deps.infraServices?.piiDetector;return t?In(t,e):[]},describeGlobal:e=>this.describeGlobal(e)})}async describeGlobal(e){let t=this.describeGlobalCache.get(e);if(t)return t;let s=(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.map(a=>({name:a.name,keyPrefix:a.keyPrefix??null}));return this.describeGlobalCache.set(e,s),s}async keyPrefixes(e){let t=new Map;for(let{name:r,keyPrefix:n}of await this.describeGlobal(e))n&&t.set(r,n);return t}discoveryConfig(e,t){return{inputMode:"record",recordId:t,depth:"full",sourceOrgId:e,targetOrgId:e,anonymizePII:!1,skipEmpty:!0,batchSize:"auto"}}discoveryOptions(e){return{maxNodes:e.maxNodes??yi}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:s}=e,{maxNodes:a}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:a},i=await Pc(n,s),u;if("kept"in i){let p=i.kept,g=Tc(p,d)??await this.schemaChangeSince(t,p);if(g===void 0)return this.holdKeptDescribes(t,p),{graph:p.graph,origin:{reusedFrom:p.step,discoveredAt:p.discoveredAt}};u=g}else u=i.none;let l;try{let p=await Ae(t,this.deps.orgRegistry,this.deps.orgManager);l=jc((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let c=await this.buildDiscoveryService().discover(this.discoveryConfig(t,e.rootRecordId),{maxNodes:a,...e.signal?{signal:e.signal}:{},...e.onProgress?{onProgress:e.onProgress}:{}}),f=new Date().toISOString();return{graph:c,origin:{rediscovered:u},keep:async p=>{let g=new Set([...c.nodes.filter(m=>m.included).map(m=>m.objectApiName),...p]),h={};for(let m of g){let y=this.describeCache.get(`${t}::${m}`);y&&(h[m]=y)}await Ac(n,{fileVersion:1,...d,step:e.step,discoveredAt:f,...l?{schemaStamp:l}:{},graph:c,describes:h,objects:this.describeGlobalCache.get(t)??[]},s)}}}async schemaChangeSince(e,t){if(!t.schemaStamp)return"the graph kept carries no stamp of the org";try{let n=await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).request({method:"GET",url:"/sobjects",headers:{"If-Modified-Since":new Date(t.schemaStamp).toUTCString()}}),s=typeof n=="object"&&n!==null?n.sobjects:void 0;return Array.isArray(s)?(this.forgetOrg(e),this.describeGlobalCache.set(e,s.flatMap(a=>{let{name:d,keyPrefix:i}=a??{};return typeof d=="string"?[{name:d,keyPrefix:typeof i=="string"?i:null}]:[]})),`the source's schema changed since the graph kept was discovered, on ${t.discoveredAt}`):void 0}catch(r){return`the source could not say whether its schema changed: ${X(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,sl);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,sl)}async describeScopableFields(e,t){return(await this.describeObject(e,t)).fields.map(n=>({name:n.name,type:n.type,referenceTo:n.referenceTo,nillable:n.nillable!==!1}))}async ruleSchemaOf(e,t){let r=new Map;for(let{objectApiName:n}of t)try{let s=await this.describeObject(e,n);r.set(n,s.fields)}catch(s){this.deps.log(`[WARN] frozen: ${n} could not be described for the rules: ${String(s)}`)}return r}mappingStoreFor(e,t,r){let n=async()=>{try{let[s]=await this.buildTargetOrgAccess().query(t,"SELECT Id FROM Organization");return typeof s?.Id=="string"?s.Id:void 0}catch(s){this.deps.log(`[WARN] frozen: the target did not say which org it is: ${String(s)}`);return}};return new Dn(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await Ae(e,this.deps.orgRegistry,this.deps.orgManager);return wn(r,t)},count:async(e,t)=>(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:n.name,createable:n.createable,cascadeChildren:(n.childRelationships??[]).flatMap(s=>s.cascadeDelete===!0&&typeof s.field=="string"&&s.field!==""?[{childSObject:s.childSObject,field:s.field}]:[]),fields:n.fields.map(s=>({name:s.name,type:s.type,createable:s.createable??!1,nillable:s.nillable??!0,defaultedOnCreate:s.defaultedOnCreate??!1,referenceTo:s.referenceTo??[],restrictedPicklist:s.restrictedPicklist??!1,picklistValues:(s.picklistValues??[]).map(a=>({value:a.value,active:a.active??!0})),updateable:s.updateable!==!1,unique:s.unique===!0,nameField:s.nameField===!0,...typeof s.filteredLookupInfo=="object"&&s.filteredLookupInfo!==null?{lookupFilter:{optional:s.filteredLookupInfo.optionalFilter===!0}}:{}})),recordTypeInfos:(n.recordTypeInfos??[]).flatMap(s=>{let{developerName:a,active:d}=s;return a?[{developerName:a,recordTypeId:s.recordTypeId,available:s.available,name:s.name,master:s.master,defaultRecordTypeMapping:s.defaultRecordTypeMapping,...d===void 0?{}:{active:d}}]:[]})}},picklistValues:async(e,t,r,n)=>{let s=await Ae(e,this.deps.orgRegistry,this.deps.orgManager);return Xi(s,t,r,n)},userId:async e=>(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).soap.getUserInfo()).userId}}toLoadConfig(e){return{protectedOrgIds:e.protectedOrgIds,identityKeys:e.identityKeys,undeletableObjects:e.undeletableObjects,requiredLookupPlaceholders:e.requiredLookupPlaceholders,excludedObjects:e.excludedObjects,requiredFieldDefaults:e.requiredFieldDefaults,picklistRules:e.picklistRules,defaultPicklistRule:e.defaultPicklistRule,duplicateErrorPatterns:e.duplicateErrorPatterns,rootObjectApiName:e.rootObject}}async readFrozenDataset(e,t){let r=t.assertOutsideRepo(e),n=t.assertOutsideRepo(Pe.join(r,"manifest.json"));if(!await Qe(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let s=or(JSON.parse(await Se.readFile(n,"utf8"))),a=[],d=t.assertOutsideRepo(Pe.join(r,"data"));if(await Qe(d))for(let f of(await Se.readdir(d)).sort()){if(!f.endsWith(".json"))continue;let p=t.assertOutsideRepo(Pe.join(d,f)),g=JSON.parse(await Se.readFile(p,"utf8"));a.push({objectApiName:g.objectApiName,records:g.records})}let i=async(f,p)=>{let g=t.assertOutsideRepo(Pe.join(r,f));return await Qe(g)?JSON.parse(await Se.readFile(g,"utf8")):p},u=await i("record-types.json",{}),l=await i("personcontact-sidecar.json",[]),c=await i(kd,{});return{dataset:{datasetVersion:s.version,objects:a,recordTypes:u,personContactSidecar:l,...c.standardPricebook?{standardPricebook:c.standardPricebook}:{}},manifest:s}}errorCodeFor(e,t){return e instanceof pr?"RULES_MISSING":e instanceof He?"GUARD_REFUSED":e instanceof ud?"SAS_PATH_REFUSED":e instanceof Pr?"SALT_MISSING":e instanceof xt?"BUDGET_EXCEEDED":e instanceof Ze?"LOAD_CONFIG":e instanceof Nr?"MAX_RECORDS":e instanceof ar?oo:e instanceof lt?"TIMEOUT":e instanceof at?e.code:e instanceof So&&e.code==="invalid"?"INVALID_PAYLOAD":t}errorDetailOf(e){if(e instanceof at)return{params:e.params};if(e instanceof pr)return{rulesPath:e.rulesPath};if(e instanceof He)return{guard:e.code,...e.params};if(e instanceof xt)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof Ze&&e.gaps)return{gaps:e.gaps,...(e.refusedBeside??[]).length>0?{refusedBeside:e.refusedBeside}:{}};if(e instanceof Ze&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof fr)return{emails:e.emails,orgId:e.orgId};if(e instanceof Xr)return{automation:e.automation,orgId:e.orgId};if(e instanceof Zr)return{apiRequests:e.apiRequests,orgId:e.orgId};if(e instanceof Qr)return{storage:e.storage,orgId:e.orgId}}loadEmailsFor(e){return nc({read:e.read,...e.plan?{plan:e.plan}:{},writes:e.writes,inserts:e.dataset.objects.map(t=>({objectApiName:t.objectApiName,rows:t.records.length})).filter(t=>t.rows>0),readLimits:()=>ji(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(ti):ri(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await vi(e.conn).catch(s=>({unread:X(s)})),r=Ji(e.read),n=Oi({run:zc({inserts:e.dataset.objects.map(s=>({objectApiName:s.objectApiName,rows:s.records.length})),...e.purged?{purged:e.purged}:{},threshold:yo(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:zi(e.read)})+(e.replayReads??0),...Ai(e.checkpoint),...oi(e.plan),...Di(e.emails?.run.ofRun)},t);return n.verdict==="unread"&&this.deps.log(`[WARN] ${e.operation}: the daily API requests the target has left could not be read (${n.unread})`),Tf(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>ot(n)).map(({objectApiName:n,ids:s})=>({objectApiName:n,rows:s.length,deletes:!Object.hasOwn(r,n)}))}orgNameOf(e){let t=this.deps.orgManager.getOrg(e);return qs(t,e)}requireConfig(e,t){let r=this.loadConfig();return r||(re(this.deps,e.type,t,e,new Error("No frozen dataset configuration saved \u2014 save the project configuration first (frozen:config:save: coverage axes, root object, budget, load rules)."),{code:"CONFIG_MISSING"}),null)}setReplayStores(e){this.replayStores=e}replayStores;replayStoresInUse(){return this.replayStores??=Uf(),this.replayStores}async sourceOf(e,t,r,n,s){if(t.replay===void 0){let a=this.requireConfig(e,r);return a?this.datasetSource(a,t.targetOrgId):void 0}try{if(t.pilot===!0)throw new at("REPLAY_NO_PILOT","A replay loads no pilot: preview it, then replay it whole. Nothing was read or written.");return await this.replaySourceOf(t.targetOrgId,t.replay,n)}catch(a){let d=this.errorCodeFor(a,"REPLAY_ERROR");s?.(d);let i=this.errorDetailOf(a);re(this.deps,e.type,r,e,a,{code:d,retryable:a instanceof lt,...i?{extraPayload:i}:{}});return}}datasetSource(e,t){let r=n=>n.assertOutsideRepo(this.resolveSasDir(e));return{config:e,sasDir:r,mappingStore:n=>this.mappingStoreFor(r(n),t,n),read:async n=>{let s=n.assertOutsideRepo(this.resolveDatasetDir(e)),{dataset:a,manifest:d}=await this.readFrozenDataset(s,n);return{dataset:a,manifest:d,datasetDir:s,label:d.version}}}}async replaySourceOf(e,t,r){$o({orgId:e,orgTier:this.targetTier(e)});let n=this.replayStoresInUse(),s=n.replays.folderOf(t.organizationId,t.checkpointId),a=await this.replayTargetOf(e),d=Pn(a.organizationId),i={folder:s,target:a,contractPath:n.replays.contractPathOf(s,d)},u=g=>new Ts(s.dir,{guard:g,orgId:d,organizationId:a.organizationId},e);if(r==="mapping")return{config:ll(t.config,void 0),sasDir:()=>s.dir,mappingStore:u,read:()=>Promise.reject(new Error("A removal of a replay reads no checkpoint")),replay:i};let l=await this.replayedCheckpointOf(n,t),c=t.choices??(await n.replays.read(s))?.targets.find(g=>g.organizationId===d)?.choices;if(c===void 0)throw new at("NO_LOAD",`No replay of checkpoint ${t.checkpointId} into ${a.name} is recorded on this machine: replay it there first, then verify. Nothing was read or written.`,{checkpoint:t.checkpointId,target:a.name});let f=_c({checkpoint:l.checkpoint,checkpointId:t.checkpointId,choices:c,target:a});if(f)throw new at(f.code,f.message,f.params);if(l.checkpoint===void 0)throw new at("REPLAY_CHECKPOINT_UNUSABLE","The checkpoint does not read.");let p=l.checkpoint;return i.checkpoint={checkpoint:p,folder:l.folder,annex:l.annex},i.choices=c,{config:ll(t.config,c),sasDir:()=>s.dir,mappingStore:u,read:async()=>(i.converted??=await this.convertReplay(i,c,e),{dataset:i.converted.conversion.dataset,label:p.name}),replay:i}}async replayedCheckpointOf(e,t){for(let r of e.checkpoints()){let n=(await r.checkpointsOf(t.organizationId)).find(s=>s.folder.checkpointId===t.checkpointId);if(n!==void 0){if(n.checkpoint===void 0)return{folder:n.folder,annex:void 0};try{return{checkpoint:n.checkpoint,folder:n.folder,annex:await Ii(n.folder)}}catch(s){throw s instanceof So?new at("REPLAY_CHECKPOINT_UNUSABLE",`${s.message}: what checkpoint '${n.checkpoint.name}' says of its record types, users and catalogue cannot be told. Nothing was read or written.`,{checkpoint:n.checkpoint.name,why:"damaged"}):s}}}throw new at("CHECKPOINT_NOT_FOUND",`No checkpoint ${t.checkpointId} of org ${t.organizationId} is kept on this machine: import its file first, or name one the checkpoint list shows. Nothing was read or written.`,{checkpoint:t.checkpointId})}async replayTargetOf(e){let t=this.buildTargetOrgAccess(),r=this.orgNameOf(e),[n]=await t.query(e,"SELECT Id FROM Organization");if(typeof n?.Id!="string")throw new Error(`${r} did not say which org it is: nothing was read or written.`);let s=n.Id,a=await t.userId?.(e);if(a===void 0)throw new Error(`${r} did not say which user the replay writes as.`);let d=this.deps.orgManager.getOrg(e),i=this.deps.sandboxRefreshes,u=[d?.orgId,i?.organizationIdOf(e),...i?.refreshesOf(e).map(l=>l.previousOrganizationId)??[]].filter(l=>typeof l=="string"&&l.slice(0,15)!==s.slice(0,15));return{name:r,organizationId:s,runningUserId:a,...d?.username?{username:d.username}:{},...d?.instanceUrl?{instanceUrl:d.instanceUrl}:{},formerOrganizationIds:[...new Set(u)],tier:d?.orgType==="Sandbox"?"sandbox":d?.orgType==="Scratch"?"scratch":"developer"}}async convertReplay(e,t,r){let n=e.checkpoint;if(n===void 0)throw new Error("The checkpoint of the replay was not read");let s=await Yc({folder:n.folder,checkpoint:n.checkpoint,annex:n.annex,choices:t,access:this.buildTargetOrgAccess(),orgId:r,organizationId:e.target.organizationId,runningUserId:e.target.runningUserId,tier:e.target.tier,...e.target.username!==void 0?{username:e.target.username}:{},targetName:e.target.name});if("refusal"in s)throw new at(s.refusal.code,s.refusal.message,{users:s.refusal.users.join(", ")});return{conversion:s.conversion,target:s.target}}replayInfoOf(e,t,r){let n=e.checkpoint,s=e.converted;if(n===void 0||s===void 0||e.choices===void 0)return;let{checkpoint:a}=n,{summary:d,filesLeft:i}=s.conversion;return{checkpoint:{checkpointId:a.checkpointId,name:a.name,organizationId:a.org.organizationId,...a.org.alias!==void 0?{alias:a.org.alias}:{},takenAt:a.takenAt,tier:a.org.tier,annex:n.annex!==void 0},target:{organizationId:Pn(e.target.organizationId),name:e.target.name},choices:e.choices,summary:{...d,records:{...d.records,toCreate:Math.max(0,d.records.toCreate-t),linkedByKey:t}},filesLeft:i.map(({objectApiName:u,name:l})=>({objectApiName:u,...l!==void 0?{name:l}:{}})),...r?{storage:r}:{},requests:s.target.requests}}async loadSentOf(e,t){let r;try{r=await e.request({method:"GET",url:"/sobjects"})}catch{return}let n=Sf.safeParse(r);if(!n.success)return;let s=new Set(n.data.sobjects.filter(a=>a.createable!==!1).map(a=>a.name.toLowerCase()));return{takes:a=>s.has(a.toLowerCase()),byThePlatform:Ud(t)}}async loadStorageOf(e){let t=await Eo(e.conn).catch(()=>{});if(t===void 0)return;let r=Math.max(0,e.automationBytes??0),n=Xc({dataset:e.dataset,storage:t,...e.sent?{sent:e.sent}:{},...e.purged?{purged:e.purged}:{},automationBytes:r,target:this.orgNameOf(e.targetOrgId),...e.replay===!0?{replay:!0}:{}}),s=1024*1024;return{estimateMB:n?.storage.estimateMB??(gl(e.dataset,e.sent)+r)/s,...r>0?{automationMB:r/s}:{},remainingMB:t.remainingMB,maxMB:t.maxMB,...n?.storage.freedMB!==void 0?{freedMB:n.storage.freedMB}:{},...n?{refusal:{code:pl,message:n.message}}:{}}}async handleSelect(e){let t=nt(Ea,e,"frozen:select:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:select:error");if(!r)return;let n=`frozen-select-${this.deps.nextId()}`;Ir(this.deps,n,"frozen","Running coverage-matrix selection");let s="Coverage-matrix selection",a=new AbortController,d=setTimeout(()=>a.abort("timeout"),Nf),i=()=>{},u=new Promise((c,f)=>{i=p=>p===void 0?c():f(p)});u.catch(()=>{}),this.registry?.register(e.id,"frozen",s,u,a),this.liveTracker?.register(e.id,"frozen",s);let l=c=>{this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:select:progress",{...c})),c.phase==="combination"&&c.index!==void 0&&c.of&&this.liveTracker?.updateProgress(e.id,Math.round((c.index-1)/c.of*100),c.index-1,c.of,c.combinationKey??"")};try{let c=new fe,f=c.assertOutsideRepo(this.resolveSasDir(r)),p=await Ae(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async M=>{let W=g.get(M);return W||(W=wn(p,M),g.set(M,W),W.catch(()=>g.delete(M))),(await W).map(V=>({...V}))},m=await this.loadTokens(f,c),y=this.discoveryOptions(r),R=new Set,L=new Gr({query:h,describeFields:M=>(R.add(M),this.describeScopableFields(t.sourceOrgId,M)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),T=new Date().toISOString(),j,x=0,U=async M=>(j??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:f,guard:c,rootRecordId:M,signal:a.signal,onProgress:W=>{W.phase==="object"&&(W.discoveredCount-x<10&&W.queueRemaining>0||(x=W.discoveredCount,l({phase:"discovery",objects:W.discoveredCount})))}}),Os((await j).graph,r.excludedObjects)),S=async M=>{if(M.length===0)return{};let W=await U(M[0]),V=await L.extract({graph:W,rootObject:r.rootObject,rootRecordIds:M,asOf:T,sasDir:f,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:c}),H={};for(let E of V.objects)H[E.objectApiName]=E.records.length;return H},w=new Kn(S,r.expectedObjects??[]),I=async(M,W)=>(await this.describeObject(t.sourceOrgId,M)).fields.find(V=>V.name.toLowerCase()===W.toLowerCase())?.type,N=await new Un({query:h,checkHealth:w,measureVolumetry:S,fieldType:I}).select({rootObject:r.rootObject,axes:r.axes,edgeCases:r.edgeCases,budgetMaxRecords:r.budgetMaxRecords,candidatesPerCombination:r.candidatesPerCombination,tokens:m},{signal:a.signal,onProgress:l}),v=await Oc(f,N,c),P=j&&!N.stopped?await j.catch(()=>{}):void 0;P?.keep&&await P.keep(R).catch(M=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(M)}`)});let C=P?Os(P.graph,r.excludedObjects):void 0,G=Oe(this.deps,e,"frozen:select:response",{selection:{...xf(N,v,C?dl(C,y.maxNodes):void 0),...P?{discovery:P.origin}:{}}});this.deps.broker.postToWebview(G),wt(this.deps,n,{roots:N.roots.length,total:N.volumetry.total,...N.stopped?{stopped:N.stopped.reason}:{}}),N.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),i()}catch(c){this.liveTracker?.fail(e.id,X(c)),i(c),re(this.deps,"frozen:select","frozen:select:error",e,c,{code:this.errorCodeFor(c,"SELECT_ERROR"),retryable:c instanceof lt,extraPayload:this.errorDetailOf(c)})}finally{clearTimeout(d)}}async handleExtract(e){let t=nt(La,e,"frozen:extract:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:extract:error");if(!r)return;let n=`frozen-extract-${this.deps.nextId()}`;Ir(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let s=new fe,a=s.assertOutsideRepo(this.resolveSasDir(r)),d=s.assertOutsideRepo(this.resolveDatasetDir(r)),i=await this.saltKeeper.forExtraction(),u=new En(i.salt);if(i.created&&this.sayTheSaltWasMade(u.saltFingerprint),!await Qe(Pe.join(a,Br))){re(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${a} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let l=await ts(a,s),c=l.roots.map(V=>V.rootRecordId);if(c.length===0){re(this.deps,"frozen:extract","frozen:extract:error",e,new Error("The last selection kept no root: every combination was uncovered, and the selection says why for each. Adjust the axes or the expected objects, then run the selection again."),{code:"SELECTION_EMPTY"});return}let f=await this.loadTokens(a,s),p=this.resolveRulesPath(r);if(!await Qe(p))throw new pr(p,`Pseudonymization rules file not found at ${p} \u2014 it is the source of truth (object.field \u2192 generator). Create it, or set rulesFilePath in the configuration.`);let g=Wn(JSON.parse(await Se.readFile(p,"utf8"))),h=await Ae(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=this.discoveryOptions(r),y=await this.graphOfStep({step:"extract",sourceOrgId:t.sourceOrgId,config:r,sasDir:a,guard:s,rootRecordId:c[0]}),R=Os(y.graph,r.excludedObjects),L=new Set,T,j=new Gr({query:V=>T?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):wn(h,V),describeFields:V=>(L.add(V),this.describeScopableFields(t.sourceOrgId,V)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),x=t.author??"sandforge",U=r.datasetVersion??Lf,{extracted:S,frozen:w,report:I,requiredLeftEmpty:A,keptUnruled:N}=await new St(ks).withTimeout("frozen:extract",async V=>{T=V;let H=await j.extract({graph:R,rootObject:r.rootObject,rootRecordIds:c,asOf:new Date().toISOString(),sasDir:a,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:f,guard:s}),E=await this.ruleSchemaOf(t.sourceOrgId,H.objects),q=hc(g,E,this.deps.infraServices?.piiDetector??new vn),Y=new Yn().anonymize({extracted:H,rules:q,pseudonymizer:u,datasetVersion:U}),ae=new Jn().run(H,Y,q,{author:x});return{extracted:H,frozen:Y,report:ae,requiredLeftEmpty:yc(H,q,E),keptUnruled:mc(H,q)}});A.length>0&&this.deps.log(`[WARN] frozen: the rules leave ${A.length} required field(s) empty, which a load will ask a value for: ${A.join(", ")}`),y.keep&&await y.keep(L).catch(V=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(V)}`)});let v=Oe(this.deps,e,"frozen:control:result",{report:hl(I)});if(this.deps.broker.postToWebview(v),!I.passed){re(this.deps,"frozen:extract","frozen:extract:error",e,new Error("Non-reidentification control FAILED \u2014 nothing was written. Fix the rules file and re-run the extraction (see frozen:control:result for the failing checks)."),{code:"CONTROL_FAILED"});return}let P={};for(let V of w.objects)P[V.objectApiName]=V.records.length;let C=this.deps.orgManager.getOrg(t.sourceOrgId),G=bd({version:U,source:{orgId:t.sourceOrgId,orgAlias:C?.alias,decisionDate:l.selectedAt},saltFingerprint:u.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:l.volumetry.budgetMax,measured:P,measuredAt:new Date().toISOString()},nonReidentification:I,author:x,coverage:{...dl(R,m.maxNodes),unboundedObjects:S.unboundedObjects,filesLeftOut:w.filesLeftOut??[],...(S.leftToThePlatform??[]).length>0?{leftToThePlatform:Mn(S.leftToThePlatform??[])}:{},...S.exclusionCosts?{exclusionCosts:S.exclusionCosts}:{},...A.length>0?{requiredLeftEmpty:A}:{},...N.length>0?{keptWithoutARule:N}:{},encryptedNotKept:S.encryptedNotKept??[]}}),M=await new Id(s).write(d,w,G,I),W=Oe(this.deps,e,"frozen:extract:response",{datasetDir:M.dir,files:M.files,recordCount:sr(w),manifest:vs(G),discovery:y.origin});this.deps.broker.postToWebview(W),wt(this.deps,n,{records:sr(w),version:G.version})}catch(s){let a=s instanceof lt,d=a?new Error(`The extraction ran out of its ${ks/6e4} minutes and stopped, and nothing was written: it reads every record of the roots the selection kept, so run again it would stop again. Keep fewer roots: lower the budget in the configuration, or narrow the axes, then run the selection and the extraction again.`):s;re(this.deps,"frozen:extract","frozen:extract:error",e,d,{code:a?Cf:this.errorCodeFor(s,"EXTRACT_ERROR"),retryable:!1,extraPayload:a?{minutes:ks/6e4}:this.errorDetailOf(s)})}}async handleRulesClear(e){let t=nt(Fa,e,"frozen:rules:clear:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:rules:clear:error");if(r)try{let n=this.resolveRulesPath(r);if(!await Qe(n))throw new pr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let s=wc(JSON.parse(await Se.readFile(n,"utf8")),t.fields);if(s.cleared.length>0){let d=`${n}.${process.pid}.writing`;await Se.writeFile(d,`${JSON.stringify(s.payload,null,2)}
19
- `,"utf8"),await Se.rename(d,n),this.deps.log(`[INFO] frozen: ${s.cleared.length} field(s) given a clear rule in ${n} (rules ${s.rulesVersion}): ${s.cleared.join(", ")}`)}let a=Oe(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:s.rulesVersion,cleared:s.cleared,alreadyRuled:s.alreadyRuled});this.deps.broker.postToWebview(a)}catch(n){re(this.deps,"frozen:rules:clear","frozen:rules:clear:error",e,n,{code:this.errorCodeFor(n,"RULES_CLEAR_ERROR"),extraPayload:this.errorDetailOf(n)})}}async handleRulesCreate(e){let t=this.resolveRulesPath(this.loadConfig()),r=!1;try{await Se.mkdir(Pe.dirname(t),{recursive:!0});try{await Se.writeFile(t,fc(pc),{encoding:"utf8",flag:"wx"}),r=!0,this.deps.log(`[INFO] frozen: empty rules file written at ${t}`)}catch(s){if(s.code!=="EEXIST")throw s;if(!(await Se.stat(t)).isFile())throw new Error(`${t} is not a file: no rules file can be written there.`)}}catch(s){re(this.deps,"frozen:rules:create","frozen:rules:create:error",e,s,{code:"RULES_CREATE_ERROR"});return}let n=!1;try{await this.openInEditor(t),n=!0}catch(s){this.deps.log(`[WARN] frozen: rules file not opened: ${X(s)}`)}this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:rules:create:response",{rulesPath:t,created:r,opened:n}))}async handleManifestGet(e){let t=this.loadConfig(),r=this.resolveDatasetDir(t),n=null;try{let d=new fe().assertOutsideRepo(Pe.join(r,"manifest.json"));await Qe(d)&&(n=vs(or(JSON.parse(await Se.readFile(d,"utf8")))))}catch(a){vt.warn(`frozen:manifest:get \u2014 unreadable manifest: ${String(a)}`)}let s=Oe(this.deps,e,"frozen:manifest:get:response",{manifest:n,datasetDir:r});this.deps.broker.postToWebview(s)}targetTier(e){let t=this.deps.orgManager.getOrg(e);return ln(t)}async handleLoad(e){let t=nt(Io,e,"frozen:load:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:error","checkpoint",E=>Xe(this.deps,{action:"checkpoint_replay",module:"checkpoint",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:E}));if(!r)return;let{config:n}=r,s=Kf(r),a=r.replay,d=this.deps.infraServices?.productionGuard;if(!d){Xe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Ot.code}),re(this.deps,"frozen:load","frozen:load:error",e,new Error(Ot.message),{code:Ot.code});return}let i=await this.replaceRefusal(t,r),u=i&&"error"in i?i:void 0,l=i&&"cameAlong"in i?i.cameAlong:void 0;if(u){u.code===oo&&Xe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:oo}),re(this.deps,"frozen:load","frozen:load:error",e,u.error,{code:u.code,retryable:u.retryable});return}let c=e.id,f=a?`Replaying checkpoint '${a.checkpoint?.checkpoint.name??""}'`:t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";Ir(this.deps,c,s.module,f),this.liveTracker?.register(c,s.module,f);let p=!1,g=!1,h=new AbortController,m=()=>{},y=new Promise((E,q)=>{m=Y=>Y===void 0?E():q(Y)});y.catch(()=>{}),this.registry?.register(c,s.module,f,y,h);let R=il(E=>{let q=Oe(this.deps,e,"frozen:load:progress",{...E});this.deps.broker.postToWebview(q),!p&&!g&&this.liveTracker?.updateProgress(c,E.progress,0,0,E.message)},100),L,T=!1,j=!1,x,U=new Date().toISOString(),S,w,I,A,N,v=(E,q,Y,ae)=>{if(j)return;j=!0;let $=E!=="stopped"&&S!==void 0,K=I?ai(si(I.run.gate,I.info.accepted&&I.info.verdict==="asks").emails):{},Z=a?.checkpoint&&a.choices?{replayCheckpoint:a.checkpoint.checkpoint.checkpointId,...Bc(a.checkpoint.checkpoint,a.choices,a.target)}:{},ne={...$?{sas:S,startedAt:U,...w?{lastWriteAt:w}:{}}:{},...K,...Z};Xe(this.deps,{...s,operationId:c,orgId:t.targetOrgId,outcome:E,guard:L,objects:q,source:{origin:a?"checkpoint":"dataset",label:x},carried:Y,...ae?{code:ae}:{},...P?{muted:pn(P)}:{},...G?.state==="taken"?{checkpointId:G.checkpointId}:{},...Object.keys(ne).length>0?{details:ne}:{}})},P,C,G,M=!1,W=!1,V=!1,H=[];try{let E=new fe,q=r.sasDir(E);S=Gn(q);let{dataset:Y,manifest:ae,datasetDir:$,label:K}=await r.read(E);x=K;let Z=this.buildTargetOrgAccess(),ne=await Ae(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),he=yo(this.deps),_e=ka(this.deps),Me=z=>new dd({connection:ne,bulkExecutor:new $a(he.bulk.threshold),bulkManager:_e,retryConfig:he.retry,...z?{signal:z}:{},onProgress:()=>{},log:se=>this.deps.log(se)}),k=Me(h.signal),F=n.mockDetection?new jr(Z,n.mockDetection):{areCalloutsMocked:async()=>!0},O=r.mappingStore(E),J=zt(ne,"frozen:load"),ee=new Cr({orgAccess:Z,writer:ds(k),restoringWriter:ds(Me(void 0)),guard:d,mockDetector:F,recordTypeResolver:new Wr(Z),mappingStore:O,config:this.toLoadConfig(n),sasGuard:E,serverTime:()=>J.serverTime()});if(t.sweep===!0&&t.reload===!0&&!t.pilot){H=await this.reloadSweepsOf({conn:ne,store:O,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,includeChanged:t.includeChanged===!0,signal:h.signal,guard:d,operationId:c,audit:io(r)});for(let{sweep:z}of H)await z.ask()}let Q=Yr([],H.flatMap(({sweep:z})=>z.takes)),me=(Q.delete??[]).length>0?this.removalAsker:void 0,te=Y.objects.map(z=>z.objectApiName),Be=t.reload===!0&&!t.pilot?await this.purgeStepsOf(O,n):void 0,D=await this.targetAutomation.read(t.targetOrgId,[...new Set([...te,...Be?.delete??[],...Q.delete??[]])]).catch(z=>({unread:X(z)})),we=Be?br(Be):void 0,et=br(Q),tt=(z,se)=>ao(z,se)||we?.(z,se)===!0||et(z,se),B=t.muteAutomation===!0?await Or(async()=>vr(ne),D,{...this.muteLeases,writes:tt}):void 0;if(P=B?.muted,me&&!h.signal.aborted){let z=await me({read:D,steps:Q,mute:B});if(z)throw new ur(z)}let ie=this.targetTier(t.targetOrgId),bt=await ee.gateLoad({orgId:t.targetOrgId,orgTier:ie,dataset:Y,manifest:ae,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:z=>R(z),onGuardDecision:z=>{L=Oo(L,z)}}),ue=Jo({read:D,...B?.plan?{plan:B.plan}:{},written:te,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(A=ue.info,ue.stop&&ue.info)throw new Xr(ue.stop.code,ue.stop.message,ue.info,t.targetOrgId);let ft=t.acceptEmails===!0,rt=Qc(Y,n,t.pilot),xe=await this.loadEmailsFor({conn:ne,orgId:t.targetOrgId,orgTier:ie,read:D,...B?.plan?{plan:B.plan}:{},writes:tt,dataset:rt,accepted:ft,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(I=xe,xe.stop)throw new fr(xe.stop.code,xe.stop.message,xe.info,t.targetOrgId);let ye=t.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:t.targetOrgId,written:te,read:D,mute:B,request:t.checkpointFirst,replay:a!==void 0}):void 0,ve=Be?await this.purgedOf(O,n):void 0,Rt=Promise.resolve().then(()=>ne.request({method:"GET",url:"/limits"}));Rt.catch(()=>{});let en={request:()=>Rt},lo=await Eo(en).catch(z=>({unread:X(z)})),tn=t.pilot?void 0:await this.loadSentOf(ne,Y),Wt=t.pilot?void 0:Xc({dataset:Y,storage:lo,...tn?{sent:tn}:{},...ve?{purged:ve}:{},automationBytes:Zc(D,B?.plan,Y,tt),target:this.orgNameOf(t.targetOrgId),...a?{replay:!0}:{}});if(Wt)throw new Qr(Wt.message,Wt.storage,t.targetOrgId);if(N=await this.loadApiCheck({conn:en,dataset:rt,...ve?{purged:ve}:{},read:D,...ye?{checkpoint:ye.estimate}:{},...B?.plan?{plan:B.plan}:{},emails:xe,orgId:t.targetOrgId,operation:`frozen:load ${c}`,...a?.converted?{replayReads:a.converted.target.requests}:{}}),N.refused)throw new Zr(N.refused.message,N,t.targetOrgId);a?.checkpoint&&a.choices&&await this.replayStoresInUse().replays.record(a.checkpoint.checkpoint,{organizationId:a.target.organizationId,name:a.target.name},a.choices),ye&&(C=await this.takeLoadCheckpoint(ye,h.signal));let Ke=B?.prepared?await B.prepared.acquire(c):void 0;Ke&&(P=Ke.outcome,V=!0);let it=Ke?xe.run.afterLease(Ke.outcome,ft):void 0;if(Ke&&it)throw P=await Ke.release(),new fr(it.code,it.message,xe.info,t.targetOrgId);M=!0;let gr=()=>ee.load({orgId:t.targetOrgId,orgTier:ie,dataset:Y,manifest:ae,sasDir:q,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...a?{linkByKeys:!0,contractOrgId:Pn(a.target.organizationId)}:{},onProgress:z=>R(z),onGuardDecision:z=>{L=Oo(L,z),(z==="allowed"||z==="confirmed")&&(T=!0)},signal:h.signal,...Ke?{lease:{giveBack:()=>Ke.release()}}:{},...H.length>0?{purgeSweep:{first:async()=>{for(let{sweep:z}of H)await z.first()},afterPurge:async()=>{for(let{sweep:z}of H)await z.afterRemoval()},stillToSweep:()=>H.filter(({sweep:z})=>!ws(z.result())).map(({loadedAt:z})=>z)}}:{}}),$e=await(bt==="confirmed"?Za({approved:!0},gr):gr()).finally(async()=>{Ke&&(P=await Ke.release())});W=!0,R.flush();let Ut=await this.settleReloadSweeps(H),mr=Ut.some(z=>z.result.status!=="success");C&&(G=await this.settleCheckpoint(C,co($e)>0)),w=Qd(await O.recorded().catch(()=>{}),U);let kt=$!==void 0?Pe.join($,"manifest.json"):void 0;g=!0;let Tt=await this.verifyLoad({orgId:t.targetOrgId,contractPath:$e.contractPath,...kt!==void 0?{manifestPath:kt}:{},dataset:Y,mappingStore:O,config:n,onProgress:R}),yr="verdict"in Tt?Tt.verdict.status:void 0,Kt=yr==="failed"||yr==="partial"?yr:void 0,Vt=$e.status==="completed"&&(mr||Kt!==void 0)?"partial":$e.status,wr=qf($e);if(v(Kt!==void 0&&wr==="success"?"partial":wr,Ps($e),await Wf(Y,O)),$!==void 0&&kt!==void 0){let z={contractPath:$e.contractPath,datasetDir:$,manifestPath:kt,targetOrgId:t.targetOrgId,status:Vt,at:new Date().toISOString()};this.recordLastRun(z)}let jt=Bf($e),b=Object.fromEntries(Object.entries(l??{}).filter(([z])=>(jt.purge.deleted[z]??0)>0)),_=Oe(this.deps,e,"frozen:load:response",{report:{...jt,...Object.keys(b).length>0?{purge:{...jt.purge,cameAlong:b}}:{},status:Vt,...Kt?{verification:Kt}:{},...P?{mutedAutomation:P}:{},...G?{checkpoint:G}:{},...Ut.length>0?{sweeps:Ut}:{},...I&&tl(I.info)?{emails:I.info}:{},...A?{automation:A}:{},...N?{apiRequests:N}:{}},...a?el(this.replayInfoOf(a,Pf($e,Y))):{}});this.deps.broker.postToWebview(_),wt(this.deps,c,{status:Vt}),p=!0,Vt!=="completed"?this.liveTracker?.partial(c):this.liveTracker?.complete(c),this.postVerification(e,Tt),m()}catch(E){R.flush();let q=await this.settleReloadSweeps(H).catch(()=>[]),Y=q.length>0?{sweeps:q}:{};if(C&&G===void 0){let O=E instanceof st||E instanceof Mt?E.written:void 0;G=await this.settleCheckpoint(C,O?co(O)>0:M&&!An(E))}let ae=G?{checkpoint:G}:{},$=V&&P?{mutedAutomation:P}:{};if(E instanceof Gt){v("stopped",void 0,void 0,E.code),re(this.deps,"frozen:load","frozen:load:error",e,E,{code:E.code,...E.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),E.code==="LOAD_CANCELLED"?(this.registry?.abort(c),wt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),m()):(wo(this.deps,c,E.message,!0),this.liveTracker?.fail(c,E.message),m(E));return}if(E instanceof st){let O=Gf(E.written);v(O,Ps(E.written),void 0,O==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(c),wt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),re(this.deps,"frozen:load","frozen:load:error",e,E,{code:"LOAD_CANCELLED",extraPayload:{written:co(E.written),...ae,...Y,...$}}),m();return}let K=An(E)||E instanceof at||E instanceof ur||E instanceof fr||E instanceof Xr||E instanceof Zr||E instanceof Qr?E:void 0,Z=K!==void 0||(L==="refused"||L==="declined")&&!T,ne=E instanceof Mt?E:void 0,he=ne?ne.cause:E,_e=K?.code??this.errorCodeFor(he,"LOAD_ERROR"),Me=ne===void 0&&!W&&!T;v(Z||Me?"stopped":"failure",ne?Ps(ne.written):void 0,void 0,K?.code??(Me?_e:void 0));let F={...ne&&he instanceof He?{guard:he.code}:this.errorDetailOf(he),...ae,...Y,...$,...Me?{written:0}:{}};re(this.deps,"frozen:load","frozen:load:error",e,E,{code:_e,retryable:he instanceof lt,extraPayload:Object.keys(F).length>0?F:void 0}),p||(wo(this.deps,c,X(E),!0),this.liveTracker?.fail(c,X(E))),m(E)}}loadCheckpointAsk(e){let{read:t}=e;return{module:e.replay===!0?"replay":"frozen",orgId:e.orgId,operationId:e.operationId,written:[...e.written],running:"objects"in t?Lt(t,e.mute?.plan,ao):{firing:[]},request:e.request}}async previewCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)return;let r=await this.targetAutomation.read(e.orgId,e.written).catch(a=>({unread:X(a)})),n=e.muteAutomation?await Or(async()=>vr(e.conn),r,{...this.muteLeases,writes:ao}).catch(a=>{vt.warn(`Frozen preview: the mute could not be planned (${X(a)})`)}):void 0,s=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(s,{}).catch(a=>{vt.warn(`Frozen preview: ${jn(a)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Gt(Ar,jn(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:cl(e.msg.id)},s;try{s=await t.scope(r,n)}catch(d){throw new Gt(Ar,jn(d))}let a=Pi(s);if(a)throw new Gt(a.code,a.message);return{checkpoints:t,ask:r,own:n,estimate:s}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:s,estimate:a}=e,d=await Ti(()=>r.take(n,s,{planned:a,signal:t}));if("stop"in d)throw new Gt(d.stop.code===Ar?Ar:"LOAD_CANCELLED",d.stop.message);return d.checkpoint}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return vt.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${X(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(lr);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(nl,t,Jr),this.deps.configStore.set(lr,e,Jr)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(Rs,{...this.lastVerifies(),[e]:t},Jr)}lastVerifies(){return this.deps.configStore.get(Rs)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(lr);return!t||Date.parse(t.at)>Date.parse(e.measuredAt)?void 0:Object.keys(this.lastRuns()).filter(n=>n!==t.targetOrgId).length===0?t.targetOrgId:void 0}moveOldVerify(){let e=this.deps.configStore.get(bs);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(Rs,{...r,[t]:e},Jr),this.deps.configStore.delete(bs)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(bs),r=t?this.orgOfOldVerify(t):void 0;return t&&r!==void 0&&e[r]===void 0&&(e[r]=t),Object.entries(e).map(([n,s])=>({orgId:n,status:s.status,measuredAt:s.measuredAt}))}lastRuns(){return this.deps.configStore.get(nl)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(lr);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(lr);return t&&e[t.targetOrgId]===void 0&&(e[t.targetOrgId]=t),Object.values(e).map(r=>({status:r.status,orgId:r.targetOrgId,at:r.at}))}async handlePreview(e){let t=nt(Io,e,"frozen:load:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:preview:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,a=await this.replaceRefusal(t,r,t.goneFirst),d=a&&"error"in a?a:void 0;if(d){re(this.deps,"frozen:load:preview","frozen:load:preview:error",e,d.error,{code:d.code,retryable:d.retryable});return}try{let i=new fe,u=r.sasDir(i),{dataset:l,manifest:c}=await r.read(i),f=this.buildTargetOrgAccess(),p=await Ae(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=zt(p,"frozen:load:preview"),m=await new Cr({orgAccess:f,writer:vf,guard:this.deps.infraServices?.productionGuard??new Qa,mockDetector:n.mockDetection?new jr(f,n.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Wr(f),mappingStore:r.mappingStore(i),config:this.toLoadConfig(n),sasGuard:i,serverTime:()=>g.serverTime(),readValidationRules:async I=>{let{toolingQueriesOver:A,toolingValidationRules:N}=await import("./chunk-N7J6NJQ6.mjs"),{toolingRetrievesOver:v}=await import("./chunk-T5VAULLQ.mjs"),P=p.tooling;return N(async C=>(await Sa({query:async G=>P.query(G),queryMore:async G=>P.queryMore(G)},C)).records,A(p),v(p))(I)}}).planLoad({orgId:t.targetOrgId,orgTier:this.targetTier(t.targetOrgId),dataset:l,manifest:c,sasDir:u,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...s?{linkByKeys:!0}:{}}).catch(async I=>{throw I instanceof Ze&&I.gaps!==void 0&&(I.refusedBeside=await this.refusedBesideOf({conn:p,orgId:t.targetOrgId,dataset:l,store:r.mappingStore(i),config:n,parsed:t,...s?{replay:s}:{}}).catch(()=>[])),I}),y=t.checkpointFirst!==void 0?await this.previewCheckpoint({msg:e,orgId:t.targetOrgId,written:l.objects.map(I=>I.objectApiName),request:t.checkpointFirst,muteAutomation:t.muteAutomation===!0,conn:p,replay:s!==void 0}):void 0,R=r.mappingStore(i),L=Jc(p),{emails:T,automation:j,apiRequests:x,automationBytes:U}=await this.previewWhatRuns({conn:p,limits:L,orgId:t.targetOrgId,dataset:l,store:R,config:n,parsed:t,...y?{checkpoint:y}:{},...s?.converted?{replayReads:s.converted.target.requests}:{}}),S=await this.previewStorageOf({conn:L,org:p,dataset:l,store:R,config:n,parsed:t,...U!==void 0?{automationBytes:U}:{},targetOrgId:t.targetOrgId,replay:s!==void 0}),w=s?this.replayInfoOf(s,m.perObject.reduce((I,A)=>I+A.reusedByKeys,0),S):void 0;this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:load:preview:response",{plan:{...m,...y?{checkpoint:y}:{},...T?{emails:T}:{},...j?{automation:j}:{},...x?{apiRequests:x}:{},...S&&!s?{storage:S}:{}},...el(w)}))}catch(i){re(this.deps,"frozen:load:preview","frozen:load:preview:error",e,i,{code:this.errorCodeFor(i,"PREVIEW_ERROR"),retryable:i instanceof lt,extraPayload:this.errorDetailOf(i)})}}async refusedBesideOf(e){let{replay:t,...r}=e,n=Jc(e.conn),{emails:s,automation:a,apiRequests:d,automationBytes:i}=await this.previewWhatRuns({...r,limits:n,...t?.converted?{replayReads:t.converted.target.requests}:{}}),u=await this.previewStorageOf({conn:n,org:e.conn,dataset:e.dataset,store:e.store,config:e.config,parsed:e.parsed,...i!==void 0?{automationBytes:i}:{},targetOrgId:e.orgId,replay:t!==void 0}),{orgId:l}=e,c=[];return a?.refused&&c.push({...a.refused,orgId:l,automation:a}),s?.refused&&c.push({...s.refused,orgId:l,emails:s}),u?.refusal&&c.push({...u.refusal,orgId:l,storage:Af(u)}),d?.refused&&c.push({...d.refused,orgId:l,apiRequests:d}),c}async previewStorageOf(e){if(e.parsed.pilot===!0)return;let t=await this.loadSentOf(e.org,e.dataset);return this.loadStorageOf({conn:e.conn,dataset:e.dataset,...t?{sent:t}:{},...e.parsed.reload===!0?{purged:await this.purgedOf(e.store,e.config).catch(()=>[])}:{},...e.automationBytes!==void 0?{automationBytes:e.automationBytes}:{},targetOrgId:e.targetOrgId,replay:e.replay})}async previewWhatRuns(e){let{parsed:t}=e;try{let r=t.reload===!0&&!t.pilot?await this.purgeStepsOf(e.store,e.config):void 0,n=r?br(r):void 0,s=(f,p)=>ao(f,p)||n?.(f,p)===!0,a=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(f=>f.objectApiName),...r?.delete??[]])]).catch(f=>({unread:X(f)})),d=t.muteAutomation===!0?await Or(async()=>vr(e.conn),a,{...this.muteLeases,writes:s}).catch(()=>{}):void 0,{info:i}=Jo({read:a,...d?.plan?{plan:d.plan}:{},written:e.dataset.objects.map(f=>f.objectApiName),accepted:t.acceptAutomation===!0,target:this.orgNameOf(e.orgId),mayMute:t.muteAutomation!==!0&&this.muteOffered}),u=Qc(e.dataset,e.config,t.pilot),l=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:a,...d?.plan?{plan:d.plan}:{},writes:s,dataset:u,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(f=>{vt.warn(`Frozen preview: the emails could not be judged (${X(f)})`)}),c=await this.loadApiCheck({conn:e.limits,dataset:u,...r?{purged:await this.purgedOf(e.store,e.config)}:{},read:a,...e.checkpoint?{checkpoint:e.checkpoint}:{},...d?.plan?{plan:d.plan}:{},...l?{emails:l}:{},orgId:e.orgId,operation:"frozen:load:preview",...e.replayReads!==void 0?{replayReads:e.replayReads}:{}}).catch(f=>{vt.warn(`Frozen preview: the API requests could not be judged (${X(f)})`)});return{...l&&tl(l.info)?{emails:l.info}:{},...i?{automation:i}:{},...c?{apiRequests:c}:{},automationBytes:Zc(a,d?.plan,e.dataset,s)}}catch(r){return vt.warn(`Frozen preview: what the target runs could not be judged (${X(r)})`),{}}}async handleVerify(e){let t=nt(Na,e,"frozen:verify:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:verify:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,a=s?void 0:this.lastRunOf(t.targetOrgId);if(!s&&!a){re(this.deps,"frozen:verify","frozen:verify:error",e,new Error("No load into this org is recorded \u2014 run a load (frozen:load) into it before verifying."),{code:"NO_LOAD"});return}let d=il(i=>{let u=Oe(this.deps,e,"frozen:load:progress",{...i});this.deps.broker.postToWebview(u)},100);try{let i=new fe,u=a?.contractPath??s?.contractPath??"";if(s&&!await Qe(u)){re(this.deps,"frozen:verify","frozen:verify:error",e,new Error(`No replay of this checkpoint into ${s.target.name} wrote its counting contract on this machine: replay it there, then verify.`),{code:"NO_LOAD"});return}if(a){let g=i.assertOutsideRepo(this.resolveSasDir(n)),h=Pe.dirname(a.contractPath)!==Pe.dirname(Nn(i,g,t.targetOrgId)),m=await Qe(a.contractPath);if(h||!m){let y=Pe.dirname(a.contractPath),R;h?m?R=`The sas directory changed since the last load: its counting contract is in ${y}, and the mapping read is the one in ${g}. Set sasDir back to the sas the load wrote to, or load the dataset again, then verify.`:R=`The sas directory changed since the last load: the load wrote to ${y}, which no longer holds its counting contract, and the mapping read is the one in ${g}. Move the sas back to ${y} and set sasDir to it, or load the dataset again, then verify.`:R=`The sas changed since the last load: ${g} no longer holds the counting contract the last load wrote there. Load the dataset again, then verify.`,re(this.deps,"frozen:verify","frozen:verify:error",e,new Error(R),{code:"SAS_CHANGED",extraPayload:{sasDir:g,loadSas:y,sasMoved:h,contractThere:m}});return}}let l=r.mappingStore(i);if(await l.isStale()){re(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The target org was refreshed after the last load: the records that load wrote are gone. Load the dataset again, then verify."),{code:"TARGET_REFRESHED"});return}let c=await l.recorded(),f=c?.removal;if(c&&f){let g=ot(c).reduce((h,m)=>h+m.ids.length,0);re(this.deps,"frozen:verify","frozen:verify:error",e,new Error(g>0?`The removal of ${f.removedAt} took part of the records the last load created and left ${g} in the org: a verification would read the ones it took as missing. Remove what is left, or reload the dataset, which purges or finds it again; then verify.`:`The records the last load created were removed on ${f.removedAt}. Load the dataset again, then verify.`),{code:"LOAD_REMOVED",extraPayload:{left:g}});return}if(!c){re(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The sas holds no mapping of the last load: nothing names the records to verify. Load the dataset again, then verify."),{code:"NO_LOAD"});return}if(!pd(Cn(i,u),c)){re(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The last load stopped part way \u2014 it was cancelled, or failed once it had written \u2014 and wrote no counting contract: the one in the sas counts an earlier load, and would judge this one by it. Reload the dataset, which purges or finds again what the stopped load wrote, or remove that load before loading the dataset again; then verify. Loaded again without a reload, the dataset would go in beside what the stopped load wrote."),{code:"LOAD_STOPPED"});return}let{dataset:p}=a?await this.readFrozenDataset(a.datasetDir,i):await r.read(i);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:u,...a?{manifestPath:a.manifestPath}:{},dataset:p,mappingStore:l,config:n,onProgress:d})}catch(i){re(this.deps,"frozen:verify","frozen:verify:error",e,i,{code:this.errorCodeFor(i,"VERIFY_ERROR"),retryable:i instanceof lt})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new Xn({orgAccess:this.buildTargetOrgAccess(),sasGuard:new fe}),r=await e.mappingStore.load(),n=await t.verify({orgId:e.orgId,contractPath:e.contractPath,dataset:e.dataset,mapping:r,mandatoryLookups:e.config.mandatoryLookups,presenceKeys:e.config.presenceKeys,...e.manifestPath!==void 0?{manifestPath:e.manifestPath}:{},author:"sandforge",onProgress:e.onProgress});return this.recordLastVerify(e.orgId,{status:n.status,measuredAt:n.measuredAt}),{verdict:n}}catch(t){return{error:t}}}postVerification(e,t){if("verdict"in t){let{verdict:n}=t,s=Oe(this.deps,e,"frozen:verify:result",{verdict:n});this.deps.broker.postToWebview(s);return}let r=t.error;re(this.deps,"frozen:verify","frozen:verify:error",e,r,{code:this.errorCodeFor(r,"VERIFY_ERROR"),retryable:r instanceof lt})}async handleRemove(e){let t=nt(Ca,e,"frozen:remove:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:error","mapping");if(!r)return;let n=(p,g)=>this.refuseRemove(e,p,g),s,a,d;try{s=r.mappingStore(new fe),a=await s.recordedLoads(),d=nr(a)}catch(p){re(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let i=Ss(d,t),u=t.sweep===!0&&i?.code==="ALREADY_REMOVED";if(i&&!u||!d){i&&n(i.message,i.code);return}let l=ot(d),c=s.filePath;if(this.removing.has(c)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(c);let f=this.registry?.holdUntilStart(e.id);try{await this.removeLoad(e,{store:s,load:d,plan:l,includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,alongside:t.sweep===!0?xo(a,d):[],muteAutomation:t.muteAutomation===!0,pending:f,audit:io(r)})}finally{this.removing.delete(c),f?.release()}}async handleRemoveAutomation(e){let t=nt(Da,e,"frozen:remove:automation:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:automation:error","mapping");if(!r)return;let{config:n}=r;try{let s=r.mappingStore(new fe),a,d;if(t.reload===!0)a=await this.purgeStepsOf(s,n,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(d=await this.purgeStepsOf(s,n));else{let l=nr(await s.recordedLoads()),c=Ss(l,t),f=t.sweptObjects!==void 0&&c?.code==="ALREADY_REMOVED";if(c&&!f||!l){c&&re(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(c.message),{code:c.code});return}a=Yr(ot(l),t.sweptObjects??[])}let i=this.targetAutomation,u=await new St(Is).withTimeout("frozen:remove:automation",()=>i.read(t.targetOrgId,a.delete??[]));this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:u,steps:a,...d?{purge:d}:{}}))}catch(s){re(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,s,{code:s instanceof lt?"TIMEOUT":this.errorCodeFor(s,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return Yr([],[]);let n=t.undeletableObjects??{},s=(await e.recordedLoads()).flatMap(a=>ot(a)).filter(({objectApiName:a})=>!Object.hasOwn(n,a));return Yr(s,r)}async handleRemovePreview(e){let t=nt(Ma,e,"frozen:remove:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:preview:error","mapping");if(!r)return;let n=(s,a,d=!1)=>re(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,s,{code:a,retryable:d});try{let s=r.mappingStore(new fe),a=nr(await s.recordedLoads()),d=Ss(a,t);if(d||!a){d&&n(new Error(d.message),d.code);return}let i=ot(a).reduce((c,f)=>c+f.ids.length,0),u=this.removalGuardRefusals(a.orgId,i),l;if(await s.isStale())u.push({code:"TARGET_REFRESHED",message:"The target org was refreshed after the load: the records it created went with the refresh, and a removal removes nothing."}),l={...this.unreadPreviewOf(a,t.includeChanged===!0),planned:i};else{let c=await Ae(a.orgId,this.deps.orgRegistry,this.deps.orgManager);l=await this.previewRemovalOf(c,a,t.includeChanged===!0)}this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:preview:response",{preview:{...l,refusals:u.map(({message:c})=>c),refusalCodes:u.map(({code:c})=>c)}}))}catch(s){n(s,this.errorCodeFor(s,"REMOVE_PREVIEW_ERROR"),!0)}}removalGuardRefusals(e,t){let r=this.deps.infraServices?.productionGuard;if(!r)return[{...Ot}];let n=this.targetTier(e),s=r.check({orgId:e,orgTier:n,operation:"delete",objectName:"the records a Frozen load created",recordCount:t,module:"frozen"});if(!s.allowed)return[{code:"GUARD_BLOCKED",message:`Operation blocked by Production Guard: ${s.blockedReason??s.impactSummary}`}];let a=r.declinedWithoutAsking(s,n);return a===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${a} (${s.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=ot(t),s=await kn(zt(e,"frozen:remove:preview"),n,{...As(t),includeChanged:r,previewOnly:!0});if(!s.preview)throw new Error("The removal preview stopped before it was through.");return{...this.unreadPreviewOf(t,r),planned:n.reduce((a,d)=>a+d.ids.length,0),objects:s.preview.objects.map(a=>({objectApiName:a.objectApiName,planned:a.planned,toDelete:a.toDelete,alreadyGone:a.alreadyGone,changedSince:a.changedSince,keptChanged:a.keptChanged,changedBy:a.changedBy,undeletable:a.undeletable,notVisible:a.notVisible,unread:a.unread,reasons:a.reasons})),userNames:s.preview.userNames}}unreadPreviewOf(e,t){let r=zn(e);return{loadedAt:e.endedAt,includeChanged:t,planned:0,objects:[],userNames:{},...e.removal?{leftBy:e.removal.removedAt}:{},...r.length>0?{keptByThePlatform:r}:{}}}async replaceRefusal(e,t,r=[]){if(e.reload!==!0||e.pilot===!0)return;let n,s={};try{let a=t.mappingStore(new fe),d=await a.recordedLoads();if(d.length===0||await a.isStale())return;if(d.some(i=>!i.created))n="A load recorded before loads kept what they created is in this sas: which of its records it created cannot be told, and a reload leaves in place those it may have linked, so it would not replace that load whole, and no removal takes it. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself, then load without reloading. Nothing was written.";else{let i=await Ae(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=d.filter(p=>ot(p).length>0),l=new Set([...u.flatMap(p=>ot(p).flatMap(g=>g.ids.map(h=>h.slice(0,15)))),...r.map(p=>p.slice(0,15))]),c=[];for(let p of u){let g=await kn(zt(i,"frozen:load:replace"),ot(p),{...As(p),includeChanged:!1,previewOnly:!0,previewHeld:!0,goesWithParent:h=>typeof h.Id=="string"&&l.has(h.Id.slice(0,15))});if(!g.preview)throw new Error("The removal preview stopped before it was through.");c.push(g.preview);for(let{objectApiName:h,cameAlong:m}of g.preview.objects){if(!m)continue;let y=s[h];s[h]={count:(y?.count??0)+m.count,objects:[...new Set([...y?.objects??[],...m.objects])]}}}let f=_f(c,e.sweep===!0);f.length>0&&(n=`A removal of the loads this reload replaces would leave ${f.reduce((g,h)=>g+h.left,0)} of their records in the org \u2014 ${f.map(g=>`${g.objectApiName} (${g.left}: ${g.why.join(", ")})`).join("; ")}: loaded again, the dataset would stand beside them, and the reload would delete what was changed since, and what stays under them along with them. Nothing was written. Take the load back first with a removal \u2014 records changed since, and what was added under them since, go too when it is told to include them \u2014 then load the dataset again.`)}}catch(a){return{error:a,code:this.errorCodeFor(a,"LOAD_ERROR"),retryable:!0}}return n!==void 0?{error:new Error(n),code:oo,retryable:!1}:Object.keys(s).length>0?{cameAlong:s}:void 0}refuseRemove(e,t,r){re(this.deps,"frozen:remove","frozen:remove:error",e,new Error(t),{code:r})}async removeLoad(e,t){let{store:r,load:n,plan:s,includeChanged:a,sweep:d,pending:i}=t,u=t.audit??{module:"frozen"},l=n.orgId,c=s.reduce((A,N)=>A+N.ids.length,0),f=(A,N)=>this.refuseRemove(e,A,N),p=this.deps.infraServices?.productionGuard;if(!p){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",code:Ot.code}),f(Ot.message,Ot.code);return}let{check:g,decision:h}=c>0?await On(p,{orgId:l,orgTier:this.targetTier(l),operation:"delete",objectName:s.map(A=>A.objectApiName).join(", "),recordCount:c,module:"frozen"}):{check:void 0,decision:"allowed"};if(g&&(h==="refused"||h==="declined")){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h}),h==="refused"?f(`Operation blocked by Production Guard: ${g.blockedReason??g.impactSummary}`,"GUARD_BLOCKED"):re(this.deps,"frozen:remove","frozen:remove:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}let m=()=>{if(!i?.signal.aborted)return!1;Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:wa});let A={status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:response",{result:A,operationId:e.id})),!0};if(m())return;let y;try{y=await r.isStale()}catch(A){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"failure",guard:h}),re(this.deps,"frozen:remove","frozen:remove:error",e,A,{code:this.errorCodeFor(A,"REMOVE_ERROR"),retryable:!0});return}if(y){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:"TARGET_REFRESHED"}),f("The target org was refreshed after the load: the records it created went with the refresh, and nothing is removed.","TARGET_REFRESHED");return}if(m())return;let R=e.id,L=c>0?`Removing ${c} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",T=new AbortController,j=()=>{},x=new Promise((A,N)=>{j=v=>v===void 0?A():N(v)});x.catch(()=>{}),Ir(this.deps,R,"frozen",L),this.registry?.register(R,"frozen",L,x,T),this.liveTracker?.register(R,"frozen",L,c);let U,S,w=[],I;try{let A=await Ae(l,this.deps.orgRegistry,this.deps.orgManager),N=new Set([n,...t.alongside].map(O=>O.endedAt));S=d?await this.sweepOfRemoval({conn:A,load:n,store:r,includeChanged:a,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:R,muted:()=>c===0?I:void 0,sweptWith:N}):void 0;for(let[O,J]of(S?t.alongside:[]).entries())w.push({loadedAt:J.endedAt,sweep:await this.sweepOfRemoval({conn:A,load:J,store:r,includeChanged:a,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:`${R}-${O+2}`,muted:()=>{},sweptWith:N})});let v=S,P=[...S?[S]:[],...w.map(({sweep:O})=>O)],C=async O=>{let J=!1;for(let ee of P)await O(ee)&&(J=!0);return J};for(let O of P)await O.ask();let G,M=this.removalAsker,W=Yr(s,P.flatMap(O=>O.takes));if((t.muteAutomation||M)&&!T.signal.aborted&&(W.delete??[]).length>0){let O=this.targetAutomation,J=await new St(Is).withTimeout("frozen:remove automation",()=>O.read(l,W.delete??[])).catch(Q=>({unread:X(Q)}));t.muteAutomation&&(G=await Or(async()=>vr(A),J,{...this.muteLeases,writes:br(W)}));let ee=await M?.({read:J,steps:W,mute:G});if(ee)throw new ur(ee)}I=G?.muted;let V,H=async()=>{let O=G?.prepared;!O||T.signal.aborted||(V=await O.acquire(R),I=V.outcome)},q=await(c===0?(async()=>(await H(),await C(O=>O.first()),await C(O=>O.afterRemoval()),Ga))():kn(zt(A,"frozen:remove"),s,{...As(n),...v?{sweep:O=>C(J=>J.first(O)),afterRemoval:O=>C(J=>J.afterRemoval(O)),automationMade:v.automationMade}:{},onUndeletable:Ra(this.deps,l,"frozen:remove"),beforeFirstWrite:H,includeChanged:a,signal:T.signal,onProgress:(O,J,ee)=>{let Q=Math.min(100,Math.round(O/Math.max(J,1)*100));va(this.deps,R,Q,O,J,ee),T.signal.aborted||this.registry?.updateProgress(R,Q),this.liveTracker?.updateProgress(R,Q,O,J,ee)}})).finally(async()=>{V&&(I=await V.release())}),Y=await S?.settle(),ae=await this.settleReloadSweeps(w),$=n.removal?.removedAt,K=zn(n),Z=Ua(q.objects,q.cancelled),ne={status:ae.reduce((O,J)=>vo(O,J.result),vo(Z,Y)),includeChanged:a,objects:q.objects,finishedAt:new Date().toISOString(),...$?{leftBy:$}:{},...Y?{sweep:Y}:{},...ae.length>0?{otherLoadSweeps:ae}:{},...K.length>0?{keptByThePlatform:K}:{},...I?{mutedAutomation:I}:{}};c>0&&Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:R,orgId:l,outcome:Ka({status:Z}),guard:h,objects:Va(ne.objects),...$?{leftBy:$}:{},...I?{muted:pn(I)}:{}});let he=Ha(ne,c,n.removal);(q.gone.length>0||Object.keys(q.stamps).length>0||q.span||he)&&(await r.recordRemoval(n.endedAt,{gone:q.gone,stamps:q.stamps,...q.span?{span:q.span}:{},...he?{mark:he}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let _e=[...Y&&ws(Y)?[n.endedAt]:[],...ae.filter(O=>ws(O.result)).map(O=>O.loadedAt)];await r.letSweptGo(_e).catch(()=>!1);let Me=Oe(this.deps,e,"frozen:remove:response",{result:ne,operationId:R});this.deps.broker.postToWebview(Me);let k=[Y,...ae.map(O=>O.result)].find(O=>O!==void 0&&O.status!=="success"),F=ne.status==="failure"?"No record this load created could be removed.":c===0&&k?k.refusal??"The sweep left records in the org.":void 0;ne.status==="cancelled"||Y?.status==="cancelled"||ae.some(O=>O.result.status==="cancelled")?(wt(this.deps,R,{aborted:!0}),this.liveTracker?.cancel(R)):(wt(this.deps,R,{status:F&&c===0?"failure":ne.status}),F?(U=new Error(F),this.liveTracker?.fail(R,F)):ne.status==="partial"?this.liveTracker?.partial(R):this.liveTracker?.complete(R))}catch(A){U=A,await S?.settle().catch(()=>{});for(let{sweep:v}of w)await v.settle().catch(()=>{});let N=An(A)||A instanceof ur?A:void 0;Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:R,orgId:l,outcome:N?"stopped":"failure",guard:h,...N?{code:N.code}:{}}),re(this.deps,"frozen:remove","frozen:remove:error",e,A,{code:N?.code??"REMOVE_ERROR",retryable:!0}),wt(this.deps,R,{status:"failure"}),this.liveTracker?.fail(R,X(A))}finally{j(U)}}async reloadSweepsOf(e){if(await e.store.isStale())return[];let t=(await e.store.recordedLoads()).filter(d=>d.created),r=new Set(t.map(d=>d.endedAt)),n={includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},s=d=>jf(d,n),a=[];for(let[d,i]of t.entries())a.push({loadedAt:i.endedAt,judged:s,sweep:await this.sweepOfRemoval({conn:e.conn,load:i,store:e.store,includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied,signal:e.signal,guard:e.guard,operationId:d===0?e.operationId:`${e.operationId}-${d+1}`,muted:()=>{},sweptWith:r,judged:s,...e.audit?{audit:e.audit}:{}})});return a}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:s}of e){let a=await n.settle();t.push({loadedAt:r,result:s?s(a):a})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return nd({input:()=>this.sweepInputOfLoad(zt(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith,e.audit?.sasMark),org:Ln(t,"frozen:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.orgId,orgTier:this.targetTier(r.orgId),operation:"delete",module:"frozen"},onGuardDecision:(n,s)=>{let a=e.judged?e.judged(n):n,d=ed(a,"");delete d.forgeId;let i=e.muted();Xe(this.deps,{action:"cleanup_delete",module:e.audit?.module??"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:a.status==="refused"?"stopped":a.status,...s?{guard:s}:{},...a.status==="refused"?{code:od(s)}:{},objects:Qi(a),details:{...d,loadedAt:r.endedAt},...i?{muted:pn(i)}:{}})},keepMade:async(n,s,a)=>{await e.store.recordMade(r.endedAt,n,s,a)}})}async sweepInputOfLoad(e,t,r,n,s=new Set,a=this.sasMarkInUse()){let d=Mo(t),i=this.targetAutomation,u;try{u=await new St(Is).withTimeout("frozen:remove sweep automation",()=>i.read(t.orgId,d.map(g=>g.objectApiName)))}catch(g){u={error:X(g)}}let l=t.writtenBetween??await td(e,d,r),{ties:c,sweptAlong:f}=await this.tiesOfLoad(t,l,n,s,a),p=new Set([...t.mapping.values(),...f].map(g=>g.slice(0,15)));return rd({writtenBetween:l,created:d,remap:p,automation:Zi(u),...t.runUserId?{runUserId:t.runUserId}:{},ties:c,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return rc(new ya(this.deps.configStore).list({orgId:e,limit:Ds}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?Gn(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n,s){let a=[],d=[],i=await r?.recordedLoads().catch(()=>[])??[];for(let l of i){if(l.endedAt===e.endedAt||l.orgId!==e.orgId)continue;let c=Mo(l).flatMap(g=>g.ids);if(n.has(l.endedAt)){d.push(...c);continue}let f=Date.parse(l.writtenBetween?.first??l.startedAt??l.endedAt),p=Date.parse(l.writtenBetween?.last??l.endedAt);a.push({ids:c,from:f,to:Number.isFinite(p)?p:f})}a.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),a.push(...ec(this.auditedLoadsInto(e.orgId),{sasMark:s,own:i.filter(l=>l.orgId===e.orgId)}));let u=ad(e.removalSpans);return{ties:{otherRuns:sd(t,a),...u?{removalBegan:u}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:d}}async handleRemoveSweep(e){let t=nt(za,e,"frozen:remove:sweep:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:sweep:error","mapping");if(!r)return;let n=(s,a)=>re(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(s),{code:a});try{let s=r.mappingStore(new fe);if(t.reload===!0){await this.listReloadSweeps(e,s,t,io(r).sasMark);return}let a=await s.recordedLoads(),d=nr(a);if(!d){n("No load into this org was recorded in this sas: there is nothing to sweep.","NO_LOAD");return}if(d.orgId!==t.targetOrgId||d.endedAt!==t.loadedAt){n("Another load was recorded since this one was shown: check what a removal takes now.","LOAD_CHANGED");return}let i=xo(a,d),u=new Set([d,...i].map(f=>f.endedAt)),{listing:l,otherLoads:c}=await new St(al).withTimeout("frozen:remove:sweep",async()=>{let f=await Ae(d.orgId,this.deps.orgRegistry,this.deps.orgManager),p=Ln(f,"frozen:remove:sweep"),g=async m=>zo(p,await this.sweepInputOfLoad(p,m,void 0,s,u,io(r).sasMark),m.removalSpans),h=[];for(let m of i)h.push({loadedAt:m.endedAt,listing:await g(m)});return{listing:await g(d),otherLoads:h}});this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:sweep:response",{loadedAt:d.endedAt,listing:l,...c.length>0?{otherLoads:c}:{}}))}catch(s){re(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,s,{code:s instanceof lt?"TIMEOUT":this.errorCodeFor(s,"SWEEP_ERROR"),retryable:!0})}}async listReloadSweeps(e,t,r,n){let s=await t.isStale()?void 0:await t.recordedLoads(),a=(s??[]).filter(i=>i.created);if(s&&!s.some(i=>i.endedAt===r.loadedAt)){re(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error("Another load was recorded since this one was shown: check what a reload replaces now."),{code:"LOAD_CHANGED"});return}let d=await new St(al).withTimeout("frozen:remove:sweep",async()=>{if(a.length===0)return[];let i=await Ae(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=Ln(i,"frozen:remove:sweep"),l=new Set(a.map(f=>f.endedAt)),c=[];for(let f of a)c.push({loadedAt:f.endedAt,listing:await zo(u,await this.sweepInputOfLoad(u,f,void 0,t,l,n),f.removalSpans)});return c});this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:d}))}sayTheSaltWasMade(e){Ia(this.deps,"info","Frozen dataset salt",`This first extraction made the salt every pseudonym is drawn with (fingerprint ${e}) and keeps it in VS Code's secret storage: every later extraction pseudonymizes the same records the same way. A teammate who extracts this dataset needs the same salt: copy it with "SandForge: Copy Frozen Dataset Salt" and give it to them as you would a password; they set it with "SandForge: Use a Frozen Dataset Salt". Whoever holds it can tell which source value a pseudonym was drawn from.`,{autoDismissMs:null,code:"FROZEN_SALT_CREATED"})}async handleStatus(e){let t=this.loadConfig(),r=this.resolveSasDir(t),n=this.resolveDatasetDir(t),s={present:!1};try{let f=await this.saltKeeper.read();f&&(s={present:!0,fingerprint:new En(f.salt).saltFingerprint,source:f.source})}catch{s={present:!1}}let a=null;try{let f=new fe;if(await Qe(Pe.join(r,Br))){let p=await ts(r,f);a={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{a=null}let d=null;try{let p=new fe().assertOutsideRepo(Pe.join(n,"manifest.json"));await Qe(p)&&(d=vs(or(JSON.parse(await Se.readFile(p,"utf8")))))}catch{d=null}let i=this.deps.configStore.get(lr),u=[];try{let f=new fe,p=f.assertOutsideRepo(r);for(let g of await md(p,f))try{let h=nr(await new Dn(p,{guard:f,orgId:g}).recordedLoads());h&&u.push(hd(h))}catch{}}catch{u.length=0}let l={configured:t!==null,sasDir:r,datasetDir:n,salt:s,mockDetectionConfigured:t?.mockDetection!==void 0,selection:a,manifest:d,lastLoad:i?{status:i.status,orgId:i.targetOrgId,at:i.at}:null,lastLoads:this.lastLoadInfos(),lastVerifies:this.lastVerifyInfos(),...u.length>0?{loadRecords:u}:{},rules:await this.rulesFileInfo(t)},c=Oe(this.deps,e,"frozen:status:response",{status:l});this.deps.broker.postToWebview(c)}};export{Mr as a,Wp as b,Up as c,Kp as d,Vp as e,Hp as f,Yp as g,Jp as h,wl as i,bl as j,vp as k,Zd as l,Gn as m,Qd as n,ec as o,Pp as p,Tp as q,Cp as r,xp as s,eg as t,Mc as u,Kr as v,ul as w};