sandforge 1.82.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 (200) hide show
  1. package/lib/{chunk-JLZRZL5E.mjs → chunk-262TP6UU.mjs} +1 -1
  2. package/lib/{chunk-Z42PHCVZ.mjs → chunk-27BBEGUD.mjs} +1 -1
  3. package/lib/{chunk-YGJF55VJ.mjs → chunk-2ADSD5WK.mjs} +1 -1
  4. package/lib/{chunk-KIMQQ6JQ.mjs → chunk-2GSMHGIV.mjs} +1 -1
  5. package/lib/chunk-2K5BYZQM.mjs +8 -0
  6. package/lib/{chunk-DJCGURW7.mjs → chunk-2KTGDYUH.mjs} +1 -1
  7. package/lib/{chunk-YAJQS3OL.mjs → chunk-2N73W63D.mjs} +1 -1
  8. package/lib/{chunk-LXDSRP2W.mjs → chunk-2R6GFNKF.mjs} +1 -1
  9. package/lib/{chunk-VZVICK7Q.mjs → chunk-2WMKJVD2.mjs} +1 -1
  10. package/lib/{chunk-CV47FDQW.mjs → chunk-36Y225OM.mjs} +1 -1
  11. package/lib/{chunk-3C2ZZIFN.mjs → chunk-3CM7LAPE.mjs} +1 -1
  12. package/lib/{chunk-HIHCYMSL.mjs → chunk-3OVTKRS4.mjs} +1 -1
  13. package/lib/{chunk-XFU3HRUV.mjs → chunk-3V4YH5KO.mjs} +1 -1
  14. package/lib/{chunk-XO5FBOQF.mjs → chunk-446GBKAC.mjs} +1 -1
  15. package/lib/{chunk-ZUOPC4W2.mjs → chunk-4GCYGQXD.mjs} +1 -1
  16. package/lib/{chunk-GCGHHN4K.mjs → chunk-4V3QO7HF.mjs} +1 -1
  17. package/lib/{chunk-VZT4E2OJ.mjs → chunk-4X5D3MSV.mjs} +1 -1
  18. package/lib/{chunk-P55MKIZX.mjs → chunk-5OGNK3JP.mjs} +1 -1
  19. package/lib/{chunk-3MGMNK3Q.mjs → chunk-6KOUYHEY.mjs} +1 -1
  20. package/lib/chunk-6QSHWIZI.mjs +48 -0
  21. package/lib/chunk-6VOQFISN.mjs +7 -0
  22. package/lib/{chunk-VYOYXTCU.mjs → chunk-6YC2ELCU.mjs} +1 -1
  23. package/lib/chunk-77IVKH7R.mjs +7 -0
  24. package/lib/{chunk-JKT5YAQ2.mjs → chunk-77MZRBWX.mjs} +1 -1
  25. package/lib/{chunk-PR74GYVI.mjs → chunk-7BQMBXKX.mjs} +1 -1
  26. package/lib/{chunk-SZGGFST2.mjs → chunk-7DPHZWA4.mjs} +1 -1
  27. package/lib/chunk-7V2UYZ6S.mjs +7 -0
  28. package/lib/{chunk-HKUWHVI7.mjs → chunk-7WSQ65WG.mjs} +1 -1
  29. package/lib/{chunk-LHU6CPGE.mjs → chunk-7ZBDACVG.mjs} +1 -1
  30. package/lib/{chunk-WT3SCUHS.mjs → chunk-AG24QMSY.mjs} +1 -1
  31. package/lib/{chunk-A65ADTCR.mjs → chunk-AHUGG3WU.mjs} +1 -1
  32. package/lib/{chunk-ZXFL2MSN.mjs → chunk-ALBY5SOH.mjs} +1 -1
  33. package/lib/chunk-AXFD2OH6.mjs +7 -0
  34. package/lib/{chunk-JESRFE2Z.mjs → chunk-BH76USTQ.mjs} +1 -1
  35. package/lib/{chunk-DBBPDSFN.mjs → chunk-BPHTA6KP.mjs} +1 -1
  36. package/lib/{chunk-3SKLBRPL.mjs → chunk-BT43WSOS.mjs} +1 -1
  37. package/lib/{chunk-32EUNQT6.mjs → chunk-BVZ5H3N4.mjs} +1 -1
  38. package/lib/{chunk-PWVDNN2C.mjs → chunk-C6RKM4BB.mjs} +1 -1
  39. package/lib/{chunk-27Z76O2O.mjs → chunk-CDWZGQAJ.mjs} +1 -1
  40. package/lib/chunk-CGZGL6VT.mjs +7 -0
  41. package/lib/{chunk-P63WJMXQ.mjs → chunk-CN5HGFG4.mjs} +1 -1
  42. package/lib/{chunk-Y4TDVDP2.mjs → chunk-CQAFVEKP.mjs} +1 -1
  43. package/lib/{chunk-G2JR3F63.mjs → chunk-CTPLYUXA.mjs} +1 -1
  44. package/lib/chunk-CXKZ6TYV.mjs +9 -0
  45. package/lib/{chunk-FKK5YBGZ.mjs → chunk-D6JT4PAB.mjs} +1 -1
  46. package/lib/{chunk-3CX7GPCR.mjs → chunk-D7XUNWWU.mjs} +1 -1
  47. package/lib/{chunk-PPHVWUFY.mjs → chunk-DB5RVDC5.mjs} +1 -1
  48. package/lib/{chunk-LAUOSXMN.mjs → chunk-DIGUC7S4.mjs} +1 -1
  49. package/lib/{chunk-6GQUZ4IP.mjs → chunk-DKDKCGXV.mjs} +1 -1
  50. package/lib/chunk-DMT5SCO3.mjs +7 -0
  51. package/lib/{chunk-KKOA62S4.mjs → chunk-DNQKVCUV.mjs} +4 -3
  52. package/lib/{chunk-3XG25GTF.mjs → chunk-DSR2MSBH.mjs} +1 -1
  53. package/lib/{chunk-ZHIZY3ZC.mjs → chunk-E3RQ575Y.mjs} +1 -1
  54. package/lib/{chunk-SAMWHL22.mjs → chunk-EOQON3E5.mjs} +1 -1
  55. package/lib/{chunk-2JZGCCPG.mjs → chunk-ETNQHIDI.mjs} +1 -1
  56. package/lib/chunk-F5SBGJWW.mjs +7 -0
  57. package/lib/chunk-FBXH4VRQ.mjs +7 -0
  58. package/lib/chunk-FKCIGJOI.mjs +15 -0
  59. package/lib/{chunk-NWOI25WY.mjs → chunk-FVLFO2S6.mjs} +1 -1
  60. package/lib/{chunk-MKTXJCXN.mjs → chunk-FYWNSMOZ.mjs} +1 -1
  61. package/lib/{chunk-52EXDVPN.mjs → chunk-GEEWPTV5.mjs} +1 -1
  62. package/lib/{chunk-XSKPYGMT.mjs → chunk-GLN4PI5P.mjs} +1 -1
  63. package/lib/{chunk-DWMRIWV5.mjs → chunk-GT5ZKU6V.mjs} +1 -1
  64. package/lib/chunk-GTRU5AV5.mjs +7 -0
  65. package/lib/chunk-H33DVU3D.mjs +7 -0
  66. package/lib/{chunk-YAIIRFKJ.mjs → chunk-HQZUQXDC.mjs} +1 -1
  67. package/lib/{chunk-MUEQRIK7.mjs → chunk-HVX2AFYW.mjs} +1 -1
  68. package/lib/chunk-I3ZO76LL.mjs +21 -0
  69. package/lib/{chunk-7WSLT5VX.mjs → chunk-I5C4O3VA.mjs} +1 -1
  70. package/lib/{chunk-6VSZNZHH.mjs → chunk-IHGYJZZ2.mjs} +1 -1
  71. package/lib/{chunk-DIS254AN.mjs → chunk-ISA2NYJV.mjs} +1 -1
  72. package/lib/{chunk-GGUOIDWP.mjs → chunk-ISAUCWYK.mjs} +1 -1
  73. package/lib/{chunk-ZUTUYBNW.mjs → chunk-ISOSTAJR.mjs} +1 -1
  74. package/lib/chunk-IXIY6Q4M.mjs +7 -0
  75. package/lib/{chunk-2UU42PTD.mjs → chunk-J3TIHLWG.mjs} +1 -1
  76. package/lib/{chunk-GGNUACTY.mjs → chunk-JAV6F6OA.mjs} +1 -1
  77. package/lib/chunk-JBWJ6UEZ.mjs +7 -0
  78. package/lib/{chunk-C2N2TNEU.mjs → chunk-JH4ZTVQN.mjs} +1 -1
  79. package/lib/{chunk-FOIWWK7G.mjs → chunk-JIPT5FUD.mjs} +1 -1
  80. package/lib/{chunk-7EYQYZJP.mjs → chunk-JREKJO3D.mjs} +1 -1
  81. package/lib/{chunk-VQJMP3DC.mjs → chunk-JUOQUG7U.mjs} +1 -1
  82. package/lib/chunk-JYUMD357.mjs +7 -0
  83. package/lib/{chunk-KP5G6FUC.mjs → chunk-K7G3W7XH.mjs} +1 -1
  84. package/lib/{chunk-T7WREYA5.mjs → chunk-KKS2KFBT.mjs} +1 -1
  85. package/lib/{chunk-TMA34QMA.mjs → chunk-KWAVSZ2B.mjs} +1 -1
  86. package/lib/{chunk-H4JUYUSL.mjs → chunk-KXUOHACP.mjs} +1 -1
  87. package/lib/{chunk-STRMWSIQ.mjs → chunk-L3I6DAHX.mjs} +1 -1
  88. package/lib/{chunk-TCBAE65A.mjs → chunk-L47JCNP3.mjs} +1 -1
  89. package/lib/{chunk-5K2I2DMP.mjs → chunk-L4MSL4U7.mjs} +1 -1
  90. package/lib/chunk-L4RJX7DG.mjs +7 -0
  91. package/lib/{chunk-47UHTN3Q.mjs → chunk-L6CLN664.mjs} +1 -1
  92. package/lib/chunk-LI2XNV7F.mjs +7 -0
  93. package/lib/chunk-LP2D3JJP.mjs +7 -0
  94. package/lib/{chunk-KJYEQHYP.mjs → chunk-LWES2KZE.mjs} +1 -1
  95. package/lib/{chunk-3HEMJTAP.mjs → chunk-LYOGCIYD.mjs} +2 -2
  96. package/lib/{chunk-VPDEJGPS.mjs → chunk-MJD6CPZZ.mjs} +1 -1
  97. package/lib/{chunk-SNEOKYV7.mjs → chunk-MTM4KG3T.mjs} +1 -1
  98. package/lib/{chunk-J24TIGSI.mjs → chunk-N2HYG3BL.mjs} +1 -1
  99. package/lib/chunk-N5UIE4IR.mjs +7 -0
  100. package/lib/{chunk-YMDFF657.mjs → chunk-NDFFIJL5.mjs} +1 -1
  101. package/lib/{chunk-WOOUISSO.mjs → chunk-NFEBX75O.mjs} +1 -1
  102. package/lib/{chunk-ZUBBEP75.mjs → chunk-NNV7IGM7.mjs} +1 -1
  103. package/lib/{chunk-Q3DY7TO2.mjs → chunk-NS6ONPWL.mjs} +1 -1
  104. package/lib/{chunk-IVZJSDJD.mjs → chunk-O7GCCRPW.mjs} +1 -1
  105. package/lib/{chunk-A7JJWOLT.mjs → chunk-OO24ZYYJ.mjs} +1 -1
  106. package/lib/chunk-OOIDCHBQ.mjs +9 -0
  107. package/lib/{chunk-AUS6NFLZ.mjs → chunk-OS5GE52G.mjs} +1 -1
  108. package/lib/chunk-OS6HFJ7L.mjs +7 -0
  109. package/lib/{chunk-V3R45ZWT.mjs → chunk-OTJH6AEA.mjs} +1 -1
  110. package/lib/{chunk-PBE44M2Y.mjs → chunk-OUU47Y7A.mjs} +1 -1
  111. package/lib/{chunk-BN33LVPQ.mjs → chunk-P6WRYJN3.mjs} +1 -1
  112. package/lib/{chunk-JJITOWZK.mjs → chunk-PDRXM5WN.mjs} +1 -1
  113. package/lib/{chunk-RYRMUPMY.mjs → chunk-PGRY365W.mjs} +1 -1
  114. package/lib/chunk-Q4PPI3KG.mjs +7 -0
  115. package/lib/chunk-QFTF2PGS.mjs +21 -0
  116. package/lib/chunk-QKJXIY6L.mjs +7 -0
  117. package/lib/{chunk-PYRZFUVU.mjs → chunk-QLRWU3MB.mjs} +1 -1
  118. package/lib/chunk-QO4MPHZD.mjs +7 -0
  119. package/lib/chunk-QP3JLFIO.mjs +7 -0
  120. package/lib/{chunk-NLB3RGIY.mjs → chunk-QQDZQCO2.mjs} +1 -1
  121. package/lib/{chunk-7CVDVBEE.mjs → chunk-QXB6U3ZP.mjs} +1 -1
  122. package/lib/chunk-R3OM3X4L.mjs +8 -0
  123. package/lib/chunk-R7GKMAT4.mjs +7 -0
  124. package/lib/{chunk-YT22LMF7.mjs → chunk-RVCPQVKM.mjs} +1 -1
  125. package/lib/{chunk-TWV4A5RK.mjs → chunk-RZKJQOOC.mjs} +1 -1
  126. package/lib/chunk-S4PRKKGC.mjs +8 -0
  127. package/lib/{chunk-JH27IKCO.mjs → chunk-SX6QWYCQ.mjs} +1 -1
  128. package/lib/{chunk-UHFLKP26.mjs → chunk-T36DZJPH.mjs} +1 -1
  129. package/lib/{chunk-CZLJZQCS.mjs → chunk-T7DDS4UQ.mjs} +1 -1
  130. package/lib/chunk-TCEXCHXR.mjs +7 -0
  131. package/lib/chunk-TMIESDE5.mjs +7 -0
  132. package/lib/chunk-TQJ5NPRC.mjs +7 -0
  133. package/lib/chunk-TUPZY2QJ.mjs +7 -0
  134. package/lib/{chunk-GBGHJTPC.mjs → chunk-U2CTKIPE.mjs} +1 -1
  135. package/lib/{chunk-3HROD5RE.mjs → chunk-U4YFYSF3.mjs} +1 -1
  136. package/lib/{chunk-Q6SXNKV2.mjs → chunk-UIR77ZJD.mjs} +1 -1
  137. package/lib/{chunk-FA4ZKDCU.mjs → chunk-UOHZW2L4.mjs} +1 -1
  138. package/lib/{chunk-7PY3VQP3.mjs → chunk-VXZ5PTOM.mjs} +1 -1
  139. package/lib/{chunk-7LKI7OAS.mjs → chunk-VZLJZEV2.mjs} +1 -1
  140. package/lib/{chunk-YH4DYI6D.mjs → chunk-W3BQGMTR.mjs} +1 -1
  141. package/lib/{chunk-CELEBWEZ.mjs → chunk-WABXKL4N.mjs} +1 -1
  142. package/lib/{chunk-EEFUE2ES.mjs → chunk-WAYQLQAD.mjs} +1 -1
  143. package/lib/{chunk-RCYEBY42.mjs → chunk-WBELLGNE.mjs} +1 -1
  144. package/lib/{chunk-SFGZFB4F.mjs → chunk-WJAZ5LHL.mjs} +1 -1
  145. package/lib/{chunk-JQZTMFO7.mjs → chunk-WXU6ZJIV.mjs} +1 -1
  146. package/lib/{chunk-GJ6SZVHT.mjs → chunk-WZN36ACK.mjs} +1 -1
  147. package/lib/{chunk-XU25YA46.mjs → chunk-X2XZQ434.mjs} +1 -1
  148. package/lib/{chunk-QAPVKPEC.mjs → chunk-X4HZD5U2.mjs} +1 -1
  149. package/lib/chunk-X6XNTOGO.mjs +7 -0
  150. package/lib/{chunk-XK5W7BVE.mjs → chunk-XAMMIPZ4.mjs} +1 -1
  151. package/lib/{chunk-DT3T7FRD.mjs → chunk-XAUQXYPW.mjs} +1 -1
  152. package/lib/{chunk-C3LNYAVJ.mjs → chunk-XCJUNX63.mjs} +1 -1
  153. package/lib/chunk-XJICAOAQ.mjs +7 -0
  154. package/lib/{chunk-CBL42DUU.mjs → chunk-XKFHTBAB.mjs} +1 -1
  155. package/lib/{chunk-O2PUGRNW.mjs → chunk-XMQ5R6TC.mjs} +1 -1
  156. package/lib/chunk-XPXEQKLR.mjs +7 -0
  157. package/lib/{chunk-6KP6WETK.mjs → chunk-Y7YUNRKK.mjs} +1 -1
  158. package/lib/{chunk-WSUKC2U3.mjs → chunk-YBZIDW6W.mjs} +1 -1
  159. package/lib/{chunk-RTWYLOCA.mjs → chunk-YEVB7LVK.mjs} +1 -1
  160. package/lib/{chunk-L4INJ5TZ.mjs → chunk-Z3MGN42K.mjs} +1 -1
  161. package/lib/{chunk-EOFO3PHS.mjs → chunk-ZB5E7NHU.mjs} +1 -1
  162. package/lib/chunk-ZCOSME6P.mjs +7 -0
  163. package/lib/{chunk-HFUDCNU5.mjs → chunk-ZOSESZ22.mjs} +1 -1
  164. package/lib/chunk-ZTHC42X6.mjs +7 -0
  165. package/lib/{chunk-XZISAZA6.mjs → chunk-ZXOUWHYE.mjs} +1 -1
  166. package/lib/sandforge-autopilot.mjs +1 -1
  167. package/lib/sandforge-backup.mjs +1 -1
  168. package/lib/sandforge-checkpoint.mjs +1 -1
  169. package/lib/sandforge-cleanup.mjs +1 -1
  170. package/lib/sandforge-clone.mjs +1 -1
  171. package/lib/sandforge-compare.mjs +1 -1
  172. package/lib/sandforge-dataops.mjs +1 -1
  173. package/lib/sandforge-empty.mjs +4 -4
  174. package/lib/sandforge-env.mjs +98 -99
  175. package/lib/sandforge-frozen.mjs +1 -1
  176. package/lib/sandforge-mcp.mjs +2 -2
  177. package/lib/sandforge-monitor.mjs +1 -1
  178. package/lib/sandforge-pipeline.mjs +1 -1
  179. package/lib/sandforge-seed.mjs +1 -1
  180. package/lib/sandforge-sync.mjs +1 -1
  181. package/lib/sandforge-users.mjs +21 -23
  182. package/oclif.manifest.json +1 -1
  183. package/package.json +1 -1
  184. package/lib/chunk-42BFLWHR.mjs +0 -7
  185. package/lib/chunk-466F37VD.mjs +0 -7
  186. package/lib/chunk-7SDZR6SR.mjs +0 -7
  187. package/lib/chunk-BMTNTBBM.mjs +0 -7
  188. package/lib/chunk-CCEH7L53.mjs +0 -7
  189. package/lib/chunk-DIL62SUN.mjs +0 -7
  190. package/lib/chunk-FZF23M6R.mjs +0 -7
  191. package/lib/chunk-GHPR5UVV.mjs +0 -7
  192. package/lib/chunk-HQQVANWQ.mjs +0 -20
  193. package/lib/chunk-IRZJU2PG.mjs +0 -22
  194. package/lib/chunk-ISSP2FZ5.mjs +0 -7
  195. package/lib/chunk-JFNLKHY6.mjs +0 -8
  196. package/lib/chunk-O4BROUGM.mjs +0 -7
  197. package/lib/chunk-PE435FVH.mjs +0 -15
  198. package/lib/chunk-RLWB7F26.mjs +0 -7
  199. package/lib/chunk-WEMLDUQA.mjs +0 -7
  200. package/lib/chunk-ZQO5PDX5.mjs +0 -48
@@ -0,0 +1,21 @@
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 zn,b as kd,c as Mn,d as sr}from"./chunk-2K5BYZQM.mjs";import{a as En,b as cd,c as Nn,d as ld,f as pd,g as Cn,i as gd,j as hd}from"./chunk-CQAFVEKP.mjs";import{a as jr,b as ud,c as Do,d as st,e as Ln,f as or,g as xo,h as fd}from"./chunk-PDRXM5WN.mjs";import{j as md,k as yd,n as wd,o as bd,p as Rd}from"./chunk-JBWJ6UEZ.mjs";import{l as wa}from"./chunk-NDFFIJL5.mjs";import{c as dd,d as de}from"./chunk-UV74P4H2.mjs";import{k as ad}from"./chunk-L4MSL4U7.mjs";import{i as ba}from"./chunk-I5C4O3VA.mjs";import{e as ya,f as To}from"./chunk-RVCPQVKM.mjs";import{G as sd,N as Mo,O as id,i as Za,l as Fn,m as Qa,n as ed,o as td,p as rd,v as nd}from"./chunk-OO24ZYYJ.mjs";import{l as od}from"./chunk-GEEWPTV5.mjs";import{a as Xi,b as vn}from"./chunk-XCA5AONB.mjs";import{$a as Io,Dc as In,Ec as Oo,Xa as Ai,Ya as Pi,Za as Ti,_a as ji,a as yi,ab as Fi,b as St,bb as Ei,cb as Ni,db as Li,eb as Ci,g as yo,h as wi,j as Oe,k as bi,l as vr,m as Ri,n as wt,o as re,s as wo,wc as ot}from"./chunk-AXFD2OH6.mjs";import{a as mn}from"./chunk-CE6ZDGBB.mjs";import{a as ra,b as na}from"./chunk-BOGNK4LV.mjs";import{Ha as Va,Na as Ha,Q as Ka,Ua as Ya,Wa as zo,Za as Ja,_a as Xa,a as Ys,b as Js,h as $a,i as _a,n as Lo,ua as Co}from"./chunk-5OGNK3JP.mjs";import{a as qi,b as vo,c as Wi,d as Gi,e as Ui,k as Yi,l as Ji}from"./chunk-XMQ5R6TC.mjs";import{A as Di,B as xi,I as $i,M as Dt,N as _i,O as bn,P as Bi}from"./chunk-IXIY6Q4M.mjs";import{a as Ba,b as No,c as Tr,d as Tn,h as qa,i as jn,j as Wa,l as Ga,m as Ua}from"./chunk-TEIBWMJM.mjs";import{c as Rn,d as kn}from"./chunk-T63U4OZJ.mjs";import{e as ga,h as ha,j as ma}from"./chunk-HQZUQXDC.mjs";import{f as pa,i as Po,j as An}from"./chunk-YBZIDW6W.mjs";import{a as Ki,c as Vi,d as Hi,r as Ao}from"./chunk-EOQON3E5.mjs";import{H as So,L as sa,i as oa,k as Sn}from"./chunk-N2HYG3BL.mjs";import{a as Or,b as On,f as ta,h as Sr}from"./chunk-7WSQ65WG.mjs";import{r as Ae}from"./chunk-OUU47Y7A.mjs";import{b as Zi,c as Qi,g as ea}from"./chunk-WXU6ZJIV.mjs";import{$a as Ia,$b as La,Jb as Aa,La as jo,Pb as Pa,Rb as Ta,Sb as ja,Ua as Fo,Va as Ra,Wb as Fa,Xb as Ea,Za as ka,_a as Eo,_b as Na,ac as Ca,bb as Pr,cb as va,db as Oa,fb as Sa,mc as za,nc as Ma,oc as Da,yc as xa}from"./chunk-R3OM3X4L.mjs";import{b as gi,c as hi,e as Je,f as mi}from"./chunk-77IVKH7R.mjs";import{q as Pn}from"./chunk-2WMKJVD2.mjs";import{a as lt,b as At}from"./chunk-VV3B6IC3.mjs";import{a as Ot}from"./chunk-4TLYUZD5.mjs";import{b as ia,d as aa,f as Ar,g as da,h as ca,i as la,j as ua,p as fa}from"./chunk-VXZ5PTOM.mjs";import{i as ki}from"./chunk-INIT2UKJ.mjs";import{h as Mi}from"./chunk-ZOSESZ22.mjs";import{b as yn}from"./chunk-HFSBDM7B.mjs";import{b as vi,c as ct,e as bo,g as Oi,h as Ro,i as Si,j as ko}from"./chunk-OHEOJISY.mjs";import{a as Ii}from"./chunk-EADHKH3A.mjs";import{h as nr}from"./chunk-Z3MGN42K.mjs";import{$ as di,E as ni,F as zt,G as yt,I as ho,L as oi,M as si,N as ii,Y as mo,Z as ai,a as kr,b as Ye,c as Zt,d as fn,da as Mt,ea as ci,f as Qt,fa as li,g as Xs,ga as ui,ha as fi,ia as pi,ja as tr,k as Zs,ka as rr,l as go,m as Qs,n as ei,o as ti,p as ri,q as Ke,r as Ge,s as pn,t as Ir,u as gn,v as er,z as hn}from"./chunk-2GSMHGIV.mjs";import{a as Me,h as me}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{a as zi}from"./chunk-ISOSTAJR.mjs";import{b as wn}from"./chunk-UNDIBZWG.mjs";import{Cc as nn,Ec as qe,Fc as on,Gc as mt,Hc as Lt,Ic as sn,Lc as We,Mc as He,Nc as an,Oc as ze,Pc as Xt,Pd as Vs,Qc as Ws,Sc as Gs,Tc as dn,Wd as Hs,Yd as Rr,Zc as Us,dd as Ks,ee as Ct,fe as un,id as cn,jd as ln,s as Bs,yc as qs,zc as Jt}from"./chunk-6QSHWIZI.mjs";import{b as Ce,e as Ds,f as rn,k as ht,l as nt,s as xs,u as $s,v as _s,z as po}from"./chunk-WZQEK4WT.mjs";import{createHash as Id}from"node:crypto";import*as xn from"node:fs/promises";import*as Er from"node:path";import*as bt from"node:fs/promises";import*as Pt from"node:path";var Fr="platform-records.json",$o=class extends Error{constructor(e){let t=e.checks.filter(r=>!r.passed).map(r=>`${r.name} (${r.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${t}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},Dn=class{guard;constructor(e){this.guard=e??new de}async write(e,t,r,n){if(!n.passed)throw new $o(n);let s=this.guard.assertOutsideRepo(e),i=this.guard.assertOutsideRepo(Pt.join(s,"data"));await bt.mkdir(i,{recursive:!0});for(let l of await bt.readdir(i))l.endsWith(".json")&&await bt.rm(this.guard.assertOutsideRepo(Pt.join(i,l)));let d=[],a=async(l,c)=>{let f=this.guard.assertOutsideRepo(l);await bt.writeFile(f,`${JSON.stringify(c)}
8
+ `,"utf8"),d.push(f)},u=this.guard.assertOutsideRepo(Pt.join(s,"manifest.json"));await bt.writeFile(u,Mn(r),"utf8"),d.push(u);for(let l of t.objects)await a(Pt.join(i,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await a(Pt.join(s,"record-types.json"),t.recordTypes),await a(Pt.join(s,"personcontact-sidecar.json"),t.personContactSidecar),await a(Pt.join(s,Fr),{...t.standardPricebook?{standardPricebook:t.standardPricebook}:{}}),{dir:s,files:d}}};var _o="manifest.json",al=["record-types.json","personcontact-sidecar.json",Fr],Bo="data",dl="sha256:";async function Df(o){let e=await qo(Er.join(o,_o));if(e===void 0)throw new Error(`No frozen dataset at ${o}: it holds no ${_o}.`);let t=[{name:_o,content:ll(e)}];for(let n of al){let s=await qo(Er.join(o,n));s!==void 0&&t.push({name:n,content:s})}for(let n of await cl(Er.join(o,Bo))){let s=await qo(Er.join(o,Bo,n));s!==void 0&&t.push({name:`${Bo}/${n}`,content:s})}let r=Id("sha256");for(let{name:n,content:s}of t.sort((i,d)=>vd(i.name,d.name)))r.update(`${n}\0${Id("sha256").update(s).digest("hex")}
9
+ `);return`${dl}${r.digest("hex")}`}async function cl(o){let e;try{e=await xn.readdir(o)}catch(t){if(t.code==="ENOENT")return[];throw t}return e.filter(t=>t.endsWith(".json"))}async function qo(o){try{return await xn.readFile(o)}catch(e){if(e.code==="ENOENT")return;throw e}}function ll(o){let e;try{e=JSON.parse(o.toString("utf8"))}catch{return o}if(Go(e)&&Go(e.controls)){let t={...e.controls};delete t.dryRunLoad,e={...e,controls:t}}return Buffer.from(Wo(e),"utf8")}function Wo(o){return Array.isArray(o)?`[${o.map(Wo).join(",")}]`:Go(o)?`{${Object.keys(o).sort(vd).map(t=>`${JSON.stringify(t)}:${Wo(o[t])}`).join(",")}}`:JSON.stringify(o)??"null"}function Go(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function vd(o,e){return o===e?0:o<e?-1:1}var Ve=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function ir(o){return o.objects.reduce((e,t)=>e+t.records.length,0)}function Nr(o){return o.orgName??o.orgId}async function Od(o){if(Uo(o),o.protectedOrgIds?.includes(o.orgId))throw new Ve("protected-environment",`Refusing frozen-dataset load on protected environment ${Nr(o)}: 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 Ve("source-is-target",`Refusing frozen-dataset load on ${Nr(o)}: 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 Ve("unmocked-callouts",`Refusing frozen-dataset load on ${Nr(o)}: 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(ir(o.dataset)===0)throw new Ve("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 Uo(o){if(!(o.orgTier==="staging"&&o.stagingReplay===!0)){if(o.orgTier==="staging")throw new Ve("non-sandbox",`Refusing frozen-dataset load on ${Nr(o)}: 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 Ve("non-sandbox",`Refusing frozen-dataset load on ${o.orgTier} org ${Nr(o)}: 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 Lr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${me(this.config.metadataTypeApiName)} WHERE ${me(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var $n=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=[],i=[];for(let d of e.records){let a={},u=e.accountKindOf?.(d.referenceId);for(let[l,c]of Object.entries(d.fields)){if(u!==void 0&&cn(Ke,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===Ki){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)),a[l]=p}i.push(a)}return{objectApiName:e.objectApiName,alignedRecords:i,removals:[...r.entries()].map(([d,a])=>({objectApiName:e.objectApiName,field:d,reason:a.reason,affectedRecords:a.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,i),uiApiWarnings:s}}detectMissingRequired(e,t){let r=t.filter((a,u)=>!e.linked?.has(e.records[u].referenceId));if(r.length===0)return[];let n=[],s=e.accountKindOf,i=s?e.records.filter(a=>!e.linked?.has(a.referenceId)).map(a=>s(a.referenceId)):[];for(let a of e.describe.fields){let u=s?ln(Ke,a.name):void 0;if(!a.createable||a.nillable&&u===void 0||a.defaultedOnCreate)continue;let l=r.filter((f,p)=>u===void 0||er(u,i[p]));if(l.length===0)continue;if(!l.some(f=>{let p=f[a.name];return p!=null&&p!==""})){let f=a.unique?"unique":a.nameField?"name":void 0,p=(a.referenceTo?.length??0)>0,g=(a.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:a.name,isLookup:p,referenceTo:a.referenceTo??[],...f?{distinct:f}:{},...u?{accountKind:u}:{},...!p&&a.type?{fieldType:a.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=dn(e.objectApiName,a=>e.describe.fields.some(u=>u.name===a&&u.createable),a=>r.some(u=>u[a]!==void 0&&u[a]!==null&&u[a]!==""));if(d!==void 0&&!n.some(a=>a.field===d)){let a=e.describe.fields.find(u=>u.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...a?{fieldType:a}:{}})}return n}async alignPicklistValue(e,t,r,n,s,i,d){let a=r==="multipicklist",u=a?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 i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:y,scope:"global"}),this.applyRule(y,u,f,a)}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 i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:m,scope:"record-type"}),this.applyRule(m,u,h,a)}async uiApiValues(e,t,r,n){let s=`${e.orgId}|${e.objectApiName}|${t}|${r}`,i=this.uiApiCache.get(s);if(i!==void 0)return i;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 Cr="Opportunity",zr="SyncedQuoteId",ul="OpportunityLineItem",Ko="QuoteLineItem";function Vo(o,e){let t=(d,a)=>{let u=new Map;for(let{referenceId:l,fields:c}of o.get(d)??[]){let f=c[a];typeof f!="string"||f===""||!e(l)||u.set(f,(u.get(f)??0)+1)}return u},r=t(ul,"OpportunityId"),n=t(Ko,"QuoteId"),s=new Set((o.get("Quote")??[]).map(d=>d.referenceId)),i=[];for(let{referenceId:d,fields:a}of o.get(Cr)??[]){let u=a[zr];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&&i.push({opportunity:d,quote:u,products:l,lines:c})}return i}function Sd(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),i=r?"its":"their",d=r?"the quote's":"the quotes'",a=s===0?`none of ${d} lines`:`${s} of ${d} lines`,u=e&&s===0?", which excludedObjects leaves out":"";return{objectApiName:Cr,count:o.length,note:`${o.length} ${t?"would be ":""}left unsynced with ${i} quote: the load ${t?"would write":"wrote"} ${n} of ${i} products and ${a}${u} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${zr} left empty, the products kept`}}var Xe=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold;refusedBeside},Dr=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 fl(o){return o.perObject.reduce((e,t)=>e+t.toInsert,0)}function pl(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 it=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${xd(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},$t=class extends Error{constructor(t,r,n){super(gl(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function gl(o,e,t){return`${Q(o)}
10
+ The load failed ${xd(e,t)}`}function xd(o,e){let t=new Map,r=(a,u)=>{u!==0&&t.set(a,(t.get(a)??0)+u)};for(let a of o.placeholders)r(a.placeholderObjectApiName,1);for(let a of o.perObject)r(a.objectApiName,a.inserted);let n=[...t.values()].reduce((a,u)=>a+u,0),s=[...Object.values(o.purge.deleted),...Object.values(o.purge.deactivated)].reduce((a,u)=>a+u,0),i=[...n>0?[`created ${n} record(s) (`+[...t].map(([a,u])=>`${a}: ${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.",i===""?`before it had written the whole dataset. ${d}`:`after it had ${i}. ${d}`}function $d(o,e){let t=[];for(let[r,n]of o.givenRules){let s=[],i={};for(let{referenceId:a,fields:u}of o.alignedByObject.get(r)??[]){if(!gt(u.RecordTypeId)||!e(a))continue;s.push(a);let l=o.withoutRecordType.get(a)??"notRead";i[l]=(i[l]??0)+1}if(s.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:s.length,why:i,...d?{predicted:d}:{}},rule:n,keys:s})}return t}function _d(o){return{namespacePrefix:o.namespacePrefix,developerName:o.developerName}}function hl(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 ml(o,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new $t(o,e.written,Q(t))}return new $t(o,e.written)}function Bd(o,e,t){let r=t.map(n=>ct(n.namespacePrefix,n.developerName));return new Xe(`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 yl(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 i=r.filter(d=>d.name===s);if(i.length>1)return Bd(e,s,i)}}}var qd="Opportunity",Bn="placeholder:",Yo=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 wl(o){if(o.startsWith(Bn))return o.split(":")[1]??"Unknown";let e=o.lastIndexOf("-");return e>0?o.slice(0,e):"Unknown"}function bl(o){return typeof o=="number"?String(o):typeof o=="boolean"?o?"TRUE":"FALSE":`'${Me(String(o))}'`}var Tt=200;function pe(o){return o.slice(0,15)}var Rl=["CreatedDate","LastModifiedDate"],kl=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function xt(o){return typeof o=="string"?Date.parse(o):Number.NaN}function Ad(o){return o.success||o.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Pd(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 Td(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 Ho(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 jd(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 qn(o,e="inserted"){return o>0?`, ${o} not ${e}: the load was cancelled first`:""}function Jo(o,e="inserted"){return o>0?`, ${o} not ${e}: the load failed`:""}function Il(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 ${Q(r)}`}}var Fd={phase:"guards",status:"started",progress:0,message:"Running the safety checks"};function _n(o,e){let{phase:t,progress:r,did:n,refused:s,notDone:i,done:d,notes:a=""}=o;return e?{phase:t,status:"error",progress:r,message:`${n}${Jo(i,d)}${a} \u2014 ${Q(e.cause)}`}:{phase:t,status:Il(s,i),progress:r,message:`${n}${qn(i,d)}${a}`}}var Mr={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 vl(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 Wd(o,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of o.personContactSidecar??[])e.get(n)===Ge&&t.set(n,r);for(let r of o.objects.find(n=>n.objectApiName===Ge)?.records??[]){if(t.has(r.referenceId)||!Ir(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ke?n:"")}return t}function Ol(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===Ke)?.records??[]){let r=t.fields.LastName;(Ir(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function Wn(o,e,t){let r=o.accountKind;return r===void 0?[...e]:e.filter(n=>er(r,t(n.referenceId)))}var xr=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new de}deps;config;sasGuard;journal;async gateLoad(e){try{await this.passEntryGuards(e)}catch(s){throw e.onProgress?.(Fd),e.onProgress?.(pt("guards",2,"Safety checks 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=yl(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:ir(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return Od({orgId:e.orgId,...e.orgName!==void 0?{orgName:e.orgName}:{},orgTier:e.orgTier,...e.stagingReplay?{stagingReplay:!0}:{},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 it||!n?.wroteSome()?r:await ml(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 i=Nd(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(i)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(a=>a.toInsert>0).map(a=>a.objectApiName),n=[...new Set([...r,...e.placeholders.map(a=>a.placeholderObjectApiName)])];if(!t||n.length===0)return e;let s=new Map,i=new Map;try{for(let{objectApiName:a,onChangeOnly:u,...l}of await t(n))u?i.set(a,[...i.get(a)??[],l.name]):s.set(a,[...s.get(a)??[],l])}catch(a){return{...e,validationRulesUnread:Q(a)}}let d=new Set(r);return{...e,perObject:e.perObject.map(a=>{if(a.toInsert===0)return a;let u=s.get(a.objectApiName)??[],l=i.get(a.objectApiName)??[];return{...a,...u.length>0?{validationRules:u}:{},...l.length>0?{validationRulesOnChange:l}:{}}}),placeholders:e.placeholders.map(a=>{let u=d.has(a.placeholderObjectApiName)?[]:s.get(a.placeholderObjectApiName)??[];return u.length>0?{...a,validationRules:u}:a})}}async prepare(e,t,r){let{orgId:n}=e;t(Fd);try{await this.passEntryGuards(e)}catch($){throw t(pt("guards",2,"Safety checks not passed",$)),$}t({phase:"guards",status:"done",progress:2,message:"Safety checks 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 i=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{i=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(K){throw t(pt("pilot",4,"Root folder not selected",K)),K}let $=i.objects.reduce((K,X)=>K+X.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${$} record(s)`})}let d=Qo(i),a=Tl(e.dataset),u=Wd(i,d),l=zl(i,d,u),c=Ys(l),f=c.flat(),p=new Qt,g=new Qt(Cl),h={...i,objects:i.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,k=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)k.add($);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||zd(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 N=[],T=new Map,j=new Map,x=new Map;for(let $ of h.objects){let K=[];for(let X of $.records)K.push(await this.resolveRecordType(e,i,$.objectApiName,X,j,N,x));T.set($.objectApiName,K)}let U=new $n(this.deps.orgAccess),S={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:N},w=new Map,I=new Map,A=new Map,L=new Map,v=new Map,P,C=Ol(i),W=$=>C.has($)?P===!1?"personAsBusiness":"person":"business",D=new Map,G=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 X=$.records.filter(O=>!y.has(O.referenceId)),ne=(O,J)=>{S.excludedObjects.push({objectApiName:K,reason:O}),v.set(K,{objectApiName:K,fromFiles:i.objects.find(ee=>ee.objectApiName===K)?.records.length??$.records.length,inserted:0,reused:$.records.length-X.length,skippedDuplicates:[],failed:X.map(ee=>({objectApiName:K,referenceId:ee.referenceId,errors:[J]}))}),X.length!==0&&t({phase:"align",objectName:K,status:"error",progress:12,message:`Skipped ${K} \u2014 ${O}`})},ge;try{ge=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===Ke&&(P=ge.fields.some(O=>O.name===pn)),ge.createable===!1&&X.length>0){ne(`Not createable in target org: ${X.length} record${X.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(ge.fields.filter(O=>O.updateable===!1).map(O=>O.name)));let _e=ge.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&&L.set(K,_e);let De=yn(ge.recordTypeInfos);if(De.some(O=>!O.master)){let O=Wa(jn(De));G.set(K,{types:De,...O?{predicted:O}:{}})}let R=El(K,ge,this.config);R.length>0&&D.set(K,R),I.set(K,new Set(ge.fields.filter(O=>O.createable&&!O.nillable&&!O.defaultedOnCreate&&(O.referenceTo?.length??0)>0).map(O=>O.name)));let E=await U.alignObject({orgId:n,objectApiName:K,records:T.get(K)??[],describe:ge,resolvedRecordTypes:j,ruleFor:(O,J)=>this.picklistRuleFor(O,J),linked:y,...K===Ke?{accountKindOf:W}:{},...V?{leaveOutEncrypted:V}:{}});S.objectResults.push(E),S.removals.push(...E.removals),S.adjustments.push(...E.adjustments),w.set(K,E.alignedRecords.map((O,J)=>({referenceId:(T.get(K)??[])[J].referenceId,fields:O})))}let H=await this.linkWhatThePlatformKeeps(n,S.objectResults,w,a,m,y,W),F=e.reload||e.linkByKeys?await this.reuseByKeysAsWritten(n,h,S.objectResults,w,a,m,y,W):{linked:[],said:[],leftEmpty:[]};for(let $ of[...H.linked,...F.linked])k.add($);let q=[...H.said,...F.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${q.length>0?` \u2014 ${q.join("; ")}`:""}`}),r.endOpenLine=void 0;let Y=new Qt(Nl(D));Fl(w,I,[p,g,Y]);for(let $ of S.objectResults){let K=(w.get($.objectApiName)??[]).filter(X=>!y.has(X.referenceId));$.missingRequired=$.missingRequired.filter(X=>Wn(X,K,W).some(ne=>gt(ne.fields[X.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let ie=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:i,refIndex:d,personContacts:u,groups:c,groupOrder:f,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:Y,loading:h,mapping:m,reused:y,reusedByKeys:k,ranks:a,recordTypeIssues:N,alignment:S,alignedByObject:w,requiredLookups:I,fixedAtInsert:A,filteredLookups:L,lostObjects:v,targetHasPersonAccounts:P,accountKindOf:W,plans:ie,givenRules:G,withoutRecordType:x,keysLeftEmpty:[...H.leftEmpty,...F.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),s=b=>e.onProgress?.(b),{orgId:i}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=await this.prepare(e,s,t),{previousLoads:a,working:u,refIndex:l,personContacts:c,groups:f,groupOrder:p,leftToThePlatform:g,untypedFeedItems:h,heldForExclusions:m,mapping:y,reused:k,ranks:N,recordTypeIssues:T,alignment:j,alignedByObject:x,requiredLookups:U,fixedAtInsert:S,lostObjects:w,targetHasPersonAccounts:I,accountKindOf:A,plans:L}=d,v=pl(fl(Nd(d,void 0,{orgId:i,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 Dr(v);let P=await this.runUserIdOf(i);P&&this.journal?.writtenAs(P);let C={deleted:{},deactivated:{},failures:[]},W=[],D=[],G=new Yo,V=new Map,H=[],F=new Set,q,Y=new Map,ie=!1,$=async()=>{let b=await this.readWrittenBetween(i,G,y),_=q?.linked??new Map,z=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(y,{created:G.list(H),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...F],...z&&z.length>0?{stillToSweep:[...z]}:{}},..._.size>0?{personContacts:Object.fromEntries(_)}:{},...Y.size>0?{withTheirRecord:Object.fromEntries(Y)}:{},...P?{runUserId:P}:{}}),ie=!0},K=()=>G.list().length>0||Object.keys(C.deleted).length>0||Object.keys(C.deactivated).length>0,X=async()=>{if(!e.signal?.aborted)return;let b=K();throw b&&await $(),new it({perObject:D,placeholders:W,purge:C},b)};t.load={keepMapping:$,mappingKept:()=>ie,wroteSome:K,written:{perObject:D,placeholders:W,purge:C}};let ne=[];if(e.reload){let b="",_={residuals:0},z={tried:0,went:0},se=be=>{let Te=Ee=>Object.values(Ee).reduce((Re,le)=>Re+le,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:`${Pd(z)}${b}`},be)};if(!e.pilot){s({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let be=await this.planPurge(i,a,y),Te=await this.foundUnderThePurge(i,be.residuals,y,l);if(Te.length>0){let le=new ar(Te);throw s(se({cause:le})),le}H=be.carried;for(let le of H.flatMap(oe=>oe.referenceIds)){let oe=y.get(le);oe&&F.add(pe(oe))}let Ee=Object.values(be.leftUnrecorded).reduce((le,oe)=>le+oe,0);Ee>0&&(C.leftUnrecorded=be.leftUnrecorded,b=` \u2014 ${Ee} 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(([le,oe])=>`${le} (${oe})`).join(", "));try{e.purgeSweep&&(await X(),await e.purgeSweep.first()),await this.purgeResiduals(e,be,[...p].reverse(),C,X,F,_,z),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(le){throw s(se(le instanceof it?void 0:{cause:le})),le}for(let le of a)if(!le.created)for(let oe of le.mapping.values())F.add(pe(oe));s(_.residuals>0||C.failures.length>0?se():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Pd(z)}${b}`})}}let ge=b=>(x.get(b)??[]).filter(_=>!k.has(_.referenceId)),_e=L.filter(b=>b.kind==="placeholder").length,De=b=>_n({phase:"placeholders",progress:25,did:`Placeholders: ${W.length} created`,refused:0,notDone:_e-W.length,done:"created"},b);_e>0&&(await X(),s({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of L)b.kind==="placeholder"?(await X(),await this.createPlaceholder(e,b,ge(b.missing.objectApiName),y,W,G)):this.applyScalarDefault(b.missing,Wn(b.missing,ge(b.missing.objectApiName),A),ne,N)}catch(b){throw s(De(b instanceof it?void 0:{cause:b})),b}_e>0&&s(De());let R=f.flatMap(b=>b.length>1?Js(b,Ml(x,U,l,c)):b),E=[],O=[],J=this.config.duplicateErrorPatterns??ud,ee=new Set(R.includes(Zt)?(x.get(Zt)??[]).map(b=>b.referenceId):[]),Z=[],he=null,te=0,Be=!1,M=b=>b===Ye&&Z.length>0?`, ${Z.length} on a case waiting for ${Z.length===1?"its task":"their tasks"}`:"",we=new Set,et=async()=>{if(q)return q;let b=await this.linkPersonContacts(i,c,y,k,I,T);for(let _ of b.linked.keys())k.add(_);return we=new Set(b.unlinked.map(_=>_.contactReferenceId).filter(_=>!k.has(_))),q=b,b},tt=b=>{if(b.objectApiName!==Ge||!q)return b;let _=q.unlinked.filter(z=>we.has(z.contactReferenceId));return _.length===0?b:{...b,failed:[...b.failed,..._.map(z=>({objectApiName:Ge,referenceId:z.contactReferenceId,errors:[vl(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)`}))},ae=()=>{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`]:[]]},Rt=(b,_)=>[...b===Ge?ae():[],..._?[_]:[],...g.counts(b).map(({why:z,count:se})=>Xs(se,z)),...h.counts(b).map(({why:z,count:se})=>Cd(se,z)),...m.counts(b).map(({why:z,count:se})=>Jd(se,z))].map(z=>`, ${z}`).join(""),fe=(b,_,z,se,be)=>{let Te=D.findIndex(vt=>vt.objectApiName===b),Ee=Te>=0?D[Te]:void 0,Re=z.filter(vt=>k.has(vt.referenceId)).length,le=Ee?.inserted??0,oe=Ee?.skippedDuplicates??[],Ne=Ee?.failed??[],dt=Ee?.writtenWithoutFields,Ie=z.length-Re-le-oe.length-Ne.length,Nt=tt({objectApiName:b,fromFiles:_,inserted:le,reused:Re,skippedDuplicates:oe,failed:Ne,...dt?{writtenWithoutFields:dt}:{},...Ie>0?{notInserted:Ie}:{}});Ee?D[Te]=Nt:D.push(Nt),s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*te/Math.max(R.length,1)),message:`${b}: ${le} inserted, ${Nt.reused} reused, ${oe.length} duplicates skipped, ${Nt.failed.length} failed${M(b)}${Jo(Ie)}${An(dt)}${Rt(b,se)} \u2014 ${Q(be)}`})},ft,rt=(b,_,z)=>{if(b.waiting>0){let Re=D.find(le=>le.objectApiName===Ye);Re&&(Re.notInserted=(Re.notInserted??0)+b.waiting)}let se=_==="cancel"&&b.waiting>0,be="";se?be=qn(b.waiting):b.waiting>0&&(be=Jo(b.waiting));let Te=b.status;z?Te="error":se&&b.status!=="error"&&(Te="stopped");let Ee=z?` \u2014 ${Q(z.cause)}`:"";s({phase:"insert",objectName:Ye,status:Te,progress:25+Math.round(55*te/Math.max(R.length,1)),message:`${b.message}${be}${b.notes}${Ee}`})},xe=async()=>{let b=he;b&&e.signal?.aborted&&(he=null,rt(b,"cancel")),await X()};t.endOpenLine=b=>{let _=ft;ft=void 0,_&&!(b instanceof it)&&_(b);let z=he;he=null,z&&rt(z,b instanceof it?"cancel":"failure")};let ye=async()=>{Be=!0;let b=Z.splice(0,Z.length),_=he;if(he=null,b.length===0)return;let z=25+Math.round(55*te/Math.max(R.length,1)),se;try{await X()}catch(oe){throw _&&rt(_,oe instanceof it?"cancel":"failure"),oe}let be=oe=>`${oe.inserted} inserted, ${oe.reused} reused, ${oe.skippedDuplicates.length} duplicates skipped, ${oe.failed.length} failed${qn(oe.notInserted??0)}${An(oe.writtenWithoutFields)}`,Te=oe=>{let Ne=D.findIndex(dt=>dt.objectApiName===Ye);Ne>=0?D[Ne]=Ho(D[Ne],oe):D.push(oe)},Ee={};try{se=await this.insertObject(e,Ye,0,b,l,y,k,E,J,G,V,Ed(D),oe=>{Ee.result=oe})}catch(oe){let Ne=Ee.result;if(Ne&&Te(Ne),_&&Ne){let dt=Ne.inserted+Ne.skippedDuplicates.length+Ne.failed.length;rt({..._,waiting:Math.max(_.waiting-dt,0),message:`${_.message}; after their task: ${be(Ne)}`},"failure",{cause:oe})}else _&&rt(_,"failure",{cause:oe});throw oe}Te(se);let Re=be(se),le="done";se.failed.length>0||_?.status==="error"?le="error":(se.notInserted??0)>0&&(le="stopped"),s({phase:"insert",objectName:Ye,status:le,progress:z,message:_?`${_.message}; after their task: ${Re}${_.notes}`:`${Ye} after their task: ${Re}`})};for(let b of R){await xe();let _=x.get(b);if(!_){let ue=w.get(b);if(ue&&b===Ge&&c.size>0){try{await et()}catch(Le){throw s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*te/Math.max(R.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${Q(Le)}`}),Le}B();let je=q?.linked??new Map,Fe=ue.failed.filter(Le=>!je.has(Le.referenceId));D.push({...ue,reused:ue.reused+ue.failed.length-Fe.length,failed:Fe})}else ue&&D.push(ue);continue}te++,s({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*te/Math.max(R.length,1)),message:`Inserting ${b}`});let z,se=u.objects.find(ue=>ue.objectApiName===b)?.records.length??_.length,be=_;if(ft=ue=>fe(b,se,be,z,ue),b===Ge&&c.size>0){let ue=await et();be=_.filter(je=>!we.has(je.referenceId));for(let je of be){let Fe=ue.own.get(je.referenceId),Le=je.fields.AccountId;Fe&&(Le==null||Le==="")&&(je.fields.AccountId=Fe.accountReferenceId)}}b===kr&&await this.matchDirectRelations(i,u,_,y,k,Y),b===Zt&&await this.matchTasksWrittenWithEmails(i,u,_,y,k,Y),mo[b]!==void 0&&(z=await this.matchActivityRelations(e,b,_,y,k,S.get(b)??new Set));let Te=0;if(b===zt){let ue=await this.matchContactRolesWrittenWithOpportunities(e,{working:u,aligned:_,refIndex:l,mapping:y,reused:k,withTheirRecord:Y,pendingFk:E,fixedAtInsert:S.get(b)??new Set});Te=ue.linked,z=ue.note}let Ee=Mt[b],Re=Ee?await this.startAsDrafts(i,b,Ee,be,O):be;if(b===Ye&&!Be&&ee.size>0){let ue=je=>ti(je,Fe=>l.get(Fe))&&ee.has(String(je.ActivityId));Z.push(...Re.filter(je=>ue(je.fields))),Re=Re.filter(je=>!ue(je.fields))}let le=Re.filter(ue=>!k.has(ue.referenceId)).length,oe=e.signal?.aborted===!0&&le>0,Ne=(ue,je,Fe=Le=>D.push(Le))=>this.insertObject(e,b,je,ue,l,y,k,E,J,G,V,Ed(D),Fe),dt=u.standardPricebook,Ie;if(oe)Ie={objectApiName:b,fromFiles:se,inserted:0,reused:Re.length-le,skippedDuplicates:[],failed:[],notInserted:le};else if(sn(b)&&dt){let ue=await Ne(Re.filter(Fe=>Fe.fields[mt]===dt),0),je=Re.filter(Fe=>Fe.fields[mt]!==dt);if(e.signal?.aborted){let Fe=je.filter(il=>k.has(il.referenceId)).length,Le={...ue,fromFiles:se,reused:ue.reused+Fe},Yt=Re.length-Le.inserted-Le.reused-Le.skippedDuplicates.length-Le.failed.length;Ie={...Le,...Yt>0?{notInserted:Yt}:{}}}else{let Fe={},Le=await Ne(je,se,Yt=>{Fe.result=Yt}).catch(Yt=>{throw D.push(Fe.result?Ho(ue,Fe.result):{...ue,fromFiles:se}),Yt});Ie=Ho(ue,Le)}}else Ie=await Ne(Re,se);ft=void 0,b===Ge&&B(),Ie=tt(Ie),Te>0&&(Ie={...Ie,writtenByThePlatform:Te});let Nt=b===Ye?Z.filter(ue=>!k.has(ue.referenceId)).length:0;(Ie.notInserted??0)>0&&(Ie.notInserted=(Ie.notInserted??0)+Nt);let vt=Ie.notInserted??0;D.push(Ie);let Ls=Rt(b,z),Cs=M(b),uo=Ie.failed.length>0,zs=uo?"error":"done";!uo&&vt>0&&(zs="stopped");let Ms=25+Math.round(55*te/Math.max(R.length,1)),fo=`${b}: ${Ie.inserted} inserted, ${Ie.reused} reused, ${Ie.skippedDuplicates.length} duplicates skipped, ${Ie.failed.length} failed${Cs}${qn(vt)}${An(Ie.writtenWithoutFields)}`;Cs&&vt===0?(he={status:uo?"error":"done",message:fo,notes:Ls,waiting:Nt},s({phase:"insert",objectName:b,status:"started",progress:Ms,message:fo})):s({phase:"insert",objectName:b,status:zs,progress:Ms,message:`${fo}${Ls}`}),b===Zt&&await ye(),vt>0&&await xe()}await ye(),await X(),s({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let ve={report:{resolved:0,unresolved:[]},unanswered:0},kt=Vo(x,b=>y.has(b)),en=new Set(kt.map(b=>b.opportunity)),lo=E.filter(b=>b.objectApiName!==Cr||b.field!==zr||!en.has(b.referenceId)),tn=kt.length>0?`, ${kt.length} synced quote${kt.length===1?"":"s"} left unset`:"",Ut=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(Ut({cause:b})),b}s(Ut());let Ue=ve.report;await X();let at={report:{restored:0,refused:[]},unanswered:0},hr=b=>_n({phase:"pass2",progress:89,did:`Statuses: ${at.report.restored} applied, ${at.report.refused.length} refused`,refused:at.report.refused.length,notDone:at.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,O,y,at)}catch(b){throw s(hr({cause:b})),b}let mr=at.report;mr.restored+mr.refused.length+at.unanswered>0&&s(hr()),await X();let $e=await et(),Kt={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 X(),await e.lease?.giveBack().catch(()=>{}),s({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await $();let yr=g.counts(),It=h.counts(),Ft=m.counts(),wr=this.writeContract(e,u,D,W,{now:r,startedAt:n},new Set(w.keys()),[...yr.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"left-to-the-platform"})),...It.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"untyped-feed-item"})),...Ft.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"excluded-parent"}))],we.size,V,Ue.unresolved.filter(b=>b.cause==="target-not-loaded"));s({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Vt=D.some(b=>b.failed.length>0)||Ue.unresolved.length>0||Kt.unresolved.length>0||mr.refused.length>0||C.failures.length>0,Ht=new Set(G.list().flatMap(({referenceIds:b})=>b)),br=await this.readBackRecordTypes(i,$d(d,b=>Ht.has(b)),y),Et={status:Vt?"completed-with-errors":"completed",orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:j,placeholders:W,requiredDefaults:ne,perObject:D,pass2:Ue,personContact:Kt,statuses:mr,purge:C,...yr.length>0?{leftToThePlatform:zn(yr)}:{},...It.length>0?{untypedFeedItems:It.map(({objectApiName:b,why:_,count:z})=>({objectApiName:b,count:z,note:Cd(z,_)}))}:{},...Ft.length>0?{heldForExcludedParents:Xd(Ft)}:{},...Yd(kt,this.config),...Ud(d.keysLeftEmpty),...br.length>0?{recordTypesGiven:br}:{},...P?{runUserId:P}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:wr};return s({phase:"done",status:Et.status==="completed"?"done":"error",progress:100,message:`Load ${Et.status}`}),Et}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 In(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new Ve("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 es(e,this.config.rootObjectApiName,t)}async reuseByIdentityKeys(e,t,r,n){for(let[s,i]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(a=>a.objectApiName===s)?.records??[];for(let[a,u]of await this.findByKeys(e.orgId,s,i,d))r.set(a,u),n.add(a)}}async findByKeys(e,t,r,n){let s=new Map,i=n.filter(l=>r.every(c=>!gt(l.fields[c])));if(i.length===0)return s;let d=["Id",...r].map(me).join(", "),a=new Map,u=100;for(let l=0;l<i.length;l+=u){let c=i.slice(l,l+u).map(p=>`(${r.map(g=>`${me(g)} = ${bl(p.fields[g])}`).join(" AND ")})`).join(" OR "),f=`SELECT ${d} FROM ${me(t)} WHERE ${c}`;for(let p of await this.deps.orgAccess.query(e,f))typeof p.Id=="string"&&a.set(Md(r.map(g=>p[g])),p.Id)}for(let l of i){let c=a.get(Md(r.map(f=>l.fields[f])));c&&s.set(l.referenceId,c)}return s}async linkWhatThePlatformKeeps(e,t,r,n,s,i,d){let a={linked:[],said:[],leftEmpty:[]};for(let[u,l]of Object.entries(jr)){let c=this.config.identityKeys?.[u]??l,f=(r.get(u)??[]).filter(g=>!i.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,i,a);p>0&&a.said.push(`${u}: ${p} found by ${c.join(", ")}, which the platform does not delete`)}return a}async reuseByKeysAsWritten(e,t,r,n,s,i,d,a){let u={linked:[],said:[],leftEmpty:[]};for(let[l,c]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(jr,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:a},i,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:i,keyFields:d}=t,a=Pl(t,this.config.requiredFieldDefaults??{}),u=a.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:i,fields:c,count:u.length}),s.said.push(`${i}: ${u.length} not looked up, ${c.join(", ")} left empty`)}let l=await this.findByKeys(e,i,d,a);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=[],i=t.standardPricebook;if(i){let[u]=await this.deps.orgAccess.query(e,Lt);typeof u?.Id=="string"?(r.set(i,u.Id),n.add(i),s.push("standard price book linked")):s.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),a=await this.matchSellingModelOptions(e,t,r,n);zd(t).includes(ze)&&d.push({objectApiName:ze,linked:a});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[i,d]of Object.entries(fn)){let a=t.objects.find(f=>f.objectApiName===i)?.records??[];if(a.length===0)continue;let u=a.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 pi(f=>this.deps.orgAccess.query(e,f),i,d,u.map(f=>f.fields))}catch(f){s.push({objectApiName:i,linked:0,notAsked:Q(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:i,linked:c})}return s}async matchSellingModelOptions(e,t,r,n){let s=[];for(let d of t.objects.find(a=>a.objectApiName===ze)?.records??[]){if(r.has(d.referenceId))continue;let a=d.fields[We],u=d.fields[He],l=typeof a=="string"?r.get(a):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,[He]:c}})}if(s.length===0)return 0;let i=await fi(d=>this.deps.orgAccess.query(e,d),s.map(d=>d.pair));for(let[d,a]of i)r.set(s[d].referenceId,a),n.add(s[d].referenceId);return i.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 i=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},a=(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,k]of g.mapping)m.has(y)||h.add(pe(k));return h}),p=new Set(f.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[k,N]of g.mapping){let T=pe(N);if(s.has(T)||i.has(T))continue;i.add(T);let j=wl(k);this.mayHaveLinked(j,k)||p.has(T)?u(j):j==="Pricebook2"&&!k.startsWith(Bn)?l.push(N):d(j,N)}return}let m=g.writtenBetween?xt(g.writtenBetween.last):xt(g.endedAt)+c+$i,y=new Map(Object.entries(g.removalStamps??{}).map(([k,N])=>[pe(k),xt(N)]));for(let{objectApiName:k,referenceIds:N}of g.created)for(let T of N){let j=g.mapping.get(T);if(j===void 0)continue;let x=pe(j);if(f[h].has(x)||i.has(x))continue;i.add(x);let U=s.get(x);if(U!==void 0){a(k,U);continue}if(this.keptByThePlatform(k)){n.keptByThePlatform[k]=(n.keptByThePlatform[k]??0)+1;continue}d(k,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,Lt);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 xt(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)),i=new Map;for(let[u,l]of r){let c=n.get(u);c===void 0||s.has(pe(l))||i.set(c,[...i.get(c)??[],l])}if(s.size===0||i.size===0)return[];let d=new Map,a=(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=i.get(c);if(!p)continue;let g;try{g=await this.readRecords(e,c,[f],p)}catch{for(let h of p)a(c,h,u);continue}for(let h of g){let m=h[f];typeof h.Id!="string"||typeof m!="string"||s.has(pe(m))&&a(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(Bn)?!1:e==="Unknown"||e===ze||Object.prototype.hasOwnProperty.call(fn,e)||Object.prototype.hasOwnProperty.call(jr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(jr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,s,i,d,a){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(),k=[...m,...y],N=new Set;try{N=await this.residualsInSight(e.orgId,u),await this.draftResiduals(e,t,l,h);for(let T of k){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,i.add(pe(j[w]))):n.failures.push({objectApiName:T,recordId:j[w],errors:S.errors})}),f+=U.length}else{let U=sn(T)?await this.customPricesFirst(e.orgId,j):T===kr?[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)=>{Ad(I)?(n.deleted[T]=(n.deleted[T]??0)+1,i.add(pe(S[A]))):n.failures.push({objectApiName:T,recordId:S[A],errors:I.errors})}),f+=w.length}}}await this.purgeAgain(e,k,n,i,h,a)}catch(T){throw await g(),p(),T}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,i,N),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,s]of t)try{for(let i of await this.readRecords(e,n,[],s))typeof i.Id=="string"&&r.add(pe(i.Id))}catch{}return r}async purgeAgain(e,t,r,n,s,i){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let a=r.failures.filter(l=>l.objectApiName===d).map(l=>l.recordId);if(a.length===0)continue;let u=sn(d)?await this.customPricesFirst(e.orgId,a).catch(()=>[a]):[a];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||(i.tried++,Ad(f)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(pe(l[p])),i.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(i=>i.objectApiName))){let i=t.failures.filter(h=>h.objectApiName===s).map(h=>h.recordId),d=h=>this.readRecords(e,s,[],h),{gone:a,unchecked:u,failure:l}=await Di(i,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(a.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,i]of Object.entries(Mt)){if(ci.has(s))continue;let d=t.residuals.get(s);if(!d||d.length===0)continue;let a=await this.statusCategories(e.orgId,i),u=a?.draft;if(!a||!u)continue;let l;try{l=await this.readRecords(e.orgId,s,["Status","LastModifiedDate"],d)}catch{continue}let c=l.flatMap(f=>{let p=a.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:xt(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),i={};for(let d of new Set(t.map(a=>a.objectApiName))){let a=t.filter(p=>p.objectApiName===d),u=new Map(a.map(p=>[pe(p.id),p])),l;try{l=await this.readRecords(e.orgId,d,["Status"],a.map(p=>p.id))}catch(p){for(let g of a)Td(r,g,`its status was not read back: ${Q(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+=Tt){let g=c.slice(p,p+Tt),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=Q(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let k=h[y];k?.success||Td(r,m,k?.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&&(i[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(i).length!==0)try{await this.deps.mappingStore.recordStamps(i)}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:i,keys:d}of t){let a=d.flatMap(u=>r.get(u)??[]);try{let u=await this.deps.orgAccess.query(e,Ga(s.objectApiName,a));n.push({...s,readBack:Ua(u,i.types)})}catch(u){let l=Q(u);n.push({...s,readBack:{read:0,types:[],unread:l}})}}return n}async readRecords(e,t,r,n){let s=["Id",...r].map(me).join(", "),i=[];for(let d=0;d<n.length;d+=Tt){let a=n.slice(d,d+Tt).map(u=>`'${Me(u)}'`).join(", ");i.push(...await this.deps.orgAccess.query(e,`SELECT ${s} FROM ${me(t)} WHERE Id IN (${a})`))}return i}async resolveRecordType(e,t,r,n,s,i,d){let a={...n.fields};r===Ke&&delete a[pn];let u=a.RecordTypeId;if(typeof u!="string"||u==="")return"RecordTypeId"in a&&d.set(n.referenceId,"masterInSource"),delete a.RecordTypeId,{referenceId:n.referenceId,fields:a};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 a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:a};if(f.length>1)throw Bd(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 Xe(`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 a.RecordTypeId,d.set(n.referenceId,"dropped"),i.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, ${hl(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:a}}return h?(a.RecordTypeId=h,s.set(n.referenceId,h),{referenceId:n.referenceId,fields:a}):(delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:a})}async planRequiredFields(e,t){let r=[],n=[];for(let s of t)for(let i of s.missingRequired){let d=`${i.objectApiName}.${i.field}`;if(!i.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let c=i.accountKind?` of a ${i.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${jl(i)} for this required field${c}`)}else r.push({kind:"default",missing:i});continue}let a=this.config.requiredLookupPlaceholders?.[d];if(!a){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${i.referenceTo.join(" or ")||"its parent"}`);continue}let u=a.targetObjectApiName??i.referenceTo[0];if(!u){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let l;if(a.recordTypeDeveloperName){let c=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,u,a.recordTypeDeveloperName);if(c!==null&&typeof c=="object"&&"ambiguous"in c){let f=c.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+ko(u,a.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 ${a.recordTypeDeveloperName} on ${u} is not available to the running user`);continue}if(l=c??void 0,!l){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} is not on ${u} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:i,key:d,name:a.name,targetObject:u,recordTypeId:l})}if(n.length>0)throw new Xe(`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:
11
+ - ${n.join(`
12
+ - `)}`,n);return r}async createPlaceholder(e,t,r,n,s,i){let{missing:d,key:a,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 Xe(`Placeholder insert failed for required lookup ${a} on ${u}: ${c?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let f=`${Bn}${u}:${a}`;n.set(f,c.id),i.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}`,i=this.config.requiredFieldDefaults?.[s],d=Xo(i,e.distinct),a=0;for(let u of t)gt(u.fields[e.field])&&(u.fields[e.field]=Zo(i,d,{referenceId:u.referenceId,rank:n.get(u.referenceId)??0}),a++);r.push({objectApiName:e.objectApiName,field:e.field,value:i,affectedRecords:a,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,s,i,d,a,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=Sl(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[L,v]of Object.entries(S.fields))if(!(v===""||v===null||v===void 0))if(typeof v=="string"&&s.has(v)){let P=i.get(v);P&&!(t===Cr&&L===zr)?w[L]=P:I.push({objectApiName:t,referenceId:S.referenceId,field:L,targetReferenceId:v})}else w[L]=v;let A=Qs(t,w);for(let L of A)delete w[L];a.push(...I.filter(L=>!A.includes(L.field)));for(let L of Gs(t,w))delete w[L];return w}),k=(S,w,I)=>{i.set(S,w),l.add(t,S,Rl.some(A=>A in I)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let N=await this.deps.writer.insert(e.orgId,t,y,(S,w)=>this.journalBatch(t,m,S,w)),T=[];N.forEach((S,w)=>{let I=m[w].referenceId;if(S.success&&S.id){k(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-N.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 ${jd(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,Q(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){k(S.referenceId,I.id,S.payload),g.writtenWithoutFields=Po(g.writtenWithoutFields,{rows:1,fields:S.fields.map(L=>({...L,rows:1}))});for(let{field:L,replacedWith:v}of S.fields){if(v!==void 0)continue;let P=c.get(t)??new Map;P.set(L,[...P.get(L)??[],S.referenceId]),c.set(t,P)}return}let A=[...I.errors,`Sent again ${jd(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((i,d)=>{let a=t[r+d];return i.success&&i.id&&a?[[a.referenceId,i.id]]:[]}))}sentAgain(e,t,r){let n=pa(r.errorDetails,t,void 0);if(!n)return;let s={...t},i=n.map(d=>{let a=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return a?.action==="replace"&&a.value!==""&&a.value!==t[d.field]?(s[d.field]=a.value,{...d,replacedWith:a.value}):(delete s[d.field],{...d})});return{payload:s,fields:i}}async matchDirectRelations(e,t,r,n,s,i){let d=new Map;for(let l of t.objects.find(c=>c.objectApiName==="Contact")?.records??[])d.set(l.referenceId,l.fields.AccountId);let a=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(a.length===0)return;let u=await li(l=>this.deps.orgAccess.query(e,l),a.map(l=>({AccountId:n.get(l.fields.AccountId),ContactId:n.get(l.fields.ContactId)})));for(let[l,c]of a.entries()){let f=u.get(l);typeof f=="string"&&(n.set(c.referenceId,f),s.add(c.referenceId),i.set(c.referenceId,c.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,s,i){let d=new Set(r.map(l=>l.referenceId)),a=new Map;for(let l of t.objects.find(c=>c.objectApiName===Ye)?.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&&a.set(c,{id:f,key:l.referenceId})}if(a.size===0)return;let u=await ri(l=>this.deps.orgAccess.query(e,l),[...new Set([...a.values()].map(l=>l.id))]);for(let[l,c]of a){let f=u.get(c.id);f!==void 0&&(n.set(l,f),s.add(l),i.set(l,c.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:s,reused:i}=t,d=w=>typeof w=="string"?s.get(w):void 0,a=new Map;for(let w of t.working.objects.find(I=>I.objectApiName===qd)?.records??[]){let I=s.get(w.referenceId),A=d(w.fields[yt]);I&&A&&!i.has(w.referenceId)&&a.set(I,A)}if(a.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=>a.get(w)).filter(w=>!i.has(r[w].referenceId));if(l.length===0)return{linked:0};let c=w=>{let I={},A=[];for(let[L,v]of Object.entries(w.fields))if(!(L==="OpportunityId"||L===yt)&&!t.fixedAtInsert.has(L)&&!(v===""||v===null||v===void 0))if(typeof v=="string"&&n.has(v)){let P=s.get(v);P?I[L]=P:A.push({objectApiName:zt,referenceId:w.referenceId,field:L,targetReferenceId:v})}else I[L]=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 oi(w=>this.deps.orgAccess.query(e.orgId,w),[...new Set([...f.values()].map(({opportunity:w})=>w))],p),{found:h,alike:m}=si(f,g),y=m.length>0?ii(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let k=w=>y?`${w}; ${y}`:w,N=[];for(let[w,I]of h){let A=r[w],L=String(I.Id);s.set(A.referenceId,L),i.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(([W,D])=>String(I[W]??"")!==String(D));C.length>0&&N.push({Id:L,...Object.fromEntries(C)})}let T=h.size,j=`${T} written by the platform with ${ni(zt)}`;if(N.length===0)return{linked:T,note:k(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:k(x(N.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",zt,N.length);let U=await this.deps.writer.update(e.orgId,zt,N),S=N.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:k(j)}:{linked:T,note:k(x(S.length,S[0]))}}async matchActivityRelations(e,t,r,n,s,i){let{orgId:d}=e,a=mo[t],u=c=>typeof c=="string"?n.get(c):void 0,l=await ai(c=>this.deps.orgAccess.query(d,c),t,r.map(c=>({[a]:u(c.fields[a]),RelationId:u(c.fields.RelationId)})));for(let[c,f]of l)n.set(r[c].referenceId,f),s.add(r[c].referenceId);return di(t,[...l].map(([c,f])=>[r[c].fields,f]),c=>!i.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 i=await this.statusCategories(e,r);return i?.draft?n.map(d=>{let a=rr(d.fields.Status,i);return a?(s.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:a}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=Tt){let s=t.slice(n,n+Tt).map(d=>`'${Me(d)}'`).join(", "),i=await this.deps.orgAccess.query(e,`SELECT Id FROM ${kr} WHERE Id IN (${s}) AND IsDirect = true`);for(let d of i)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await ui(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:i,referenceIds:d}of t.list()){let a=[...new Set(d.flatMap(l=>{let c=r.get(l);return c?[c]:[]}))],u=t.sentAuditDates(i);for(let l=0;l<a.length;l+=Tt){let c=await this.writtenDatesOf(e,i,a.slice(l,l+Tt));if(!c)return;for(let f of c){let p=xt(f.SystemModstamp),g=y=>{let k=u?Number.NaN:xt(f[y]);return Number.isFinite(k)?k: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=>`'${Me(s)}'`).join(", ");for(let s of kl)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${s.join(", ")} FROM ${me(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return tr(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:s}=n.report,i=new Map;for(let d of t){let a=r.get(d.referenceId);a&&i.set(d.objectApiName,[...i.get(d.objectApiName)??[],{...d,id:a}])}n.unanswered=[...i.values()].reduce((d,a)=>d+a.length,0);for(let[d,a]of i){if(e.signal?.aborted)continue;let u=a.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:a[f].referenceId,status:a[f].status,detail:c.errors.join("; ")})}),n.unanswered-=l.length}}async patchCycleFks(e,t,r,n){let{unresolved:s}=n.report,i=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=i.get(u.objectApiName)??new Map,p=f.get(l)??{Id:l};p[u.field]=c,f.set(l,p),i.set(u.objectApiName,f)}let a=u=>u.reduce((l,c)=>l+Object.keys(c).length-1,0);n.unanswered=[...i.values()].reduce((u,l)=>u+a([...l.values()]),0);for(let[u,l]of i){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-=a(c.slice(0,f.length))}}async linkPersonContacts(e,t,r,n,s,i){let d={linked:new Map,own:new Map,unlinked:[]},a=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&&a.set(p,[...a.get(p)??[],f])}let l=a.size===0||s===!1?new Map:await hn(f=>this.deps.orgAccess.query(e,f),[...a.keys()]),c=new Map;for(let[f,p]of a){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===""?Mr.accountNotInDataset:Mr.accountNotLoaded});continue}if(n.has(f.contactReferenceId))continue;let g=i.find(m=>m.objectApiName===Ke&&m.referenceId===f.accountReferenceId),h=Mr.noPersonAccounts;s!==!1&&(h=g?`${Mr.businessAccount}: ${g.detail}`:`${Mr.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,i,d,a=0,u=new Map,l=[]){let c=new Map;for(let{objectApiName:h,referenceId:m,field:y}of l){let k=c.get(h)??{};k[y]=[...k[y]??[],m],c.set(h,k)}let f=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let k=f.get(h)??{};k[y]=(k[y]??0)+m,f.set(h,k)}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,k)=>y+k,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===Ge?a:0,k=h.failed.filter(S=>Al(S.errors)).length;if(k>0&&(m["parent-refused"]=k),h.failed.length-k>y){let S=i.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[S]=h.failed.length-k-y}y>0&&(m["person-contact-not-sent"]=y);let N=0;for(let[S,w]of Object.entries(f.get(h.objectApiName)??{}))m[S]=w,N+=w;let T=h.skippedDuplicates.length+h.failed.length+N,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 cd(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 En(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 Sl(o,e,t,r){if(r.size===0)return;let n=new Set(o===Ye&&!go(e,s=>t.get(s))?["ActivityId"]:[]);for(let[s,i]of Object.entries(e)){if(typeof i!="string"||n.has(s)||!t.has(i))continue;let d=r.get(i);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 Al(o){return o.length===1&&o[0].startsWith("PARENT_REFUSED:")}function gt(o){return o==null||o===""}var Gd=/\{(n|referenceId)\}/g;function Xo(o,e){if(typeof o=="string")return o.match(Gd)?"token":e}function Zo(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 Pl(o,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:s}=o,i=o.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return o.records.map(d=>{let a={...d.fields};for(let u of i){let l=e[`${t}.${u.field}`];l===void 0||!gt(a[u.field])||Wn(u,[d],s).length!==0&&(a[u.field]=Zo(l,Xo(l,u.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:a}})}function Ud(o,e=!1){return o.length===0?{}:{keysLeftEmpty:o.map(({objectApiName:t,fields:r,count:n})=>{let s=n===1?"its":"their",i=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: ${i} 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: ${i} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function Tl(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 Kd(o){let e=Qo(o),t=new Map(o.objects.map(n=>[n.objectApiName,n.records])),r=new Set;return new Set([...Vd(t,r),...Hd(t,r,Wd(o,e),n=>e.get(n))])}function Vd(o,e){let t=(o.get(zt)??[]).filter(a=>!e.has(a.referenceId));if(t.length===0)return new Set;let r=new Map,n=a=>{if(typeof a!="string"||a==="")return;let u=r.get(a);return u===void 0&&(u=String(r.size+1).padStart(15,"0"),r.set(a,u)),u},s=new Set((o.get(Ge)??[]).map(a=>a.referenceId)),i=new Map;for(let a of o.get(qd)??[]){if(e.has(a.referenceId))continue;let u=a.fields[yt];typeof u!="string"||!s.has(u)||i.set(n(a.referenceId),n(u))}if(i.size===0)return new Set;let d=t.map(a=>({OpportunityId:n(a.fields.OpportunityId),[yt]:n(a.fields[yt]),IsPrimary:a.fields.IsPrimary}));return new Set(ho(d,a=>i.get(a)).map(a=>t[a].referenceId))}function Hd(o,e,t,r){let n=l=>(o.get(l)??[]).filter(c=>!e.has(c.referenceId)),s=new Set,i=new Map;for(let l of n(Ge))t.has(l.referenceId)||i.set(l.referenceId,l.fields.AccountId);let d=new Set((o.get("Account")??[]).map(l=>l.referenceId));for(let l of n(kr)){let{AccountId:c,ContactId:f}=l.fields;typeof c!="string"||typeof f!="string"||i.get(f)===c&&d.has(c)&&s.add(l.referenceId)}let a=new Set([...o.values()].flatMap(l=>l.map(c=>c.referenceId))),u=new Set(n(Zt).map(l=>l.referenceId));for(let l of n(Ye)){let c=l.fields.ActivityId,f=l.fields.RelatedToId;typeof c!="string"||!u.has(c)||typeof f!="string"||!a.has(f)||go(l.fields,r)||s.add(c)}return s}function Nd(o,e,t){let{working:r,loading:n,alignedByObject:s,reused:i,reusedByKeys:d,alignment:a,ranks:u}=o,l=o.targetHasPersonAccounts===!1?new Set:o.personContacts,c=w=>(s.get(w)??[]).filter(I=>!i.has(I.referenceId)),f=[...new Set([...o.groupOrder,...r.objects.map(w=>w.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=Vd(s,i),h=Hd(s,i,l,w=>o.refIndex.get(w)),m=[];for(let w of f){let I=r.objects.find(F=>F.objectApiName===w)?.records.length??0,A=e?.residuals.get(w)?.length??0;if(I===0&&A===0)continue;let L=s.get(w),P=(L??n.objects.find(F=>F.objectApiName===w)?.records??[]).filter(F=>i.has(F.referenceId)),C=P.filter(F=>d.has(F.referenceId)).length,W=L?c(w):[],D=W.filter(F=>l.has(F.referenceId)).length;p+=D;let G=W.filter(F=>g.has(F.referenceId)||h.has(F.referenceId)).length,V=(o.filteredLookups.get(w)??[]).flatMap(({field:F,referenceTo:q})=>{let Y=W.filter(ie=>!gt(ie.fields[F])).length;return Y>0?[{field:F,referenceTo:q,records:Y}]:[]}),H=t.undeletableObjects[w]!==void 0;m.push({objectApiName:w,fromFiles:I,toInsert:W.length-D-G,reusedByKeys:C,reusedFromCatalog:P.length-C,...G>0?{writtenByThePlatform:G}:{},fieldsDropped:a.removals.filter(F=>F.objectApiName===w).length,picklistsRewritten:a.adjustments.filter(F=>F.objectApiName===w).length,notSent:I-(L?L.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])),k=(w,I)=>y(w,I).length,N=w=>{let I=Wn(w,y(w.objectApiName,w.field),o.accountKindOf),A=t.requiredFieldDefaults[`${w.objectApiName}.${w.field}`],L=Xo(A,w.distinct),v=I[0];return{objectApiName:w.objectApiName,field:w.field,affectedRecords:I.length,...L?{perRecord:L}:{},...L&&v?{example:String(Zo(A,L,{referenceId:v.referenceId,rank:u.get(v.referenceId)??0}))}:{}}},T=e?.leftUnrecorded??{},j=e?.keptByThePlatform??{},x=o.heldForExclusions.counts(),U=$d(o,w=>!i.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:a.excludedObjects,removals:a.removals,placeholders:o.plans.flatMap(w=>w.kind==="placeholder"?[{objectApiName:w.missing.objectApiName,field:w.missing.field,placeholderObjectApiName:w.targetObject,placeholderName:w.name,affectedRecords:k(w.missing.objectApiName,w.missing.field)}]:[]),requiredDefaults:o.plans.flatMap(w=>w.kind==="default"?[N(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:Xd(x)}:{},...Yd(Vo(s,w=>S.has(w)),t,!0),...Ud(o.keysLeftEmpty,!0),...U.length>0?{recordTypesGiven:U}:{}}}var Ld=5;function jl(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 Yd(o,e,t=!1){let r=Sd(o,(e.excludedObjects??[]).includes(Ko),t);return r?{quotesLeftUnsynced:[r]}:{}}function Fl(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...e.get(n)??[]],d=s.filter(a=>!t.some(u=>u.leaveOut(n,a.referenceId,a.fields,i)));d.length!==s.length&&(o.set(n,d),r=!0)}}}function El(o,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let s of e.fields){let i=s.referenceTo??[];i.length===0||!i.every(d=>r.has(d))||!s.createable||s.defaultedOnCreate||Jt(o,s.name,s.nillable)&&(t.requiredLookupPlaceholders?.[`${o}.${s.name}`]||n.push({field:s.name,excludedObject:i[0]}))}return n}function Nl(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 Jd(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 Xd(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:Jd(r,t)}))}var Ll={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function Cl(o,e){if(o!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:Ll}function Cd(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 Qo(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 zl(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 i of n.records)for(let[d,a]of Object.entries(i.fields))if(!(n.objectApiName===Ke&&d===pn)&&typeof a=="string"){let u=e.get(a);u&&u!==n.objectApiName&&s.add(u)}r.set(n.objectApiName,s)}t.size>0&&r.has(Ke)&&r.get(Ge)?.add(Ke);for(let{sourceObject:n,targetObject:s}of fa(new Set(r.keys()),[]))r.get(s)?.add(n);for(let{sourceObject:n,targetObject:s}of ei(new Set(r.keys())))r.get(n)?.delete(s),r.get(s)?.add(n);return r}function Ml(o,e,t,r=new Map){let n=new Map;for(let[s,i]of o){let d=e.get(s),a=new Set;if(d)for(let u of i)for(let l of d){let c=u.fields[l],f=typeof c=="string"?t.get(c):void 0;f&&f!==s&&a.add(f)}n.set(s,a)}return r.size>0&&n.set(Ge,new Set([...n.get(Ge)??[],Ke])),n}function Dl(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,He,Xt],s=[We,He],i=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(qe),a=d.filter(h=>e.has(h.referenceId)&&i(h.fields,We)),u=o.standardPricebook,l=h=>u!==void 0&&h.fields[mt]===u,c=new Set(a.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([...a,...f].filter(h=>i(h.fields,He)).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 zd(o){return[...Object.keys(fn),ze].filter(e=>o.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function xl(o,e){for(let t of o.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function Md(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 es(o,e,t){if(!e)throw new Xe("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 Xe(`Pilot root ${t??"<first>"} not found in ${e} records (${r.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let s=Qo(o),i=new Set([n]),d=!0;for(;d;){d=!1;for(let l of o.objects)for(let c of l.records)i.has(c.referenceId)||Object.values(c.fields).some(f=>typeof f=="string"&&i.has(f))&&(i.add(c.referenceId),d=!0)}let a=l=>{for(;l.length>0;){let c=l.pop(),f=xl(o,c);if(f)for(let p of Object.values(f.fields))typeof p=="string"&&s.has(p)&&!i.has(p)&&(i.add(p),l.push(p))}};a([...i]);let u=Dl(o,i).filter(l=>!i.has(l));for(let l of u)i.add(l);return a(u),{...o,objects:o.objects.map(l=>({...l,records:l.records.filter(c=>i.has(c.referenceId))})).filter(l=>l.records.length>0)}}import{randomBytes as $l}from"node:crypto";import{readFile as _l}from"node:fs/promises";var ts="frozen.salt";function Bl(){return $l(32).toString("base64url")}function Zd(o){let e=o[Ba];return e?{salt:e,source:"environment"}:void 0}function hp(o,e=process.env){let t=async()=>{let r=Zd(e);if(r)return r;let n=await o.getSecret(ts);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=Bl();if(await o.storeSecret(ts,n),await o.getSecret(ts)!==n)throw new Tr;return{salt:n,source:"secretStorage",created:!0}}}}function Qd(o=process.env,e){let t=async()=>{let r=Zd(o);if(r)return r;if(e===void 0)return;let n=(await _l(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new Tr;return r}}}import{createHash as ql}from"node:crypto";import{appendFileSync as Wl,mkdirSync as Gl,readFileSync as Ul}from"node:fs";import*as $r from"node:path";var Kl=15*6e4;function Gn(o){return`sha256:${ql("sha256").update($r.resolve(o)).digest("hex").slice(0,16)}`}function ec(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 Vl(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+Kl})}function tc(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:Vl(n,e.own)))continue;let s=Date.parse(r.lastWriteAt??""),i=Number.isFinite(s)?s:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,i):i,to:i})}return t}var rc="frozen-loads.ndjson";function bp(o,e){Gl(o,{recursive:!0}),Wl($r.join(o,rc),`${JSON.stringify(e)}
13
+ `)}function Hl(o,e){return o.slice(0,15)===e.slice(0,15)}function Rp(o,e){let t;try{t=Ul($r.join(o,rc),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
14
+ `)){if(n.trim()==="")continue;let s;try{s=JSON.parse(n)}catch{continue}let{organizationId:i,sas:d,startedAt:a,endedAt:u,lastWriteAt:l}=s??{};typeof i!="string"||typeof u!="string"||Hl(i,e)&&r.push({endedAt:u,...typeof d=="string"?{sas:d}:{},...typeof a=="string"?{startedAt:a}:{},...typeof l=="string"?{lastWriteAt:l}:{}})}return r}function nc(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 Yl="FROZEN_EMAILS_EXCEEDED";function Ap(o,e){return[...Ea(o.counted,e),...o.uncounted!==void 0?[` emails: not counted, ${o.uncounted} could not be read`]:[],...o.deliverability?[` ${Ca(o.deliverability.reading)}`]:[]]}function Jl(o){return typeof o.unread=="string"}async function oc(o){let{read:e,plan:t,writes:r,target:n}=o,s=await ea({read:e,...t?{plan:t}:{},writes:r,readDeliverability:o.readDeliverability,accepted:o.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:o.mayMute}),i=[],d;if(Jl(e))d=`the target's automation: ${e.unread}`;else{let c=Ct(e,t,r).automation,f={objects:o.inserts.map(g=>({...g,storageBytes:0}))};d=ja(c,Ta(f));let p=Vs(c);if(p.length>0){let g=await o.readLimits().catch(h=>({unread:Q(h)}));i=Pa(f,p,g)}}let a=Fa(i,n),u=a?{code:Yl,message:`${a} Nothing was written.`}:s.gate.stop,{deliverability:l}=s.gate;return{run:s,info:{counted:i.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 Xl="AUTOMATION_NOT_ACCEPTED";function Zl(o){let e=new Set(o);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function Ql(o){return typeof o.unread=="string"}function eu({kind:o,name:e}){return o==="flow"?`flow "${e}"`:o==="process"?`process "${e}"`:o==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var sc={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function ic(o){return`${o.objectApiName}: ${eu(o)} (${o.writes.join(", ")})`}function tu(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(ic).join("; ")}.`);for(let{part:n,reason:s}of o.unread??[]){let i=sc[n];r.push(`${i[0].toUpperCase()}${i.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 rs(o){let{read:e,target:t}=o,r=Zl(o.written),n=[],s=[],i=[];if(Ql(e))s=[{part:"automation",reason:e.unread}];else{let u=Ct(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=Da(e);let c=Ma(u.automation,za(u.automation,[...o.written])),f=[...new Set(c.flatMap(p=>p.permissionSet??[]))];i=[...xa(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 a={code:Xl,message:tu(d,t,i)};return{info:{...d,refused:a},stop:a}}function Fp(o,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...o.firing.map(t=>` ${ic(t)}`),...(o.unread??[]).map(({part:t,reason:r})=>` ${sc[t]} could not be read: ${r}`),...o.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}import{existsSync as af}from"node:fs";import*as Se from"node:fs/promises";import*as rl from"node:os";import*as Pe from"node:path";var dr=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
15
+ - ${r.join(`
16
+ - `)}`:t);this.violations=r;this.name="RulesFileError"}violations},ru=/^\d+\.\d+\.\d+$/,ac=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,nu=new Set(No);function ns(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Un(o){let e=[];if(!ns(o))throw new dr("Rules file must be a JSON object");let t=o.rulesVersion;(typeof t!="string"||!ru.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=o.rules;if(!ns(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new dr("Invalid rules file",e);let n={};for(let[s,i]of Object.entries(r)){if(!ac.test(s)){e.push(`"${s}": key must match "ObjectApiName.FieldApiName"`);continue}if(!ns(i)){e.push(`"${s}": rule must be an object with a "generator" property`);continue}let d=i.generator;if(typeof d!="string"||!nu.has(d)){e.push(`"${s}": unknown generator ${JSON.stringify(d)} (supported: ${No.join(", ")})`);continue}let a=i.approved===!0;if(d==="keep"&&!a){e.push(`"${s}": generator "keep" requires "approved": true (explicit human review)`);continue}let u={generator:d};i.approved!==void 0&&(u.approved=a),typeof i.comment=="string"&&(u.comment=i.comment),n[s]=u}if(e.length>0)throw new dr("Invalid rules file",e);return{rulesVersion:t,rules:n}}function dc(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)}
17
+ `}var cc={rulesVersion:"1.0.0",rules:{}};function lc(o){if(o===null)return{found:!1};try{let e=Un(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 ou=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],su=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...ou.flatMap(o=>[`BusinessHours.${o}StartTime`,`BusinessHours.${o}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),iu=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":su.has(r)||iu.has(t)||o.keptBySchema?.has(r)===!0?"keep":"clear")}function uc(o,e,t){let r=new Set(o.keptBySchema??[]),n=new Set(o.personalBySchema??[]);for(let[s,i]of e){let d=new Set(t.detectPII(s,i.map(a=>({apiName:a.name,label:a.label??a.name,type:a.type}))).piiFields.map(a=>a.fieldApiName));for(let a of i){let u=`${s}.${a.name}`;d.has(a.name)?n.add(u):a.type==="picklist"&&(a.restrictedPicklist===!0||a.nillable===!1)&&a.compoundFieldName===void 0&&r.add(u)}}return{...o,keptBySchema:r,personalBySchema:n}}function fc(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 i=`${r.objectApiName}.${s}`;e.rules[i]===void 0&&ut(e,r.objectApiName,s)==="keep"&&t.add(i)}return[...t].sort()}function pc(o,e,t){let r=[];for(let n of o.objects){let s=t.get(n.objectApiName)??[];for(let l of s){let c=ln(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&&!er(c,gn(p.fields,!1)))return!1;let g=p.fields[l.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${l.name}`)}let i=n.objectApiName,d=dn(i,l=>s.some(c=>c.name===l&&c.createable!==!1),l=>ut(e,i,l)!=="clear"),a=`${i}.${d}`;d!==void 0&&n.records.some(l=>{let c=l.fields[d];return c!=null&&c!==""})&&!r.includes(a)&&r.push(a)}return r.sort()}var au="Cleared on review of the extraction result: kept in clear text without a rule before.";function gc(o,e){let t=Un(o),r=e.filter(u=>!ac.test(u));if(r.length>0)throw new dr('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(u=>JSON.stringify(u)));let n=o,s={...n.rules},i=[],d=[];for(let u of[...new Set(e)].sort()){if(t.rules[u]!==void 0){d.push(u);continue}s[u]={generator:"clear",comment:au},i.push(u)}let a=i.length>0?du(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:a,rules:s},rulesVersion:a,cleared:i,alreadyRuled:d}}function du(o){let[e,t]=o.split(".").map(Number);return`${e}.${t+1}.0`}import*as hc from"node:fs/promises";import*as mc from"node:path";var os=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,yc=/^[A-Z][A-Z0-9_]*$/,jt=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function _r(o,e){for(let i of Object.keys(e))if(!yc.test(i))throw new jt(`Invalid token name ${JSON.stringify(i)}`);let t=new Set;for(let i of o.matchAll(os))t.add(i[1]);let r=[...t].filter(i=>!(i in e));if(r.length>0)throw new jt(`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(os,(i,d)=>e[d]),s=n.match(os);if(s)throw new jt(`Unresolved placeholder(s) after render: ${s.join(", ")}`);return n}async function wc(o,e,t){let n=(t??new de).assertOutsideRepo(mc.join(o,e)),s=JSON.parse(await hc.readFile(n,"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))throw new jt(`Token file ${n} must contain a JSON object`);let i={};for(let[d,a]of Object.entries(s)){if(!yc.test(d))throw new jt(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof a!="string")throw new jt(`Token ${d} in ${n} must be a string`);i[d]=a}return i}var Br=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function cu(o,e){return e?e.aborted?(o.catch(()=>{}),Promise.reject(new Br)):new Promise((t,r)=>{let n=()=>r(new Br);e.addEventListener("abort",n,{once:!0}),o.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),r(s)})}):o}var lu=2500,uu=3,fu=5;function pu(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,fu).map(([t,r])=>({objectApiName:t,count:r}))}var _t=class extends Error{constructor(t,r,n,s){let i=pu(t,s),d=i.map(u=>`${u.objectApiName} ${u.count}`),a=i.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(i.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}. ${a}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},ss=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},Kn=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??lu,n=e.candidatesPerCombination??uu,s=me(e.rootObject),{signal:i}=t,d=p=>t.onProgress?.(p),a=[],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 _t(p,g,r,s);return{roots:a,uncovered:u,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:i?.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:i,tell:d},{roots:a,uncovered:u,ownMeasures:l,at:c})}catch(p){if(p instanceof Br)return f();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:s,candidateLimit:i,signal:d,tell:a}=t,{roots:u,uncovered:l,ownMeasures:c,at:f}=r,p=j=>cu(j,d),g=new Map,h=new Map;for(let j of e.axes)a({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?[[]]:mu(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 k=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,i,e.tokens,{step:p,onCandidate:U=>{f.candidate=U,a({phase:"candidate",combinationKey:j,candidate:U,candidates:i})}}));for(let[j,x]of m.entries()){let U=y(x);a({phase:"combination",combinationKey:U,index:j+1,of:m.length});let S=x.map(A=>{let L=me(e.axes.find(v=>v.name===A.axis)?.filterField??"");return A.value===null?`${L} = NULL`:`${L} = ${hu(A.value,h.get(A.axis))}`}).join(" AND "),w=await k(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:bc(w,i)})}for(let[j,x]of e.edgeCases.entries()){let U=`edge:${x.name}`;a({phase:"combination",combinationKey:U,index:j+1,of:e.edgeCases.length});let S=await k(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":bc(S,i)})}f.during="measure",f.combinationKey=void 0,f.candidate=void 0,u.length>0&&a({phase:"measure",roots:u.length});let N=u.length===0?{}:await p(this.deps.measureVolumetry(u.map(j=>j.rootRecordId))),T=Object.values(N).reduce((j,x)=>j+x,0);if(T>s)throw new _t(N,T,s,n);return{roots:u,uncovered:l,volumetry:{measured:N,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 i of n){if(!("axisValue"in i))throw new ss(`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=i.axisValue;d==null?s.push(null):typeof d=="string"?s.push(d):s.push(String(d))}return[...new Set(s)].sort((i,d)=>(i??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,s){let i=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(i,n??{}))),a=0,u;for(let l of d){let c=l.Id;if(typeof c!="string"||c==="")continue;a++,s.onCandidate(a);let f=await s.step(this.deps.checkHealth.check(c));if(f.healthy)return{id:c,probed:a,...f.measured?{measured:f.measured}:{}};u=f.reason}return{id:null,probed:a,lastReason:u}}};function bc(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 gu=new Set(["int","long","double","currency","percent"]);function hu(o,e){let t=`'${Me(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&&gu.has(e)&&/^-?\d+(\.\d+)?$/.test(o)?o:t}}function mu(o){let e=[[]];for(let{axis:t,values:r}of o){let n=[];for(let s of e)for(let i of r)n.push([...s,{axis:t,value:i}]);e=n}return e}var Vn=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 cr from"node:fs/promises";import*as is from"node:path";var qr="selection.json";async function Rc(o,e,t){let r=t??new de,n=r.assertOutsideRepo(o);await cr.mkdir(n,{recursive:!0});let s=r.assertOutsideRepo(is.join(n,qr));return await cr.writeFile(s,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
18
+ `,"utf8"),s}async function as(o,e){let r=(e??new de).assertOutsideRepo(is.join(o,qr)),n=JSON.parse(await cr.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 lr from"node:fs/promises";import*as ds from"node:path";var kc="discovery.json",wu=1440*6e4,bu=nt({name:Ce(),fields:ht(nt({name:Ce(),type:Ce(),referenceTo:ht(Ce())}).loose()),childRelationships:ht(nt({childSObject:Ce(),field:Ce(),relationshipName:Ce()}).loose())}).loose(),Ru=nt({fileVersion:_s(1),sourceOrgId:Ce().min(1),rootObject:Ce().min(1),maxNodes:Ds().int().positive(),step:$s(["select","extract"]),discoveredAt:po.datetime(),schemaStamp:po.datetime().optional(),graph:nt({nodes:ht(nt({objectApiName:Ce(),included:rn()}).loose()),edges:ht(nt({sourceObject:Ce(),targetObject:Ce()}).loose())}).loose(),describes:xs(Ce(),bu),objects:ht(nt({name:Ce(),keyPrefix:Ce().nullable()}))});async function Ic(o,e,t=new de){let r=t.assertOutsideRepo(o);await lr.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(ds.join(r,kc));return await lr.writeFile(n,`${JSON.stringify(e)}
19
+ `,"utf8"),n}async function vc(o,e=new de){let t=e.assertOutsideRepo(ds.join(o,kc)),r;try{r=await lr.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=Ru.safeParse(n);return s.success?{kept:s.data}:{none:"the graph kept in the sas could not be read"}}function Oc(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<=wu))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 Sc(o){let e=Date.parse(o);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as Yn from"node:fs/promises";import*as Ac from"node:path";var ku="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Iu="rt-map.json",vu=10;function Ou(o,e){return Ar.has(o)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>Ar.has(r))?{...t,nillable:!0}:t)}function Bt(o){if(!("attributes"in o))return o;let e={...o};return delete e.attributes,e}var cs=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),ua(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Wr(o,e){return e.filter(t=>t.type==="reference"&&Jt(o,t.name,t.nillable)).map(t=>t.name)}function Su(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 Au=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,Hn=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Gr=class{deps;soqlBuilder=new ia;constructor(e){this.deps=e}query(e){return ki(e,t=>this.deps.query(t))}async extract(e){if(!Au.test(e.asOf))throw new Hn(`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 Hn("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new de,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,s=new Lo;s.add(e.rootObject,e.rootRecordIds),s.addReached(e.rootObject,e.rootRecordIds);let i=new Map,d=new Qt,a=new Set,u={},l=new cs(this.deps.keyPrefixes),c=new Map,f=async I=>{let A=c.get(I);if(A)return A;let L=await this.deps.describeFields(I);return c.set(I,L),L},p=async I=>{let A=await f(I);A.some(v=>v.name==="CreatedDate")||a.add(I);let L=A.filter(v=>v.type==="base64").map(v=>v.name);return L.length>0&&(u[I]=L),A},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(la(e.graph,g),f,g),m=h.graph,y=[...m.nodes].filter(I=>I.included).sort((I,A)=>I.level-A.level),k=new Set(y.map(I=>I.objectApiName));for(let I of y){let A=await p(I.objectApiName),L=this.selectFields(I.objectApiName,A,e.excludedFields),v=A.some(F=>F.name==="CreatedDate"),P=this.soqlBuilder.build({node:I,fields:Ou(I.objectApiName,A),selectFields:L,edges:m.edges,cache:s,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:v?n:void 0,everyEdge:!Ar.has(I.objectApiName),readObjects:k,catalog:Ar,fromAboveOnly:!0});if(!P.scoped)continue;let C=[],W=[];for(let[F,q]of P.statements.entries()){let Y=await this.query(q);if(C.push(...Y),!(F<P.byIdCount))for(let ie of Y)typeof ie.Id=="string"&&W.push(ie.Id)}let D=d.keep(I.objectApiName,await this.keepWhatStatusesNeed(h.added.get(I.objectApiName),C,i),Wr(I.objectApiName,A)),G=i.get(I.objectApiName);G||(G=new Map,i.set(I.objectApiName,G));let V=[];for(let F of D){let q=F.Id;typeof q!="string"||q===""||(V.push(q),G.has(q)||G.set(q,Bt(F)))}s.addRead(I.objectApiName,V);let H=new Set(V);s.addReached(I.objectApiName,W.filter(F=>H.has(F))),l.learnFrom(i);for(let F of A)if(F.type==="reference")for(let q of D){let Y=q[F.name];if(!(typeof Y!="string"||Y===""))for(let ie of await l.objectsOf(Y,F.referenceTo))s.add(ie,[Y])}I.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:A,selectFields:L,bucket:G,cache:s,owners:l,recordsByObject:i,leftToThePlatform:d,extraWhere:v?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:y,edges:m.edges,cache:s,recordsByObject:i,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},i,p,n,l,d,g),await Pu(i,p,d);let N=await this.addStandardPrices(e,i,n);await this.addSellingModelOptions({...e,graph:m},i,p,n,g);let T=(i.get(an)?.size??0)>0,j=await this.exclusionCosts(i,p,g,T),x=await this.leaveOutWhatReadsMasked(i,f),U=[...i.entries()].sort(([I],[A])=>I.localeCompare(A)).map(([I,A])=>{let L=[...A.values()].sort((P,C)=>String(P.Id).localeCompare(String(C.Id)));I===qe&&(L=Ws(L,{sellingModel:T}));let v=L.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 Yn.mkdir(r,{recursive:!0});let w=t.assertOutsideRepo(Ac.join(r,Iu));return await Yn.writeFile(w,`${JSON.stringify(S,null,2)}
20
+ `,"utf8"),{objects:U,asOf:e.asOf,recordTypeMap:S,unboundedObjects:[...a],fileFields:u,...N?{standardPricebookSourceId:N}:{},leftToThePlatform:d.counts(),...j.length>0?{exclusionCosts:j}:{},...x.length>0?{encryptedNotKept:x}:{}}}async leaveOutWhatReadsMasked(e,t){let r=Hi(Vi(s=>this.deps.query(s)),async s=>({fields:await t(s)})),n=[];for(let[s,i]of e)if(i.size!==0)for(let d of await r(s)){let a=!1;for(let u of i.values())d in u&&(a||=u[d]!==null&&u[d]!==void 0,delete u[d]);a&&n.push(`${s}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(a=>a.objectApiName)),s=new Map,i=[],d=[];for(let a of e.nodes){let u=nn[a.objectApiName];if(!a.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(a.objectApiName));c&&(s.set(u.object,{parent:a.objectApiName,lookup:c.name}),i.push(Su(u.object,l,a.level+1)),d.push({sourceObject:a.objectApiName,targetObject:u.object,relationshipName:c.name,type:"lookup",required:Jt(u.object,c.name,c.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...d]},added:s}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,s=new Set([...n.get(t)??[]].filter(a=>!r.has(a)));if(s.size===0)return;let i=[];for(let a of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:s,extraWhere:e.extraWhere}))i.push(...await this.query(a));let d=e.leftToThePlatform.keep(t,i,Wr(t,e.fields));for(let a of d)typeof a.Id=="string"&&!r.has(a.Id)&&r.set(a.Id,Bt(a));e.owners.learnFrom(e.recordsByObject);for(let a of e.fields)if(a.type==="reference")for(let u of d){let l=u[a.name];if(!(typeof l!="string"||l===""))for(let c of await e.owners.objectsOf(l,a.referenceTo))n.add(c,[l])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=Mt[e.parent],s=n?await tr(d=>this.query(d),n):void 0,i=new Set;for(let[d,a]of r.get(e.parent)??[])s&&rr(a.Status,s)&&i.add(d);return t.filter(d=>{let a=d[e.lookup];return typeof a=="string"&&i.has(a)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(nn)){let n=e.nodes.find(m=>m.objectApiName===r.object),s=e.recordsByObject.get(t),i=Mt[t];if(!n||!s||s.size===0||!i)continue;let d=e.cache.reachedOf(t),a=[...s].filter(([m])=>!d?.has(m));if(a.length===0)continue;let u=await tr(m=>this.query(m),i);if(!u)continue;let l=a.filter(([,m])=>rr(m.Status,u)).map(([m])=>m);if(l.length===0)continue;let c=await e.describe(r.object),f=new Lo;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=Wr(r.object,c);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let k of y)typeof k.Id=="string"&&!g.has(k.Id)&&g.set(k.Id,Bt(k))}}}async completeRequiredParents(e,t,r,n,s,i,d){let a=new Set(e.graph.nodes.filter(f=>f.included).map(f=>f.objectApiName)),u=ca(e.graph,d),l=f=>a.has(f)||u.has(f),c=new Map;for(let f=0;f<vu;f++){s.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&da(g,y));for(let y of h.values())for(let k of m){let N=y[k.name];if(typeof N!="string"||N===""||i.has(N)||!k.referenceTo.some(l))continue;let T=(await s.objectsOf(N,k.referenceTo)).filter(l);for(let j of T)t.get(j)?.has(N)||c.get(j)?.has(N)||p.set(j,(p.get(j)??new Set).add(N))}}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 k=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(T=>T.name==="CreatedDate")?n:void 0}),N=Wr(g,m);for(let T of k)for(let j of i.keep(g,await this.query(T),N))typeof j.Id=="string"&&!y.has(j.Id)&&y.set(j.Id,Bt(j))}}}async addStandardPrices(e,t,r){let n=t.get(qe);if(!n||n.size===0)return;let[s]=await this.query(Lt),i=typeof s?.Id=="string"?s.Id:void 0;if(!i)return;let d=g=>[We,He,Xt].map(h=>String(g[h]??"")).join("|"),a=new Set,u=new Set;for(let g of n.values()){if(g[mt]===i)continue;let h=g[We];typeof h=="string"&&h!==""&&(a.add(h),u.add(d(g)))}if(a.size===0)return;let l=async(g,h)=>{let m=await this.deps.describeFields(g),y=this.selectFields(g,m,e.excludedFields).map(N=>me(N)).join(", "),k=m.some(N=>N.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${k}`)},c=t.get(on);if(c||(c=new Map,t.set(on,c)),!c.has(i))for(let g of await l(on,`Id = '${Me(i)}'`))c.set(i,Bt(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:a},whole:{field:mt,ids:new Set([i])},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,Bt(h));return i}async addSellingModelOptions(e,t,r,n,s){if(s.has(ze)||e.graph.nodes.some(m=>m.objectApiName===ze&&!m.included))return;let i=t.get(qe),d=t.get(aa),a=t.get(an);if(!i||!d||!a)return;let u=m=>`${String(m[We]??"")}|${String(m[He]??"")}`,l=new Set,c=new Set,f=new Set;for(let m of i.values()){let y=m[We],k=m[He];typeof y!="string"||!d.has(y)||typeof k!="string"||!a.has(k)||(l.add(y),c.add(k),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:He,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,Bt(y))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let s=[],i=a=>`record${a===1?"":"s"}`,d=new Map;for(let[a,u]of e){if(u.size===0)continue;let l=(await t(a)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==a&&r.has(g.referenceTo[0])&&Jt(a,g.name,g.nillable)),c=a===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 N of l){let T=h[N.name],j=N.referenceTo[0];if(!(typeof T!="string"||T==="")&&!e.get(j)?.has(T)){m={field:N.name,excluded:j};break}}let y=h[He];if(!m&&c&&typeof y=="string"&&e.get(an)?.has(y)&&(m={field:He,excluded:ze}),!m)continue;f.set(g,m.excluded);let k=p.get(m.excluded)??{field:m.field,count:0};k.count++,p.set(m.excluded,k)}f.size>0&&d.set(a,f);for(let[g,{field:h,count:m}]of p)s.push({objectApiName:a,excludedObject:g,count:m,note:g===ze?`${m} ${a} ${i(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${a} ${i(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[a,u]of Object.entries(nn)){let l=e.get(a),c=Mt[a];if(!l||l.size===0||!c)continue;let f=await tr(y=>this.query(y),c);if(!f)continue;let p=new Set,g=new Map,h=d.get(u.object);for(let[y,k]of e.get(u.object)??[]){let N=k[u.lookup];if(typeof N!="string")continue;let T=h?.get(y);T?g.has(N)||g.set(N,T):p.add(N)}let m=new Map;for(let[y,k]of l){if(!rr(k.Status,f))continue;let N=r.has(u.object)?u.object:p.has(y)?void 0:g.get(y);N&&m.set(N,(m.get(N)??0)+1)}for(let[y,k]of m){let N=k===1;s.push({objectApiName:a,excludedObject:y,count:k,note:`${k} ${a} ${i(k)} past Draft will be loaded as ${N?"a draft":"drafts"} and stay so: `+(y===u.object?`the platform gives ${a} this status only with ${u.object} records under it, and excludedObjects leaves ${u.object} out`:`none of ${N?"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(i=>i.name).filter(i=>!n.has(i));return s.includes("Id")||s.unshift("Id"),s}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??ku,r=_r(t,e.tokens??{}),n=await this.query(r),s=[];for(let i of n)typeof i.Id=="string"&&typeof i.SobjectType=="string"&&typeof i.DeveloperName=="string"&&typeof i.Name=="string"&&s.push({id:i.Id,sobjectType:i.SobjectType,developerName:i.DeveloperName,..."NamespacePrefix"in i?{namespacePrefix:typeof i.NamespacePrefix=="string"&&i.NamespacePrefix!==""?i.NamespacePrefix:null}:{},name:i.Name});return s}};async function Pu(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...s.values()],d=Wr(n,await e(n)),a=t.keep(n,i,d);if(a.length===i.length)continue;r=!0;let u=new Set(a.map(l=>l.Id));for(let l of s.keys())u.has(l)||s.delete(l)}}}var Jn=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))},i=new Map;for(let c of s.objects)for(let f of c.records)i.set(f.sourceId,f.referenceId);let d=new Map(s.recordTypeMap.map(c=>[c.id,c])),a={};for(let c of s.objects)a[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,i,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?i.get(s.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:u,recordTypes:a,personContactSidecar:Tu(s,i),...l?{standardPricebook:l}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,s,i){let d={};for(let[a,u]of Object.entries(t)){if(a==="Id")continue;if(u==null){d[a]=u;continue}if(a==="RecordTypeId"&&typeof u=="string"){let c=n.get(u);d[a]=c?c.name:"";continue}if(typeof u=="string"){let c=r.get(u);if(c!==void 0){d[a]=c;continue}}let l=ut(s,e,a);d[a]=i.pseudonymize(l,u)}for(let[a,u]of Object.entries(d))typeof u=="string"&&wn(u)&&(d[a]="");return d}};function Tu(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 i=e.get(s);i!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:i})}return t}var ju=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,Fu=/^\+3363998\d{4}$/,Eu=/^[a-z0-9-]+@example\.invalid$/,Nu=/^\d{2}0+$/,Lu=3,Xn=class{run(e,t,r,n={}){let s=new Set,i=new Map;for(let c of t.objects)for(let f of c.records)s.add(f.referenceId),i.set(f.referenceId,{objectApiName:c.objectApiName,record:f});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},a=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=i.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"?a.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,i,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,i){for(let[d,a]of Object.entries(t.fields)){if(d==="Id"||a===null||a===void 0||a===""||ut(n,e,d)==="keep")continue;let l=r.fields[d];if(Cu(l,a)){s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof a=="string"&&a.length>=Lu)for(let[c,f]of Object.entries(r.fields))c===d||typeof f!="string"||f!==a||ut(n,e,c)==="keep"||c==="RecordTypeId"&&i.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[i,d]of Object.entries(t.fields))i!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||ut(r,e,i)==="clear"&&d!==""&&d!==null&&d!==void 0&&s.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:i,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,s){let i={registrationSIV:d=>ju.test(d),phoneE164:d=>Fu.test(d),email:d=>Eu.test(d),postalCodeGeneralize:(d,a)=>Nu.test(d)&&d.length===a.trim().length};for(let d of e.objects)for(let a of d.records){let u=n.get(a.referenceId);if(u)for(let[l,c]of Object.entries(a.fields)){if(typeof c!="string"||c==="")continue;let f=ut(r,d.objectApiName,l),p=i[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:a.referenceId,field:l,detail:`format not conserved for ${f}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[s,i]of Object.entries(t.fields))typeof i=="string"&&wn(i)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:s,detail:"checksum-valid Salesforce ID survived the sweep"})}};function Cu(o,e){return o===e?!0:o==null||e===null||e===void 0?!1:String(o)===String(e)}var Ur=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let s=n===void 0?Oi(r):{namespacePrefix:n,developerName:r},i=`${e}|${t}|${String(s.namespacePrefix)}|${s.developerName}`,d=this.cache.get(i);if(d!==void 0)return d;let a=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${Me(t)}' AND DeveloperName = '${Me(s.developerName)}'`,u=vi(await this.orgAccess.query(e,a)),l=Si(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(i,c),c}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(i=>i.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return jn(yn((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 eo from"node:fs";var zu=2e3,Mu=3,Du=10,xu=o=>new Promise(e=>setTimeout(e,o)),Zn=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new de}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??xu,n=g=>e.onProgress?.(g),s=e.measurementIntervalMs??zu,i=e.maxAttempts??Mu,d=Nn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let a=null,u=null,l=null,c=0;for(let g=1;g<=i;g++){c=g,l=await this.measure(e,d);let h=ls(l);if(a!==null&&h===a){u=l;break}a=h,g<i&&await r(s)}let f=this.buildChecks(e,d,u??l,u!==null),p={status:Gu(f,d,u),checks:f,attempts:c,measuredAt:t().toISOString(),objects:Uu(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?Tc(e.mapping):void 0,n={};for(let s of Object.keys(t.objects).sort()){let i=`SELECT COUNT() FROM ${me(s)}`;if(!r){n[s]=await this.deps.orgAccess.count(e.orgId,i);continue}let d=0;for(let a of jc(r.get(s)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${i} WHERE ${a}`);n[s]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??Du,s=e.mapping?Tc(e.mapping):void 0;for(let[i,d]of Object.entries(e.mandatoryLookups??{}))for(let a of d){let u=new Set([...Pc(t,i,a),...us(t.objects[i]?.parentNotLoaded,a)].flatMap(f=>{let p=e.mapping?.get(f);return p===void 0?[]:[p]})),l=s?jc((s.get(i)??[]).filter(f=>!u.has(f))):[""],c=[];for(let f of l){let p=`SELECT Id FROM ${me(i)} WHERE ${me(a)} = 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[`${i}.${a}`]=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(a=>e.mapping?.has(a.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let n=r.map(a=>e.mapping?.get(a.accountReferenceId)),s=await hn(a=>this.deps.orgAccess.query(e.orgId,a),n),i=[],d=0;for(let a of r){let u=e.mapping.get(a.accountReferenceId),l=s.get(u);l!==void 0&&(d++,e.mapping.get(a.contactReferenceId)!==l&&i.push(a.accountReferenceId))}return{checked:d,unrestored:i.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 i=new Set(Pc(t,n,s)),d=(e.dataset.objects.find(l=>l.objectApiName===n)?.records??[]).filter(l=>!i.has(l.referenceId)),a=[...new Set(d.map(l=>l.fields[s]).filter(l=>typeof l=="string"&&l!==""))].sort();if(a.length===0){r[n]=[];continue}let u=new Set;for(let l=0;l<a.length;l+=Qn){let c=a.slice(l,l+Qn).map(p=>`'${Me(p)}'`).join(", "),f=await this.deps.orgAccess.query(e.orgId,`SELECT ${me(s)} k FROM ${me(n)} WHERE ${me(s)} IN (${c})`);for(let p of f)u.add(String(p.k))}r[n]=a.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 i=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:i.length===0,detail:i.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${i.join("; ")}`});let d=Fc(t),a=$u(t,r);s.push({name:"load",passed:d.records===0&&a.length===0,detail:Bu(d,a)});let u=Object.entries(r.orphans).filter(([,f])=>f.length>0),l=Wu(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=sr(JSON.parse(eo.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(i=>`${i.name}=${i.passed?"OK":"KO"}`).join(", ")},eo.writeFileSync(n,Mn(s),"utf8")}};function ls(o){return Array.isArray(o)?`[${o.map(ls).join(",")}]`:typeof o=="object"&&o!==null?`{${Object.entries(o).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${ls(r)}`).join(",")}}`:JSON.stringify(o)}function Pc(o,e,t){return us(o.objects[e]?.writtenWithout,t)}function us(o,e){let t=o?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Kr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function Fc(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(Kr.notLoadable);s>0&&e.notLoadable.push({objectApiName:t,records:s});let i=n(Kr.refused),d=n(Kr.heldBack),a=i+d;a!==0&&(e.refused+=i,e.heldBack+=d,e.records+=a,r.expected===0?e.whole.push({objectApiName:t,notLoaded:a}):e.part.push({objectApiName:t,notLoaded:a,of:a+r.expected}))}return e}function $u(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 _u(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 Bu(o,e=[]){let t=qu(o),r=_u(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(i=>`${i.objectApiName} (${i.notLoaded} not loaded)`).join(", ")]:[],...o.part.length>0?["Objects it wrote part of \u2014 "+o.part.map(i=>`${i.objectApiName} (${i.notLoaded} of ${i.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 qu(o){return o.notLoadable.length===0?"":`; ${o.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the simulation said \u2014 `+o.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function Wu(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=us(r.parentNotLoaded,n).length;s>0&&e.push({link:`${t}.${n}`,count:s})}return e}function Gu(o,e,t){if(t===null)return"unstable";let r=o.filter(i=>!i.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(i=>i.length>0);return r.every(i=>i.name==="load"||i.name==="orphans")&&!n&&Fc(e).whole.length===0?"partial":"failed"}function Uu(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=[...Kr.refused,...Kr.heldBack].reduce((c,f)=>c+(n.exclusionReasons[f]??0),0),i=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([c])=>t(c)===r).reduce((c,[,f])=>c+f.length,0),a=e?.presence[r]?.length??0,u=r==="Account"?e?.personContact.unrestored.length??0:0,l=e!==null&&i===n.expected&&s===0&&d===0&&a===0&&u===0;return{objectApiName:r,status:l?"passed":"failed",expected:n.expected,found:i,notLoaded:s,orphans:d,missingKeys:a,...u>0?{personContactsUnlinked:u}:{}}})}var Qn=200;function Tc(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 jc(o){let e=[];for(let t=0;t<o.length;t+=Qn){let r=o.slice(t,t+Qn).map(n=>`'${Me(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var ps=200;function gs(o,e=ps){return{insert:(t,r,n,s)=>fs(o.insert(r,n,e,s?Ku(s):void 0)),update:(t,r,n)=>fs(o.update(r,n,e)),delete:(t,r,n)=>fs(o.delete(r,n,e))}}function Ku(o){let e=0,t=0;return{sending:(r,n,s)=>{t=s},answered:(r,n,s,i)=>{i?s.forEach((d,a)=>{let u=i[a];u!==void 0&&o(u,[d])}):(o(e,s),e+=t),t=0}}}async function fs(o){try{return await o}catch(e){if(e instanceof od)return e.written;throw e}}var Vu=200;function Ec(o){let e={threshold:o.threshold,perCall:ps,...o.duplicateRules?{duplicateRules:o.duplicateRules}:{}},t=o.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:s})=>n+Math.ceil(s/Vu),0);return Mo(t,e)+Mo((o.purged??[]).filter(({rows:n})=>n>0),e)+id(t.length,o.automationRead??0)+r}function ce(o){return o.slice(0,15)}var Cc=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ke(o){return zi(o)??o}function Nc(o,e){return`${o}-${ke(e)}`}var hs="005",ms="00G",zc="00D",ys="00e",Mc="OwnerId",ks="RecordTypeId",ws="SetupOwnerId",Hr="CurrencyIsoCode",ro="Pricebook2",qt=200,bs=new Set([...ya,To]),Hu=["Title","Name"];async function*Rs(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 Yu(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 Ju(o){let e=yd(o.checkpoint,o.choices),t=new Map;for(let p of o.checkpoint.objects)for(let g of await Yu(o,p.objectApiName))t.set(ce(g),p.objectApiName);let r=new Set,n=new Set,s=new Set,i=new Set,d=new Map,a=new Set,u=[],l=new Set;for(let p of e.replayed)for await(let g of Rs(o,p.objectApiName)){l.add(ce(g.Id));for(let[h,m]of Object.entries(g)){if(bs.has(h)||typeof m!="string"||(h===Hr&&m!==""&&a.add(m),!Cc.test(m)))continue;let y=ce(m);if(h===ks)s.add(y);else if(y.startsWith(hs))r.add(y);else if(y.startsWith(ms)&&h===Mc)n.add(y);else if(y.startsWith(ys)&&h===ws)i.add(y);else if(!t.has(y)&&!y.startsWith(zc)){let k=`${p.objectApiName}.${h}`,N=d.get(k)??new Set;N.add(y),d.set(k,N)}}if(p.objectApiName===qe){let h=g[mt],m=g[We];if(typeof h=="string"&&typeof m=="string"){let y=g[Xt];u.push({book:ce(h),product:ce(m),currency:typeof y=="string"?y:""})}}}let c=[];if((o.checkpoint.files?.links??0)>0)for await(let p of wa(o.folder))l.has(ce(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 Rs(o,p.objectApiName)){let h=Hu.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:i,notHeld:d,currencies:a,standardPricebook:Xu(o,u,t),fileLinks:c,filesLeft:f}}function Xu(o,e,t){let r=o.checkpoint.objects.some(a=>a.objectApiName===ro||a.objectApiName===qe);if(no(o.annex,"standardPricebook")&&o.annex.standardPricebookId)return{id:ke(o.annex.standardPricebookId),how:"annex"};let n=e.filter(a=>t.has(a.product));if(n.length===0||!r)return{how:"none"};let s=new Set(n.map(a=>`${a.product}|${a.currency}`)),i=new Map;for(let a of n){let u=i.get(a.book)??new Set;u.add(`${a.product}|${a.currency}`),i.set(a.book,u)}let d=[...i].filter(([,a])=>a.size===s.size).map(([a])=>a);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=>`'${Me(e)}'`).join(", ")}function Dc(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 Zu(o){if(o===void 0)return;let e=Dc(o);return e===o?void 0:o.slice(e.length)}async function Qu(o){let{access:e,orgId:t,survey:r,source:n}=o,s=0,i=async v=>(s++,e.query(t,v)),d=new Map,a=new Map,u=async v=>{s++;try{d.set(v,await e.describe(t,v))}catch(P){a.set(v,Q(P))}};for(let v of r.objects.replayed)await u(v.objectApiName);r.fileLinks.length>0&&await u(nr);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(ce)])].sort();for(let v of Vr(f,qt))for(let P of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Id IN (${to(v)})`)){let C=c(P);C&&l.set(ce(C.id),C)}let p=new Map;if(no(n.annex,"users")){let v=o.tier==="sandbox"?Zu(o.username):void 0,P=new Map;for(let D of n.annex.users){let G=ce(D.id),V=l.get(G);if(V?.isActive===!0&&V.userType==="Standard")continue;let H=n.checkpoint.org.tier==="sandbox"?Dc(D.username):D.username,F=[D.username,H,...v!==void 0?[`${H}${v}`]:[]];P.set(G,[...new Set(F.map(q=>q.toLowerCase()))])}let C=[...new Set([...P.values()].flat())].sort(),W=new Map;for(let D of Vr(C,qt)){let G=D.map(V=>`'${Me(V)}'`).join(", ");for(let V of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Username IN (${G})`)){let H=c(V);H&&W.set(H.username.toLowerCase(),H)}}for(let[D,G]of P){let V=G.map(H=>W.get(H)).find(H=>H!==void 0);V&&p.set(D,V)}}let g=[],h=[...d.keys()].filter(v=>d.get(v)?.fields.some(P=>P.name===ks));if(h.length>0){let v=xc(d),P=await i(`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${v?", IsPersonType":""} FROM RecordType WHERE SobjectType IN (${h.map(C=>`'${me(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 i("SELECT QueueId, SobjectType FROM QueueSobject"))typeof P.QueueId!="string"||typeof P.SobjectType!="string"||v.set(ce(P.QueueId),[...v.get(ce(P.QueueId))??[],P.SobjectType]);for(let P of await i("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(ce(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 i("SELECT IsoCode, IsActive FROM CurrencyType"))typeof v.IsoCode=="string"&&v.IsActive===!0&&y.add(v.IsoCode)}let N;if(r.standardPricebook.id!==void 0){let[v]=await i(Lt);typeof v?.Id=="string"&&(N=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 W of Vr(P,qt))for(let D of await i(`SELECT Id FROM ${me(v)} WHERE Id IN (${to(W)})`))typeof D.Id=="string"&&(T.add(ce(D.Id)),C++);return C},U=new Set(r.objects.replayed.map(v=>v.objectApiName));for(let[v,P]of j){if(a.has(v)||md(v))continue;let C=[...P].sort(),W=C.slice(0,qt);try{await x(v,W)>0&&await x(v,C.slice(qt))}catch(D){if(U.has(v))throw D}}let S=new Map;for(let[v,P]of r.notHeld){let[C,W]=v.split("."),D=d.get(C)?.fields.find(H=>H.name===W),G=D?.type==="reference"?D.referenceTo??[]:[];if(G.length!==1)continue;let V=S.get(G[0])??new Set;for(let H of P)V.add(H);S.set(G[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||a.has(v.objectApiName))continue;let P={names:new Set,owners:new Set};for(let C of await i(`SELECT Id, Name, SetupOwnerId FROM ${me(v.objectApiName)}`))typeof C.Name=="string"&&P.names.add(C.Name),typeof C.SetupOwnerId=="string"&&P.owners.add(ce(C.SetupOwnerId));w.set(v.objectApiName,P)}let I=new Set;for(let v of Vr([...r.profiles].sort(),qt))for(let P of await i(`SELECT Id FROM Profile WHERE Id IN (${to(v)})`))typeof P.Id=="string"&&I.add(ce(P.Id));let A=new Set,L=[...new Set(r.fileLinks.map(v=>ce(v.ContentDocumentId)))];if(!a.has(nr))for(let v of Vr(L.sort(),qt))for(let P of await i(`SELECT Id FROM ContentDocument WHERE Id IN (${to(v)})`))typeof P.Id=="string"&&A.add(ce(P.Id));return{organizationId:ke(o.organizationId),runningUserId:ke(o.runningUserId),describes:d,missing:a,usersById:l,usersByUsername:p,recordTypes:g,queues:m,...y!==void 0?{currencies:y}:{},...N!==void 0?{standardPricebookId:N}:{},sameIds:T,customSettings:w,profiles:I,files:A,requests:s}}function xc(o){return o.get("Account")?.fields.some(e=>e.name===To)===!0}function ef(o,e,t){let r=[...new Set(Object.values(o.ownerMap??{}).map(ce))].sort(),n=r.filter(i=>{let d=e.usersById.get(i);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(i=>e.usersById.get(i)?.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 Wt=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 tf(o,e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0||qs(o,e.name)}function rf(o){let e=o.length;return typeof e=="number"&&e>0?e:void 0}var nf=new Set(["id","reference","boolean","double","int","long","percent","currency","date","datetime","time","picklist","multipicklist"]);async function of(o){let{survey:e,target:t,choices:r,annex:n}=o,s=ef(r,t,o.targetName);if(s)return{refusal:s};let i=new Wt(R=>`${R.object}|${R.reason}`);for(let R of e.objects.leftOut)i.add({object:R.objectApiName,reason:R.reason},R.records);let d=e.objects.replayed.filter(R=>t.missing.has(R.objectApiName)?(i.add({object:R.objectApiName,reason:"notInTarget"},R.records),!1):t.describes.get(R.objectApiName)?.createable===!1?(i.add({object:R.objectApiName,reason:"notCreateable"},R.records),!1):!0),a=new Set(d.map(R=>R.objectApiName)),u=new Wt(R=>`${R.field}|${R.reason}`),l={kept:0,toRunningUser:0,reasons:{notInTarget:0,inactive:0,queueMissing:0}},c=new Wt(R=>`${R.object}|${R.recordType}|${R.outcome}`),f=new Wt(R=>R),p=new Map,g=!1,h={inserted:0,alreadyThere:0},m=new Map,y=new Map,k=xc(t.describes),N=new Set,T=e.standardPricebook,j=T.id!==void 0?ce(T.id):void 0,x=new Map(Object.entries(r.ownerMap??{}).map(([R,E])=>[ce(R),ke(E)])),U=R=>{let E=t.usersById.get(R);if(E?.userType==="Standard"&&E.isActive)return{id:E.id};let O=t.usersByUsername.get(R);return O?.userType==="Standard"&&O.isActive?{id:O.id}:{why:E!==void 0||O!==void 0?"inactive":"notInTarget"}},S=(R,E)=>{let O=Z=>Z.sobjectTypes.includes(R),J=t.queues.find(Z=>ce(Z.id)===E&&O(Z));if(J)return J.id;let ee=no(n,"queues")?n.queues.find(Z=>ce(Z.id)===E):void 0;if(ee!==void 0)return t.queues.find(Z=>Z.developerName===ee.developerName&&O(Z))?.id},w=(R,E,O)=>{let J=ce(E),ee=no(n,"recordTypes")?n.recordTypes.find(B=>ce(B.id)===J):void 0,Z=t.recordTypes.filter(B=>B.sobjectType===R&&B.isActive),he,te="default";if(ee!==void 0&&(he=Z.find(B=>B.developerName===ee.developerName&&(B.namespacePrefix??null)===(ee.namespacePrefix??null)),he&&(te="byName")),he===void 0&&(he=Z.find(B=>ce(B.id)===J),he&&(te="byId")),he===void 0&&O){let B=Z.filter(ae=>ae.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`};he=B[0]}let Be={recordType:ee!==void 0?ct(ee.namespacePrefix,ee.developerName):ke(E),outcome:te};if(he===void 0)return{given:Be};let M=he,we=t.describes.get(R)?.recordTypeInfos?.find(B=>ce(B.recordTypeId)===ce(M.id));if(we!==void 0&&!we.available)return{refused:`${ct(M.namespacePrefix,M.developerName)} is not assigned to the user who replays in ${o.targetName}: assign it to them, or leave ${R} out`};let et={name:M.name,developerName:M.developerName,namespacePrefix:M.namespacePrefix??null},tt=y.get(R)??new Map;return tt.set(M.id,et),y.set(R,tt),{ref:et,given:Be}},I=[];for(let R of d){let E=R.objectApiName,O=t.describes.get(E);if(O===void 0)continue;let J=new Map(O.fields.map(te=>[te.name,te])),ee=R.fields.filter(te=>!bs.has(te)&&!J.has(te)&&!(te===Hr&&t.currencies===void 0));ee.length>0&&p.set(E,new Set(ee));let Z=R.customSetting,he=t.customSettings.get(E);for await(let te of Rs(o,E)){let Be=ce(te.Id);if(t.sameIds.has(Be)){m.set(Nc(E,te.Id),ke(te.Id));continue}let M={objectApiName:E,key:Be,referenceId:Nc(E,te.Id),fields:{},pointsAt:new Map,sourceId:ke(te.Id),emptied:[]},we=(B,ae)=>{M.refused??={reason:B,...ae!==void 0?{path:ae}:{}}},et=(E==="Account"||E==="Contact")&&Ir(te);et&&!k&&we("personAccountsUnsupported",`turn person accounts on in ${o.targetName}, or leave ${E} out`),et&&E==="Contact"&&N.add(Be);let tt=E==="Account"?gn(te,!1):void 0;for(let[B,ae]of Object.entries(te)){if(bs.has(B)||tt!==void 0&&cn(E,B,tt))continue;let Rt=J.get(B);if(Rt===void 0){B===Hr&&typeof ae=="string"&&ae!==""&&(g||=t.currencies===void 0);continue}if(ae==null||ae==="")continue;if(B===Hr&&typeof ae=="string"){t.currencies!==void 0&&!t.currencies.has(ae)&&(we("inactiveCurrency",`activate ${ae} in ${o.targetName}, or leave ${E} out`),f.add(ae)),M.fields[B]=ae;continue}if(B===ks&&typeof ae=="string"){let ye=w(E,ae,et);ye.given!==void 0&&(M.recordType=ye.given),ye.refused!==void 0?we("recordTypeUnavailable",ye.refused):ye.ref!==void 0&&(M.fields[B]=ye.ref.name,M.recordTypeDeveloperName=ct(ye.ref.namespacePrefix,ye.ref.developerName));continue}if(Rt.type!=="reference"||typeof ae!="string"||!Cc.test(ae)){M.fields[B]=ae;continue}let fe=ce(ae),ft=tf(E,Rt),rt=(ye,ve)=>{ft?we("requiredLookupMissing",ve):M.emptied.push({field:`${E}.${B}`,reason:ye})};if(fe.startsWith(zc)){M.fields[B]=t.organizationId;continue}if(B===ws){(fe.startsWith(ys)?t.profiles.has(fe):t.usersById.has(fe))?M.fields[B]=ke(ae):we("requiredLookupMissing",`the ${fe.startsWith(ys)?"profile":"user"} its row is of is not in ${o.targetName}`);continue}if(B===Mc&&(fe.startsWith(hs)||fe.startsWith(ms))){let ye=x.get(fe);if(ye!==void 0)M.owner="kept",M.fields[B]=ye;else if(r.owners==="me")M.owner="toRunningUser";else if(fe.startsWith(ms)){let ve=S(E,fe);M.owner=ve!==void 0?"kept":"queueMissing",ve!==void 0&&(M.fields[B]=ve)}else{let ve=U(fe);M.owner=ve.id!==void 0?"kept":ve.why??"notInTarget",ve.id!==void 0&&(M.fields[B]=ve.id)}continue}if(fe.startsWith(hs)){let ye=U(fe);ye.id!==void 0?M.fields[B]=ye.id:ft?M.fields[B]=t.runningUserId:M.emptied.push({field:`${E}.${B}`,reason:"userNotInTarget"});continue}if(j!==void 0&&fe===j){t.sameIds.has(fe)?M.fields[B]=ke(ae):a.has(ro)&&e.heldBy.has(fe)?M.pointsAt.set(B,fe):t.standardPricebookId!==void 0?M.fields[B]=t.standardPricebookId:rt("objectNotHeld",`${o.targetName} has no standard price book`);continue}let xe=e.heldBy.get(fe);xe!==void 0&&t.sameIds.has(fe)?M.fields[B]=ke(ae):xe!==void 0&&a.has(xe)?M.pointsAt.set(B,fe):xe!==void 0?rt("objectNotReplayed",`replay ${xe} too`):t.sameIds.has(fe)?M.fields[B]=ke(ae):rt("objectNotHeld",`the checkpoint holds no record it points at, and ${o.targetName} holds none under its Id`)}if(E===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`),Z!==void 0&&he!==void 0){let B=M.fields[ws];if(Z==="list"?typeof te.Name=="string"&&he.names.has(te.Name):typeof B=="string"&&he.owners.has(ce(B))){h.alreadyThere++;continue}}I.push(M)}}let A=new Map(I.map(R=>[R.key,R])),L=new Map;for(let R of I)for(let E of R.pointsAt.values()){let O=L.get(E);O?O.push(R):L.set(E,[R])}let v=I.filter(R=>R.refused!==void 0);for(let R=0;R<v.length;R++){let E=v[R];for(let O of L.get(E.key)??[])O.refused===void 0&&(O.refused={reason:"parentRefused",path:`its ${E.objectApiName} is refused: lift that first`},v.push(O))}let P=new Wt(R=>`${R.object}|${R.reason}`),C=new Map,W=[];for(let R of I){if(R.refused!==void 0){P.add({object:R.objectApiName,...R.refused});continue}for(let O of R.emptied)u.add(O);R.recordType!==void 0&&c.add({object:R.objectApiName,...R.recordType}),R.owner==="kept"?l.kept++:R.owner!==void 0&&(l.toRunningUser++,R.owner!=="toRunningUser"&&l.reasons[R.owner]++);for(let[O,J]of R.pointsAt){let ee=A.get(J);ee!==void 0&&ee.refused===void 0?R.fields[O]=ee.referenceId:u.add({field:`${R.objectApiName}.${O}`,reason:"objectNotReplayed"})}N.has(R.key)&&typeof R.fields.AccountId=="string"&&W.push({accountReferenceId:R.fields.AccountId,contactReferenceId:R.referenceId});let E=C.get(R.objectApiName)??[];E.push({referenceId:R.referenceId,fields:R.fields,...R.recordTypeDeveloperName!==void 0?{recordTypeDeveloperName:R.recordTypeDeveloperName}:{}}),C.set(R.objectApiName,E)}for(let R of d)R.customSetting!==void 0&&(h.inserted+=C.get(R.objectApiName)?.length??0);let D=t.describes.get(nr);if(D!==void 0&&D.createable!==!1){let R=[];for(let E of e.fileLinks){let O=A.get(ce(E.LinkedEntityId));O===void 0||O.refused!==void 0||t.files.has(ce(E.ContentDocumentId))&&R.push({referenceId:`${nr}-${ke(E.ContentDocumentId)}_${O.sourceId}`,fields:{ContentDocumentId:ke(E.ContentDocumentId),LinkedEntityId:O.referenceId,ShareType:E.ShareType,Visibility:E.Visibility}})}R.length>0&&C.set(nr,R)}let G=new qa(o.salt),V=r.mask?new Ka(void 0,o.salt):void 0,H=r.mask?new kn:void 0,F=[],q=[];for(let[R,E]of C){let O=t.describes.get(R);if(O===void 0)continue;let J=new Set(E.flatMap(M=>Object.keys(M.fields))),ee=O.fields.filter(M=>J.has(M.name)).map(M=>{let we=rf(M);return{name:M.name,queryable:!0,createable:M.createable,isReference:M.type==="reference",type:M.type,...we!==void 0?{length:we}:{}}});if(r.contactPoints==="neutralized"){let M=G.forObject(R,ee);if(M)for(let we of E)M(we.fields)}if(V===void 0||H===void 0)continue;let Z=ee.filter(M=>!nf.has((M.type??"").toLowerCase())),he=new Set(Rn(H,Z.map(M=>({name:M.name,type:M.type??"string"})))),te=Z.filter(M=>he.has(M.name)).map(M=>({name:M.name,type:M.type??"string",...M.length!==void 0?{length:M.length}:{}}));for(let M of te)F.push(`${R}.${M.name}`);for(let M of Z)!he.has(M.name)&&(M.type??"").toLowerCase()==="textarea"&&q.push(`${R}.${M.name}`);if(te.length===0)continue;let Be=V.anonymize({objectApiName:R,records:E.map(M=>M.fields),sourceIds:E.map(M=>M.referenceId),fields:te,methods:{}});E.forEach((M,we)=>{M.fields=Be[we]??M.fields})}let Y={};for(let[R,E]of y)Y[R]=[...E.values()];let ie=[...C].map(([R,E])=>({objectApiName:R,records:E})),$=j!==void 0?A.get(j):void 0,K=$!==void 0&&$.refused===void 0&&$.objectApiName===ro?$.referenceId:void 0,X={datasetVersion:"1.0.0",objects:ie,recordTypes:Y,personContactSidecar:W,...K!==void 0?{standardPricebook:K}:{}},ne=ie.reduce((R,E)=>R+E.records.length,0),ge=e.objects.replayed.some(R=>R.objectApiName===ro||R.objectApiName===qe),_e=P.entries(),De={records:{toCreate:ne-(K!==void 0?1:0),linkedById:m.size,linkedByKey:0,refusedBeforeWrite:_e.reduce((R,E)=>R+E.n,0)},owners:l,recordTypes:c.entries().map(({key:R,n:E})=>({...R,records:E})).sort((R,E)=>Lc(`${R.object}.${R.recordType}`,`${E.object}.${E.recordType}`)),notReplayed:i.entries().map(({key:R,n:E})=>({...R,records:E})),lookupsEmptied:u.entries().map(({key:R,n:E})=>({...R,records:E})).sort((R,E)=>Lc(R.field,E.field)),refused:_e.map(({key:R,n:E})=>({object:R.object,records:E,reason:R.reason,...R.path!==void 0?{path:R.path}:{}})),fieldsNotInTarget:[...p].map(([R,E])=>({object:R,fields:[...E].sort()})),...e.objects.replayed.some(R=>R.customSetting!==void 0)?{customSettings:h}:{},currencies:{refused:f.entries().map(({key:R,n:E})=>({code:R,records:E})),...g?{singleCurrencyTarget:!0}:{}},...ge?{standardPricebook:T.how}:{},masked:{fields:F.sort(),...r.mask?{unmaskedFreeText:q.sort()}:{}},contactPoints:r.contactPoints,degraded:sf(n),auditDates:"new"};return{conversion:{dataset:X,summary:De,identityKeys:Object.fromEntries(r.link.map(R=>[R.objectApiName,[...R.fields]])),linkedById:m,filesLeft:e.filesLeft}}}function sf(o){return o===void 0?["recordTypes","users","queues","standardPricebook"]:[...new Set(o.unread.map(e=>e.part))]}function Lc(o,e){return o<e?-1:o>e?1:0}async function $c(o){let e={folder:o.folder,checkpoint:o.checkpoint,annex:o.annex,choices:o.choices},t=await Ju(e),r=await Qu({...o,source:e,survey:t});return{...await of({...e,survey:t,target:r,targetName:o.targetName,...o.salt!==void 0?{salt:o.salt}:{}}),target:r,survey:t}}var df={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.")}},cf=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",fr=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},pr=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=Eo},nl="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=nl};function so(o){let e=o<10?100:10;return String(o<=0?0:Math.ceil(o*e-1e-9)/e)}function _c(o){let e;return{request:t=>(e===void 0&&(e=Promise.resolve().then(()=>o.request(t)),e.catch(()=>{})),e)}}function Bc(o){if("unread"in o.storage)return;let e=Math.max(0,o.automationBytes??0),t=ol(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:i}=o.storage;if(t<=s*n+r)return;let d={estimateMB:t/n,...e>0?{automationMB:e/n}:{},remainingMB:s,maxMB:i,...r>0?{freedMB:r/n}:{}},a=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 ${i} MB${a}. To replay part of it, ${wd.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 ${i} MB${a}. 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 lf=nt({sobjects:ht(nt({name:Ce().min(1),createable:rn().optional()}).loose())}).loose();function ol(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 qc(o,e,t,r){if(!("objects"in o))return 0;let n=$a(Ct(o,e,r),r),s=new Map(t.objects.map(i=>[i.objectApiName,i.records.length]));return _a(n,i=>s.get(i)??0)}function uf(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 Wc(o,e,t){if(t!==!0)return o;try{return es(o,e.rootObject)}catch{return o}}function Gc(o){return o?{replay:o}:{}}function ff(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 pf(o,e){let t=Ia(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:Eo,message:t}}:{}}}function Yr(o,e){let t=[...new Set(o.map(r=>r.objectApiName))];return Hs({setToDraft:xi(t),delete:Bi(t)},e)}function Is(o){return o.status==="success"&&(o.left??[]).length===0}function Uc(o){return o.verdict!=="nothingSends"||o.counted.length>0||o.uncounted!==void 0}function gf(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",Kc="frozen:config",ur="frozen:lastRun",Vc="frozen:lastRuns",vs="frozen:lastVerify",Os="frozen:lastVerifies",Hc="tokens.json",hf="rules.json",gr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},mf=async o=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(o),{preview:!1})},yf="0.1.0",wf=10*6e4,Ss=15*6e4,bf="EXTRACT_TIMEOUT",Yc=30*6e4,As=6e4,Jc=12e4,Rf=50;function kf(o,e){let t=0,r=null,n=null,s=d=>{o(...d),t=Date.now(),r=null},i=((...d)=>{r=d;let a=e-(Date.now()-t);a<=0?(n&&(clearTimeout(n),n=null),s(d)):n||(n=setTimeout(()=>{n=null,r&&s(r)},a))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&s(r)},i}function Xc(o,e){let t=kf(o,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),o(n)},{flush:t.flush})}async function Ze(o){try{return await Se.access(o),!0}catch{return!1}}function If(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 sl(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,Rf).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:If(t)}))}))}}function Ps(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:sl(o.controls.nonReidentification),dryRunLoad:o.controls.dryRunLoad,author:o.controls.author,date:o.controls.date},...o.coverage?{coverage:o.coverage}:{}}}function vf(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 Ts(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 Zc(o,e){return{objects:o.nodes.filter(ha).length,truncated:o.truncated===!0,maxNodes:e}}function Of(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 js(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(st(o).length>0)return;let t=Of(Ln(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 Fs(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 Sf(o,e=!1){let t=new Map;for(let{objects:r}of o)for(let n of r){let s=n.heldByAutomation??0,i=(n.keptDependents??0)-(e?s:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",a=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",i>0?(d?`${i} kept for records that stay under them (${d})`:`${i} 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,i)+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 a)l.why.add(c);t.set(n.objectApiName,l)}return[...t].map(([r,{left:n,why:s}])=>({objectApiName:r,left:n,why:[...s]}))}function Af(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 Pf(o){return o.status==="completed"?"success":o.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Tf(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 Qc(o){return`frozen:${o}`}var io=(o,e)=>e==="insert"||e==="update",Gt=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function Es(o){let e=new Map,t=r=>{let n=e.get(r)??mi(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 jf(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 Qe=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="ReplayRefused"}code;params},Ns=class extends Cn{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 Ff(){let o=oa();return{checkpoints:()=>[o,ad(o)].flatMap(e=>{if(!af(e))return[];let t=sa({root:e});return"store"in t?[t.store]:[]}),replays:new hd({root:gd()})}}function el(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 ao(o){return o.replay?{module:"checkpoint",sasMark:Gn(o.replay.folder.dir)}:{module:"frozen"}}function Ef(o){return o.replay?{action:"checkpoint_replay",module:"checkpoint"}:{action:"frozen_load",module:"frozen"}}var tl=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=Qd();openInEditor=mf;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new Xi;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-QO4MPHZD.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!==Qc(r)))return!0;return!1}async loadingDuring(e,t){let r=vn(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(!cf.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(vn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(vn(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(Kc)??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=ot(Ai,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(Kc,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(rl.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),hf))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await Ze(t)?await Se.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:Q(n)}}return{path:t,...lc(r)}}async loadTokens(e,t){return await Ze(Pe.join(e,Hc))?wc(e,Hc,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let s=await new At(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(a=>({name:a.name,label:a.label,type:a.type,referenceTo:a.referenceTo??[],relationshipName:a.relationshipName??null,isMasterDetail:a.cascadeDelete===!0,nillable:a.nillable!==!1,createable:a.createable!==!1,updateable:a.updateable!==!1,restrictedPicklist:a.restrictedPicklist===!0,defaultedOnCreate:a.defaultedOnCreate===!0,...a.compoundFieldName?{compoundFieldName:a.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(a=>({childSObject:a.childSObject,field:a.field,relationshipName:a.relationshipName??a.field,isCascadeDelete:a.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,s),s}buildDiscoveryService(){return new ma({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?Rn(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(i=>({name:i.name,keyPrefix:i.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??ga}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:s}=e,{maxNodes:i}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:i},a=await vc(n,s),u;if("kept"in a){let p=a.kept,g=Oc(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=a.none;let l;try{let p=await Ae(t,this.deps.orgRegistry,this.deps.orgManager);l=Sc((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:i,...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 Ic(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(i=>{let{name:d,keyPrefix:a}=i??{};return typeof d=="string"?[{name:d,keyPrefix:typeof a=="string"?a: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: ${Q(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,Yc);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,Yc)}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 Cn(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 mn(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(i=>({value:i.value,active:i.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:i,active:d}=s;return i?[{developerName:i,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 Ha(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 Ze(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let s=sr(JSON.parse(await Se.readFile(n,"utf8"))),i=[],d=t.assertOutsideRepo(Pe.join(r,"data"));if(await Ze(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"));i.push({objectApiName:g.objectApiName,records:g.records})}let a=async(f,p)=>{let g=t.assertOutsideRepo(Pe.join(r,f));return await Ze(g)?JSON.parse(await Se.readFile(g,"utf8")):p},u=await a("record-types.json",{}),l=await a("personcontact-sidecar.json",[]),c=await a(Fr,{});return{dataset:{datasetVersion:s.version,objects:i,recordTypes:u,personContactSidecar:l,...c.standardPricebook?{standardPricebook:c.standardPricebook}:{}},manifest:s}}errorCodeFor(e,t){return e instanceof gr?"RULES_MISSING":e instanceof Ve?"GUARD_REFUSED":e instanceof dd?"SAS_PATH_REFUSED":e instanceof Tr?"SALT_MISSING":e instanceof _t?"BUDGET_EXCEEDED":e instanceof Xe?"LOAD_CONFIG":e instanceof Dr?"MAX_RECORDS":e instanceof ar?oo:e instanceof lt?"TIMEOUT":e instanceof Qe?e.code:e instanceof So&&e.code==="invalid"?"INVALID_PAYLOAD":t}errorDetailOf(e){if(e instanceof Qe)return{params:e.params};if(e instanceof gr)return{rulesPath:e.rulesPath};if(e instanceof Ve)return{guard:e.code,...e.params};if(e instanceof _t)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof Xe&&e.gaps)return{gaps:e.gaps,...(e.refusedBeside??[]).length>0?{refusedBeside:e.refusedBeside}:{}};if(e instanceof Xe&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof pr)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 oc({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:()=>Aa(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(Zi):Qi(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await Ra(e.conn).catch(s=>({unread:Q(s)})),r=Va(e.read),n=ka({run:Ec({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:Na(e.read)})+(e.replayReads??0),...va(e.checkpoint),...ta(e.plan),...La(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})`),pf(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>st(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 Ks(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??=Ff(),this.replayStores}async sourceOf(e,t,r,n,s){if(t.replay===void 0){let i=this.requireConfig(e,r);return i?this.datasetSource(i,t.targetOrgId):void 0}try{if(t.pilot===!0)throw new Qe("REPLAY_NO_PILOT","A replay loads no pilot: simulate it, then replay it whole. Nothing was read or written.");return await this.replaySourceOf(t.targetOrgId,t.replay,n)}catch(i){let d=this.errorCodeFor(i,"REPLAY_ERROR");s?.(d);let a=this.errorDetailOf(i);re(this.deps,e.type,r,e,i,{code:d,retryable:i instanceof lt,...a?{extraPayload:a}:{}});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:i,manifest:d}=await this.readFrozenDataset(s,n);return{dataset:i,manifest:d,datasetDir:s,label:d.version}}}}async replaySourceOf(e,t,r){let n=this.targetTier(e),s=n==="staging"?this.stagingReplayOf(e,t,r):void 0;Uo({orgId:e,orgName:this.orgNameOf(e),orgTier:n,...s?{stagingReplay:s}:{}});let i=this.replayStoresInUse(),d=i.replays.folderOf(t.organizationId,t.checkpointId),a=await this.replayTargetOf(e),u=Sn(a.organizationId),l={folder:d,target:a,contractPath:i.replays.contractPathOf(d,u),...s?{stagingReplay:s}:{}},c=m=>new Ns(d.dir,{guard:m,orgId:u,organizationId:a.organizationId},e);if(r==="mapping")return{config:el(t.config,void 0),sasDir:()=>d.dir,mappingStore:c,read:()=>Promise.reject(new Error("A removal of a replay reads no checkpoint")),replay:l};let f=await this.replayedCheckpointOf(i,t),p=t.choices??(await i.replays.read(d))?.targets.find(m=>m.organizationId===u)?.choices;if(p===void 0)throw new Qe("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 g=bd({checkpoint:f.checkpoint,checkpointId:t.checkpointId,choices:p,target:a});if(g)throw new Qe(g.code,g.message,g.params);if(f.checkpoint===void 0)throw new Qe("REPLAY_CHECKPOINT_UNUSABLE","The checkpoint does not read.");let h=f.checkpoint;return l.checkpoint={checkpoint:h,folder:f.folder,annex:f.annex},l.choices=p,{config:el(t.config,p),sasDir:()=>d.dir,mappingStore:c,read:async()=>(l.converted??=await this.convertReplay(l,p,e),{dataset:l.converted.conversion.dataset,label:h.name}),replay:l}}stagingReplayOf(e,t,r){if(r!=="load")return!0;let n=this.orgNameOf(e);if(t.confirmStaging===n)return!0;throw new Qe("REPLAY_STAGING_UNCONFIRMED",`${n} is a sandbox marked Staging, which may hold real data: a replay goes into it once its name is typed to confirm it. Nothing was read or written.`,{target:n})}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 ba(n.folder)}}catch(s){throw s instanceof So?new Qe("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 Qe("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,i=await t.userId?.(e);if(i===void 0)throw new Error(`${r} did not say which user the replay writes as.`);let d=this.deps.orgManager.getOrg(e),a=this.deps.sandboxRefreshes,u=[d?.orgId,a?.organizationIdOf(e),...a?.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:i,...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 $c({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 Qe(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:i}=n,{summary:d,filesLeft:a}=s.conversion;return{checkpoint:{checkpointId:i.checkpointId,name:i.name,organizationId:i.org.organizationId,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,tier:i.org.tier,annex:n.annex!==void 0},target:{organizationId:Sn(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:a.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=lf.safeParse(r);if(!n.success)return;let s=new Set(n.data.sobjects.filter(i=>i.createable!==!1).map(i=>i.name.toLowerCase()));return{takes:i=>s.has(i.toLowerCase()),byThePlatform:Kd(t)}}async loadStorageOf(e){let t=await Fo(e.conn).catch(()=>{});if(t===void 0)return;let r=Math.max(0,e.automationBytes??0),n=Bc({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??(ol(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:nl,message:n.message}}:{}}}async handleSelect(e){let t=ot(Pi,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()}`;vr(this.deps,n,"frozen","Running coverage-matrix selection");let s="Coverage-matrix selection",i=new AbortController,d=setTimeout(()=>i.abort("timeout"),wf),a=()=>{},u=new Promise((c,f)=>{a=p=>p===void 0?c():f(p)});u.catch(()=>{}),this.registry?.register(e.id,"frozen",s,u,i),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 de,f=c.assertOutsideRepo(this.resolveSasDir(r)),p=await Ae(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async D=>{let G=g.get(D);return G||(G=mn(p,D),g.set(D,G),G.catch(()=>g.delete(D))),(await G).map(V=>({...V}))},m=await this.loadTokens(f,c),y=this.discoveryOptions(r),k=new Set,N=new Gr({query:h,describeFields:D=>(k.add(D),this.describeScopableFields(t.sourceOrgId,D)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),T=new Date().toISOString(),j,x=0,U=async D=>(j??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:f,guard:c,rootRecordId:D,signal:i.signal,onProgress:G=>{G.phase==="object"&&(G.discoveredCount-x<10&&G.queueRemaining>0||(x=G.discoveredCount,l({phase:"discovery",objects:G.discoveredCount})))}}),Ts((await j).graph,r.excludedObjects)),S=async D=>{if(D.length===0)return{};let G=await U(D[0]),V=await N.extract({graph:G,rootObject:r.rootObject,rootRecordIds:D,asOf:T,sasDir:f,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:c}),H={};for(let F of V.objects)H[F.objectApiName]=F.records.length;return H},w=new Vn(S,r.expectedObjects??[]),I=async(D,G)=>(await this.describeObject(t.sourceOrgId,D)).fields.find(V=>V.name.toLowerCase()===G.toLowerCase())?.type,L=await new Kn({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:i.signal,onProgress:l}),v=await Rc(f,L,c),P=j&&!L.stopped?await j.catch(()=>{}):void 0;P?.keep&&await P.keep(k).catch(D=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(D)}`)});let C=P?Ts(P.graph,r.excludedObjects):void 0,W=Oe(this.deps,e,"frozen:select:response",{selection:{...vf(L,v,C?Zc(C,y.maxNodes):void 0),...P?{discovery:P.origin}:{}}});this.deps.broker.postToWebview(W),wt(this.deps,n,{roots:L.roots.length,total:L.volumetry.total,...L.stopped?{stopped:L.stopped.reason}:{}}),L.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),a()}catch(c){this.liveTracker?.fail(e.id,Q(c)),a(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=ot(ji,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()}`;vr(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let s=new de,i=s.assertOutsideRepo(this.resolveSasDir(r)),d=s.assertOutsideRepo(this.resolveDatasetDir(r)),a=await this.saltKeeper.forExtraction(),u=new Tn(a.salt);if(a.created&&this.sayTheSaltWasMade(u.saltFingerprint),!await Ze(Pe.join(i,qr))){re(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${i} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let l=await as(i,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(i,s),p=this.resolveRulesPath(r);if(!await Ze(p))throw new gr(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=Un(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:i,guard:s,rootRecordId:c[0]}),k=Ts(y.graph,r.excludedObjects),N=new Set,T,j=new Gr({query:V=>T?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):mn(h,V),describeFields:V=>(N.add(V),this.describeScopableFields(t.sourceOrgId,V)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),x=t.author??"sandforge",U=r.datasetVersion??yf,{extracted:S,frozen:w,report:I,requiredLeftEmpty:A,keptUnruled:L}=await new At(Ss).withTimeout("frozen:extract",async V=>{T=V;let H=await j.extract({graph:k,rootObject:r.rootObject,rootRecordIds:c,asOf:new Date().toISOString(),sasDir:i,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:f,guard:s}),F=await this.ruleSchemaOf(t.sourceOrgId,H.objects),q=uc(g,F,this.deps.infraServices?.piiDetector??new kn),Y=new Jn().anonymize({extracted:H,rules:q,pseudonymizer:u,datasetVersion:U}),ie=new Xn().run(H,Y,q,{author:x});return{extracted:H,frozen:Y,report:ie,requiredLeftEmpty:pc(H,q,F),keptUnruled:fc(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(N).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:sl(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),W=kd({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:{...Zc(k,m.maxNodes),unboundedObjects:S.unboundedObjects,filesLeftOut:w.filesLeftOut??[],...(S.leftToThePlatform??[]).length>0?{leftToThePlatform:zn(S.leftToThePlatform??[])}:{},...S.exclusionCosts?{exclusionCosts:S.exclusionCosts}:{},...A.length>0?{requiredLeftEmpty:A}:{},...L.length>0?{keptWithoutARule:L}:{},encryptedNotKept:S.encryptedNotKept??[]}}),D=await new Dn(s).write(d,w,W,I),G=Oe(this.deps,e,"frozen:extract:response",{datasetDir:D.dir,files:D.files,recordCount:ir(w),manifest:Ps(W),discovery:y.origin});this.deps.broker.postToWebview(G),wt(this.deps,n,{records:ir(w),version:W.version})}catch(s){let i=s instanceof lt,d=i?new Error(`The extraction ran out of its ${Ss/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:i?bf:this.errorCodeFor(s,"EXTRACT_ERROR"),retryable:!1,extraPayload:i?{minutes:Ss/6e4}:this.errorDetailOf(s)})}}async handleRulesClear(e){let t=ot(Ti,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 Ze(n))throw new gr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let s=gc(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)}
21
+ `,"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 i=Oe(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:s.rulesVersion,cleared:s.cleared,alreadyRuled:s.alreadyRuled});this.deps.broker.postToWebview(i)}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,dc(cc),{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: ${Q(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 de().assertOutsideRepo(Pe.join(r,"manifest.json"));await Ze(d)&&(n=Ps(sr(JSON.parse(await Se.readFile(d,"utf8")))))}catch(i){Ot.warn(`frozen:manifest:get \u2014 unreadable manifest: ${String(i)}`)}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 Us(t)}async handleLoad(e){let t=ot(Io,e,"frozen:load:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:error","load",F=>Je(this.deps,{action:"checkpoint_replay",module:"checkpoint",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:F}));if(!r)return;let{config:n}=r,s=Ef(r),i=r.replay,d=this.deps.infraServices?.productionGuard;if(!d){Je(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:St.code}),re(this.deps,"frozen:load","frozen:load:error",e,new Error(St.message),{code:St.code});return}let a=await this.replaceRefusal(t,r),u=a&&"error"in a?a:void 0,l=a&&"cameAlong"in a?a.cameAlong:void 0;if(u){u.code===oo&&Je(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=i?`Replaying checkpoint '${i.checkpoint?.checkpoint.name??""}'`:t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";vr(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((F,q)=>{m=Y=>Y===void 0?F():q(Y)});y.catch(()=>{}),this.registry?.register(c,s.module,f,y,h);let k=Xc(F=>{let q=Oe(this.deps,e,"frozen:load:progress",{...F});this.deps.broker.postToWebview(q),!p&&!g&&this.liveTracker?.updateProgress(c,F.progress,0,0,F.message)},100),N,T=!1,j=!1,x,U=new Date().toISOString(),S,w,I,A,L,v=(F,q,Y,ie)=>{if(j)return;j=!0;let $=F!=="stopped"&&S!==void 0,K=I?na(ra(I.run.gate,I.info.accepted&&I.info.verdict==="asks").emails):{},X=i?.checkpoint&&i.choices?{replayCheckpoint:i.checkpoint.checkpoint.checkpointId,...Rd(i.checkpoint.checkpoint,i.choices,i.target),...i.stagingReplay?{replayIntoStaging:!0}:{}}:{},ne={...$?{sas:S,startedAt:U,...w?{lastWriteAt:w}:{}}:{},...K,...X};Je(this.deps,{...s,operationId:c,orgId:t.targetOrgId,outcome:F,guard:N,objects:q,source:{origin:i?"checkpoint":"dataset",label:x},carried:Y,...ie?{code:ie}:{},...P?{muted:un(P)}:{},...W?.state==="taken"?{checkpointId:W.checkpointId}:{},...Object.keys(ne).length>0?{details:ne}:{}})},P,C,W,D=!1,G=!1,V=!1,H=[];try{let F=new de,q=r.sasDir(F);S=Gn(q);let{dataset:Y,manifest:ie,datasetDir:$,label:K}=await r.read(F);x=K;let X=this.buildTargetOrgAccess(),ne=await Ae(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),ge=yo(this.deps),_e=wi(this.deps),De=z=>new sd({connection:ne,bulkExecutor:new Mi(ge.bulk.threshold),bulkManager:_e,retryConfig:ge.retry,...z?{signal:z}:{},onProgress:()=>{},log:se=>this.deps.log(se)}),R=De(h.signal),E=n.mockDetection?new Lr(X,n.mockDetection):{areCalloutsMocked:async()=>!0},O=r.mappingStore(F),J=Dt(ne,"frozen:load"),ee=new xr({orgAccess:X,writer:gs(R),restoringWriter:gs(De(void 0)),guard:d,mockDetector:E,recordTypeResolver:new Ur(X),mappingStore:O,config:this.toLoadConfig(n),sasGuard:F,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:ao(r)});for(let{sweep:z}of H)await z.ask()}let Z=Yr([],H.flatMap(({sweep:z})=>z.takes)),he=(Z.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,M=await this.targetAutomation.read(t.targetOrgId,[...new Set([...te,...Be?.delete??[],...Z.delete??[]])]).catch(z=>({unread:Q(z)})),we=Be?Rr(Be):void 0,et=Rr(Z),tt=(z,se)=>io(z,se)||we?.(z,se)===!0||et(z,se),B=t.muteAutomation===!0?await Sr(async()=>Or(ne),M,{...this.muteLeases,writes:tt}):void 0;if(P=B?.muted,he&&!h.signal.aborted){let z=await he({read:M,steps:Z,mute:B});if(z)throw new fr(z)}let ae=this.targetTier(t.targetOrgId),Rt=await ee.gateLoad({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:ae,...i?.stagingReplay?{stagingReplay:!0}:{},dataset:Y,manifest:ie,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:z=>k(z),onGuardDecision:z=>{N=Oo(N,z)}}),fe=rs({read:M,...B?.plan?{plan:B.plan}:{},written:te,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(A=fe.info,fe.stop&&fe.info)throw new Xr(fe.stop.code,fe.stop.message,fe.info,t.targetOrgId);let ft=t.acceptEmails===!0,rt=Wc(Y,n,t.pilot),xe=await this.loadEmailsFor({conn:ne,orgId:t.targetOrgId,orgTier:ae,read:M,...B?.plan?{plan:B.plan}:{},writes:tt,dataset:rt,accepted:ft,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(I=xe,xe.stop)throw new pr(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:M,mute:B,request:t.checkpointFirst,replay:i!==void 0}):void 0,ve=Be?await this.purgedOf(O,n):void 0,kt=Promise.resolve().then(()=>ne.request({method:"GET",url:"/limits"}));kt.catch(()=>{});let en={request:()=>kt},lo=await Fo(en).catch(z=>({unread:Q(z)})),tn=t.pilot?void 0:await this.loadSentOf(ne,Y),Ut=t.pilot?void 0:Bc({dataset:Y,storage:lo,...tn?{sent:tn}:{},...ve?{purged:ve}:{},automationBytes:qc(M,B?.plan,Y,tt),target:this.orgNameOf(t.targetOrgId),...i?{replay:!0}:{}});if(Ut)throw new Qr(Ut.message,Ut.storage,t.targetOrgId);if(L=await this.loadApiCheck({conn:en,dataset:rt,...ve?{purged:ve}:{},read:M,...ye?{checkpoint:ye.estimate}:{},...B?.plan?{plan:B.plan}:{},emails:xe,orgId:t.targetOrgId,operation:`frozen:load ${c}`,...i?.converted?{replayReads:i.converted.target.requests}:{}}),L.refused)throw new Zr(L.refused.message,L,t.targetOrgId);i?.checkpoint&&i.choices&&await this.replayStoresInUse().replays.record(i.checkpoint.checkpoint,{organizationId:i.target.organizationId,name:i.target.name},i.choices),ye&&(C=await this.takeLoadCheckpoint(ye,h.signal));let Ue=B?.prepared?await B.prepared.acquire(c):void 0;Ue&&(P=Ue.outcome,V=!0);let at=Ue?xe.run.afterLease(Ue.outcome,ft):void 0;if(Ue&&at)throw P=await Ue.release(),new pr(at.code,at.message,xe.info,t.targetOrgId);D=!0;let hr=()=>ee.load({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:ae,...i?.stagingReplay?{stagingReplay:!0}:{},dataset:Y,manifest:ie,sasDir:q,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...i?{linkByKeys:!0,contractOrgId:Sn(i.target.organizationId)}:{},onProgress:z=>k(z),onGuardDecision:z=>{N=Oo(N,z),(z==="allowed"||z==="confirmed")&&(T=!0)},signal:h.signal,...Ue?{lease:{giveBack:()=>Ue.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})=>!Is(z.result())).map(({loadedAt:z})=>z)}}:{}}),$e=await(Rt==="confirmed"?Yi({approved:!0},hr):hr()).finally(async()=>{Ue&&(P=await Ue.release())});G=!0,k.flush();let Kt=await this.settleReloadSweeps(H),yr=Kt.some(z=>z.result.status!=="success");C&&(W=await this.settleCheckpoint(C,co($e)>0)),w=ec(await O.recorded().catch(()=>{}),U);let It=$!==void 0?Pe.join($,"manifest.json"):void 0;g=!0;let Ft=await this.verifyLoad({orgId:t.targetOrgId,contractPath:$e.contractPath,...It!==void 0?{manifestPath:It}:{},dataset:Y,mappingStore:O,config:n,onProgress:k}),wr="verdict"in Ft?Ft.verdict.status:void 0,Vt=wr==="failed"||wr==="partial"?wr:void 0,Ht=$e.status==="completed"&&(yr||Vt!==void 0)?"partial":$e.status,br=Pf($e);if(v(Vt!==void 0&&br==="success"?"partial":br,Es($e),await jf(Y,O)),$!==void 0&&It!==void 0){let z={contractPath:$e.contractPath,datasetDir:$,manifestPath:It,targetOrgId:t.targetOrgId,status:Ht,at:new Date().toISOString()};this.recordLastRun(z)}let Et=Af($e),b=Object.fromEntries(Object.entries(l??{}).filter(([z])=>(Et.purge.deleted[z]??0)>0)),_=Oe(this.deps,e,"frozen:load:response",{report:{...Et,...Object.keys(b).length>0?{purge:{...Et.purge,cameAlong:b}}:{},status:Ht,...Vt?{verification:Vt}:{},...P?{mutedAutomation:P}:{},...W?{checkpoint:W}:{},...Kt.length>0?{sweeps:Kt}:{},...I&&Uc(I.info)?{emails:I.info}:{},...A?{automation:A}:{},...L?{apiRequests:L}:{}},...i?Gc(this.replayInfoOf(i,ff($e,Y))):{}});this.deps.broker.postToWebview(_),wt(this.deps,c,{status:Ht}),p=!0,Ht!=="completed"?this.liveTracker?.partial(c):this.liveTracker?.complete(c),this.postVerification(e,Ft),m()}catch(F){k.flush();let q=await this.settleReloadSweeps(H).catch(()=>[]),Y=q.length>0?{sweeps:q}:{};if(C&&W===void 0){let O=F instanceof it||F instanceof $t?F.written:void 0;W=await this.settleCheckpoint(C,O?co(O)>0:D&&!On(F))}let ie=W?{checkpoint:W}:{},$=V&&P?{mutedAutomation:P}:{};if(F instanceof Gt){v("stopped",void 0,void 0,F.code),re(this.deps,"frozen:load","frozen:load:error",e,F,{code:F.code,...F.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),F.code==="LOAD_CANCELLED"?(this.registry?.abort(c),wt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),m()):(wo(this.deps,c,F.message,!0),this.liveTracker?.fail(c,F.message),m(F));return}if(F instanceof it){let O=Tf(F.written);v(O,Es(F.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,F,{code:"LOAD_CANCELLED",extraPayload:{written:co(F.written),...ie,...Y,...$}}),m();return}let K=On(F)||F instanceof Qe||F instanceof fr||F instanceof pr||F instanceof Xr||F instanceof Zr||F instanceof Qr?F:void 0,X=K!==void 0||(N==="refused"||N==="declined")&&!T,ne=F instanceof $t?F:void 0,ge=ne?ne.cause:F,_e=K?.code??this.errorCodeFor(ge,"LOAD_ERROR"),De=ne===void 0&&!G&&!T;v(X||De?"stopped":"failure",ne?Es(ne.written):void 0,void 0,K?.code??(De?_e:void 0));let E={...ne&&ge instanceof Ve?{guard:ge.code}:this.errorDetailOf(ge),...ie,...Y,...$,...De?{written:0}:{}};re(this.deps,"frozen:load","frozen:load:error",e,F,{code:_e,retryable:ge instanceof lt,extraPayload:Object.keys(E).length>0?E:void 0}),p||(wo(this.deps,c,Q(F),!0),this.liveTracker?.fail(c,Q(F))),m(F)}}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?Ct(t,e.mute?.plan,io):{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(i=>({unread:Q(i)})),n=e.muteAutomation?await Sr(async()=>Or(e.conn),r,{...this.muteLeases,writes:io}).catch(i=>{Ot.warn(`Frozen preview: the mute could not be planned (${Q(i)})`)}):void 0,s=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(s,{}).catch(i=>{Ot.warn(`Frozen preview: ${Pn(i)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Gt(Pr,Pn(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:Qc(e.msg.id)},s;try{s=await t.scope(r,n)}catch(d){throw new Gt(Pr,Pn(d))}let i=Oa(s);if(i)throw new Gt(i.code,i.message);return{checkpoints:t,ask:r,own:n,estimate:s}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:s,estimate:i}=e,d=await Sa(()=>r.take(n,s,{planned:i,signal:t}));if("stop"in d)throw new Gt(d.stop.code===Pr?Pr:"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 Ot.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${Q(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(ur);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(Vc,t,Jr),this.deps.configStore.set(ur,e,Jr)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(Os,{...this.lastVerifies(),[e]:t},Jr)}lastVerifies(){return this.deps.configStore.get(Os)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(ur);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(vs);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(Os,{...r,[t]:e},Jr),this.deps.configStore.delete(vs)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(vs),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(Vc)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(ur);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(ur);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=ot(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,i=await this.replaceRefusal(t,r,t.goneFirst),d=i&&"error"in i?i: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 a=new de,u=r.sasDir(a),{dataset:l,manifest:c}=await r.read(a),f=this.buildTargetOrgAccess(),p=await Ae(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=Dt(p,"frozen:load:preview"),m=await new xr({orgAccess:f,writer:df,guard:this.deps.infraServices?.productionGuard??new Ji,mockDetector:n.mockDetection?new Lr(f,n.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Ur(f),mappingStore:r.mappingStore(a),config:this.toLoadConfig(n),sasGuard:a,serverTime:()=>g.serverTime(),readValidationRules:async I=>{let{toolingQueriesOver:A,toolingValidationRules:L}=await import("./chunk-TQJ5NPRC.mjs"),{toolingRetrievesOver:v}=await import("./chunk-QO4MPHZD.mjs"),P=p.tooling;return L(async C=>(await Ii({query:async W=>P.query(W),queryMore:async W=>P.queryMore(W)},C)).records,A(p),v(p))(I)}}).planLoad({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:this.targetTier(t.targetOrgId),...s?.stagingReplay?{stagingReplay:!0}:{},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 Xe&&I.gaps!==void 0&&(I.refusedBeside=await this.refusedBesideOf({conn:p,orgId:t.targetOrgId,dataset:l,store:r.mappingStore(a),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,k=r.mappingStore(a),N=_c(p),{emails:T,automation:j,apiRequests:x,automationBytes:U}=await this.previewWhatRuns({conn:p,limits:N,orgId:t.targetOrgId,dataset:l,store:k,config:n,parsed:t,...y?{checkpoint:y}:{},...s?.converted?{replayReads:s.converted.target.requests}:{}}),S=await this.previewStorageOf({conn:N,org:p,dataset:l,store:k,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}:{}},...Gc(w)}))}catch(a){re(this.deps,"frozen:load:preview","frozen:load:preview:error",e,a,{code:this.errorCodeFor(a,"PREVIEW_ERROR"),retryable:a instanceof lt,extraPayload:this.errorDetailOf(a)})}}async refusedBesideOf(e){let{replay:t,...r}=e,n=_c(e.conn),{emails:s,automation:i,apiRequests:d,automationBytes:a}=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,...a!==void 0?{automationBytes:a}:{},targetOrgId:e.orgId,replay:t!==void 0}),{orgId:l}=e,c=[];return i?.refused&&c.push({...i.refused,orgId:l,automation:i}),s?.refused&&c.push({...s.refused,orgId:l,emails:s}),u?.refusal&&c.push({...u.refusal,orgId:l,storage:uf(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?Rr(r):void 0,s=(f,p)=>io(f,p)||n?.(f,p)===!0,i=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(f=>f.objectApiName),...r?.delete??[]])]).catch(f=>({unread:Q(f)})),d=t.muteAutomation===!0?await Sr(async()=>Or(e.conn),i,{...this.muteLeases,writes:s}).catch(()=>{}):void 0,{info:a}=rs({read:i,...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=Wc(e.dataset,e.config,t.pilot),l=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:i,...d?.plan?{plan:d.plan}:{},writes:s,dataset:u,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(f=>{Ot.warn(`Frozen preview: the emails could not be judged (${Q(f)})`)}),c=await this.loadApiCheck({conn:e.limits,dataset:u,...r?{purged:await this.purgedOf(e.store,e.config)}:{},read:i,...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=>{Ot.warn(`Frozen preview: the API requests could not be judged (${Q(f)})`)});return{...l&&Uc(l.info)?{emails:l.info}:{},...a?{automation:a}:{},...c?{apiRequests:c}:{},automationBytes:qc(i,d?.plan,e.dataset,s)}}catch(r){return Ot.warn(`Frozen preview: what the target runs could not be judged (${Q(r)})`),{}}}async handleVerify(e){let t=ot(Fi,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,i=s?void 0:this.lastRunOf(t.targetOrgId);if(!s&&!i){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=Xc(a=>{let u=Oe(this.deps,e,"frozen:load:progress",{...a});this.deps.broker.postToWebview(u)},100);try{let a=new de,u=i?.contractPath??s?.contractPath??"";if(s&&!await Ze(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(i){let g=a.assertOutsideRepo(this.resolveSasDir(n)),h=Pe.dirname(i.contractPath)!==Pe.dirname(En(a,g,t.targetOrgId)),m=await Ze(i.contractPath);if(h||!m){let y=Pe.dirname(i.contractPath),k;h?m?k=`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.`:k=`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.`:k=`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(k),{code:"SAS_CHANGED",extraPayload:{sasDir:g,loadSas:y,sasMoved:h,contractThere:m}});return}}let l=r.mappingStore(a);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=st(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(!ld(Nn(a,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}=i?await this.readFrozenDataset(i.datasetDir,a):await r.read(a);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:u,...i?{manifestPath:i.manifestPath}:{},dataset:p,mappingStore:l,config:n,onProgress:d})}catch(a){re(this.deps,"frozen:verify","frozen:verify:error",e,a,{code:this.errorCodeFor(a,"VERIFY_ERROR"),retryable:a instanceof lt})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new Zn({orgAccess:this.buildTargetOrgAccess(),sasGuard:new de}),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=ot(Ei,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,i,d;try{s=r.mappingStore(new de),i=await s.recordedLoads(),d=or(i)}catch(p){re(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let a=js(d,t),u=t.sweep===!0&&a?.code==="ALREADY_REMOVED";if(a&&!u||!d){a&&n(a.message,a.code);return}let l=st(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(i,d):[],muteAutomation:t.muteAutomation===!0,pending:f,audit:ao(r)})}finally{this.removing.delete(c),f?.release()}}async handleRemoveAutomation(e){let t=ot(Li,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 de),i,d;if(t.reload===!0)i=await this.purgeStepsOf(s,n,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(d=await this.purgeStepsOf(s,n));else{let l=or(await s.recordedLoads()),c=js(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}i=Yr(st(l),t.sweptObjects??[])}let a=this.targetAutomation,u=await new At(As).withTimeout("frozen:remove:automation",()=>a.read(t.targetOrgId,i.delete??[]));this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:u,steps:i,...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(i=>st(i)).filter(({objectApiName:i})=>!Object.hasOwn(n,i));return Yr(s,r)}async handleRemovePreview(e){let t=ot(Ci,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,i,d=!1)=>re(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,s,{code:i,retryable:d});try{let s=r.mappingStore(new de),i=or(await s.recordedLoads()),d=js(i,t);if(d||!i){d&&n(new Error(d.message),d.code);return}let a=st(i).reduce((c,f)=>c+f.ids.length,0),u=this.removalGuardRefusals(i.orgId,a),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(i,t.includeChanged===!0),planned:a};else{let c=await Ae(i.orgId,this.deps.orgRegistry,this.deps.orgManager);l=await this.previewRemovalOf(c,i,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[{...St}];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 i=r.declinedWithoutAsking(s,n);return i===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${i} (${s.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=st(t),s=await bn(Dt(e,"frozen:remove:preview"),n,{...Fs(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((i,d)=>i+d.ids.length,0),objects:s.preview.objects.map(i=>({objectApiName:i.objectApiName,planned:i.planned,toDelete:i.toDelete,alreadyGone:i.alreadyGone,changedSince:i.changedSince,keptChanged:i.keptChanged,changedBy:i.changedBy,undeletable:i.undeletable,notVisible:i.notVisible,unread:i.unread,reasons:i.reasons})),userNames:s.preview.userNames}}unreadPreviewOf(e,t){let r=Ln(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 i=t.mappingStore(new de),d=await i.recordedLoads();if(d.length===0||await i.isStale())return;if(d.some(a=>!a.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 a=await Ae(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=d.filter(p=>st(p).length>0),l=new Set([...u.flatMap(p=>st(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 bn(Dt(a,"frozen:load:replace"),st(p),{...Fs(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=Sf(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(i){return{error:i,code:this.errorCodeFor(i,"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:i,sweep:d,pending:a}=t,u=t.audit??{module:"frozen"},l=n.orgId,c=s.reduce((A,L)=>A+L.ids.length,0),f=(A,L)=>this.refuseRemove(e,A,L),p=this.deps.infraServices?.productionGuard;if(!p){Je(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",code:St.code}),f(St.message,St.code);return}let{check:g,decision:h}=c>0?await In(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")){Je(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(!a?.signal.aborted)return!1;Je(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:hi});let A={status:"cancelled",includeChanged:i,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){Je(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){Je(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 k=e.id,N=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,L)=>{j=v=>v===void 0?A():L(v)});x.catch(()=>{}),vr(this.deps,k,"frozen",N),this.registry?.register(k,"frozen",N,x,T),this.liveTracker?.register(k,"frozen",N,c);let U,S,w=[],I;try{let A=await Ae(l,this.deps.orgRegistry,this.deps.orgManager),L=new Set([n,...t.alongside].map(O=>O.endedAt));S=d?await this.sweepOfRemoval({conn:A,load:n,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:k,muted:()=>c===0?I:void 0,sweptWith:L}):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:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:`${k}-${O+2}`,muted:()=>{},sweptWith:L})});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 W,D=this.removalAsker,G=Yr(s,P.flatMap(O=>O.takes));if((t.muteAutomation||D)&&!T.signal.aborted&&(G.delete??[]).length>0){let O=this.targetAutomation,J=await new At(As).withTimeout("frozen:remove automation",()=>O.read(l,G.delete??[])).catch(Z=>({unread:Q(Z)}));t.muteAutomation&&(W=await Sr(async()=>Or(A),J,{...this.muteLeases,writes:Rr(G)}));let ee=await D?.({read:J,steps:G,mute:W});if(ee)throw new fr(ee)}I=W?.muted;let V,H=async()=>{let O=W?.prepared;!O||T.signal.aborted||(V=await O.acquire(k),I=V.outcome)},q=await(c===0?(async()=>(await H(),await C(O=>O.first()),await C(O=>O.afterRemoval()),_i))():bn(Dt(A,"frozen:remove"),s,{...Fs(n),...v?{sweep:O=>C(J=>J.first(O)),afterRemoval:O=>C(J=>J.afterRemoval(O)),automationMade:v.automationMade}:{},onUndeletable:yi(this.deps,l,"frozen:remove"),beforeFirstWrite:H,includeChanged:i,signal:T.signal,onProgress:(O,J,ee)=>{let Z=Math.min(100,Math.round(O/Math.max(J,1)*100));Ri(this.deps,k,Z,O,J,ee),T.signal.aborted||this.registry?.updateProgress(k,Z),this.liveTracker?.updateProgress(k,Z,O,J,ee)}})).finally(async()=>{V&&(I=await V.release())}),Y=await S?.settle(),ie=await this.settleReloadSweeps(w),$=n.removal?.removedAt,K=Ln(n),X=qi(q.objects,q.cancelled),ne={status:ie.reduce((O,J)=>vo(O,J.result),vo(X,Y)),includeChanged:i,objects:q.objects,finishedAt:new Date().toISOString(),...$?{leftBy:$}:{},...Y?{sweep:Y}:{},...ie.length>0?{otherLoadSweeps:ie}:{},...K.length>0?{keptByThePlatform:K}:{},...I?{mutedAutomation:I}:{}};c>0&&Je(this.deps,{action:"cleanup_delete",module:u.module,operationId:k,orgId:l,outcome:Wi({status:X}),guard:h,objects:Gi(ne.objects),...$?{leftBy:$}:{},...I?{muted:un(I)}:{}});let ge=Ui(ne,c,n.removal);(q.gone.length>0||Object.keys(q.stamps).length>0||q.span||ge)&&(await r.recordRemoval(n.endedAt,{gone:q.gone,stamps:q.stamps,...q.span?{span:q.span}:{},...ge?{mark:ge}:{}})||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&&Is(Y)?[n.endedAt]:[],...ie.filter(O=>Is(O.result)).map(O=>O.loadedAt)];await r.letSweptGo(_e).catch(()=>!1);let De=Oe(this.deps,e,"frozen:remove:response",{result:ne,operationId:k});this.deps.broker.postToWebview(De);let R=[Y,...ie.map(O=>O.result)].find(O=>O!==void 0&&O.status!=="success"),E=ne.status==="failure"?"No record this load created could be removed.":c===0&&R?R.refusal??"The sweep left records in the org.":void 0;ne.status==="cancelled"||Y?.status==="cancelled"||ie.some(O=>O.result.status==="cancelled")?(wt(this.deps,k,{aborted:!0}),this.liveTracker?.cancel(k)):(wt(this.deps,k,{status:E&&c===0?"failure":ne.status}),E?(U=new Error(E),this.liveTracker?.fail(k,E)):ne.status==="partial"?this.liveTracker?.partial(k):this.liveTracker?.complete(k))}catch(A){U=A,await S?.settle().catch(()=>{});for(let{sweep:v}of w)await v.settle().catch(()=>{});let L=On(A)||A instanceof fr?A:void 0;Je(this.deps,{action:"cleanup_delete",module:u.module,operationId:k,orgId:l,outcome:L?"stopped":"failure",guard:h,...L?{code:L.code}:{}}),re(this.deps,"frozen:remove","frozen:remove:error",e,A,{code:L?.code??"REMOVE_ERROR",retryable:!0}),wt(this.deps,k,{status:"failure"}),this.liveTracker?.fail(k,Q(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=>gf(d,n),i=[];for(let[d,a]of t.entries())i.push({loadedAt:a.endedAt,judged:s,sweep:await this.sweepOfRemoval({conn:e.conn,load:a,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 i}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:s}of e){let i=await n.settle();t.push({loadedAt:r,result:s?s(i):i})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return ed({input:()=>this.sweepInputOfLoad(Dt(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith,e.audit?.sasMark),org:Fn(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 i=e.judged?e.judged(n):n,d=Xa(i,"");delete d.forgeId;let a=e.muted();Je(this.deps,{action:"cleanup_delete",module:e.audit?.module??"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:i.status==="refused"?"stopped":i.status,...s?{guard:s}:{},...i.status==="refused"?{code:td(s)}:{},objects:Ja(i),details:{...d,loadedAt:r.endedAt},...a?{muted:un(a)}:{}})},keepMade:async(n,s,i)=>{await e.store.recordMade(r.endedAt,n,s,i)}})}async sweepInputOfLoad(e,t,r,n,s=new Set,i=this.sasMarkInUse()){let d=Do(t),a=this.targetAutomation,u;try{u=await new At(As).withTimeout("frozen:remove sweep automation",()=>a.read(t.orgId,d.map(g=>g.objectApiName)))}catch(g){u={error:Q(g)}}let l=t.writtenBetween??await Za(e,d,r),{ties:c,sweptAlong:f}=await this.tiesOfLoad(t,l,n,s,i),p=new Set([...t.mapping.values(),...f].map(g=>g.slice(0,15)));return Qa({writtenBetween:l,created:d,remap:p,automation:Ya(u),...t.runUserId?{runUserId:t.runUserId}:{},ties:c,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return nc(new gi(this.deps.configStore).list({orgId:e,limit:Bs}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?Gn(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n,s){let i=[],d=[],a=await r?.recordedLoads().catch(()=>[])??[];for(let l of a){if(l.endedAt===e.endedAt||l.orgId!==e.orgId)continue;let c=Do(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);i.push({ids:c,from:f,to:Number.isFinite(p)?p:f})}i.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),i.push(...tc(this.auditedLoadsInto(e.orgId),{sasMark:s,own:a.filter(l=>l.orgId===e.orgId)}));let u=nd(e.removalSpans);return{ties:{otherRuns:rd(t,i),...u?{removalBegan:u}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:d}}async handleRemoveSweep(e){let t=ot(Ni,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,i)=>re(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(s),{code:i});try{let s=r.mappingStore(new de);if(t.reload===!0){await this.listReloadSweeps(e,s,t,ao(r).sasMark);return}let i=await s.recordedLoads(),d=or(i);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 a=xo(i,d),u=new Set([d,...a].map(f=>f.endedAt)),{listing:l,otherLoads:c}=await new At(Jc).withTimeout("frozen:remove:sweep",async()=>{let f=await Ae(d.orgId,this.deps.orgRegistry,this.deps.orgManager),p=Fn(f,"frozen:remove:sweep"),g=async m=>zo(p,await this.sweepInputOfLoad(p,m,void 0,s,u,ao(r).sasMark),m.removalSpans),h=[];for(let m of a)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(),i=(s??[]).filter(a=>a.created);if(s&&!s.some(a=>a.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 At(Jc).withTimeout("frozen:remove:sweep",async()=>{if(i.length===0)return[];let a=await Ae(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=Fn(a,"frozen:remove:sweep"),l=new Set(i.map(f=>f.endedAt)),c=[];for(let f of i)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){bi(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 Tn(f.salt).saltFingerprint,source:f.source})}catch{s={present:!1}}let i=null;try{let f=new de;if(await Ze(Pe.join(r,qr))){let p=await as(r,f);i={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{i=null}let d=null;try{let p=new de().assertOutsideRepo(Pe.join(n,"manifest.json"));await Ze(p)&&(d=Ps(sr(JSON.parse(await Se.readFile(p,"utf8")))))}catch{d=null}let a=this.deps.configStore.get(ur),u=[];try{let f=new de,p=f.assertOutsideRepo(r);for(let g of await pd(p,f))try{let h=or(await new Cn(p,{guard:f,orgId:g}).recordedLoads());h&&u.push(fd(h))}catch{}}catch{u.length=0}let l={configured:t!==null,sasDir:r,datasetDir:n,salt:s,mockDetectionConfigured:t?.mockDetection!==void 0,selection:i,manifest:d,lastLoad:a?{status:a.status,orgId:a.targetOrgId,at:a.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{Df as a,fl as b,pl as c,hp as d,Qd as e,Gn as f,ec as g,tc as h,bp as i,Rp as j,Ap as k,Fp as l,tl as m};