sandforge 1.84.1 → 1.86.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 (277) hide show
  1. package/README.md +1 -1
  2. package/lib/{chunk-S42RBRH2.mjs → chunk-22L43JMK.mjs} +1 -1
  3. package/lib/{chunk-Y2DRK37K.mjs → chunk-2LSGWTWX.mjs} +1 -1
  4. package/lib/{chunk-24RFOFYT.mjs → chunk-2YJJTQNC.mjs} +1 -1
  5. package/lib/chunk-34SMB5PA.mjs +10 -0
  6. package/lib/chunk-35B73566.mjs +7 -0
  7. package/lib/{chunk-3TZSBHEY.mjs → chunk-35IJ4WEU.mjs} +1 -1
  8. package/lib/chunk-3EHPAFKV.mjs +7 -0
  9. package/lib/{chunk-6YL7BNYD.mjs → chunk-3HAVVEXF.mjs} +1 -1
  10. package/lib/{chunk-6JWWSDM6.mjs → chunk-3I6FXFCN.mjs} +1 -1
  11. package/lib/{chunk-WUUKFE2U.mjs → chunk-3KJCSYXY.mjs} +1 -1
  12. package/lib/{chunk-2HVOZUM4.mjs → chunk-3L6DVNCR.mjs} +1 -1
  13. package/lib/chunk-3LRFPGYZ.mjs +7 -0
  14. package/lib/{chunk-GWZRR3MM.mjs → chunk-3MVWGL5A.mjs} +1 -1
  15. package/lib/{chunk-KGU4SVIT.mjs → chunk-4CSBZZAL.mjs} +1 -1
  16. package/lib/{chunk-JE6SCT6R.mjs → chunk-4NSXPONF.mjs} +1 -1
  17. package/lib/{chunk-UIOMAX56.mjs → chunk-4VLP6RHC.mjs} +1 -1
  18. package/lib/{chunk-YA6ATMTB.mjs → chunk-4XROG5CT.mjs} +1 -1
  19. package/lib/chunk-54V4FVEY.mjs +7 -0
  20. package/lib/chunk-55OJJT2Q.mjs +7 -0
  21. package/lib/{chunk-6QE6R6RL.mjs → chunk-5EHHQ5UX.mjs} +1 -1
  22. package/lib/{chunk-FITPY3L4.mjs → chunk-5JMQXHJ2.mjs} +1 -1
  23. package/lib/{chunk-W6PN6TJG.mjs → chunk-65AMXOQU.mjs} +1 -1
  24. package/lib/{chunk-3Q353S2R.mjs → chunk-6HHSAPIM.mjs} +1 -1
  25. package/lib/chunk-6KVBCFVS.mjs +7 -0
  26. package/lib/chunk-6NG7C2U3.mjs +476 -0
  27. package/lib/chunk-6ROL3KBM.mjs +7 -0
  28. package/lib/{chunk-2JDAOWUW.mjs → chunk-72AWCN7U.mjs} +1 -1
  29. package/lib/{chunk-JLSIWO4Z.mjs → chunk-7KHA5UIQ.mjs} +1 -1
  30. package/lib/chunk-7O6EFNQS.mjs +10 -0
  31. package/lib/{chunk-WWTCWWZI.mjs → chunk-A2CH2QGX.mjs} +1 -1
  32. package/lib/chunk-A2TXLAC3.mjs +276 -0
  33. package/lib/chunk-ALWVNR34.mjs +7 -0
  34. package/lib/{chunk-D4GF4FAB.mjs → chunk-ATBQIE2V.mjs} +1 -1
  35. package/lib/{chunk-NED4MBIM.mjs → chunk-ATQML7ZK.mjs} +1 -1
  36. package/lib/chunk-AVY742BJ.mjs +7 -0
  37. package/lib/{chunk-YWEQQL3C.mjs → chunk-AXTB2HJS.mjs} +1 -1
  38. package/lib/chunk-BBZUGKBZ.mjs +10 -0
  39. package/lib/chunk-BIDXK7KA.mjs +7 -0
  40. package/lib/{chunk-O677VOGO.mjs → chunk-BLMJ4WVI.mjs} +1 -1
  41. package/lib/{chunk-RE7RYF3B.mjs → chunk-BNHJCJJM.mjs} +1 -1
  42. package/lib/{chunk-5M5FQ7RP.mjs → chunk-BNPQEQXC.mjs} +1 -1
  43. package/lib/chunk-C5AUNG6T.mjs +37 -0
  44. package/lib/{chunk-ETDCBLGU.mjs → chunk-C5EQ7GFC.mjs} +1 -1
  45. package/lib/{chunk-MJZU3U5O.mjs → chunk-C7CKDZMC.mjs} +61 -61
  46. package/lib/{chunk-HCGXK7G7.mjs → chunk-CB4U22NR.mjs} +1 -1
  47. package/lib/chunk-CJAWKLAL.mjs +7 -0
  48. package/lib/chunk-CL75DEMQ.mjs +9 -0
  49. package/lib/{chunk-VCUXCK36.mjs → chunk-CLUNF4FK.mjs} +1 -1
  50. package/lib/chunk-CSMGP53U.mjs +7 -0
  51. package/lib/{chunk-7YNM6KFZ.mjs → chunk-CT324C7I.mjs} +1 -1
  52. package/lib/{chunk-7UVKIWKV.mjs → chunk-CZXDJXQP.mjs} +1 -1
  53. package/lib/{chunk-43TOMFV4.mjs → chunk-D2X6U3MS.mjs} +1 -1
  54. package/lib/{chunk-M6K34KGF.mjs → chunk-DAUX63UB.mjs} +1 -1
  55. package/lib/chunk-DB7JNALQ.mjs +10 -0
  56. package/lib/chunk-DDNCJVZ2.mjs +17 -0
  57. package/lib/{chunk-FP7CYB2F.mjs → chunk-DLSU66MY.mjs} +1 -1
  58. package/lib/{chunk-JKJ74BX5.mjs → chunk-DO6PSHQZ.mjs} +1 -1
  59. package/lib/{chunk-MDMPJEV3.mjs → chunk-DUBECLZV.mjs} +1 -1
  60. package/lib/{chunk-KZTZDC7H.mjs → chunk-DYHF6DNT.mjs} +1 -1
  61. package/lib/chunk-E5FSPXYH.mjs +930 -0
  62. package/lib/{chunk-Q7GIJBCD.mjs → chunk-EGL3I3IX.mjs} +1 -1
  63. package/lib/chunk-EIYMQPMG.mjs +7 -0
  64. package/lib/{chunk-RHNTHGNU.mjs → chunk-EUIALBMX.mjs} +1 -1
  65. package/lib/{chunk-NCZKWSC7.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
  66. package/lib/{chunk-PAXNWTYK.mjs → chunk-FM4QCTO7.mjs} +1 -1
  67. package/lib/{chunk-HV7VPEXP.mjs → chunk-FRSIEASH.mjs} +1 -1
  68. package/lib/{chunk-QAFPQ3YB.mjs → chunk-FV6MOSHD.mjs} +1 -1
  69. package/lib/chunk-FYG47CNA.mjs +7 -0
  70. package/lib/chunk-GB6W4Q56.mjs +7 -0
  71. package/lib/chunk-GEV2DCMK.mjs +7 -0
  72. package/lib/{chunk-NSQWI7ZY.mjs → chunk-GFB2DNCB.mjs} +1 -1
  73. package/lib/chunk-GFGMGFSH.mjs +7 -0
  74. package/lib/{chunk-RGUQOSBU.mjs → chunk-GIFQXB2Q.mjs} +1 -1
  75. package/lib/{chunk-JAEDM4SI.mjs → chunk-GP5J3DGS.mjs} +1 -1
  76. package/lib/chunk-GQZEX7LH.mjs +231 -0
  77. package/lib/{chunk-JSAJS3MY.mjs → chunk-GYDTM62J.mjs} +1 -1
  78. package/lib/{chunk-OPMO6I45.mjs → chunk-GYFIXUJG.mjs} +1 -1
  79. package/lib/chunk-GZW2GNFK.mjs +7 -0
  80. package/lib/chunk-H6BHWAX7.mjs +8 -0
  81. package/lib/{chunk-EAC5QCE3.mjs → chunk-HDDJ3CVN.mjs} +1 -1
  82. package/lib/{chunk-5SMWFNE7.mjs → chunk-HDWB4ZOG.mjs} +1 -1
  83. package/lib/chunk-HGVPBJR6.mjs +7 -0
  84. package/lib/{chunk-BBRWFKS5.mjs → chunk-HLROVOR6.mjs} +1 -1
  85. package/lib/{chunk-LKTNQEBS.mjs → chunk-HUOR4M2L.mjs} +1 -1
  86. package/lib/chunk-HZCS6EED.mjs +8 -0
  87. package/lib/{chunk-36JOHEJL.mjs → chunk-HZUI56KZ.mjs} +1 -1
  88. package/lib/chunk-IAB5H7WN.mjs +7 -0
  89. package/lib/{chunk-X4BXESMQ.mjs → chunk-IQ5UKRHU.mjs} +1 -1
  90. package/lib/{chunk-54WZUS7J.mjs → chunk-IRQ4WANV.mjs} +1 -1
  91. package/lib/{chunk-5IZTFMJM.mjs → chunk-IT3DGX37.mjs} +1 -1
  92. package/lib/chunk-J347SPU6.mjs +49 -0
  93. package/lib/{chunk-QO53K5W2.mjs → chunk-JANBNTR5.mjs} +1 -1
  94. package/lib/chunk-JFXQZPRY.mjs +9 -0
  95. package/lib/{chunk-KAZS5Z6W.mjs → chunk-JRLYWVF4.mjs} +1 -1
  96. package/lib/{chunk-GKY2JMHY.mjs → chunk-JSNMUTY6.mjs} +1 -1
  97. package/lib/chunk-JTNJKSAA.mjs +7 -0
  98. package/lib/{chunk-7WATA4SB.mjs → chunk-JV2LAKWQ.mjs} +1 -1
  99. package/lib/{chunk-WAPSSYMT.mjs → chunk-JV7K2ZHK.mjs} +1 -1
  100. package/lib/{chunk-ZBAWJUG2.mjs → chunk-K4TQ7YHX.mjs} +1 -1
  101. package/lib/chunk-K5PUMHZU.mjs +7 -0
  102. package/lib/chunk-KH4KLCYG.mjs +7 -0
  103. package/lib/{chunk-OLCVHL7I.mjs → chunk-KQVLZVOP.mjs} +1 -1
  104. package/lib/chunk-KWUS7UAV.mjs +19 -0
  105. package/lib/{chunk-JGZPD4IM.mjs → chunk-L6G73FXM.mjs} +1 -1
  106. package/lib/{chunk-BAWCOKRW.mjs → chunk-LG466Q5H.mjs} +1 -1
  107. package/lib/{chunk-GMIGWR6U.mjs → chunk-LHNAR6FC.mjs} +1 -1
  108. package/lib/chunk-LT4GHEI2.mjs +7 -0
  109. package/lib/{chunk-EC72TIEG.mjs → chunk-MR262Y3B.mjs} +1 -1
  110. package/lib/{chunk-LA4KIATH.mjs → chunk-NCCHOV2N.mjs} +1 -1
  111. package/lib/chunk-NICRSGLS.mjs +7 -0
  112. package/lib/chunk-NV5QA2HY.mjs +7 -0
  113. package/lib/{chunk-PR3XCSPO.mjs → chunk-O3GIN5TU.mjs} +1 -1
  114. package/lib/chunk-O6FHK6NQ.mjs +13 -0
  115. package/lib/{chunk-M4BLK6HJ.mjs → chunk-O7YIEFG7.mjs} +1 -1
  116. package/lib/chunk-OCUVAA5E.mjs +7 -0
  117. package/lib/chunk-OLCS7JCT.mjs +14 -0
  118. package/lib/chunk-ON7Y63FK.mjs +9 -0
  119. package/lib/{chunk-N4WPCWJO.mjs → chunk-OO2WY3UB.mjs} +1 -1
  120. package/lib/{chunk-MSIEU5MR.mjs → chunk-OT2NHL2V.mjs} +1 -1
  121. package/lib/{chunk-6WX5ZU7Q.mjs → chunk-P2M5ZXWU.mjs} +1 -1
  122. package/lib/{chunk-GNRSF65U.mjs → chunk-P4YOHLZ4.mjs} +1 -1
  123. package/lib/chunk-PBHDPTT6.mjs +343 -0
  124. package/lib/chunk-PE7CHD2W.mjs +7 -0
  125. package/lib/{chunk-PBY2O6OF.mjs → chunk-PIQ2I67B.mjs} +1 -1
  126. package/lib/chunk-PKYDNZJK.mjs +7 -0
  127. package/lib/chunk-PVZ72OOQ.mjs +7 -0
  128. package/lib/chunk-QACFTHJM.mjs +8 -0
  129. package/lib/{chunk-J3DND3BC.mjs → chunk-QGVL5EW3.mjs} +1 -1
  130. package/lib/chunk-QHE2RUWX.mjs +7 -0
  131. package/lib/{chunk-QKEKG2LD.mjs → chunk-RCW5BZNW.mjs} +1 -1
  132. package/lib/{chunk-4JE4BYXK.mjs → chunk-RJ6HHG7J.mjs} +1 -1
  133. package/lib/{chunk-ZQWIVYVM.mjs → chunk-RPTEEI4R.mjs} +1 -1
  134. package/lib/chunk-RQW5S67A.mjs +7 -0
  135. package/lib/chunk-RTCMYMED.mjs +7 -0
  136. package/lib/chunk-RWVX7XSD.mjs +7 -0
  137. package/lib/{chunk-WY5V5PR3.mjs → chunk-RZOINFNL.mjs} +1 -1
  138. package/lib/chunk-SOOTWGMQ.mjs +7 -0
  139. package/lib/chunk-STQ2JMIZ.mjs +7 -0
  140. package/lib/{chunk-6PD6K7LP.mjs → chunk-SUIPDW5O.mjs} +1 -1
  141. package/lib/{chunk-TNT27RBG.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
  142. package/lib/{chunk-4EOHEDFP.mjs → chunk-T542Z54E.mjs} +1 -1
  143. package/lib/chunk-TAN2CIRI.mjs +21 -0
  144. package/lib/{chunk-A3MYSOOC.mjs → chunk-TCNBINOG.mjs} +1 -1
  145. package/lib/chunk-TFDF3DBN.mjs +7 -0
  146. package/lib/chunk-TICZXC53.mjs +9 -0
  147. package/lib/chunk-TLX45X5U.mjs +7 -0
  148. package/lib/{chunk-QTG6LUZT.mjs → chunk-TMIV3IWH.mjs} +1 -1
  149. package/lib/chunk-TQ6HEJ73.mjs +11 -0
  150. package/lib/chunk-TTU5EQZ6.mjs +7 -0
  151. package/lib/chunk-TYUYPFDJ.mjs +7 -0
  152. package/lib/chunk-TZXYVMZC.mjs +7 -0
  153. package/lib/chunk-UCUFLFNK.mjs +7 -0
  154. package/lib/chunk-UK3QLBHW.mjs +7 -0
  155. package/lib/{chunk-IZGCEOYO.mjs → chunk-UM2B4GR7.mjs} +1 -1
  156. package/lib/chunk-UZFTTNOP.mjs +7 -0
  157. package/lib/chunk-V3AXSKSU.mjs +7 -0
  158. package/lib/chunk-VA6EEI6X.mjs +21 -0
  159. package/lib/{chunk-OFTT7J2M.mjs → chunk-VFKG2G37.mjs} +1 -1
  160. package/lib/chunk-VJNEW5MQ.mjs +7 -0
  161. package/lib/{chunk-L53JWJ3S.mjs → chunk-VKREON6Q.mjs} +1 -1
  162. package/lib/{chunk-NOBQTEQD.mjs → chunk-VNNDYPBL.mjs} +1 -1
  163. package/lib/{chunk-ZJW6YOMV.mjs → chunk-VRBETPHY.mjs} +1 -1
  164. package/lib/{chunk-EPFCERGL.mjs → chunk-VT6P3X6R.mjs} +1 -1
  165. package/lib/{chunk-ZV7ZFQQC.mjs → chunk-VUTQY76O.mjs} +1 -1
  166. package/lib/chunk-WF5S4FW5.mjs +7 -0
  167. package/lib/{chunk-Z4LKKOFY.mjs → chunk-WJGK6VGU.mjs} +1 -1
  168. package/lib/{chunk-5CRLRHOJ.mjs → chunk-WJHMB3SL.mjs} +1 -1
  169. package/lib/{chunk-OUZQPYT3.mjs → chunk-WQCXOZEJ.mjs} +1 -1
  170. package/lib/{chunk-L2E5WBGD.mjs → chunk-WVVFR4E3.mjs} +1 -1
  171. package/lib/{chunk-PWRJRL5U.mjs → chunk-XBYXT74L.mjs} +1 -1
  172. package/lib/chunk-XJE3LJHP.mjs +7 -0
  173. package/lib/{chunk-CPQIZGG5.mjs → chunk-XV4CVZYD.mjs} +1 -1
  174. package/lib/chunk-Y37ED7AS.mjs +7 -0
  175. package/lib/{chunk-YTLUYSMF.mjs → chunk-YGBNZYT4.mjs} +1 -1
  176. package/lib/{chunk-4CVUUVGJ.mjs → chunk-YGTOX7IL.mjs} +1 -1
  177. package/lib/{chunk-OMNMLKDT.mjs → chunk-YJ27WHKR.mjs} +1 -1
  178. package/lib/chunk-YRULC27A.mjs +7 -0
  179. package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
  180. package/lib/chunk-YTOTMJTY.mjs +15 -0
  181. package/lib/{chunk-B63POIPQ.mjs → chunk-YZKZC62O.mjs} +1 -1
  182. package/lib/{chunk-DPMRIMUC.mjs → chunk-YZQN7BRB.mjs} +1 -1
  183. package/lib/{chunk-7SQSWVAU.mjs → chunk-Z5IUK2QO.mjs} +1 -1
  184. package/lib/{chunk-M2ABR4JM.mjs → chunk-ZEGSMW5A.mjs} +1 -1
  185. package/lib/{chunk-PR42EZSR.mjs → chunk-ZIKLQZBG.mjs} +1 -1
  186. package/lib/chunk-ZVU7MD2S.mjs +7 -0
  187. package/lib/sandforge-autopilot.mjs +33 -27
  188. package/lib/sandforge-backup.mjs +19 -19
  189. package/lib/sandforge-checkpoint.mjs +1 -1
  190. package/lib/sandforge-cleanup.mjs +1 -1
  191. package/lib/sandforge-clone.mjs +1 -1
  192. package/lib/sandforge-compare.mjs +32 -14
  193. package/lib/sandforge-dataops.mjs +1 -1
  194. package/lib/sandforge-empty.mjs +11 -13
  195. package/lib/sandforge-env.mjs +105 -105
  196. package/lib/sandforge-frozen.mjs +1 -1
  197. package/lib/sandforge-mcp.mjs +2 -2
  198. package/lib/sandforge-monitor.mjs +1 -1
  199. package/lib/sandforge-pipeline.mjs +13 -13
  200. package/lib/sandforge-seed.mjs +1 -1
  201. package/lib/sandforge-sync.mjs +1 -1
  202. package/lib/sandforge-users.mjs +13 -15
  203. package/lib/sandforge.mjs +1 -1
  204. package/lib/sf/sandforge/dataops.mjs +2 -2
  205. package/lib/sfPlugin.mjs +1 -1
  206. package/oclif.manifest.json +1 -1
  207. package/package.json +1 -1
  208. package/lib/chunk-23SEDORH.mjs +0 -11
  209. package/lib/chunk-26POJDIT.mjs +0 -7
  210. package/lib/chunk-2AZQHBEF.mjs +0 -7
  211. package/lib/chunk-2METQHGG.mjs +0 -7
  212. package/lib/chunk-2WFIVO4F.mjs +0 -13
  213. package/lib/chunk-2YHZBUZE.mjs +0 -7
  214. package/lib/chunk-326AJTIU.mjs +0 -272
  215. package/lib/chunk-3PVRGTVK.mjs +0 -7
  216. package/lib/chunk-5XTUSN72.mjs +0 -8
  217. package/lib/chunk-6I6TWNV5.mjs +0 -7
  218. package/lib/chunk-6O222PW6.mjs +0 -7
  219. package/lib/chunk-6ZLKIT3H.mjs +0 -7
  220. package/lib/chunk-7QYHEHMA.mjs +0 -9
  221. package/lib/chunk-B3FBHVNN.mjs +0 -21
  222. package/lib/chunk-BEA27DLS.mjs +0 -7
  223. package/lib/chunk-BRY3PLIZ.mjs +0 -7
  224. package/lib/chunk-CBH3TOWK.mjs +0 -341
  225. package/lib/chunk-CVHNXJH3.mjs +0 -7
  226. package/lib/chunk-DGDRQRCW.mjs +0 -7
  227. package/lib/chunk-DUN2EPRC.mjs +0 -7
  228. package/lib/chunk-E3A3LOCY.mjs +0 -7
  229. package/lib/chunk-F2424IKX.mjs +0 -7
  230. package/lib/chunk-F3AQW6IU.mjs +0 -7
  231. package/lib/chunk-FNJ4SGWO.mjs +0 -7
  232. package/lib/chunk-GOOVPVWX.mjs +0 -7
  233. package/lib/chunk-H2BHESDA.mjs +0 -9
  234. package/lib/chunk-H4CGM6YO.mjs +0 -7
  235. package/lib/chunk-HIDW7FNV.mjs +0 -9
  236. package/lib/chunk-HSBXRQTI.mjs +0 -7
  237. package/lib/chunk-HUZPBE47.mjs +0 -7
  238. package/lib/chunk-I6E6T6YY.mjs +0 -7
  239. package/lib/chunk-IUM4NFKI.mjs +0 -10
  240. package/lib/chunk-IVFVNNGB.mjs +0 -37
  241. package/lib/chunk-JCFBFF4Y.mjs +0 -7
  242. package/lib/chunk-JTJK2D36.mjs +0 -7
  243. package/lib/chunk-KB4ZHM4Q.mjs +0 -10
  244. package/lib/chunk-KJWFYBMU.mjs +0 -15
  245. package/lib/chunk-LC3NDW4N.mjs +0 -7
  246. package/lib/chunk-OM5NORJG.mjs +0 -7
  247. package/lib/chunk-OVNMB6Q2.mjs +0 -7
  248. package/lib/chunk-PEDQPM2P.mjs +0 -926
  249. package/lib/chunk-PH7SP4YK.mjs +0 -21
  250. package/lib/chunk-PMN4PAC3.mjs +0 -19
  251. package/lib/chunk-PMWAFDUB.mjs +0 -48
  252. package/lib/chunk-PPLVFX6N.mjs +0 -7
  253. package/lib/chunk-PZBZ7MNC.mjs +0 -7
  254. package/lib/chunk-QROPNEGY.mjs +0 -14
  255. package/lib/chunk-RGBGUCJA.mjs +0 -156
  256. package/lib/chunk-RKTFFCNS.mjs +0 -7
  257. package/lib/chunk-ROV3QXEF.mjs +0 -475
  258. package/lib/chunk-RT47RKLY.mjs +0 -7
  259. package/lib/chunk-SI267LYR.mjs +0 -8
  260. package/lib/chunk-SRPWW4A2.mjs +0 -10
  261. package/lib/chunk-T3G6VZNS.mjs +0 -7
  262. package/lib/chunk-T63U4OZJ.mjs +0 -7
  263. package/lib/chunk-TEIBWMJM.mjs +0 -7
  264. package/lib/chunk-TW3N6W5Z.mjs +0 -7
  265. package/lib/chunk-UBIKR5VO.mjs +0 -7
  266. package/lib/chunk-UI3JQVRU.mjs +0 -8
  267. package/lib/chunk-UX3BVH2Y.mjs +0 -7
  268. package/lib/chunk-VINGECAJ.mjs +0 -10
  269. package/lib/chunk-VOXJHJIE.mjs +0 -7
  270. package/lib/chunk-WB2RIVO3.mjs +0 -7
  271. package/lib/chunk-WXDLQT2O.mjs +0 -10
  272. package/lib/chunk-XBQGZGWR.mjs +0 -7
  273. package/lib/chunk-XGGOUNPP.mjs +0 -7
  274. package/lib/chunk-XKWW3GKF.mjs +0 -7
  275. package/lib/chunk-YHR4WQPR.mjs +0 -7
  276. package/lib/chunk-ZQQXSCVI.mjs +0 -7
  277. package/lib/chunk-ZRUDYB7O.mjs +0 -7
@@ -0,0 +1,14 @@
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{c as Xn,e as Zn,l as er}from"./chunk-TQ6HEJ73.mjs";import{a as Qn,b as Jn}from"./chunk-65AMXOQU.mjs";import{p as Ct,q as Sr}from"./chunk-6HHSAPIM.mjs";import{d as hr,h as yr,m as wr}from"./chunk-EUIALBMX.mjs";import{c as Hn}from"./chunk-Q7TLC3I2.mjs";import{a as br,b as Rr}from"./chunk-HF6LAK3G.mjs";import{j as or,k as sr,l as ir,m as ar,n as ur}from"./chunk-ATBQIE2V.mjs";import{b as dr}from"./chunk-UCUFLFNK.mjs";import{a as pr,b as mr}from"./chunk-TQ2TQHTT.mjs";import{d as Bt}from"./chunk-HFSBDM7B.mjs";import{c as nr,g as Xe,h as Nt,j as rr}from"./chunk-OHEOJISY.mjs";import{a as tr}from"./chunk-EADHKH3A.mjs";import{E as ke,_ as Kn,b as Oe,da as Yn,q as Ke,r as Ye,t as vt}from"./chunk-SZOJ7BEJ.mjs";import{h as Ft}from"./chunk-TZE3Y7IQ.mjs";import{b as F}from"./chunk-CA5NAXSU.mjs";import{a as fr,b as gr}from"./chunk-PC247GKX.mjs";import{a as xt,b as cr,c as lr}from"./chunk-TUACWKIH.mjs";import{$d as Ve,Cc as Bn,Jc as xn,Lc as Cn,Mc as _n,P as An,Uc as In,Vc as jn,Zd as ze,_ as En,_d as Ln,aa as Tn,ae as Dn,ba as qe,be as Ot,ca as On,ce as Wn,da as kn,ea as Pn,fa as Mn,fe as Un,ge as kt,ha as Ge,ia as $n,ie as He,ja as Fn,la as vn,m as Sn,ma as Nn,ne as Qe,oe as Je,qe as qn,re as Pt,se as Gn,ve as Mt,we as zn,xe as $t,ye as Vn}from"./chunk-J347SPU6.mjs";import{b as Q,e as G,i as We,k as X,l as B,s as Tt,v as Rn,z as Ue}from"./chunk-WZQEK4WT.mjs";import{randomUUID as Os}from"node:crypto";import{hostname as ks,homedir as Ps,uptime as Ms}from"node:os";import{mkdir as $s,readFile as Nr,readdir as Fs,rename as Br,writeFile as vs}from"node:fs/promises";import{dirname as _t,join as Dt}from"node:path";function Ar(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:F(e)}]}}function Er(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function Gd(e){return{typeOrg:()=>Qn(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:Bn()}).then(Er,Ar),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(Er,Ar)}}var he=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ns(e){return e instanceof he||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var Bs=60,xs=5*6e4,Cs=3e4,_s=6e4,Is=200,js=448,Ls=384,nt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ye=Q().regex(nt),Ds=B({id:ye,permissionSetId:ye,permissionSet:Q().min(1).max(255)}),Ws=B({runId:Q().min(1).max(255),host:Q().min(1).max(255),pid:G().int().nonnegative(),hostStartedAt:Ue.datetime({offset:!0}),acquiredAt:Ue.datetime({offset:!0}),endsAt:Ue.datetime({offset:!0}),needs:X(ye),assigning:X(ye),created:X(Ds)}),xr=B({version:Rn(1),organizationId:ye,userId:ye,leases:X(Ws)}),Us=B(fr),qs=gr(e=>{let t=Us.safeParse(e);return t.success?t.data:void 0});function Cr(e=process.env,t=Ps()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Dt(t,".sandforge","mute-leases")}function Gs(e,t,n){if(!nt.test(t)||!nt.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Dt(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var _r={host:ks(),pid:xt.pid,startedAt:xt.startedAt},zs=6e4,le=new Set;function Ir(e,t,n){return`${e}
8
+ ${t}
9
+ ${n}`}function Vs(e,t,n,r={}){let o=r.now?.()??Date.now();if(!(Date.parse(e.endsAt)>o)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return le.has(Ir(t,e.runId,e.acquiredAt));let s=r.bootedAt?.()??Date.now()-Ms()*1e3,i=Date.parse(e.hostStartedAt);return Number.isFinite(i)&&i<s-zs?!1:(r.isAlive??lr)(e.pid)}var Hs=e=>new Promise(t=>setTimeout(t,e));function Ze(e,t,n){let r=n?.code;return new Error(`The journal of the mute leases in ${_t(e)} could not be ${t}${typeof r=="string"?` (${r})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function Qs(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+cr).toISOString()}}function jr(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function Js(e){return`nothing was assigned. ${jr(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function et(e,t,n,r,o=Js,s=_s){let i=n.self??_r,a={self:i,...n.checks?{checks:n.checks}:{}},u=Date.now()+s;for(await $s(_t(e),{recursive:!0,mode:js}).catch(c=>{throw Ze(e,"made",c)});;){let c;try{c=qs.acquire(`${e}.lock`,d=>d,a)}catch(d){throw Ze(e,"locked",d)}if("lock"in c)try{let d=await Ks(e,t).catch(g=>{throw Ze(e,"read",g)});return await r(d,async g=>{let p=`${e}.${process.pid}-${Os()}.tmp`;try{await vs(p,JSON.stringify(g,null,2),{encoding:"utf8",mode:Ls}),await Br(p,e)}catch(m){throw Ze(e,"written",m)}})}finally{c.lock.release()}if(Date.now()>u){let d=Qs(c.busy,i);throw new he({code:"MUTE_FAILED",message:`The journal of the mute leases in ${_t(e)} stayed locked for a minute by process ${d.pid} on ${d.host}: ${o(d)}`})}await Hs(Is)}}async function Ks(e,t){let n={version:1,...t,leases:[]},r;try{r=await Nr(e,"utf8")}catch(o){if(o.code==="ENOENT")return n;throw o}try{let o=xr.safeParse(JSON.parse(r));if(o.success)return o.data}catch{}return await Br(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var Ys=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function tt(e,t,n,r){let o=t.leases.filter(d=>d!==n&&r(d)),s=[...n.created],i=new Set,a=n.assigning[0];if(a!==void 0){let d=new Set(t.leases.flatMap(g=>g===n?[]:g.created.map(p=>p.id))),f=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${a}')`).then(g=>g.records).catch(()=>[]);for(let g of f){let p=typeof g.Id=="string"?g.Id:void 0,m=typeof g.PermissionSetId=="string"?g.PermissionSetId:void 0;if(!p||!m||d.has(p)||s.some(b=>b.id===p))continue;let w=g.PermissionSet;s.push({id:p,permissionSetId:m,permissionSet:typeof w?.Name=="string"?w.Name:m}),i.add(p)}}let u={removed:[],passed:[],left:[],found:[]};for(let d of s){let f=o.find(m=>m.needs.includes(d.permissionSetId));if(f){f.created.some(m=>m.id===d.id)||f.created.push(d),u.passed.push(d);continue}let g=await e.deleteAssignment(d.id),p=g.errors?.[0]?.statusCode??g.errors?.[0]?.errorCode;g.success||p!==void 0&&Ys.has(p)?(u.removed.push(d),i.has(d.id)&&u.found.push(d)):u.left.push({...d,why:g.errors?.[0]?.message??p??"the org refused the delete"})}let c=t.leases.indexOf(n);return u.left.length===0?t.leases.splice(c,1):t.leases[c]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:u.left.map(({id:d,permissionSetId:f,permissionSet:g})=>({id:d,permissionSetId:f,permissionSet:g}))},u}function fe(e){return e.map(t=>t.permissionSet)}function Tr(e,t){let n=o=>fe(o).join(", "),r=[];return e.removed.length>0&&r.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&r.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&r.push(`${e.left.map(o=>`${o.permissionSet} (${o.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),r}function Or(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function Lr(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function Xs(e,t,n){let r=[];for(let o of[...t.leases])n(o)||r.push(...(await tt(e,t,o,n)).found);return r}var rt="SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess",Pe="the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)";function ot(e){return e?.PermissionsAssignPermissionSets===!0||e?.PermissionsManageUsers===!0}async function zd(e){try{let[t]=(await e.query(rt)).records;return t!==void 0&&!ot(t)}catch{return!1}}async function Zs(e){let t;try{t=(await e.query(rt)).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${F(n)})`}return ot(t)?void 0:Pe}function kr(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var Pr=/^[A-Za-z][A-Za-z0-9_]*$/;async function ei(e,t){let r=t.map(kr).filter(i=>Pr.test(i.developerName)&&(!i.namespace||Pr.test(i.namespace)));if(r.length===0)return new Map;let o=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(r.map(i=>`'${i.developerName}'`))].join(", ")+")"),s=new Map;for(let i of t){let{namespace:a,developerName:u}=kr(i),c=o.records.find(d=>String(d.Name??"").toLowerCase()===u.toLowerCase()&&String(d.NamespacePrefix??"").toLowerCase()===a.toLowerCase());typeof c?.Id=="string"&&s.set(i,c.Id)}return s}async function Mr(e,t,n){if(n.length===0)return new Map;let r=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(s=>`'${s}'`).join(", ")})`),o=new Map;for(let s of r.records){let i=s.PermissionSetId,a=s.Id;typeof i=="string"&&typeof a=="string"&&o.set(i,a)}return o}function It(e,t,n){return{state:t,assigned:[],held:[],permissions:Pt(e),silenced:e.silenced.map(r=>({...r})),stillRan:e.stillRuns.map(r=>({...r})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(r=>({...r}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(r=>({...r}))}:{},...n?{reason:n}:{}}}var Dr="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function ti(e,t,n={}){let r,o;try{let p=await e.typeOrg();r=Jn(p),o=p.id}catch(p){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${F(p)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(r)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let s=n.writes??(()=>!0),i=(p,m,w)=>({plan:m,automation:t,planned:p,acquire:async()=>({outcome:p,release:async()=>p}),narrow:w}),{plan:a,automation:u,planned:c}=Lt(t,s),d=(p,m)=>b=>{let R=(P,j)=>m(P,j)&&b(P,j),E=Lt(t,R);return E.plan.assign.length===0?i(E.planned,E.plan,d(p,R)):(jt.set(E.plan,p),{plan:E.plan,automation:E.automation,planned:E.planned,acquire:P=>$r(e,E.plan,P,n),narrow:d(p,R)})};if(a.assign.length===0)return i(c,a,d(0,s));let f=await Zs(e);if(f!==void 0)return{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${f}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}};let g=await ri(n.dir??Cr(),o);return jt.set(a,g),{plan:a,automation:u,planned:c,acquire:p=>$r(e,a,p,n),narrow:d(g,s)}}var jt=new WeakMap,ni=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function ri(e,t){if(!nt.test(t))return 0;let n=`${t.slice(0,15)}-`,r;try{r=await Fs(e)}catch{return 0}let o=0;for(let s of r)if(!(!s.startsWith(n)||!ni.test(s)))try{let i=xr.safeParse(JSON.parse(await Nr(Dt(e,s),"utf8")));if(!i.success)continue;for(let a of i.data.leases)o+=(a.assigning.length>0?1:0)+a.created.length}catch{}return o}function Lt(e,t){let n=qn(e,t);return n.assign.length===0?{plan:n,automation:e,planned:It(n,"nothing",Dr)}:{plan:n,automation:Gn(e,Pt(n)),planned:It(n,"planned")}}async function $r(e,t,n,r={}){let o=r.self??_r,s=()=>r.checks?.now?.()??Date.now(),i=r.minutes??Bs,a=S=>{throw new he({code:"MUTE_FAILED",message:S})},u=await e.identity().catch(S=>a(`The target would not say who the run writes as (${F(S)}).`)),c={organizationId:u.organization_id,userId:u.user_id},d=Gs(r.dir??Cr(),c.organizationId,c.userId),f=t.assign.map(S=>S.permissionSet),g=await ei(e,f).catch(S=>a(`The permission sets to assign could not be read (${F(S)}).`)),p=f.filter(S=>!g.has(S));p.length>0&&a(`The target holds no permission set ${p.join(", ")}: nothing was assigned.`);let m=f.map(S=>g.get(S)),w=new Map(f.map(S=>[g.get(S),S])),b=S=>Vs(S,d,o,r.checks),R=new Date(s()).toISOString(),E=Ir(d,n,R),P=!1,j=m.map(S=>w.get(S)),T=r.retryEveryMs??Cs,L,C=(S,N)=>{if(L!==void 0)return;let k=new Set(S.map(M=>M.id)),v=!1,_=()=>clearInterval(L);L=setInterval(()=>{v||(v=!0,et(d,c,r,async(M,re)=>{let U=M.leases.find(V=>V.runId===n&&V.acquiredAt===R);if(U){U.assigning=[],U.created=[...U.created,...N.filter(K=>!U.created.some(oe=>oe.id===K.id))].filter(K=>!k.has(K.id));let V=await tt(e,M,U,b);for(let K of V.removed)k.add(K.id);await re(M)}_()},void 0,0).catch(()=>{}).finally(()=>{v=!1}))},T),L.unref?.()},ce=await et(d,c,r,async(S,N)=>{let k=fe(await Xs(e,S,b)),v=await Mr(e,c.userId,m),_=m.filter($=>!v.has($)),M={runId:n,host:o.host,pid:o.pid,hostStartedAt:o.startedAt,acquiredAt:R,endsAt:new Date(s()+i*6e4).toISOString(),needs:m,assigning:[..._],created:[]};S.leases.push(M),le.add(E),await N(S),P=!0;let re=[...M.assigning],U=()=>N(S).then(()=>{re=[...M.assigning]},$=>F($)),V=async $=>{M.assigning=[];let D=await tt(e,S,M,b);le.delete(E);let I=await U();I!==void 0&&C(D.removed,[...D.passed,...D.left]);let q=I!==void 0&&re.length===0?{sets:j,until:M.endsAt}:void 0,Te=Tr(D,I===void 0);return a([$,...I!==void 0&&I!==$?[I]:[],...Te.length>0?Te:["Nothing was assigned."],...I!==void 0&&(D.passed.length>0||D.left.length>0||q)?[Or(o.pid,q)]:[],...k.length>0?[`Taking its lease, the run took back ${k.join(", ")}, ${Lr(k)}.`]:[]].join(" "))};for(let $ of _){let D=await e.createAssignment({AssigneeId:c.userId,PermissionSetId:$});if(M.assigning=M.assigning.filter(q=>q!==$),D.success&&D.id){M.created.push({id:D.id,permissionSetId:$,permissionSet:w.get($)});let q=await U();if(q!==void 0)return V(q);continue}let I=D.errors?.[0];if((I?.statusCode??I?.errorCode)==="DUPLICATE_VALUE"){let q=await U();if(q!==void 0)return V(q);continue}return V(`${w.get($)} could not be assigned to the user the run writes as: ${I?.message??I?.statusCode??"the org refused it"}.`)}let K=await Mr(e,c.userId,m).catch(()=>new Map),oe=m.filter($=>!K.has($));if(oe.length>0)return V(`Read back, the user the run writes as does not hold ${oe.map($=>w.get($)).join(", ")}.`);let je=new Set(M.created.map($=>$.permissionSetId));return{endsAt:M.endsAt,assigned:M.created.map($=>$.permissionSet),held:m.filter($=>!je.has($)).map($=>w.get($)),found:k}}).catch(S=>{if(le.delete(E),Ns(S))throw S;return a(`${F(S)}${P?"":" Nothing was assigned."}`)}),J={...It(t,"muted"),assigned:ce.assigned,held:ce.held,leaseEndsAt:ce.endsAt,...ce.found.length>0?{tookBackOfEnded:ce.found}:{}},_e=r.renewEveryMs??xs,Ee=_e>0?setInterval(()=>{et(d,c,r,async(S,N)=>{let k=S.leases.find(_=>_.runId===n&&_.acquiredAt===R);if(!k||!le.has(E))return;let v=new Date(s()+i*6e4).toISOString();k.endsAt=v,await N(S),J.leaseEndsAt=v}).catch(()=>{})},_e):void 0;Ee?.unref?.();let Ie;return{outcome:J,release:()=>(Ie??=(async()=>{Ee&&clearInterval(Ee);let S={};try{await et(d,c,r,async(k,v)=>{let _=k.leases.find(M=>M.runId===n&&M.acquiredAt===R);le.delete(E),_&&(S.done=await tt(e,k,_,b),await v(k))},k=>`nothing was taken back. ${jr(k)} Should none of its runs be muting this org, end process ${k.pid}`);let N=S.done?.left??[];return{...J,released:N.length===0,takenBack:fe(S.done?.removed??[]),...S.done&&S.done.passed.length>0?{passed:fe(S.done.passed)}:{},...N.length>0?{notTakenBack:fe(N),reason:`${N.map(k=>`${k.permissionSet} (${k.why})`).join(", ")} could not be taken back: the lease ends at ${J.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(N){le.delete(E);let k=S.done;if(C(k?.removed??[],k?[...k.passed,...k.left]:[]),k!==void 0){let v=J.leaseEndsAt,_=v!==void 0&&Date.parse(v)>s()?{sets:j,until:v}:void 0;return{...J,released:!1,takenBack:fe(k.removed),notTakenBack:fe([...k.passed,...k.left]),reason:[F(N),...Tr({...k,removed:[]},!1),Or(o.pid,_)].join(" ")}}return{...J,released:!1,takenBack:[],reason:`the assignments could not be taken back (${F(N)}): this process tries again while it runs, and takes them back once it can use the journal; past ${J.leaseEndsAt}, or once process ${o.pid} has ended, the next run that mutes this org releases the lease`}}})(),Ie)}}var oi=2,si=3;function ii(e){return!e||e.assign.length===0?0:oi+si+2*e.assign.length+(jt.get(e)??0)}function Vd(e){let t=ii(e);return t>0?{mute:t}:{}}function ai(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function Hd(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function Qd(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:ai(`the target's automation could not be read (${t.unread})`)};let r=await ti(await e(),t,n);if("refused"in r)throw new he(r.refused);return Ur(r)}var Wr=new WeakMap;function Ur(e){return Wr.set(e.plan,e),{automation:e.automation,...e.plan.assign.length>0?{prepared:e}:{},muted:e.planned,plan:e.plan}}function Jd(e,t){if(e.plan===void 0||e.automation===void 0)return e;let n=e.prepared??Wr.get(e.plan);if(n){let s=n.narrow?.(t);return s?Ur(s):e}let{plan:r,planned:o}=Lt(e.automation,t);return{automation:e.automation,muted:o,plan:r}}function Fr(e){return`${e.objectApiName}
10
+ ${e.kind}
11
+ ${e.name}`}var ui=["insert","update","delete","undelete"];function di(e,t,n){if(!e||!t.plan)return;let r=new Set(t.plan.assign.map(a=>a.permissionSet)),o=e.assign.map(a=>a.permissionSet).filter(a=>!r.has(a));if(o.length===0)return;let s=new Set(o),i=new Set((t.plan.alsoLifts??[]).map(Fr));return{notAssigned:o,noLongerLifts:(e.alsoLifts??[]).filter(a=>s.has(a.permissionSet)&&!i.has(Fr(a))&&ui.some(u=>n(a.objectApiName,u)))}}var ci=5,li={validationRule:"validation rule(s)",flow:"flow(s)",process:"process(es)",workflowRule:"workflow rule(s)"};function Kd(e,t,n){let r=di(e,t,n);if(!r)return[];let{notAssigned:o,noLongerLifts:s}=r,i=o.length===1,a=[`mute: planned again for the objects the rows write: ${o.join(", ")} ${i?"is":"are"} not assigned, what ${i?"it silences":"they silence"} being on objects they write nothing of`+((t.plan?.assign.length??0)===0?"; nothing is left to mute, and the run goes on as without the option":"")];if(s.length<=ci)return[...a,...s.map(c=>` no longer lifts: ${$t(c)}`)];let u=new Map;for(let c of s){let d=`${c.objectApiName}
12
+ ${c.kind}
13
+ ${c.permissionSet}`,f=u.get(d);f?f.count++:u.set(d,{entry:c,count:1})}return[...a,...[...u.values()].map(({entry:c,count:d})=>` no longer lifts: ${d} ${li[c.kind]} on ${c.objectApiName} (in ${c.permissionSet})`)]}function Yd(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function Xd(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??Dr}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+Lr(e.tookBackOfEnded));for(let o of e.silenced)n.push(` silenced: ${Mt(o)} (bypass ${o.permission})`);for(let o of e.stillRan)n.push(` still runs: ${Mt(o)} (${zn(o.why)})`);for(let o of e.alsoLifted??[])n.push(` also lifts: ${$t(o)}`);for(let o of e.liftsUnread??[])n.push(` ${Vn(o)}`);let r=e.takenBack??(e.released===!0?e.assigned:[]);if(r.length>0&&n.push(` taken back: ${r.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let o=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${o?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}var fi=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function qr(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}function Gr(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t):[]}function zr(e){return typeof e=="string"&&fi.test(e)?e:void 0}function Vr(e){let t=new Map;for(let r of Gr(qr(e,"variables"))){let o=r.name,s=zr(r.objectType);typeof o=="string"&&s&&t.set(o.toLowerCase(),s)}let n=[];for(let r of Gr(qr(e,"recordCreates"))){let o=r.inputReference,s=zr(r.object)??(typeof o=="string"?t.get(o.toLowerCase()):void 0);s&&!n.some(i=>i.toLowerCase()===s.toLowerCase())&&n.push(s)}return n}var Hr={AccountPartner:["Role"],CampaignMember:["Status"],Case:["Status"],Contract:["Status"],Lead:["Status"],Opportunity:["StageName"],OpportunityPartner:["Role"],Order:["Status"],Partner:["Role"],ServiceAppointment:["Status"],Solution:["Status"],Task:["Priority","Status"],WorkOrder:["Status"],WorkOrderLineItem:["Status"]};function nc(e,t){let n=new Map,r=t!==void 0&&Object.prototype.hasOwnProperty.call(Hr,t)?Hr[t]:[];for(let o of e){let s=o.type==="multipicklist";if(o.type!=="picklist"&&!s&&!o.picklistValues?.length)continue;let i=(o.type==="combobox"||o.restrictedPicklist===!1)&&!r.includes(o.name);n.set(o.name,{multi:s,restricted:o.restrictedPicklist===!0,required:o.nillable===!1&&o.defaultedOnCreate!==!0,...o.controllerName?{controllerName:o.controllerName}:{},...i?{anyValue:i}:{}})}return n}var gi=new Set;function pi(e,t){let n=new Set(e),r=[],o=new Set,s=(i,a)=>{if(o.has(i))return;let u=t.get(i)?.controllerName;u&&n.has(u)&&a<e.length&&s(u,a+1),!o.has(i)&&(o.add(i),r.push(i))};for(let i of e)s(i,0);return r}function mi(e){return typeof e=="boolean"?String(e):typeof e=="string"&&e!==""?e:void 0}function hi(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o)??[];s.includes(r)||s.push(r),n.set(o,s)}return[...n]}function yi(e,t,n,r,o,s,i){let a=new Set(o.values),u=a,c,d=r.controllerName?mi(e[r.controllerName]):void 0,f=d===void 0?void 0:o.allowedByControllingValue?.get(d);f&&(u=new Set(o.values.filter(R=>f.has(R))),c=r.controllerName);let g=n.filter(R=>!u.has(R));if(g.length===0)return[];let p=R=>i&&!i.has(R)?"not-in-target":a.has(R)?"controlling-value":"record-type",m,w,b=n.filter(R=>u.has(R));return r.multi&&b.length>0?e[t]=b.join(";"):(o.defaultValue!==null&&u.has(o.defaultValue)?(m=o.defaultValue,w="default"):r.required&&(m=o.values.find(R=>u.has(R)),w=m===void 0?void 0:"first"),m===void 0?delete e[t]:e[t]=m),hi(g,p).map(([R,E])=>({field:t,reason:R,values:E,recordType:s,...R==="controlling-value"&&c?{controllingField:c}:{},...m!==void 0&&w?{replacedBy:m,replacement:w}:{}}))}function rc(e,t,n,r,o=gi){let s=[];for(let i of pi(Object.keys(e),n)){let a=e[i];if(typeof a!="string"||o.has(i))continue;let u=n.get(i),c=t?.get(i),d=u?.restricted?r?.picklists.get(i):void 0;if(!c&&!d)continue;if(a===""){delete e[i];continue}let f=u?.multi?a.split(";"):[a];if(u&&d&&r){s.push(...yi(e,i,f,u,d,r.recordType,c));continue}if(!c||u?.anyValue)continue;let g=f.filter(m=>!c.has(m));if(g.length===0)continue;let p=f.filter(m=>c.has(m));u?.multi&&p.length>0?e[i]=p.join(";"):delete e[i],s.push({field:i,reason:"not-in-target",values:[...new Set(g)]})}return s}var wi="012000000000000AAA",st="Master",Kr="";function oc(e,t){return e?.get(typeof t=="string"?t:Kr)}async function bi(e,t,n){try{return{picklists:await e(t,n)}}catch(r){return{error:F(r)}}}var Qr=class{constructor(t){this.read=t}read;reads=new Map;said=new Set;async forRows(t){let n=new Map,r=[],{read:o}=this;if(!o)return{byRecordType:n,notes:r};if(t.withoutRecordTypes){let c=[...t.fields].filter(([f,g])=>g.restricted&&g.controllerName&&t.written(f)).map(([f])=>f),d=new Set(c.filter(f=>t.rows.some(g=>typeof g[f]=="string"&&g[f]!=="")));if(d.size>0){let f={targetId:wi,developerName:st},g=await this.readFor(o,t.objectApiName,f.targetId);this.keep(n,r,t.objectApiName,Kr,d,f,g)}return{byRecordType:n,notes:r}}if(!t.recordTypeMappings||!t.written("RecordTypeId"))return{byRecordType:n,notes:r};let s=[...t.fields].filter(([c,d])=>d.restricted&&t.written(c)).map(([c])=>c);if(s.length===0)return{byRecordType:n,notes:r};let i=new Map(t.recordTypeMappings.map(c=>[c.sourceId,c])),a=new Map;for(let c of t.rows){let d=c.RecordTypeId;if(!(typeof d!="string"||!i.has(d)))for(let f of s){let g=c[f];if(typeof g!="string"||g==="")continue;let p=a.get(d)??new Set;p.add(f),a.set(d,p)}}let u=await Promise.all([...a].map(async([c,d])=>{let f=i.get(c);return{sourceId:c,fields:d,target:f,answer:await this.readFor(o,t.objectApiName,f.targetId)}}));for(let{sourceId:c,fields:d,target:f,answer:g}of u)this.keep(n,r,t.objectApiName,c,d,f,g);return{byRecordType:n,notes:r}}readFor(t,n,r){let o=`${n}|${r}`,s=this.reads.get(o);return s||(s=bi(t,n,r),this.reads.set(o,s)),s}keep(t,n,r,o,s,i,a){let u=`${r}|${i.targetId}`;if("error"in a){this.said.has(u)||(this.said.add(u),n.push({recordType:i.developerName,error:a.error}));return}t.set(o,{recordType:i.developerName,picklists:a.picklists});let c=[...s].filter(d=>!a.picklists.has(d)&&!this.said.has(`${u}|${d}`));if(c.length!==0){for(let d of c)this.said.add(`${u}|${d}`);n.push({recordType:i.developerName,leftOut:c})}}};function sc(e){return e.error!==void 0?{recordSummary:`(picklist values of record type ${e.recordType} could not be read \u2014 checked against each field's values)`,messages:[e.error]}:{recordSummary:`(picklist values of record type ${e.recordType} not given for ${(e.leftOut??[]).join(", ")} \u2014 checked against each field's values)`,messages:[`The target's answer for record type ${e.recordType} leaves out ${(e.leftOut??[]).join(", ")}.`]}}var Jr=class{entries=new Map;get size(){return this.entries.size}add(t,n){for(let r of n){let o=[t,r.field,r.reason,r.recordType??"",r.controllingField??"",r.replacement??"",r.replacedBy??""].join("\0"),s=this.entries.get(o);if(s){s.entry.rows++;for(let i of r.values)s.values.add(i);continue}this.entries.set(o,{entry:{objectApiName:t,field:r.field,reason:r.reason,values:[],rows:1,...r.recordType!==void 0?{recordType:r.recordType}:{},...r.controllingField!==void 0?{controllingField:r.controllingField}:{},...r.replacedBy!==void 0?{replacedBy:r.replacedBy}:{},...r.replacement!==void 0?{replacement:r.replacement}:{}},values:new Set(r.values)})}}list(){return[...this.entries.values()].map(({entry:t,values:n})=>({...t,values:[...n].sort()}))}};function Ri(e){let t=`${e.rows} row${e.rows===1?"":"s"}`,n=e.values.map(s=>`"${s}"`).join(", "),r=e.reason==="not-in-target"?"not a value of the field in the target":e.reason==="record-type"?`not allowed for record type ${e.recordType??""}`:`not allowed with the value of ${e.controllingField??"its controlling field"}`,o=e.replacedBy===void 0?"left out":e.replacement==="first"?`replaced by "${e.replacedBy}", the first value record type ${e.recordType??""} allows: the field is required and has no default there`:`replaced by "${e.replacedBy}", the default of record type ${e.recordType??""}`;return`${e.field} on ${t}: ${n} ${r}, ${o}`}function ic(e){return e.length===0?"":`, picklist values not written as read: ${e.map(Ri).join("; ")}`}function fc(e){let t={...e.picklistValueMappings?.length?{picklistValueMappings:e.picklistValueMappings}:{},...e.recordTypeMappings?.length?{recordTypeMappings:e.recordTypeMappings}:{},...e.defaultValues?.length?{defaultValues:e.defaultValues}:{},...e.truncateFields?.length?{truncateFields:e.truncateFields}:{},...e.ignoredGaps?.length?{ignoredGaps:e.ignoredGaps}:{},...e.skippedRows?.length?{skippedRows:e.skippedRows}:{}};return Object.keys(t).length>0?t:void 0}var Si=new Set(["picklist_value_refused","picklist_value_absent","currency_inactive"]);function eo(e){let t=An(e.gapId);return t?t.objectApiName!==e.object?{ignored:`the gap is of ${t.objectApiName}, not of ${e.object}`}:t.field===void 0||t.value===void 0?{ignored:"the gap names no field and value whose rows to hold back"}:Si.has(t.kind)?{held:{field:t.field,...t.recordType!==void 0?{recordType:t.recordType}:{},value:t.value}}:{ignored:`a ${t.kind} gap does not offer it: its rows are not exactly those holding its value`}:{ignored:"not the id of a gap"}}function gc(e){let t=eo(e);return"ignored"in t?t.ignored:void 0}function Yr(e,t,n){if(e===void 0)return!0;let r=t??st;if(e===r)return!0;let o=Xe(e),s=Xe(r);if(o.namespacePrefix!==void 0||s.namespacePrefix===void 0||s.developerName!==e)return!1;if(n===void 0)return!0;let i=Nt(e,n,a=>a);return"found"in i&&i.found.namespacePrefix===s.namespacePrefix}function Ai(e){return e==null||e===""}var Xr=class{entries=new Map;get size(){return this.entries.size}add(t,n=1){let r=[t.kind,t.objectApiName,t.field??"",t.recordType??"",t.from??"",t.to??""].join("\0"),o=this.entries.get(r);if(o){o.rows+=n;return}this.entries.set(r,{...t,rows:n})}list(){return[...this.entries.values()].map(t=>({...t}))}},it=class{picklists=new Map;defaults=new Map;truncated=new Map;skipped=new Map;ignoredGaps;constructor(t){for(let n of t?.picklistValueMappings??[]){let r=this.picklists.get(n.object)??[];r.push(n),this.picklists.set(n.object,r)}for(let n of t?.defaultValues??[]){let r=this.defaults.get(n.object)??[];r.push(n),this.defaults.set(n.object,r)}for(let{object:n,field:r}of t?.truncateFields??[]){let o=this.truncated.get(n)??new Set;o.add(r),this.truncated.set(n,o)}this.ignoredGaps=new Set(t?.ignoredGaps??[]);for(let n of t?.skippedRows??[]){let r=eo(n);if(!("held"in r))continue;let o=this.skipped.get(n.object)??[];o.push(r.held),this.skipped.set(n.object,o)}}skipsRowsOf(t){return this.skipped.has(t)}namesARecordTypeBare(t){return[...(this.picklists.get(t)??[]).map(r=>r.recordType),...(this.skipped.get(t)??[]).map(r=>r.recordType)].some(r=>r!==void 0&&r!==st&&Xe(r).namespacePrefix===void 0)}holdsBack(t,n,r,o,s){for(let i of this.skipped.get(t)??[]){if(!Yr(i.recordType,r,s))continue;let a=n(i.field);if(!(typeof a!="string"||!a.split(";").includes(i.value)))return o.add({kind:"skip_rows",objectApiName:t,field:i.field,...i.recordType!==void 0?{recordType:i.recordType}:{},from:i.value}),!0}return!1}changesRowsOf(t){return this.picklists.has(t)||this.defaults.has(t)}defaultOf(t,n){let r=this.defaults.get(t)?.find(o=>o.field===n);return r===void 0?void 0:String(r.value)}applyToRow(t,n,r,o,s){for(let i of this.picklists.get(t)??[]){if(!Yr(i.recordType,r,s))continue;let a=n[i.field];if(typeof a!="string"||a==="")continue;let u=a.split(";");if(!u.includes(i.from))continue;let c=u.flatMap(d=>d!==i.from?[d]:i.to===null?[]:[i.to]);c.length===0?delete n[i.field]:n[i.field]=[...new Set(c)].join(";"),o.add({kind:i.to===null?"leave_empty":"map_value",objectApiName:t,field:i.field,...i.recordType!==void 0?{recordType:i.recordType}:{},from:i.from,...i.to!==null?{to:i.to}:{}})}for(let{field:i,value:a}of this.defaults.get(t)??[])Ai(n[i])&&(n[i]=a,o.add({kind:"set_default",objectApiName:t,field:i,to:String(a)}))}truncate(t,n,r,o){for(let s of this.truncated.get(t)??[]){let i=n[s],a=r.get(s);typeof i!="string"||a===void 0||a<=0||i.length<=a||(n[s]=i.slice(0,a),o.add({kind:"truncate",objectApiName:t,field:s}))}}truncatedFieldsOf(t){return this.truncated.get(t)??new Set}};function pc(e,t){let n=new Map(t.map(i=>[i.objectApiName,i])),r=[],o=new Map,s=[];for(let i of e){let a=n.get(i.object),u=Zr(i.object,i.from,a?.source??[],"the source");if("reason"in u){s.push({decision:i,reason:u.reason});continue}if(i.to===null){o.set(u.type.recordTypeId,i);continue}let c=Zr(i.object,i.to,a?.target??[],"the target");if("reason"in c){s.push({decision:i,reason:c.reason});continue}o.set(u.type.recordTypeId,i),r.push({sourceId:u.type.recordTypeId,targetId:c.type.recordTypeId,developerName:c.type.developerName})}return{mappings:r,bySource:o,unresolved:s}}function Zr(e,t,n,r){let o=Nt(t,n.filter(s=>!s.master),Bt);if("found"in o)return{type:o.found};if("ambiguous"in o){let s=o.ambiguous.map(Bt),i=s.find(a=>a.namespacePrefix);return{reason:rr(e,t,r,s)+(i?"; a package's is named with its namespace: "+nr(i.namespacePrefix,i.developerName):"")}}return{reason:`${r} has no ${e} record type named ${t}`}}function mc(e,t){return t.bySource.size===0?e?[...e]:void 0:[...(e??[]).filter(n=>!t.bySource.has(n.sourceId)),...t.mappings]}import{createHash as du}from"node:crypto";var Ei="__pass2__";function to(e){let t=e.errors??[],n=t.some(s=>s.skipped===!0),r=t.some(s=>s.objectApiName===Ei&&s.failedCount>0);return e.failedCount===0&&e.failedReads.length===0&&!n&&!r?"success":e.successCount+e.updatedCount+e.linkedCount+(e.wouldInsertCount??0)>0?"partial":"failure"}function Ti(e){let t=(e.writtenByThePlatform??[]).reduce((n,{rows:r})=>n+r,0);return t>0?{writtenByThePlatformCount:t}:{}}function yc(e,t,n){return{forgeId:`forge-${Date.now()}`,status:n.status,graph:t,duration:Date.now()-n.startedAt,timestamp:new Date().toISOString(),idRemapCount:e.remapCount,idRemapTable:e.remapTable,idRemapExisting:e.existingSourceIds,...e.withTheirRecordSourceIds?{idRemapWithTheirRecord:e.withTheirRecordSourceIds}:{},...e.withTheirRecordCount!==void 0&&e.withTheirRecordCount>0?{withTheirRecordCount:e.withTheirRecordCount}:{},...e.linkedToCreatedCount!==void 0&&e.linkedToCreatedCount>0?{linkedToCreatedCount:e.linkedToCreatedCount}:{},...Ti(e),createdCount:e.successCount,...e.updatedCount>0?{updatedCount:e.updatedCount}:{},linkedExistingCount:e.linkedCount,existingRecords:e.existingRecords,idRemapByObject:e.remapByObject,idRemapCreated:e.createdByObject,readByObject:e.readByObject,failedReads:e.failedReads,errors:e.errors,truncatedObjects:e.truncatedObjects,...e.cappedObjects?{cappedObjects:e.cappedObjects}:{},...e.fieldExclusionsUnmatched?{fieldExclusionsUnmatched:e.fieldExclusionsUnmatched}:{},...e.orphanParentsCapped?{orphanParentsCapped:e.orphanParentsCapped}:{},...e.files?{files:e.files}:{},...e.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:e.fileContentFieldsLeftOut}:{},...e.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:e.encryptedFieldsLeftOut}:{},...e.picklistValuesChanged?{picklistValuesChanged:e.picklistValuesChanged}:{},...e.currenciesReplaced?{currenciesReplaced:e.currenciesReplaced}:{},...e.recordTypesGiven?{recordTypesGiven:e.recordTypesGiven}:{},...e.writtenWithoutFields?{writtenWithoutFields:e.writtenWithoutFields}:{},...e.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:e.lookupsLeftEmptyByFilter}:{},...e.contactPoints?{contactPoints:e.contactPoints}:{},...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.apiCalls!==void 0?{apiCalls:e.apiCalls}:{},...e.dryRun?{dryRun:!0,wouldInsertCount:e.wouldInsertCount}:{},...e.gaps?{gaps:e.gaps}:{},...e.decisionsApplied?{decisionsApplied:e.decisionsApplied}:{},...e.mayHaveBeenWritten?{mayHaveBeenWritten:e.mayHaveBeenWritten}:{},...e.remapInJournal?{remapInJournal:!0}:{},...e.sample?{sample:e.sample}:{},...e.roots?{roots:e.roots}:{},...e.reads?{reads:e.reads}:{}}}var no="RUN_CANCELLED";function Sc(e){return{idRemapByObject:e.remapByObject,errors:e.errors,notSentByObject:e.notSentByObject,writtenWithoutFields:e.writtenWithoutFields,mayHaveBeenWritten:e.mayHaveBeenWritten}}function Ac(e){let t=new Map,n=r=>{let o=t.get(r)??er(r);return t.set(r,o),o};for(let r of e.idRemapByObject??[]){let o=n(r.objectApiName);o.created+=r.created,o.updated+=r.updated??0}for(let r of e.errors??[]){if(r.objectApiName.startsWith("__")||r.referenceData===!0||r.stage==="scope"&&r.failedCount===0&&r.skipped!==!0)continue;let o=n(r.objectApiName);o.failed+=r.failedCount,r.skipped===!0&&(o.skipped=r.failedCount>0?"counted":"uncounted")}for(let r of e.notSentByObject??[]){let o=n(r.objectApiName);o.notSent=(o.notSent??0)+r.notSent}for(let r of e.writtenWithoutFields??[]){let o=n(r.objectApiName);o.writtenWithoutFields=(o.writtenWithoutFields??0)+r.rows}for(let{objectApiName:r,sourceIds:o}of e.mayHaveBeenWritten??[]){let s=n(r);s.mayHaveBeenWritten=(s.mayHaveBeenWritten??0)+o.length}return[...t.values()]}function Ec(e,t){return t.some(r=>r.created+r.updated>0)?"cancelled":(e?to(e):"success")==="success"?"stopped":"cancelled"}function Tc(e){if(!e)return{};let t=e.refusedForms??[];return{details:{contactPoints:e.neutralized?"neutralized":"kept",contactPointFields:e.fields.length,contactPointValues:e.values,...t.length>0?{contactPointOtherForm:t.reduce((n,r)=>n+r.otherForm,0),contactPointWithoutField:t.reduce((n,r)=>n+r.withoutField,0)}:{}}}}function Oc(e){return Object.fromEntries((e.idRemapByObject??[]).map(t=>[t.objectApiName,t.created+t.linked+(t.updated??0)]))}var Lc=2e3,Dc=1e4,Oi=En;function Wc(e,t,n=Oi){let r=t!==void 0&&t>0?Math.floor(t):void 0;return r!==void 0&&r<=n?[]:e.nodes.filter(o=>o.included&&o.recordCountUnknown!==!0).map(o=>({objectApiName:o.objectApiName,rows:r===void 0?o.recordCount:Math.min(o.recordCount,r)})).filter(o=>o.rows>n).sort((o,s)=>s.rows-o.rows)}var Ht=.8,po=.5;function Qt(e){return Math.max(0,e.remainingMB-po-(e.uncountedWrites?.mb??0))}var ve=1024,ut=2*ve,mo=4*ve,ki=8*ve,Pi=1*ve,Mi=4*ve,$i=255,Fi=/__kav$/i,vi=new Map([Oe,Ke,Ye,"Campaign","CampaignMember"].map(e=>[e.toLowerCase(),e]));function dt(e){return vi.get(e.toLowerCase())??e}function ro(e,t=0){let n=0;for(let r of Object.values(e))typeof r=="string"&&r.length>t&&(n+=Buffer.byteLength(r,"utf8"));return n}function Ut(e,t){let n=dt(e);return n===Oe?ro(t):n===Ke?vt(t)?mo:ut:n===Ye&&vt(t)?0:n==="Campaign"?ki:n==="CampaignMember"?Pi:Fi.test(e)?Mi+ro(t,$i):ut}function ho(e,t){let n=Math.min(t.personAccounts??0,t.rows),r=t.rows-n,o=dt(e);return o===Ke?r*ut+n*mo:o===Ye?r*ut:r*Ut(e,{})}function Uc(e){let t=new Map;for(let{objectApiName:n,rows:r,storageBytes:o}of e.objects){let s=t.get(n)??{rows:0,bytes:0};t.set(n,{rows:s.rows+r,bytes:s.bytes+o})}return Object.fromEntries([...t].filter(([,n])=>n.rows>0).map(([n,r])=>[n,r.bytes/r.rows]))}function Ni(e){let t=e.map(({objectApiName:m,rows:w,counted:b,mayAdd:R=0,mayBeByThePlatform:E})=>{let P={rows:R,storageBytes:R*Ut(m,{}),...R>0?{mayAdd:R}:{},...E&&E.rows>0?{mayBeByThePlatform:E}:{}};return b?{objectApiName:m,...P,rows:b.rows+P.rows,storageBytes:ho(m,b)+P.storageBytes}:{objectApiName:m,...P,rows:w.length+P.rows,storageBytes:w.reduce((j,T)=>j+Ut(m,T),0)+P.storageBytes}}).filter(({rows:m})=>m>0).sort((m,w)=>w.rows-m.rows||m.objectApiName.localeCompare(w.objectApiName)),n=e.reduce((m,w)=>m+(w.leftOut?.writtenBefore??0),0),r=e.filter(m=>(m.leftOut?.heldBack??0)>0).map(({objectApiName:m,leftOut:w})=>({objectApiName:m,rows:w?.heldBack??0})),o=e.filter(m=>(m.leftOut?.byThePlatform??0)>0).map(({objectApiName:m,leftOut:w})=>({objectApiName:m,rows:w?.byThePlatform??0})),s=e.flatMap(({objectApiName:m,leftOut:w})=>w?.linkedByValue&&w.linkedByValue.rows>0?[{objectApiName:m,...w.linkedByValue}]:[]),i=m=>e.filter(w=>(w.leftOut?.[m]??0)>0).map(({objectApiName:w,leftOut:b})=>({objectApiName:w,rows:b?.[m]??0})),a=i("recordTypeNotInTarget"),u=i("withoutParent"),c=i("noParentInSource"),d=i("outsideFilter"),f=i("linkedToTarget"),g=i("currencyReplaced"),p=e.flatMap(({objectApiName:m,leftEmpty:w=[]})=>w.filter(({rows:b})=>b>0).map(({field:b,rows:R})=>({objectApiName:m,field:b,rows:R})));return{objects:t,...p.length>0?{leftEmpty:p}:{},totalRows:t.reduce((m,w)=>m+w.rows,0),storageBytes:t.reduce((m,w)=>m+w.storageBytes,0),...n>0||r.length>0||a.length>0||o.length>0||s.length>0||u.length>0||c.length>0||d.length>0||f.length>0||g.length>0?{leftOut:{writtenBefore:n,heldBack:r,...a.length>0?{recordTypeNotInTarget:a}:{},...o.length>0?{byThePlatform:o}:{},...s.length>0?{linkedByValue:s}:{},...u.length>0?{withoutParent:u}:{},...c.length>0?{noParentInSource:c}:{},...d.length>0?{outsideFilter:d}:{},...f.length>0?{linkedToTarget:f}:{},...g.length>0?{currencyReplaced:g}:{}}}:{}}}function qc(e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null,...e.queryScope==="records"?["records"]:[]])}var Bi=16,oo=class{kept=new Map;note(t,n,r=Date.now()){this.kept.delete(t),this.kept.set(t,{at:r,total:n.totalRows,objects:n.objects.map(({objectApiName:o,rows:s})=>({objectApiName:o,rows:s}))});for(let o of this.kept.keys()){if(this.kept.size<=Bi)break;this.kept.delete(o)}}of(t){return this.kept.get(t)}},xi=500;function Ci(e,t){return e>2*t||e-t>xi}function Gc(e,t,n=Date.now()){return{minutesBefore:Math.max(1,Math.ceil((n-e.at)/6e4)),total:e.total,objects:e.objects.map(({objectApiName:r,rows:o})=>({objectApiName:r,rows:o})),...Ci(t,e.total)?{farAbove:!0}:{}}}function zc(e){let t=e.objects.reduce((n,r)=>n+(r.mayAdd??0),0);return t>0?{pricesForLines:t}:{}}function Vc(e){let t=e.objects.find(n=>n.mayBeByThePlatform)?.mayBeByThePlatform;return!t||t.rows<=0?{}:{rolesMayBeByThePlatform:{rows:t.rows,...t.before===!0?{before:!0}:{}}}}function Hc(e,t){return t===void 0?e:{request:n=>e.request(n),writtenTo:t}}var at=B({Max:G(),Remaining:G()}).loose(),_i=B({DataStorageMB:at,DailyApiRequests:at.optional(),DailyBulkApiBatches:at.optional(),FileStorageMB:at.optional()}).loose(),Ii=B({DailyApiRequests:B({Max:G(),Remaining:G()}).loose()}).loose(),ji="the org does not tell this user its daily API requests";function yo(e,t,n){if(e!==null&&typeof e=="object"&&!(t in e))throw new Error(n)}async function Li(e){let t=await e.request({method:"GET",url:"/limits"});yo(t,"DataStorageMB",Sn);let n=_i.parse(t),r=n.DataStorageMB.Remaining,o=e.writtenTo,s=o!==void 0?Zn(o,r,(i,a)=>ho(i,{rows:a})):void 0;return o!==void 0&&Xn(o,r),{maxMB:n.DataStorageMB.Max,remainingMB:r,...s?{uncountedWrites:s}:{},...n.DailyApiRequests?{dailyApiRequests:{max:n.DailyApiRequests.Max,remaining:n.DailyApiRequests.Remaining}}:{},...n.DailyBulkApiBatches?{dailyBulkApiBatches:{max:n.DailyBulkApiBatches.Max,remaining:n.DailyBulkApiBatches.Remaining}}:{},...n.FileStorageMB?{fileStorage:{maxMB:n.FileStorageMB.Max,remainingMB:n.FileStorageMB.Remaining}}:{}}}async function so(e){let t=await e.request({method:"GET",url:"/limits"});yo(t,"DailyApiRequests",ji);let n=Ii.parse(t);return{max:n.DailyApiRequests.Max,remaining:n.DailyApiRequests.Remaining}}var qt=200,wo=2e3,Di=.1;function Wi(e){return e.reduce((t,{rows:n,bulk:r,readRows:o,perCall:s})=>{let i=Math.min(qt,Math.max(1,s??qt)),a=n<=0?0:r?ur(n):Math.ceil(n/i),u=o&&o>0?Math.ceil(o/wo):0;return t+a+u},0)}var Jt=["checkpoint","mute","readBack","deliverability","fit"],Ui={checkpoint:"for the checkpoint taken first",mute:"to assign and take back the permission sets that mute the target's automation",readBack:"to read back the record types the target gave",deliverability:"to read whether the target delivers its emails",fit:"to fit the run to the storage"};function qi(e){return Jt.reduce((t,n)=>t+Math.max(0,e[n]??0),e.run)}function Gi(e){return Jt.some(t=>(e[t]??0)>0)?{...e}:void 0}function Wt(e,t){let n=typeof e=="number"?void 0:Gi(e),r=typeof e=="number"?e:qi(e),o=n?{parts:n}:{};if(!t)return{verdict:"unread",estimate:r,unread:"the limits the org answered list no DailyApiRequests",...o};if("unread"in t)return{verdict:"unread",estimate:r,unread:t.unread,...o};let{max:s,remaining:i}=t;return{verdict:r>i?"exceeds":i-r<Di*s?"near":"fits",estimate:r,max:s,remaining:i,...o}}function zi(e){if(!e)return"";let t=Jt.filter(n=>(e[n]??0)>0).map((n,r)=>`${e[n]}${r===0?" of them":""} ${Ui[n]}`);return t.length>0?` (${t.join(", ")})`:""}var Me="API_BUDGET_EXCEEDED";function Vi(e,t,n){if(e.verdict==="exceeds")return`The run takes about ${e.estimate} API requests${zi(e.parts)}, and ${t} has ${e.remaining} of its ${e.max} daily requests left: it would stop part way through, its records refused with REQUEST_LIMIT_EXCEEDED. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records. `+(n?`${n} `:"")+"Nothing was written."}function Hi(e){return e.verdict==="near"?{apiRequests:{estimate:e.estimate,remaining:e.remaining,max:e.max,...e.parts?{parts:{...e.parts}}:{}}}:{}}var ct="CHECKPOINT_REFUSED";function Qi(e){return e?{checkpoint:e.estimate.apiRequests}:{}}function Ji(e){let t=e?.refusal;if(t!==void 0)return{code:ct,message:Ct(t),refusal:t}}var Ki="The run was stopped while it took the checkpoint first: nothing of it was kept, and nothing was written.";async function Qc(e){let t;try{t=await e()}catch(n){return{stop:{code:ct,message:Sr(n)}}}return t.taken?{checkpoint:t.checkpoint}:"stopped"in t?{stop:{code:no,message:Ki}}:{stop:{code:ct,message:Ct(t.refusal),refusal:t.refusal}}}var io=1e4,Yi=1e4,Xi=.01;function Zi(e,t,n){return t<2e3||br.has(e)||(n??Rr).has(e)}function lt(e,t,n){if(t<=0)return{jobs:[],rest:0};if(Zi(e,t,n.restOnly))return{jobs:[],rest:t};let r=[];for(let o=t;o>0;o-=io){let s=Math.min(o,io);if(s<2e3)return{jobs:r,rest:s};r.push(s)}return{jobs:r,rest:0}}function ea(e){return sr({stateReads:ar(e,or,"save")})}function ta(e,t,n){let{jobs:r,rest:o}=lt(e,t,n);return r.reduce((s,i)=>s+ea(i),0)+Math.ceil(o/qt)}var na=4,ra=3;function oa(e){let t=new Set(e.updatedAfterInsert??[]),n=new Map((e.plan.leftOut?.linkedByValue??[]).map(({objectApiName:u,rows:c})=>[u,c])),r=[...e.plan.objects.map(({objectApiName:u,rows:c})=>({objectApiName:u,rows:c+(n.get(u)??0)})),...[...n].filter(([u])=>!e.plan.objects.some(c=>c.objectApiName===u)).map(([u,c])=>({objectApiName:u,rows:c}))],o=e.plan.objects.filter(({objectApiName:u})=>t.has(u)).map(({objectApiName:u,rows:c})=>({objectApiName:u,rows:c})),{bulk:s}=e,i=e.files!==void 0&&e.files>0?e.files:0,a=s?na*r.filter(({rows:u})=>u>0).length:0;return{run:(s?[...r,...o].reduce((u,{objectApiName:c,rows:d})=>u+ta(c,d,s),0):Wi([...r,...o]))+i+a+Math.max(0,e.sentBefore??0),...Qi(e.checkpoint),...e.mute!==void 0&&e.mute>0?{mute:e.mute}:{},...e.readBack!==void 0&&e.readBack>0?{readBack:e.readBack}:{},...e.deliverability!==void 0&&e.deliverability>0?{deliverability:e.deliverability}:{}}}var sa=200;function ia(e){let t={...e.measures.restOnly?{restOnly:e.measures.restOnly}:{}},n=new Set(e.updatedAfterInsert??[]),r=e.plan.objects.map(({objectApiName:a,rows:u})=>({objectApiName:a,rows:u,writes:lt(a,u,t),updates:n.has(a)?lt(a,u,t):void 0})),o=r.flatMap(({writes:a,updates:u})=>u?[a,u]:[a]),s=e.measures.files,i=s&&"count"in s&&s.count>0?s.count:0;return{objects:r.map(({objectApiName:a,rows:u,writes:c})=>({objectApiName:a,rows:u,jobs:c.jobs.length})),sourceRequests:(e.measures.sourceReads??r.reduce((a,{rows:u})=>a+Math.ceil(Math.max(0,u)/wo),0)+i+Math.ceil(i/sa))+ra*r.filter(({rows:a})=>a>0).length+(e.sourceSentBefore===void 0?Math.max(0,e.measures.heldReads??0):Math.max(0,e.sourceSentBefore)),bulkBatches:o.reduce((a,{jobs:u})=>a+u.reduce((c,d)=>c+Math.ceil(d/Yi),0),0),durationSeconds:o.reduce((a,{jobs:u,rest:c})=>a+u.reduce((d,f)=>d+ir(f,"save"),0)+c*Xi,0),restObjects:r.filter(({rows:a,writes:u})=>a>0&&u.jobs.length===0).map(({objectApiName:a})=>a)}}var aa="the limits the org answered list no DailyBulkApiBatches";function ua(e,t){if(e.verdict==="exceeds")return`The run writes through Bulk API jobs that take about ${e.estimate} of the daily Bulk API batches, and ${t} has ${e.remaining} of its ${e.max} left: its jobs would be refused part way through. Run it once the org has batches to spare \u2014 the limit is counted over the last 24 hours, and Bulk API 1.0 shares it \u2014 or leave objects out. Nothing was written.`}function da(e,t){if(e.verdict==="exceeds")return`The run reads the source records in about ${e.estimate} API requests, and ${t} has ${e.remaining} of its ${e.max} daily requests left: the reads would stop part way through, and the org's own integrations with them. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or leave objects out. Nothing was written.`}function ca(e,t){if(e.verdict==="exceeds")return`The files to copy take about ${Z(e.estimateMB)} MB of file storage, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB${Re(ie(e),t)}: leave out the objects whose files take it, turn the copy of files off on Review, or free file storage in ${t}. Nothing was written.`}function la(e,t){return`A clone of the whole org reads a few objects whole, and ${e.map(({objectApiName:r,rows:o})=>`${r} (${o} rows)`).join(", ")} ${e.length===1?"holds":"hold"} more than the ${t} rows of one object the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting or leave the object out on Review. Nothing was written.`}var fa=200;function ga(e){if(!e||e.length===0)return;let t=Math.min(...e.map(r=>r.bound)),n=e.map(({objectApiName:r,rows:o})=>({objectApiName:r,rows:o}));return{code:"READ_BOUND_EXCEEDED",message:la(n,t),readBound:{bound:t,objects:n.slice(0,fa)}}}var bo="FILES_UNREAD",Ro="FILE_STORAGE_UNREAD";function pa(e,t,n){if(!e)return{};if("unmeasured"in e)return{files:{unmeasured:!0},stop:{code:bo,message:`The source would neither sum nor list its files, so what they take of the file storage ${n} has left is not known: turn the copy of files off on Review, or run it again once the source answers. Nothing was written.`}};if(e.count<=0)return{};let r=So({storageBytes:e.bytes},"unread"in t?t:t.fileStorage??{unread:"the limits the org answered list no FileStorageMB"});if(r.verdict==="unread")return{files:{count:e.count,check:r},stop:{code:Ro,message:`The file storage ${n} has left could not be read (${r.unread}), so the ${e.count} files to copy could not be checked against it: turn the copy of files off on Review, or run it again once the org answers. Nothing was written.`}};let o=ca(r,n);return{files:{count:e.count,check:r},...o!==void 0&&r.verdict==="exceeds"?{stop:{code:"STORAGE_EXCEEDED",message:o,storage:{estimateMB:Number(Z(r.estimateMB)),remainingMB:r.remainingMB,kind:"files",...ie(r)}}}:{}}}function ma(e){let t=e.wholeOrg,n=t?.measures.files,r=Wt(oa({...e,...t?{bulk:t.measures.restOnly?{restOnly:t.measures.restOnly}:{},...n&&"count"in n?{files:n.count}:{}}:{}}),e.budget),o=Vi(r,e.target,dr),s=[],i=Ji(e.checkpoint);i&&s.push(i),o!==void 0&&s.push({code:Me,message:o,...t&&r.verdict==="exceeds"?{api:{kind:"requests",org:"target",estimate:r.estimate,remaining:r.remaining}}:{}});let a;if(t){let f=ia({...e,measures:t.measures,...t.sourceSentBefore!==void 0?{sourceSentBefore:t.sourceSentBefore}:{}}),g=f.bulkBatches>0?Wt(f.bulkBatches,t.bulkBatches??{unread:aa}):void 0,p=g&&ua(g,e.target);p!==void 0&&g?.verdict==="exceeds"&&s.push({code:Me,message:p,api:{kind:"bulkBatches",org:"target",estimate:g.estimate,remaining:g.remaining}});let m=Wt(f.sourceRequests,t.sourceBudget),w=da(m,t.source);w!==void 0&&m.verdict==="exceeds"&&s.push({code:Me,message:w,api:{kind:"requests",org:"source",estimate:m.estimate,remaining:m.remaining}}),a={source:m,...g?{bulkBatches:g}:{},cost:f}}let[u,...c]=s,d=c.filter(f=>f.code===Me);return{api:r,...u?{stop:u}:{},...t&&d.length>0?{alsoRefused:d}:{},...a?{wholeOrg:a}:{},asks:e.checkpoint!==void 0||t!==void 0||r.verdict==="near",confirmation:{...Hi(r),...e.checkpoint?{checkpoint:e.checkpoint}:{}}}}function So(e,t,n=0){let r=Math.max(0,n),o=e.storageBytes+r,s=o/1048576,i=r>0?{automationMB:r/1048576}:{};if("unread"in t)return{verdict:"unread",estimateMB:s,unread:t.unread,...i};let{maxMB:a,remainingMB:u,uncountedWrites:c}=t,d=Qt(t)*1048576;return{verdict:o>d?"exceeds":o>Ht*d?"near":"fits",estimateMB:s,maxMB:a,remainingMB:u,...i,...c?{uncountedWrites:c}:{}}}function ie(e){if(e.verdict==="unread")return{};let t=e.uncountedWrites?.mb??0,n=e.remainingMB-t,r=e.verdict==="exceeds"&&e.estimateMB<=n||e.verdict==="near"&&e.estimateMB<=Ht*n;return{...e.uncountedWrites?{uncountedWrites:e.uncountedWrites}:{},...r?{roundingMB:po}:{}}}function Re(e,t){let{uncountedWrites:n,roundingMB:r}=e,o=[...n?[`about ${Z(n.mb)} MB of it taken by what ${ha(n,t)}, which Salesforce has not counted yet`]:[],...r!==void 0?[`up to ${r} MB of it may be taken already: Salesforce says it to the MB`]:[]];return o.length>0?` (${o.join("; ")})`:""}function ha(e,t){let{runs:n,minutes:r,writing:o=0}=e;return n===1&&o===1?`a run from this machine is still writing to ${t}, begun ${r} minute(s) ago`:`${n===1?"a run":`${n} runs`} from this machine wrote to ${t} in the last ${r} minute(s)`+(o>0?`, ${o} of them still writing`:"")}function ya(e,t){if(!t||t.length===0)return 0;let n=new Map;for(let{objectApiName:r,bytes:o}of t)n.set(r,(n.get(r)??0)+Math.max(0,o));return e.objects.reduce((r,{objectApiName:o,rows:s})=>r+s*(n.get(o)??0),0)}function gt(e){return`about ${Z(e.estimateMB)} MB of data storage`+(e.automationMB!==void 0&&e.automationMB>0?`, about ${Z(e.automationMB)} MB of it for what the target's automation creates under them`:"")}function wa(e,t){let n=Ni(e),r=t.emailTextBytes,o=e.some(i=>dt(i.objectApiName)===Oe&&i.counted);if(r===void 0||!Number.isFinite(r)||!o)return n;let s=n.objects.map(i=>dt(i.objectApiName)===Oe?{...i,storageBytes:i.storageBytes+Math.max(0,r)}:i);return{...n,objects:s,storageBytes:s.reduce((i,a)=>i+a.storageBytes,0)}}function ba(e,t,n){return e.flatMap(({objectApiName:r,included:o,piiFields:s,anonymizeFields:i})=>{if(!o||!t.has(r))return[];let a=new Set(n?i:[]),u=s.filter(c=>!a.has(c));return u.length>0?[{objectApiName:r,fields:u}]:[]})}function Ra(e){let t=e.leftOut??[],n=new Set(t.map(({objectApiName:s})=>s)),r=[...t,...e.nodes.filter(s=>s.leftOutByUser===!0&&!n.has(s.objectApiName)).map(({objectApiName:s})=>({objectApiName:s,reason:"excludedByUser"}))],o=new Map;for(let{reason:s}of r)o.set(s,(o.get(s)??0)+1);return{objects:r,counts:[...o].map(([s,i])=>({reason:s,count:i})).sort((s,i)=>i.count-s.count||s.reason.localeCompare(i.reason))}}var Sa=2;async function Jc(e){let t=b=>({unread:F(b)}),n=wa(e.objects,e.measures),r=await Li(e.target.limits).catch(t),o="unread"in r?await so(e.target.limits).catch(t):r.dailyApiRequests,s=await so(e.source.limits).catch(t),i=So(n,r,ya(n,e.automation)),a=tu(i,e.target.org),u=e.sample?Pa({sample:e.sample,storage:r,target:e.target.org,...e.sampleAsked?{asked:e.sampleAsked}:{}}):void 0,c=pa(e.measures.files,r,e.target.org),d=e.sentBefore?.(),f=ma({plan:n,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...e.readBack!==void 0?{readBack:e.readBack}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{},...e.mute!==void 0?{mute:e.mute}:{},deliverability:e.deliverability??Sa,...d?{sentBefore:d.target}:{},budget:o,target:e.target.org,wholeOrg:{measures:e.measures,bulkBatches:"unread"in r?r:r.dailyBulkApiBatches,sourceBudget:s,source:e.source.org,...d?.source!==void 0?{sourceSentBefore:d.source}:{}}}),g=[ga(e.measures.readWholeOver),u,u===void 0&&a!==void 0&&i.verdict==="exceeds"?{code:"STORAGE_EXCEEDED",message:`${a} Nothing was written.`,storage:{estimateMB:Number(Z(i.estimateMB)),remainingMB:i.remainingMB,...ie(i)}}:void 0,c.stop,f.stop,...f.alsoRefused??[]].filter(b=>b!==void 0),p=e.measures.restOnly?{restOnly:e.measures.restOnly}:{},m=new Set(n.objects.map(({objectApiName:b})=>b)),{wholeOrg:w}=f;return{wouldInsert:n.objects.map(({objectApiName:b,rows:R})=>{let{jobs:E,rest:P}=lt(b,R,p);return{objectApiName:b,rows:R,jobs:E.length,byRest:P}}),totalRows:n.totalRows,targetRequests:f.api,sourceRequests:w.source,...w.bulkBatches?{bulkBatches:w.bulkBatches}:{},storage:i,...c.files?{files:c.files}:{},durationSeconds:w.cost.durationSeconds,leftOut:{...Ra(e.graph),...n.leftOut?{rows:n.leftOut}:{}},personalAsIs:ba(e.graph.nodes,m,e.anonymizePII),wouldBeRefused:g,...e.measures.personAccountsAsBusiness?{personAccountsAsBusiness:e.measures.personAccountsAsBusiness}:{},...e.sample?{sample:e.sample}:{}}}var Aa="SAMPLE_STORAGE_UNREAD",Ao="SAMPLE_CANNOT_FIT",Ea="SAMPLE_TOO_LARGE",Eo="SAMPLE_PLAN_MISMATCH",Gt="SAMPLE_PLAN_GONE";function Ta(e){let{storage:t,bounds:n,target:r}=e;if("unread"in t&&!(n.withinMB!==void 0||n.maxTotal!==void 0))return{code:Aa,message:`The data storage ${r} has left could not be read (${t.unread}), and a sample is fitted to it: there is nothing to hold it to. Give the most it may take (--fit-within <MB>) or the most records (--max-total <n>), or run it again once the org answers. Nothing was written.`}}function Oa(e,t){if(e.remainingMB===void 0||e.share===void 0)return;let n=Math.max(0,t.remainingMB-(e.roundingMB??0)-(t.uncountedWrites?.mb??0));return Math.floor(e.share*n*1048576)}function ka(e){let{sample:t,storage:n,target:r}=e,o=Oa(t.budget,n);if(o===void 0||t.storageBytes<=o)return;let s=No(t.storageBytes/1048576,o/1048576),i=Z(t.budget.bytes/1048576),a=n.uncountedWrites;return{code:"STORAGE_EXCEEDED",message:`The sample was fitted to ${i} MB of the data storage ${r} had left (${t.budget.remainingMB} MB), and ${r} now says ${n.remainingMB} MB left${Re(a?{uncountedWrites:a}:{},r)}, which holds ${s.bound} MB of a sample: the sample takes about ${s.over} MB. Simulate again \u2014 run the dry run again \u2014 to draw a sample that fits: a run never cuts its sample short. Nothing was written.`,storage:{estimateMB:Number(s.over),remainingMB:n.remainingMB,...a?{uncountedWrites:a}:{}},sample:{fittedMB:Number(i),holdsMB:Number(s.bound)}}}function Pa(e){let{sample:t,storage:n,target:r}=e;return"unread"in n?Ta({storage:n,bounds:e.asked??t.budget,target:r}):ka({sample:t,storage:n,target:r})}var Ma=new Set(["gone","changed","otherOrg","otherSetup","otherSha"]),$a={changed:"is no longer as its dry run wrote it: its ids changed since",otherOrg:"was drawn of another org than the source",otherSetup:"was drawn for another setup of the run \u2014 other flags, filters, objects or options of the sample",otherSha:"is not the plan its dry run printed"};function Fa(e,t){return t==="resume"?{code:Gt,message:`The plan of the sample this run resumes ${e==="gone"?"is no longer on this machine":"is no longer as it was written"}: the records it was to write cannot be taken up after where it stopped (--resume). Remove what it wrote (--remove), or run the clone again without --resume to draw a new sample. Nothing was written.`,sample:{plan:e}}:e==="gone"?{code:Gt,message:'No plan of a sample is at the path given to --fit-plan: give the folder its dry run printed ("sample plan: \u2026"), within a day of it, or leave --fit-plan out to draw a new sample. Nothing was written.',sample:{plan:e}}:{code:Eo,message:`The plan given to --fit-plan ${$a[e]}: run the dry run again with the flags of this run, and replay the plan it prints. Nothing was written.`,sample:{plan:e}}}var va=new Set([Ea,Ao,Gt,Eo]),Na=20;function Kc(e,t){if(e instanceof Error){if(e.name==="SampleRefusedError"){let{code:n,heaviest:r,sample:o}=e;if(typeof n!="string"||!va.has(n))return;let s=Array.isArray(r)?r.flatMap(u=>{let c=u?.objectApiName;return typeof c=="string"?[c]:[]}):[],i=Pn({code:n,sample:o})?.sample??{},a={...i,...n===Ao&&i.heaviest===void 0&&s.length>0?{heaviest:s.slice(0,Na)}:{}};return ge.of({code:n,message:e.message,...Object.keys(a).length>0?{sample:a}:{}})}if(e.name==="SamplePlanError"&&t!=="draw"){let{refusal:n}=e;return typeof n!="string"||!Ma.has(n)?void 0:ge.of(Fa(n,t))}}}var Ba=B({SingleEmail:B({Max:G(),Remaining:G()}).loose().optional(),DailyWorkflowEmails:B({Max:G(),Remaining:G()}).loose().optional()}).loose();async function Yc(e){let t=Ba.parse(await e.request({method:"GET",url:"/limits"})),n={};for(let r of["SingleEmail","DailyWorkflowEmails"]){let o=t[r];o&&(n[r]={max:o.Max,remaining:o.Remaining})}return n}var xa=15;function To(e){let t=e.SingleEmail;return t!==void 0&&t.max<=xa}function Ca(e){return To(e)&&e.DailyWorkflowEmails!==void 0}function _a(e,t,n=!1){let r=e.map(a=>({...a,sentBy:[...a.sentBy]})),o=(a,u)=>{let c=r.find(d=>d.objectApiName===a.objectApiName&&d.limit===u);if(!c){let d={...a,limit:u,sentBy:[...a.sentBy]};return r.push(d),d}c.perRecord+=a.perRecord;for(let d of a.sentBy)c.sentBy.includes(d)||c.sentBy.push(d);return c},s=e.filter(a=>a.limit==="SingleEmail"),i=e.filter(a=>a.limit==="DailyWorkflowEmails");if(n)for(let a of s)o(a,"DailyWorkflowEmails");if(t)for(let a of i)o(a,"SingleEmail").alertsAmong=!0;return r}function Oo(e){let t=new Map(e.objects.map(n=>[n.objectApiName,{rows:n.rows,byThePlatform:0}]));for(let{objectApiName:n,rows:r}of e.leftOut?.byThePlatform??[]){let o=t.get(n)??{rows:0,byThePlatform:0};t.set(n,{rows:o.rows+r,byThePlatform:o.byThePlatform+r})}return t}function Kt(e){return new Set([...Oo(e)].flatMap(([t,{rows:n}])=>n>0?[t]:[]))}function Ia(e,t,n){let r=Oo(e),o=new Map;for(let i of t){let{rows:a,byThePlatform:u}=r.get(i.objectApiName)??{rows:0,byThePlatform:0};if(a===0)continue;let c=o.get(i.limit)??{limit:i.limit,objects:[],emails:0,verdict:"fits"};c.objects.push({objectApiName:i.objectApiName,rows:a,perRecord:i.perRecord,sentBy:i.sentBy,...u>0?{byThePlatform:u}:{}}),c.emails+=a*i.perRecord,o.set(i.limit,c)}let s=ft(n)?n.unread:void 0;return[...o.values()].map(i=>{if(s!==void 0||ft(n))return{...i,verdict:"unread",unread:s};let a=n[i.limit];return a?{...i,verdict:i.emails>a.remaining?"exceeds":"fits",remaining:a.remaining,max:a.max}:{...i,verdict:"unread",unread:`the org's limits list no ${i.limit}`}})}function ft(e){return typeof e.unread=="string"}function ja(e,t,n){let r=!ft(n)&&To(n),o=!ft(n)&&Ca(n),s=Ia(e,_a(t,r,o),n);if(!r)return s;let i=Kt(e);return t.some(u=>u.limit==="DailyWorkflowEmails"&&i.has(u.objectApiName))?s.map(u=>u.limit==="SingleEmail"?{...u,alertsCounted:!0}:u):s}async function Xc(e){if(e.plan.totalRows===0||e.objects.length===0)return{checks:[]};let t;try{t=await e.readAutomation(e.objects)}catch(i){return{checks:[],unread:`the target's automation: ${F(i)}`}}let n=Da(t,La(e.plan)),r=n!==void 0?{unread:n}:{},o=Wn(t);if(o.length===0)return{checks:[],...r};let s=await e.readLimits().catch(i=>({unread:F(i)}));return{checks:ja(e.plan,o,s),...r}}function La(e){let t=Kt(e);return(n,r)=>r==="insert"&&t.has(n)}function Da(e,t,n="the target's"){let r=[ko(e.unread,n),qa(e,t)].filter(o=>o!==void 0).join("; ");return r!==""?r:void 0}var Wa={flows:"flows",processes:"processes",workflowRules:"workflow rules"};function ko(e,t){let n=e.flatMap(({part:r,reason:o})=>{let s=Wa[r];return s!==void 0?[`${t} ${s}: ${o}`]:[]});return n.length>0?n.join("; "):void 0}var we=10;function Ua(e){if(e.condition!=="unreadable")return;let t=e.apiName.indexOf("__");return t>0?e.apiName.slice(0,t):void 0}function qa(e,t){let n=e.objects.flatMap(o=>{let i=[...new Set(ze(o).filter(u=>t(o.objectApiName,u.write)).flatMap(u=>u.fired).flatMap(({flow:u,keptQuiet:c})=>u!==void 0&&c!==!0&&u.condition!=="read"&&u.timing!=="beforeSave"?[u]:[]))].map(u=>{let c=Ua(u);return c!==void 0?`${u.label} (package ${c}, whose flows the org lets no one read)`:u.label});if(i.length===0)return[];let a=i.length>we?` and ${i.length-we} more`:"";return[{count:i.length,words:`${i.slice(0,we).join(", ")}${a} on ${o.objectApiName}`}]});return n.length===0?void 0:`the definition${n.reduce((o,{count:s})=>o+s,0)===1?"":"s"} of ${n.map(({words:o})=>o).join("; ")}`}function Zc(e){return{limit:e.limit,emails:e.emails,remaining:e.remaining??0,max:e.max??0,objects:e.objects.map(({objectApiName:t,perRecord:n})=>({objectApiName:t,perRecord:n})),...e.alertsCounted?{alertsCounted:!0}:{}}}function el(e){return{limit:e.limit,emails:e.emails,unread:e.unread??""}}var Ga={SingleEmail:{one:"single email",more:"single emails"},DailyWorkflowEmails:{one:"workflow email",more:"workflow emails"}};function Po(e,t){let n=Ga[t];return`${e} ${e===1?n.one:n.more}`}function za(e,t){return e.alertsCounted?`, its email alerts among them: ${t} counts them against its single emails, as a Developer Edition does`:""}function tl(e,t){let n=e.filter(o=>o.verdict==="exceeds");if(n.length===0)return;let r=n.map(o=>`about ${Po(o.emails,o.limit)}`+(o.alertsCounted?" (its email alerts among them, as a Developer Edition counts them)":"")+`, ${o.remaining??0} of ${o.max??0} left today`).join("; ");return`The target's automation would make ${t} send ${r}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. Assign the user a bypass that keeps what sends quiet \u2014 muting the target's automation for the run (--mute-automation on the command line, the Mute box on a page) assigns, for the run alone, those the target's flows test \u2014 or write fewer records.`}function nl(e,t){return e.map(n=>{let r=n.objects.map(s=>`${s.perRecord} per ${s.objectApiName}, by ${s.sentBy.join(", ")}`+(s.byThePlatform?`; ${s.byThePlatform} ${s.objectApiName} written by the platform with ${ke(s.objectApiName)}, whose flows run all the same`:"")).join("; "),o=` emails: these records make ${t} send about ${Po(n.emails,n.limit)} (${r})`+za(n,t);return n.verdict==="unread"?`${o}; what it has left today could not be read (${n.unread??""})`:n.verdict==="fits"?`${o}; it has ${n.remaining??"?"} of ${n.max??"?"} left today`:`${o}, more than the ${n.remaining??"?"} of ${n.max??"?"} it has left today: past them the action fails, and a record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER). A bypass that keeps the flow quiet, or a smaller run, avoids it`})}var Mo="EMAILS_NOT_ACCEPTED";function rl(e,t={}){let n=[ko(e,"the target's"),...t.applyAssignmentRules===!0?e.filter(({part:r})=>r==="assignmentRules").map(({reason:r})=>`the target's assignment rules: ${r}`):[]].filter(r=>r!==void 0);return n.length>0?n.join("; "):void 0}function ol(e){return"requests"in e&&typeof e.requests=="number"?Math.max(0,e.requests):go}function sl(e){let t=e?.read?.requests??0;return t>0?{deliverability:t}:{}}var $o={clone:{run:"this clone",allTheSame:"to clone all the same"},sync:{run:"this sync",allTheSame:"to sync all the same"},seed:{run:"this seed",allTheSame:"to seed all the same"},autopilot:{run:"this Autopilot run",allTheSame:"to run it all the same"},rewind:{run:"this rewind",allTheSame:"to rewind all the same"},undo:{run:"this undo",allTheSame:"to undo all the same"},masking:{run:"this masking",allTheSame:"to mask all the same"},restore:{run:"this restore",allTheSame:"to restore all the same"},cleanup:{run:"this cleanup",allTheSame:"to delete all the same"},empty:{run:"this emptying",allTheSame:"to empty all the same"},load:{run:"this load",allTheSame:"to load all the same"}},Va={flow:"flow",process:"process",workflowRule:"workflow rule",assignmentRule:"assignment rule"},Ha={email:"",notRead:" (its definition was not read)",assignment:" (applied: it can mail the owner it assigns)"};function Fo(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function $e(e){let t=new Map;for(let n of e){let r=t.get(n.objectApiName)??[];r.push(`${Va[n.kind]} "${n.name}"${Ha[n.why]}`),t.set(n.objectApiName,r)}return[...t].map(([n,r])=>{let o=r.length>we?[...r.slice(0,we),`${r.length-we} more`]:r;return`${Fo(o)} on ${n}`}).join("; ")}var ao="read with one line of anonymous Apex that sends nothing";function vo(e){return"level"in e&&e.level==="withheld"}function Qa(e){return"unread"in e?`deliverability: not read (${e.unread}) \u2014 the run is refused without --accept-emails, as on All email`:e.level==="all"?`deliverability: All email \u2014 the emails of what still runs go out (${ao})`:`deliverability: System email only or No access \u2014 none of the emails its flows, processes, workflow rules and Apex send goes out, and the org still counts them against its daily email limits (${ao})`}function Ja(e,t){let{run:n,allTheSame:r}=$o[e.run],{target:o}=e,s=$e(e.senders),i=e.sendersUnread,a=s!==""?`what still runs as ${n} writes its records sends some: ${s}`+(i!==void 0?`; what could not be read may send more (${i})`:""):`what runs as ${n} writes its records could not all be read (${i??""}), so it may send some`,u=[];"unread"in t?u.push(`Whether ${o} delivers the emails its automation sends could not be read (${t.unread}), and ${a}.`,`Nothing was written. Add --accept-emails ${r}, or check Setup > Deliverability: on System email only or No access, none of them goes out.`):u.push(`${o} delivers every email its automation sends (Setup > Deliverability: All email), and ${a}.`,e.keepsAddresses===!0?`They go to the addresses the records and the alerts name: those of the records ${n} writes, as they hold them, the records' owners, the records already in ${o}, and an address an alert names.`:`They go to the addresses the records and the alerts name: those ${n} writes are under .invalid, but not the records' owners, the records already in ${o}, nor an address an alert names.`,`Nothing was written. Add --accept-emails ${r}, set the org's deliverability to System email only, or turn off what sends them.`);let c=e.muteQuiets??[];if(c.length>0){let d=new Set(c.map(g=>`${g.objectApiName}\0${g.kind}\0${g.name}`)),f=e.senders.filter(g=>!d.has(`${g.objectApiName}\0${g.kind}\0${g.name}`));u.push(`--mute-automation keeps quiet ${$e(c)}, which ${c.length===1?"tests":"test"} a bypass a permission set of ${o} holds`+(f.length>0?`; it cannot quiet ${$e(f)}.`:"."))}return u.join(" ")}function il(e){if(e.senders.length===0&&e.sendersUnread===void 0)return{verdict:"nothingSends",confirmation:{}};let t=e.reading??{unread:"the run did not read it"},n={reading:t,senders:[...e.senders],...e.sendersUnread!==void 0?{sendersUnread:e.sendersUnread}:{}},r=Qa(t);return vo(t)?{verdict:"withheld",deliverability:n,confirmation:{},line:r,audit:"withheld"}:{verdict:"asks",deliverability:n,confirmation:{deliverability:e.keepsAddresses===!0?{...n,keepsAddresses:!0}:n},...e.accepted?{}:{stop:{code:Mo,message:Ja(e,t)}},line:r,audit:"unread"in t?"unread":"all"}}function al(e,t){let n=Kt(t);return e.filter(r=>!n.has(r.objectApiName))}function ul(e){if(e.length===0)return;let t=[...new Set(e.map(n=>n.objectApiName))];return` emails: ${$e(e)} send nothing: the run writes no ${Fo(t)} record. A real run is refused all the same, and names them: it asks before it reads which records it writes`}function dl(e){let t=u=>`${u.objectApiName}\0${u.kind}\0${u.name}`,n=new Set(e.planned.map(t)),r=e.held.filter(u=>!n.has(t(u)));if(r.length===0||e.accepted)return;let o=e.reading;if(o!==void 0&&vo(o))return;let{run:s,allTheSame:i}=$o[e.run],a=o===void 0?`whether ${e.target} delivers them was not read, as nothing that sends one was to run`:"unread"in o?`whether ${e.target} delivers them could not be read (${o.unread})`:`${e.target} delivers every one of them (All email)`;return{code:Mo,relit:r,message:`The mute's lease does not hold every permission set it was to assign, and what they were to keep quiet still runs for ${s}: ${$e(r)} may send emails, and ${a}. The run's question did not ask about them. Nothing was written. Add --accept-emails ${i}, or run it again once the lease can assign them.`}}function cl(e){if(e.verdict==="unread")return{estimateMB:e.estimateMB,unread:e.unread};let{roundingMB:t}=ie(e);return{estimateMB:e.estimateMB,maxMB:e.maxMB,remainingMB:e.remainingMB,near:e.verdict==="near",...e.uncountedWrites?{uncountedWrites:e.uncountedWrites}:{},...t!==void 0?{roundingMB:t}:{}}}function Z(e){return zt(e,e<10?2:1)}function zt(e,t){if(e<=0)return"0";let n=10**t;return(Math.ceil(e*n-1e-9)/n).toString()}function No(e,t){let n={over:e<10?2:1,bound:t<10?2:1};for(;;){let r={over:zt(e,n.over),bound:zt(t,n.bound)},o=Math.max(n.over,n.bound);if(Number(r.over)>Number(r.bound)||o>=6)return r;n={over:o+1,bound:o+1}}}function Bo(e){return e.map(({objectApiName:t,kind:n,name:r})=>({objectApiName:t,kind:n,name:r}))}function Ka(e){return Bo(Ot(e,"insert"))}function Ya(e,t){let n=new Set(t);return Bo(Ot(e,"update",r=>n.has(r)))}var xo=["lookups","statuses","invitees","retry","upsert"];function ll(e,t={}){let n=Vt(e,t.leftOut),r=new Set(n),o=new Map,s=(d,f)=>{if(!r.has(d))return;let g=o.get(d)??new Set;g.add(f),o.set(d,g)},i=e.edges.filter(d=>wr(d)&&r.has(d.sourceObject)&&r.has(d.targetObject)),a=new Map;for(let{sourceObject:d,targetObject:f}of i)d!==f&&a.set(d,[...a.get(d)??[],f]);let u=(d,f)=>{let g=new Set([d]),p=[d];for(let m=p.shift();m!==void 0;m=p.shift())for(let w of a.get(m)??[]){if(w===f)return!0;g.has(w)||(g.add(w),p.push(w))}return!1},c=i.filter(d=>d.required!==!0&&d.insertOnly!==!0);for(let{sourceObject:d,targetObject:f}of c)(d===f||u(f,d))&&s(f,"lookups");for(let d of Object.keys(Yn))s(d,"statuses");for(let d of Object.keys(Kn))s(d,"invitees");if(t.retry===!0)for(let{sourceObject:d,targetObject:f}of c)d!==f&&s(f,"retry");if(t.upsert===!0)for(let d of n)s(d,"upsert");return n.flatMap(d=>{let f=o.get(d);return f?[{objectApiName:d,steps:xo.filter(g=>f.has(g))}]:[]})}function Xa(e){let t=new Set(e.flatMap(n=>n.steps));return xo.filter(n=>t.has(n))}function fl(e,t=[]){let n=new Set(t);return Un(e,(r,o)=>o==="insert"||o==="update"&&n.has(r))}function gl(e,t,n){let r=new Set(Ve(e).map(i=>i.toLowerCase())),o=t.filter(i=>!r.has(i.toLowerCase())),s=Qe(e,o);return o.map(i=>{let a=s.find(c=>c.permission.toLowerCase()===i.toLowerCase()),u=a?.permissionSet?.name;return{permission:i,...u?{permissionSet:u}:{},others:a?.others.map(c=>c.name)??[],...a&&!u?{noneHolds:!0}:{},...u&&n?.alias&&n.username?{command:Je(u,n.alias,n.username)}:{}}})}function Za(e){return e==="flows"||e==="triggers"||e==="processes"||e==="workflowRules"||e==="automation"}function Ne(e){return e.unread.flatMap(({part:t,reason:n})=>Za(t)?[{part:t,reason:n}]:[])}var pl="OWNER_MAP_INACTIVE",ml="OWNER_MAP_UNKNOWN",ge=class e extends Error{code;storage;ceiling;reason;api;readBound;sample;roots;constructor(t,n,r,o,s,i){super(n),this.name="ForgeRunGateError",this.code=t,r&&(this.storage=r),o!==void 0&&(this.ceiling=o),s!==void 0&&(this.reason=s),i?.api&&(this.api=i.api),i?.readBound&&(this.readBound=i.readBound),i?.sample&&(this.sample=i.sample),i?.roots&&(this.roots=i.roots)}static of(t){return new e(t.code,t.message,t.storage,void 0,t.refusal?.code,{...t.api?{api:t.api}:{},...t.readBound?{readBound:t.readBound}:{},...t.sample?{sample:t.sample}:{},...t.roots?{roots:t.roots}:{}})}get stop(){if(kn(this.code))return{code:this.code,...this.storage?{storage:this.storage}:{},...this.ceiling!==void 0?{ceiling:this.ceiling}:{},...this.reason!==void 0&&this.code===ct?{reason:this.reason}:{},...this.api&&this.code===Me?{api:this.api}:{},...this.readBound&&this.code==="READ_BOUND_EXCEEDED"?{readBound:this.readBound}:{},...this.sample?{sample:this.sample}:{},...this.roots&&(eu.has(this.code)||this.code==="STORAGE_EXCEEDED")?{roots:this.roots}:{}}}},eu=new Set(["ROOTS_QUERY_REFUSED","NO_ROOTS","ROOTS_EXCEEDED","ROOTS_PLAN_MISMATCH","ROOTS_PLAN_GONE"]);function hl(e){return e instanceof ge||e instanceof Error&&e.name==="ForgeRunGateError"&&typeof e.code=="string"}var uo="FILE_STORAGE_EXCEEDED";function yl(e){if(!(e instanceof Error)||e.name!=="ForgeFilesRefusedError")return;let{code:t,storage:n}=e;if(t===bo||t===Ro)return new ge(t,e.message);let r=n?.neededBytes,o=n?.remainingBytes;if(t!==uo||typeof r!="number"||typeof o!="number"||!Number.isFinite(r)||!Number.isFinite(o))return;let s=o/1048576;return new ge(uo,e.message,{estimateMB:Number(No(r/1048576,s).over),remainingMB:s,kind:"files"})}function tu(e,t){if(e.verdict==="exceeds")return`The records to write take ${gt(e)}, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB${Re(ie(e),t)}: leave objects out, lower the records per object, or free data storage in ${t}.`}var co=10;function wl(e,t,n){let r=[`write gate: ${e.totalRows} record(s) to write to ${n}, ${gt(t)}`];for(let s of e.objects.slice(0,co))r.push(` ${s.objectApiName.padEnd(42)}${String(s.rows).padStart(8)}`);let o=e.objects.slice(co);if(o.length>0){let s=o.reduce((i,a)=>i+a.rows,0);r.push(` and ${o.length} more object(s), ${s} record(s)`)}for(let{objectApiName:s,mayAdd:i}of e.objects)i!==void 0&&r.push(` counted in: up to ${i} ${s} record(s) the run may read as it writes them, a price in the currency of the record its lines belong to, the source's own beside the one read`);for(let{objectApiName:s,mayBeByThePlatform:i}of e.objects)i!==void 0&&r.push(` counted in: up to ${i.rows} ${s} record(s) the platform `+(i.before===!0?`may have written with ${ke(s)}, in the run this one takes up`:`may write itself with ${ke(s)}`)+", which the run then links to and does not send");r.push(...nu(e.leftOut));for(let{objectApiName:s,field:i,rows:a}of e.leftEmpty??[])r.push(` written empty: ${s}.${i} on ${a} record(s), the record it names held back by the run, never written`);return t.verdict==="unread"?(r.push(` the data storage ${n} has left could not be read (${t.unread}): whether the records fit is not known`),r):(r.push(` data storage of ${n}: ${t.remainingMB} MB left of ${t.maxMB} MB`+Re(ie(t),n)),t.verdict==="near"&&r.push(` that is more than ${Math.round(Ht*100)} % of what ${n} has left: Salesforce counts storage a while after a load, so less may be left than it says`),r)}function nu(e){if(!e)return[];let t=[];e.writtenBefore>0&&t.push(` not counted: ${e.writtenBefore} record(s) the run it retries or resumes wrote, which it links to and does not write again`);for(let{objectApiName:n,rows:r}of e.heldBack)t.push(` not counted: ${n}, ${r} record(s), held back for a record type closed to the user the run writes as`);for(let{objectApiName:n,rows:r}of e.recordTypeNotInTarget??[])t.push(` not counted: ${n}, ${r} record(s), held back for a record type the target has none of, which it would refuse`);for(let{objectApiName:n,rows:r}of e.withoutParent??[])t.push(` not counted: ${n}, ${r} record(s) held back with a record they cannot be written without, held back itself`);for(let{objectApiName:n,rows:r}of e.noParentInSource??[])t.push(` not counted: ${n}, ${r} record(s) left aside: a lookup they may not leave empty names a record the source does not hold, which no copy can write`);for(let{objectApiName:n,rows:r}of e.outsideFilter??[])t.push(` not counted: ${n}, ${r} record(s) left aside: a lookup they may not leave empty names a record outside its object's filter, which the run does not copy`);for(let{objectApiName:n,rows:r}of e.byThePlatform??[])t.push(` not counted: ${n}, ${r} record(s) written by the platform with ${ke(n)}, which the run links to and does not send`);for(let{objectApiName:n,rows:r,fields:o}of e.linkedByValue??[])t.push(` not counted: ${n}, ${r} record(s) the target holds under the same ${o.join(", ")}, which the run links to and does not create`);for(let{objectApiName:n,rows:r}of e.linkedToTarget??[])t.push(` not counted: ${n}, ${r} record(s), the standard price book: linked to the target's own, never written`);for(let{objectApiName:n,rows:r}of e.currencyReplaced??[])t.push(` not counted: ${n}, ${r} record(s) in a currency the target lacks, replaced by the source's own price in the currency written, for the same product and price book`);return t}var ru={flow:e=>`flow "${e}" runs before a record is deleted, and can refuse the delete`,trigger:e=>`Apex trigger ${e} runs on a delete, and can refuse it`,packageTrigger:e=>`Apex trigger ${e}, installed by a managed package, runs on a delete and can refuse it; no one in the org can change it`,lock:()=>"once activated, a record locks the records under it, which a removal then takes only with it, or once it is back in Draft"},ou=["flows","triggers"];function bl(e,t,n=[],r="--remove"){let o=ou.filter(i=>n.some(a=>a.part===i)),s=o.length===0?[]:[` ${o.map(i=>ee[i]).join(" and ")} could not be read: whether one refuses the removal is not known`];if(e.length===0&&o.length===0)return[`reversibility: nothing found in ${t} that refuses a removal of this run's records (no flow before a delete, no Apex trigger on one, no record that locks past Draft)`];if(e.length===0){let i=[...o.includes("flows")?[]:["no flow before a delete"],...o.includes("triggers")?[]:["no Apex trigger on a delete"],"no record that locks past Draft"];return[`reversibility: nothing found in ${t} that refuses a removal of this run's records in what could be read (${i.join(", ")})`,...s]}return[`reversibility: a removal of this run's records (${r}) may be refused in ${t}:`,...e.map(({objectApiName:i,kind:a,name:u})=>` ${i}: ${ru[a](u??"")}`),...s]}var ee={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function se({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}var su={lookups:"a lookup filled in once its record exists",statuses:"an order or a contract given back its status after it went in as a draft",invitees:"an event's invitee given its answer",retry:"a lookup the run it retries left empty filled in",upsert:"a record the target holds written over by --upsert"};function be(e){return e.map(t=>`${t.objectApiName}: ${se(t)}`).join("; ")}function Yt(e,t,n){return e.flatMap(r=>{if(r.command){let o=r.others.length>0?`; ${r.others.join(", ")} hold${r.others.length===1?"s":""} it too`:"";return[`${r.permissionSet} is the smallest permission set of ${t} that holds ${r.permission}${o}. Assigned to the user ${n} writes as, it keeps quiet what ${r.permission} excludes: ${r.command}`]}return r.noneHolds?[`No permission set of ${t} holds ${r.permission}: an admin creates one that includes it, and assigns it to the user ${n} writes as.`]:[]})}function Xt(e,t,n,r){let o=[...new Set(e.flatMap(s=>s.permissionSet??[]))];return!n||o.length===0?[]:r?[`--mute-automation would be refused: ${Pe}.`]:[`With --mute-automation, the ${t} assigns ${o.join(", ")} to the user it writes as for the ${t} alone, under a lease, and what ${o.length===1?"it keeps":"they keep"} quiet does not fire.`]}function Rl(e,t,n={}){let r=n.updated??[],o=Ka(e),s=Ya(e,r.map(c=>c.objectApiName)),i=Ne(e);if(o.length===0&&s.length===0&&i.length===0)return;let a=[];if(o.length>0&&a.push(`${t} runs automation on the records this clone inserts: ${be(o)}.`),s.length>0){let c=Xa(r.filter(d=>s.some(f=>f.objectApiName===d.objectApiName))).map(d=>su[d]);a.push(`${t} runs automation as this clone updates records it inserted (${c.join("; ")}): ${be(s)}.`)}let u=r.length>0?"inserts and updates":"inserts";for(let{part:c,reason:d}of i)a.push(`${ee[c][0].toUpperCase()}${ee[c].slice(1)} of ${t} could not be read (${d}), so what fires as the clone ${u} is not known.`);return a.push(...Yt(n.assign??[],t,"the clone")),a.push(...Xt(n.assign??[],"clone",n.mayMute===!0,e.cannotAssign===!0)),a.push(`Nothing was written. Add --accept-automation to clone all the same, or turn that automation off in ${t} first.`),a.join(" ")}function Sl(e,t,n={}){let r=kt(e,n.drafted??[]),o=Ne(e);if(r.length===0&&o.length===0)return;let s=[],i=r.filter(u=>u.write==="update"),a=r.filter(u=>u.write==="delete");if(a.length>0){let u=a.map(c=>`${c.objectApiName}: ${se(c)} (${Fe[c.when]})`);s.push(`${t} runs automation on the records this removal deletes: ${u.join("; ")}.`)}i.length>0&&s.push(`${t} runs automation as this removal sets activated records back to Draft, the only way the platform deletes them: ${be(i)}.`);for(let{part:u,reason:c}of o)s.push(`${ee[u][0].toUpperCase()}${ee[u].slice(1)} of ${t} could not be read (${c}), so what fires as the removal deletes is not known.`);return s.push(...Yt(n.assign??[],t,"the removal")),s.push(...Xt(n.assign??[],"removal",n.mayMute===!0,e.cannotAssign===!0)),s.push(`Nothing was deleted. Add --accept-automation to remove all the same, or turn that automation off in ${t} first.`),s.join(" ")}var Fe={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"};function Al(e,t,n,r){let o=[`removal automation: what ${t} runs as the removal takes the records back`];for(let i of kt(e,r))o.push(i.write==="delete"?` ${i.objectApiName}: ${Fe[i.when]}: ${se(i)}`:` ${i.objectApiName}: set back to Draft before its delete: ${se(i)}`);let s=Ne(e);o.length===1&&s.length===0&&o.push(` nothing fires on the ${n} object(s) it deletes records of`);for(let{part:i,reason:a}of s)o.push(` ${ee[i]} could not be read: ${a}`);return o}var iu={bringBack:"brought back from the recycle bin",recreate:"made again with a new Id",giveBack:"given back its values from before the run",setToDraft:"set back to Draft before its delete"};function El(e,t,n,r="removal",o){let s=Ne(e),i=(a,u)=>{let c=[au[u](t)];for(let d of He(e,a))c.push(d.step==="delete"?` ${d.objectApiName}: ${Fe[d.when]}: ${se(d)}`:` ${d.objectApiName}: ${iu[d.step]}: ${se(d)}`);if(c.length===1&&s.length===0){let d=new Set(Object.values(a).flat()).size,f=uu.has(u)?"deletes":"writes";c.push(` nothing fires on the ${d} object(s) it ${f} records of`)}return c};return[...i(n,r),...o?i(o,Co(r)):[],...s.map(({part:a,reason:u})=>` ${ee[a]} could not be read: ${u}`)]}var au={removal:e=>`removal automation: what ${e} runs as the removal takes the run back`,reload:e=>`reload automation: what ${e} runs as the reload purges what earlier loads created`,reloadSweep:e=>`reload automation: what ${e} runs as the reload's sweep deletes what the target's automation made for the loads it replaces`,replayAgain:e=>`replay automation: what ${e} runs as the replay purges what earlier replays created`,replayAgainSweep:e=>`replay automation: what ${e} runs as the replay's sweep deletes what the target's automation made for the replays it replaces`};function Tl(e,t,n){let r=He(e,n.steps),o=n.sweep?He(e,n.sweep):[],s=Ne(e);if(r.length===0&&o.length===0&&s.length===0)return;let i=c=>r.filter(d=>d.step===c),a=lo[n.subject??"removal"],u=[];if(i("bringBack").length>0&&u.push(`${t} runs automation as ${a.this} brings back from the recycle bin what the run deleted: ${be(i("bringBack"))}.`),i("giveBack").length>0&&u.push(`${t} runs automation as ${a.this} gives the records the run wrote over their values from before it: ${be(i("giveBack"))}.`),i("setToDraft").length>0&&u.push(`${t} runs automation as ${a.this} sets activated records back to Draft, the only way the platform deletes them: ${be(i("setToDraft"))}.`),i("delete").length>0){let c=i("delete").map(d=>`${d.objectApiName}: ${se(d)} (${Fe[d.when]})`);u.push(`${t} runs automation on the records ${a.this} deletes: ${c.join("; ")}.`)}if(o.length>0){let c=o.map(d=>`${d.objectApiName}: ${se(d)} (${Fe[d.when]})`);u.push(`${t} runs automation on the records ${lo[Co(n.subject??"removal")].this} deletes: ${c.join("; ")}.`)}for(let{part:c,reason:d}of s)u.push(`${ee[c][0].toUpperCase()}${ee[c].slice(1)} of ${t} could not be read (${d}), so what fires as ${a.the} writes is not known.`);return u.push(...Yt(n.assign??[],t,a.who)),u.push(...Xt(n.assign??[],a.run,n.mayMute===!0,e.cannotAssign===!0)),u.push(`Nothing was written or deleted. Add --accept-automation to ${a.verb} all the same, or turn that automation off in ${t} first.`),u.join(" ")}var uu=new Set(["reloadSweep","replayAgainSweep"]);function Co(e){return e==="replayAgain"||e==="replayAgainSweep"?"replayAgainSweep":"reloadSweep"}var lo={removal:{this:"this removal",the:"the removal",who:"the removal",run:"removal",verb:"remove"},reload:{this:"this reload's purge",the:"the reload's purge",who:"the reload",run:"reload",verb:"reload"},reloadSweep:{this:"this reload's sweep",the:"the reload's sweep",who:"the reload",run:"reload",verb:"reload"},replayAgain:{this:"this replay's purge",the:"the replay's purge",who:"the replay",run:"replay",verb:"replay again"},replayAgainSweep:{this:"this replay's sweep",the:"the replay's sweep",who:"the replay",run:"replay",verb:"replay again"}};var cu=2e3,lu=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Io(e,t){let n=e!==void 0&&Number.isFinite(e)?Math.floor(e):t;return Math.min(qe,Math.max(1,n))}function vl(e){return e===void 0||!Number.isFinite(e)?cu:Math.max(1,Math.floor(e/10))}function jo(e){return e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):On}function Nl(e){let t=$n(e);if(t!==void 0)return{issue:t};let n=Mn(e);return n?{objectApiName:n.objectApiName,query:{...n.where!==null?{where:n.where}:{},...n.orderBy!==null?{orderBy:n.orderBy}:{},...n.limit!==null?{limit:n.limit}:{}}}:{issue:{kind:"noObject"}}}function Bl(e){if(e.where!==void 0&&!vn.safeParse(e.where).success)return{kind:"where"};if(e.orderBy!==void 0&&!Nn.safeParse(e.orderBy).success)return{kind:"orderBy"};if(e.limit!==void 0&&!(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=qe))return{kind:"limit"}}function xl(e,t,n,r){let o=Ft(e),s=[...t.where!==void 0?[`(${t.where})`]:[],...n!==void 0&&n!==""?[`(${n})`]:[]],i=s.length>0?` WHERE ${s.join(" AND ")}`:"",a=t.limit!==void 0&&t.limit<=r?t.limit:r+1;return`SELECT Id FROM ${o}${i} ORDER BY ${t.orderBy??"Id"} LIMIT ${a}`}function fu(e,t,n){return!Number.isFinite(e)||e<1||!Number.isFinite(t)||t<=0||!Number.isFinite(n)||n<=0?0:Math.max(0,Math.min(Math.floor(e)-1,Math.floor(n*e/t)))}function Cl(e,t,n){let r=t.where!==void 0?` WHERE ${t.where}`:"";return`SELECT Id FROM ${Ft(e)}${r} ORDER BY ${t.orderBy??Ge} LIMIT ${Math.max(1,Math.floor(n))}`}function _l(e,t,n){if(e.verdict!=="exceeds")return;let r=fu(n.count,e.estimateMB,Qt(e)),o=ie(e),s=`the ${n.count} ${n.objectApiName} records the query chooses`,i=r>=1?`about ${r} of ${s} fit, each with what its clone copies: a LIMIT of ${r} in the query clones that many \u2014 after ORDER BY ${Ge}, the newest \u2014, or narrow its WHERE; or leave objects out, or free data storage in ${t}.`:`one of ${s} takes more than that by itself, with what its clone copies: leave objects out, clone less deep, or free data storage in ${t}.`;return{code:"STORAGE_EXCEEDED",message:`The records to write take ${gt(e)}, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB${Re(o,t)}: ${i} ${ae}`,storage:{estimateMB:Number(Z(e.estimateMB)),remainingMB:e.remainingMB,...o},...Se(n.objectApiName).roots?{roots:{objectApiName:n.objectApiName,...r>=1?{fits:r}:{}}}:{}}}function gu(e){let t=new Set,n=[];for(let r of e){let o=pr(r);t.has(o)||(t.add(o),n.push(r))}return n.sort(mr)}function _o(e){return du("sha256").update(gu(e).join(`
14
+ `)).digest("hex")}function Il(e){return lu.test(e)}function pu(e,t){let n=r=>r===void 0?void 0:r.replace(/\s+/g," ").trim();return n(e?.where)===n(t?.where)&&n(e?.orderBy??"Id")===n(t?.orderBy??"Id")&&e?.limit===t?.limit}function jl(e,t){if(e.sourceOrgId!==t.sourceOrgId)return"otherOrg";if(e.objectApiName.toLowerCase()!==t.objectApiName.toLowerCase()||t.query!==void 0&&!pu(e.query,t.query)||t.ids!==void 0&&_o(t.ids)!==e.sha256)return"otherQuery";if(_o(e.ids)!==e.sha256)return"changed"}var ae="Nothing was written.";function Se(e,t={}){return e!==void 0&&/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(e)?{roots:{objectApiName:e,...t}}:{}}function Ll(e,t){return{code:"ROOTS_QUERY_REFUSED",message:`${Fn(e)}. Nothing was read or written.`,...Se(t)}}function Dl(e,t,n){let r=t?.where!==void 0?` WHERE ${t.where}`:"";return{code:"NO_ROOTS",message:t===void 0?`None of the ${e} records named is in the source org: there is nothing to clone. ${ae}`:`The query chooses no ${e} record of the source org: there is nothing to clone. Count what it chooses there with sf data query -q "SELECT COUNT() FROM ${e}${r}", and check its WHERE. ${ae}`,...Se(e,{cap:n})}}function Wl(e,t,n,r){let o=qe.toLocaleString("en-US"),s=n==="query"&&r?.orderBy!==void 0,i=`${s?"":`ORDER BY ${Ge} `}LIMIT ${t}`,a=n==="query"?`Give the query ${i}`+(r?.limit!==void 0?` in place of its LIMIT ${r.limit}`:"")+` to clone the first ${t} of its order, narrow its WHERE, or raise --max-roots (the sandforge.forge.maxRoots setting) up to ${o}; past that, copy a sample of the whole org with a filter on its roots.`:`Name ${t} at most, or raise --max-roots up to ${o}.`;return{code:"ROOTS_EXCEEDED",message:`The ${n==="query"?"query chooses":"records named are"} more than the ${t} ${e} records a run clones, and nothing holds ${n==="query"?"it":"them"} to that: refused before anything else was read, rather than cut at an order nobody chose. ${a} ${ae}`,...Se(e,{cap:t,...s?{ordered:!0}:{}})}}var mu={otherOrg:"were read of another org than this run reads",otherQuery:"were chosen by another query, of another object, or are other records",changed:"are no longer the ids it was kept with"};function Ul(e,t){return{code:"ROOTS_PLAN_MISMATCH",message:`The records the dry run chose ${mu[t]}: run the dry run again with this query, and give the run the plan it keeps. ${ae}`,...Se(e).roots?{roots:{objectApiName:e,plan:t}}:{}}}function ql(e){return{code:"ROOTS_PLAN_GONE",message:`The run this one resumes cloned the records a query chose, and its journal does not name them: reading the query again could choose others. Remove what it wrote, then run the clone again. ${ae}`,...Se(e).roots?{roots:{objectApiName:e,plan:"gone"}}:{}}}function Gl(e,t,n){let r=n[n.length-1],o=r?` (${r.objectApiName} came to ${r.rows.toLocaleString("en-US")} after ${n.length} object${n.length===1?"":"s"})`:"";return{code:"READ_BOUND_EXCEEDED",message:`The ${e} roots reach more than ${t.toLocaleString("en-US")} records${o}, and a clone from records holds all it reads before it writes. Take fewer records (a LIMIT), clone less deep (--depth direct), leave objects out, or raise --max-read-total. `+ae,readBound:{bound:t,objects:n.slice(0,200).map(s=>({...s})),of:"roots"}}}function zl(e){let{bound:t,sent:n,next:r,objectApiName:o,sourceRequestsLeft:s}=e,i=s===void 0?"the source would not say what it has left today":`a tenth of the ${s.toLocaleString("en-US")} it has left today`;return{code:"API_BUDGET_EXCEEDED",message:`Reading what the ${e.roots} roots reach would send the source more than ${t.toLocaleString("en-US")} requests (${i}): ${n} sent, ${r} more for ${o}. Take fewer records, clone less deep (--depth direct), or leave objects out. ${ae}`,api:{kind:"requests",org:"source",estimate:n+r,remaining:s??t,reading:{bound:t}}}}var Zt=class{constructor(t,n){this.given=t;this.store=n}given;store;has(t){return this.given.has(t)||this.store?.mapping(t)?.earlier===!0}retried(t){return this.given.has(t)}get(t){let n=this.given.get(t);if(n!==void 0)return n;let r=this.store?.mapping(t);return r?.earlier?r.targetId:void 0}get from(){return this.given.size===0&&(this.store?.earlierMapped??0)>0?"resume":"retry"}get size(){return this.given.size+(this.store?.earlierMapped??0)}keys(){return this.given.keys()}[Symbol.iterator](){return this.given.entries()}};function ue(e){return e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Lo(e){let t=e?.roots,n=e?.rootObjectApiName??t?.objectApiName,r=!!(n&&(e?.rootRecordId||t));return{isScoped:r,dryRun:e?.dryRun??!1,referenceFallback:e?.referenceFallback??(r?"nullify":"keep"),rootRecordId:e?.rootRecordId,rootObjectApiName:n,...t&&n?{roots:{...t,objectApiName:n,cap:Io(t.cap,Tn),readTotal:jo(t.readTotal)}}:{},recordTypeMappings:e?.recordTypeMappings,maxRecordsPerObject:e?.maxRecordsPerObject,referenceDataObjects:new Set(e?.referenceDataObjects??["BusinessHours","OperatingHours"]),expandOrphanParents:e?.expandOrphanParents??!1,maxOrphanParentExpansions:e?.maxOrphanParentExpansions??20,upsertMode:e?.upsertMode==="auto"?"auto":"off",writeApi:e?.writeApi==="auto"?"auto":"rest",fieldExclusions:e?.fieldExclusions??{},excludedObjects:new Set(e?.excludedObjects??[]),ownerMappings:e?.ownerMappings??{},objectSoqlFilters:e?.objectSoqlFilters,fieldMappings:e?.fieldMappings??{},anonymization:e?.anonymization,keepContactPoints:e?.keepContactPoints===!0,files:e?.files?{maxFileBytes:Math.min(e.files.maxFileBytes>0?e.files.maxFileBytes:10*1048576,35*1048576),acceptedAsIs:e.files.acceptedAsIs===!0}:void 0,writtenBefore:new Zt(new Map(Object.entries(e?.writtenBefore??{})),e?.stream?.store),beforeWrite:e?.beforeWrite,stream:e?.stream?{pageSize:ue(e.stream.pageSize),ceiling:ue(e.stream.ceiling),resumeAfter:e.stream.resumeAfter?new Map(Object.entries(e.stream.resumeAfter)):e.stream.store?.checkpoints()??new Map,onPage:e.stream.onPage,...e.stream.store?{store:e.stream.store}:{},...e.stream.summaryBound!==void 0?{summaryBound:Math.max(0,Math.floor(e.stream.summaryBound))}:{},...ue(e.stream.secondPassPageSize)!==void 0?{secondPassPageSize:ue(e.stream.secondPassPageSize)}:{},...ue(e.stream.writeWindow)!==void 0?{writeWindow:ue(e.stream.writeWindow)}:{},...e.stream.everything===!0?{everything:!0}:{},...ue(e.stream.wholeReadBound)!==void 0?{wholeReadBound:ue(e.stream.wholeReadBound)}:{},...e.stream.sample&&e.stream.everything===!0?{sample:e.stream.sample}:{}}:void 0,decisions:new it(e?.decisions),recordTypeDecisions:new Map}}async function Do(e,t){let{records:n,pages:r}=await tr(e,t);return{records:n,requests:r}}var wu=25,Jo=15,ht=5,yt=25,tn=60,nn=20,go=6+tn+nn+1+6+1+20,Be=4,bu="SELECT ApiName, Label, TriggerType, RecordTriggerType, TriggerObjectOrEvent.QualifiedApiName, ActiveVersionId, HasAsyncAfterCommitPath FROM FlowDefinitionView WHERE IsActive = true AND TriggerType IN ('RecordBeforeSave', 'RecordAfterSave', 'RecordBeforeDelete')",Ru="SELECT Name, NamespacePrefix, TableEnumOrId, EntityDefinition.QualifiedApiName, UsageBeforeInsert, UsageAfterInsert, UsageBeforeUpdate, UsageAfterUpdate, UsageBeforeDelete, UsageAfterDelete, UsageAfterUndelete FROM ApexTrigger WHERE Status = 'Active'",Su="SELECT ApiName, Label, TriggerObjectOrEvent.QualifiedApiName, ActiveVersionId FROM FlowDefinitionView WHERE IsActive = true AND ProcessType = 'Workflow'",Au="SELECT Id, Name, NamespacePrefix, TableEnumOrId FROM WorkflowRule",Eu="SELECT Name, SobjectType FROM AssignmentRule WHERE Active = true",Tu="SELECT DeveloperName, MasterLabel, SobjectType FROM DuplicateRule WHERE IsActive = true",Ou="SELECT DeveloperName, NamespacePrefix FROM UserSetupEntityAccess WHERE KeyPrefix = '0CP'";function Wo(e){return`SELECT Metadata FROM Flow WHERE Id = '${e}'`}function ku(e,t){if(t.length>ht)throw new Error(`A Tooling composite holds ${ht} queries, not ${t.length}`);return{allOrNone:!1,compositeRequest:t.map((n,r)=>({method:"GET",url:`${e}/tooling/query?q=${encodeURIComponent(n)}`,referenceId:`q${r}`}))}}function Pu(e,t){if(t.length>yt)throw new Error(`A Tooling composite retrieves ${yt} records, not ${t.length}`);return{allOrNone:!1,compositeRequest:t.map(({sobject:n,id:r},o)=>{if(!ne.test(r))throw new Error(`Not a record id: ${r}`);return{method:"GET",url:`${e}/tooling/sobjects/${n}/${r}`,referenceId:`r${o}`}})}}var mt="PROCESSING_HALTED",Mu=B({compositeResponse:X(B({body:We(),httpStatusCode:G(),referenceId:Q()}).loose())}),$u=B({records:X(Tt(Q(),We()))}).loose(),Fu=Tt(Q(),We()),vu=X(B({errorCode:Q().optional(),message:Q().optional()}).loose());function Ko(e,t,n,r,o){let s=Mu.safeParse(e);if(!s.success)throw new Error("The org answered the Tooling composite with no composite answer");let i=new Map(s.data.compositeResponse.map(a=>[a.referenceId,a]));return Array.from({length:t},(a,u)=>{let c=i.get(`${n}${u}`);if(!c)return{refused:`The org gave no answer to this ${r} of the composite`};if(c.httpStatusCode<400){let g=o(c.body);return g?{records:g}:{refused:`The org answered with status ${c.httpStatusCode} and no rows`}}let d=vu.safeParse(c.body),f=d.success?d.data[0]:void 0;return{refused:f?[f.errorCode,f.message].filter(Boolean).join(": "):`status ${c.httpStatusCode}`,...f?.errorCode===mt?{halted:!0}:{}}})}function Nu(e,t){return Ko(e,t,"q","query",n=>{let r=$u.safeParse(n);return r.success?r.data.records:void 0})}function Bu(e,t){return Ko(e,t,"r","retrieve",n=>{let r=Fu.safeParse(n);return r.success?[r.data]:void 0})}function xu(e){return async t=>Bu(await e.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(Pu(`/services/data/v${e.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length)}function sf(e){return{query:async(t,n)=>{let r=await e(t);return Do({query:async o=>r.query(o),queryMore:async o=>r.queryMore(o)},n)},toolingQuery:async(t,n)=>{let r=await e(t);return Do({query:async o=>r.tooling.query(o),queryMore:async o=>r.tooling.queryMore(o)},n)},toolingQueries:async(t,n)=>{let r=await e(t),o=await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(ku(`/services/data/v${r.version}`,n)),headers:{"Content-Type":"application/json"}});return Nu(o,n.length)},toolingRetrieves:async(t,n)=>xu(await e(t))(n)}}async function Cu(e,t,n,r){let o=t.map(d=>({retrieving:r?d.queries.filter(f=>f.retrieve!==void 0):[],waiting:r?d.queries.filter(f=>f.retrieve===void 0):[...d.queries],left:d.requests})),s={retrieving:yt,waiting:ht},i=(d,f)=>{for(let g of o){let p=f.filter(m=>m.queue===g).map(m=>m.query);p.length>0&&g[d].unshift(...p)}},a=(d,f)=>{for(let g of o){let p=f.filter(m=>m.queue===g).map(m=>m.query);p.length===0&&g.retrieving.length===0||(g.reason??=d,g.waiting.unshift(...p,...g.retrieving.splice(0)))}},u=0,c=async()=>{for(;;){let d=o.find(T=>T.left>0&&(T.retrieving.length>0||T.waiting.length>0));if(!d)return;let f=d.retrieving.length>0?"retrieving":"waiting";d.left--,u++;let g=[];for(let T of o){if(T!==d&&T.left<=0)continue;let L=s[f]-g.length;if(L<=0)break;for(let C of T[f].splice(0,L))g.push({query:C,queue:T})}let p;try{p=r&&f==="retrieving"?await r(g.map(({query:T})=>T.retrieve)):await e(g.map(({query:T})=>T.soql))}catch(T){let L=F(T);if(f==="retrieving")a(L,g);else for(let{query:C}of g)C.refused(L);continue}let m=f==="retrieving"?"retrieve":"query",w=[],b=[],R=0,E,P;if(g.forEach((T,L)=>{let C=p[L]??{refused:`The org gave no answer to this ${m} of the composite`};"records"in C?(T.query.take(C.records),R++):C.halted?(w.push(T),E??=C.refused):f==="retrieving"?(b.push(T),P??=C.refused):T.query.refused(C.refused)}),f==="retrieving"&&R===0){a(P??E??mt,g);continue}if(b.length>0){for(let{queue:T}of b)T.reason??=P;i("waiting",b)}if(w.length===0)continue;let j=g.length-w.length;if(j===0){for(let{query:T}of w)T.refused(E??mt);continue}s[f]=Math.min(s[f],j);for(let{queue:T}of w)T.reason=E;i(f,w)}};await Promise.all(Array.from({length:Math.max(1,n)},c));for(let d of o)for(let f of[...d.retrieving,...d.waiting])f.refused(d.reason??mt);return u}function _u(e){return`SELECT Metadata FROM WorkflowRule WHERE Id = '${e}'`}function Iu(e){return`SELECT FlowVersionViewId, ApiName, ObjectType FROM FlowVariableView WHERE FlowVersionViewId IN (${e.map(n=>`'${n}'`).join(", ")})`}function ju(e){return`SELECT DurableId, QualifiedApiName FROM EntityDefinition WHERE QualifiedApiName IN (${e.map(n=>`'${n}'`).join(", ")})`}function Lu(e){return`SELECT Id, DeveloperName, NamespacePrefix FROM CustomPermission WHERE DeveloperName IN (${e.map(n=>`'${n}'`).join(", ")})`}function Du(e){return`SELECT SetupEntityId, ParentId, Parent.Name, Parent.Label, Parent.NamespacePrefix FROM SetupEntityAccess WHERE SetupEntityType = 'CustomPermission' AND SetupEntityId IN (${e.map(n=>`'${n}'`).join(", ")}) AND Parent.IsOwnedByProfile = false AND Parent.PermissionSetGroupId = null`}function Wu(e,t){let n=t.map(r=>`'${r}'`).join(", ");return`SELECT ParentId, COUNT(Id) n FROM ${e} WHERE ParentId IN (${n}) GROUP BY ParentId`}var ne=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,rn=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,Uu="myvariable_current",qu={RecordBeforeSave:"beforeSave",RecordAfterSave:"afterSave",RecordBeforeDelete:"beforeDelete"},Gu={Create:"create",Update:"update",CreateAndUpdate:"createAndUpdate",Delete:"delete"},Yo={onCreateOnly:"create",onAllChanges:"createAndUpdate",onCreateOrTriggeringUpdate:"createAndUpdate"},zu=[["UsageBeforeInsert","beforeInsert"],["UsageAfterInsert","afterInsert"],["UsageBeforeUpdate","beforeUpdate"],["UsageAfterUpdate","afterUpdate"],["UsageBeforeDelete","beforeDelete"],["UsageAfterDelete","afterDelete"],["UsageAfterUndelete","afterUndelete"]],Vu={emailAlert:"email",emailSimple:"email",customNotificationAction:"notification",outboundMessage:"outbound"},Hu={emailSimple:"SingleEmail",emailAlert:"DailyWorkflowEmails"},Qu={Alert:"email",OutboundMessage:"outbound"},Ju=new Set(["sms","mms","twilio","whatsapp","vonage","nexmo","messagebird","plivo","sinch"]);function an(e){if(typeof e!="object"||e===null)return;let t=e.QualifiedApiName;return typeof t=="string"&&t!==""?t:void 0}var y=e=>typeof e=="string"?e:"";function A(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}function z(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t):[]}function un(e,t,n,r){return{apiName:e,label:t||e,timing:n,startsOn:r,condition:"notRead",permissions:[],paths:[],messages:[],switches:[]}}function Ku(e){let t=an(e.TriggerObjectOrEvent),n=qu[y(e.TriggerType)];if(!t||!n)return;let r=n==="beforeDelete"?"delete":Gu[y(e.RecordTriggerType)]??"createAndUpdate",o=y(e.ActiveVersionId),s=un(y(e.ApiName),y(e.Label),n,r);return e.HasAsyncAfterCommitPath===!0&&(s.paths=[{kind:"async"}]),{objectApiName:t,id:ne.test(o)?o:null,flow:s}}function Yu(e){let t=y(e.ActiveVersionId);return{objectApiName:an(e.TriggerObjectOrEvent),id:ne.test(t)?t:null,flow:un(y(e.ApiName),y(e.Label),"afterSave","createAndUpdate")}}function Xu(e){let t=an(e.EntityDefinition)??(y(e.TableEnumOrId)||void 0),n=y(e.Name);if(!t||!n)return;let r=y(e.NamespacePrefix);return{objectApiName:t,trigger:{name:r?`${r}.${n}`:n,events:zu.filter(([o])=>e[o]===!0).map(([,o])=>o)}}}function Uo(e){return e.startsOn==="create"||e.startsOn==="createAndUpdate"?e.timing==="afterSave"?0:1:e.startsOn==="update"?2:3}function Xo(e){let t=new Set(ss(JSON.stringify(e??null)).filter(o=>xe(o)==="Permission").map(on));if(t.size===0)return[];let n=A(e,"filterFormula"),r=new Set((typeof n=="string"?Ce(n):[]).filter(o=>xe(o.reference)==="Permission"&&o.value===void 0).map(o=>on(o.reference)));return[...t].sort((o,s)=>o.localeCompare(s)).map(o=>({name:o,bypass:r.has(o)}))}function Zo(e){return typeof e!="string"?[]:us(Ce(e)).filter(t=>xe(t.reference)!=="Permission").map(t=>({...t,where:"start",bypass:!0}))}function Zu(e){let t=A(e,"filterFormula");if(typeof t=="string"&&t.trim()!=="")return[...new Set(bt(t).flatMap(r=>{let o=nd(r);return o?[o]:[]}))];let n=z(A(e,"filters"));return n.length===0||!rd(y(A(e,"filterLogic")),n.length)?[]:[...new Set(n.filter(r=>y(r.operator)==="IsNull"&&A(r.value,"booleanValue")===!1).map(r=>y(r.field)).filter(r=>ed.test(r)))]}var ed=/^[A-Za-z][A-Za-z0-9_]*$/,td=/^(?:\{!\s*)?\$Record\.([A-Za-z][A-Za-z0-9_]*)\s*\}?$/i;function nd(e){let t=pe(e,"NOT");if(t===void 0)return;let n=cn(t),r=pe(n,"ISBLANK")??pe(n,"ISNULL");return r===void 0?void 0:td.exec(r.trim())?.[1]}function rd(e,t){let n=e.trim().toLowerCase();if(n==="and"||t===1&&n!=="or")return!0;if(!/^\d+(\s+and\s+\d+)*$/.test(n))return!1;let r=new Set(n.split(/\s+and\s+/).map(Number));return Array.from({length:t},(o,s)=>s+1).every(o=>r.has(o))}var es={permission:"Permission",setup:"Setup",user:"User",profile:"Profile",custommetadata:"CustomMetadata"},ts=String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`,ns=new RegExp(String.raw`\$(?:Permission|Setup|User|Profile|CustomMetadata)\.${ts}`,"gi"),Ae=String.raw`(?:\{!\s*)?(\$(?:Permission|Setup|User|Profile|CustomMetadata)\.${ts})\s*\}?`,od=new RegExp(`^${Ae}$`,"i"),sd=new RegExp(`^NOT\\s+${Ae}$`,"i"),rs=new RegExp(`^(?:${Ae}\\s*(==?|<>|!=)\\s*(TRUE|FALSE)|(TRUE|FALSE)\\s*(==?|<>|!=)\\s*${Ae})$`,"i"),qo=String.raw`("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')`,os=new RegExp(`^(?:${Ae}\\s*(==?|<>|!=)\\s*${qo}|${qo}\\s*(==?|<>|!=)\\s*${Ae})$`,"i");function de(e){let t=e.indexOf("."),n=es[e.slice(1,t).toLowerCase()];return n?`$${n}${e.slice(t)}`:e}function xe(e){return es[e.slice(1,e.indexOf(".")).toLowerCase()]}function on(e){return e.slice(e.indexOf(".")+1)}function ss(e){return[...new Set([...e.matchAll(ns)].map(t=>de(t[0])))]}var id=new RegExp(`^${ns.source}$`,"i");function is(e){return typeof e=="string"&&id.test(e)}function wt(e,t){return e.toLowerCase()===t.toLowerCase()}function as(e){return e.slice(1,-1).replace(/\\(.)/g,"$1")}function us(e){let t=new Map;for(let n of e)t.set(`${n.reference.toLowerCase()}=${n.value??""}`,n);return[...t.values()]}function Go(e,t){return e.some(n=>wt(n.reference,t.reference)&&n.value===t.value)}function Ce(e){return bt(e).flatMap(ad)}function dn(e){return sn(e).flatMap(ud)}function ad(e){let t=rs.exec(e);if(t){let[,o,s,i,a,u,c]=t,d=s??u,f=(i??a).toUpperCase();return(d.startsWith("=")?f==="FALSE":f==="TRUE")?[{reference:de(o??c)}]:[]}let n=os.exec(e);if(n){let[,o,s,i,a,u,c]=n;return(s??u).startsWith("=")?[]:[{reference:de(o??c),value:as(i??a)}]}let r=pe(e,"NOT");if(r===void 0){let o=sd.exec(e);return o?[{reference:de(o[1])}]:[]}return dn(r)}function ud(e){let t=od.exec(e);if(t)return[{reference:de(t[1])}];let n=rs.exec(e);if(n){let[,s,i,a,u,c,d]=n,f=i??c,g=(a??u).toUpperCase();return(f.startsWith("=")?g==="TRUE":g==="FALSE")?[{reference:de(s??d)}]:[]}let r=os.exec(e);if(r){let[,s,i,a,u,c,d]=r;return(i??c).startsWith("=")?[{reference:de(s??d),value:as(a??u)}]:[]}let o=pe(e,"NOT");return o===void 0?[]:Ce(o)}function bt(e){let t=cn(e),n=pe(t,"AND");if(n)return Rt(n,",").flatMap(bt);let r=Rt(t,"&&");return r.length>1?r.flatMap(bt):[t]}function sn(e){let t=cn(e),n=pe(t,"OR");if(n)return Rt(n,",").flatMap(sn);let r=Rt(t,"||");return r.length>1?r.flatMap(sn):[t]}function pe(e,t){let n=new RegExp(`^${t}\\s*\\(([\\s\\S]*)\\)$`,"i").exec(e);return n&&ds(n[1])?n[1]:void 0}function cn(e){let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")")&&ds(t.slice(1,-1));)t=t.slice(1,-1).trim();return t}function ds(e){let t=0;for(let{char:n,quoted:r}of cs(e))if(!r){if(n==="(")t++;else if(n===")"&&--t<0)return!1}return t===0}function Rt(e,t){let n=[],r=0,o=0;for(let{char:s,index:i,quoted:a}of cs(e))a||(s==="("?r++:s===")"?r--:r===0&&e.startsWith(t,i)&&(n.push(e.slice(o,i).trim()),o=i+t.length));return n.push(e.slice(o).trim()),n.filter(s=>s!=="")}function*cs(e){let t=null;for(let n=0;n<e.length;n++){let r=e[n];if(t){r==="\\"?n++:r===t&&(t=null),yield{char:r,index:n,quoted:!0};continue}if(r==='"'||r==="'"){t=r,yield{char:r,index:n,quoted:!0};continue}yield{char:r,index:n,quoted:!1}}}function dd(e){let t=A(e,"start");if(typeof t=="object"&&t!==null){let n=y(A(A(t,"connector"),"targetReference"))||void 0,r=z(A(t,"scheduledPaths")).map(o=>y(A(A(o,"connector"),"targetReference"))||void 0);return{name:n,everyPath:r.every(o=>o===n)}}return{name:y(A(e,"startElementReference"))||void 0,everyPath:!0}}function cd(e,t){let n=e.leftValueReference,r=e.rightValue;if(is(n)){let s=de(n);if(typeof A(r,"booleanValue")=="boolean")return[{reference:s}];let i=A(r,"stringValue");return typeof i=="string"?[{reference:s,value:i}]:[]}let o=typeof n=="string"?t.get(n):void 0;return o===void 0?[]:[...dn(o),...Ce(o)]}function ld(e,t){let n=e.leftValueReference,r=typeof n=="string"?t.get(n):void 0;return ss([typeof n=="string"?n:"",y(A(e.rightValue,"elementReference")),r??""].join(" "))}function fd(e,t,n){let{leftValueReference:r,operator:o,rightValue:s}=e;if(o!=="EqualTo"&&o!=="NotEqualTo")return"unknown";let i=o==="EqualTo",a=A(s,"booleanValue");if(is(r)){if(!wt(r,t.reference))return"unknown";if(typeof a=="boolean"&&t.value===void 0)return a===i?"true":"false";let d=A(s,"stringValue");return typeof d=="string"&&t.value!==void 0?d===t.value===i?"true":"false":"unknown"}let u=typeof r=="string"?n.get(r):void 0;if(u===void 0||typeof a!="boolean")return"unknown";let c=a===i;return Go(dn(u),t)?c?"true":"false":Go(Ce(u),t)?c?"false":"true":"unknown"}function gd(e,t,n){let r=z(e.conditions);if(r.length===0)return"unknown";let o=r.map(i=>fd(i,t,n)),s=y(e.conditionLogic).toLowerCase()||"and";return s==="and"?o.includes("false")?"false":o.every(i=>i==="true")?"true":"unknown":s==="or"?o.includes("true")?"true":o.every(i=>i==="false")?"false":"unknown":"unknown"}function pd(e,t,n){for(let r of z(e.rules)){let o=gd(r,t,n),s=!y(A(r.connector,"targetReference"));if(o!=="false"){if(o==="true")return s;if(!s)return!1}}return!y(A(e.defaultConnector,"targetReference"))}function ls(e){let t=z(A(e,"decisions")),n=new Map(z(A(e,"formulas")).filter(f=>typeof f.expression=="string").map(f=>[y(f.name),y(f.expression)])),r=f=>z(f.rules).flatMap(g=>z(g.conditions)),o=[...new Set(t.flatMap(f=>r(f).flatMap(g=>ld(g,n))))];if(o.length===0)return{permissions:[],switches:[]};let{name:s,everyPath:i}=dd(e),a=i?t.find(f=>y(f.name)===s):void 0,u=a?us(r(a).flatMap(f=>cd(f,n))).filter(f=>pd(a,f,n)):[],c=o.filter(f=>xe(f)==="Permission").map(f=>({name:on(f),bypass:u.some(g=>wt(g.reference,f)&&g.value===void 0),where:"decision"})).sort((f,g)=>f.name.localeCompare(g.name)),d=o.filter(f=>xe(f)!=="Permission").flatMap(f=>{let g=u.filter(p=>wt(p.reference,f));return g.length>0?g.map(p=>({...p,where:"decision",bypass:!0})):[{reference:f,where:"decision",bypass:!1}]}).sort((f,g)=>f.reference.localeCompare(g.reference));return{permissions:c,switches:d}}function md(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(t=>t!=="").map(t=>t.toLowerCase())}function hd(...e){return e.some(t=>{let n=md(t);return n.some(r=>Ju.has(r))||n.some((r,o)=>r==="text"&&/^messages?$/.test(n[o+1]??""))})}function fs(e){return z(A(e,"actionCalls")).flatMap(t=>{let n=y(t.actionType),r=y(t.label)||y(t.name)||y(t.actionName),o=Vu[n],s=Hu[n];return o?[{kind:o,name:r,...s?{limit:s}:{}}]:n==="apex"&&hd(y(t.actionName),y(t.name),r)?[{kind:"sms",name:r,guessed:!0}]:[]})}function yd(e){return z(A(A(e,"start"),"scheduledPaths")).map(t=>{let n=y(t.label)||y(t.name)||void 0;if(y(t.pathType)==="AsyncAfterCommit")return{kind:"async",label:n};let r=Number(t.offsetNumber),o=y(t.timeSource)==="RecordField"?y(t.recordField):"";return{kind:"scheduled",label:n,...Number.isFinite(r)?{offset:r}:{},...y(t.offsetUnit)?{unit:y(t.offsetUnit)}:{},...o?{field:o}:{}}})}function gs(e,t){let n=Vr(t);n.length>0&&(e.creates=n)}function wd(e,t){if(typeof t!="object"||t===null)return;let n=A(t,"start"),r=ls(t);e.permissions=[...Xo(n),...r.permissions],e.switches=[...Zo(A(n,"filterFormula")),...r.switches];let o=Zu(n);o.length>0&&(e.requiresFilled=o),e.paths=yd(t),e.messages=fs(t),gs(e,t)}function bd(e,t){let n=new Map(z(A(t,"processMetadataValues")).map(o=>[y(o.name),y(A(o.value,"stringValue"))]));e.startsOn=Yo[n.get("TriggerType")??""]??"createAndUpdate";let r=ls(t);return e.permissions=r.permissions,e.switches=r.switches,e.messages=fs(t),gs(e,t),n.get("ObjectType")||void 0}function Rd(e,t){e.startsOn=Yo[y(A(t,"triggerType"))]??"createAndUpdate";let n=A(t,"formula");e.permissions=typeof n=="string"?Xo({filterFormula:n}):[],e.switches=Zo(n);let r=z(A(t,"workflowTimeTriggers"));return e.paths=r.map(o=>{let s=Number(o.timeLength);return{kind:"scheduled",...Number.isFinite(s)?{offset:s}:{},...y(o.workflowTimeTriggerUnit)?{unit:y(o.workflowTimeTriggerUnit)}:{},...y(o.offsetFromField)?{field:y(o.offsetFromField)}:{}}}),e.messages=[A(t,"actions"),...r.map(o=>o.actions)].flatMap(z).flatMap(o=>{let s=Qu[y(o.type)];return s?[{kind:s,name:y(o.name),...s==="email"?{limit:"DailyWorkflowEmails"}:{}}]:[]}),A(t,"active")===!0}function ps(e,t){return(e?`${e}__${t}`:t).toLowerCase()}function en(e,t){let n=Hn(t);return n===void 0?{part:e,reason:F(t)}:{part:e,reason:`the org could not be reached (${n})`,unreachable:n}}var zo={flows:0,triggers:1,conditions:2,processes:3,workflowRules:4,definitions:5,assignmentRules:6,duplicateRules:7,userPermissions:8,permissionSets:9};function Sd(e){return[...e].sort((t,n)=>zo[t.part]-zo[n.part]||(t.reason<n.reason?-1:t.reason>n.reason?1:0))}async function pt(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let s=r++;n[s]=await e[s]()}};return await Promise.all(Array.from({length:Math.min(t,e.length)},o)),n}var Vo=[Cn,hr,In,jn,_n],Ho=["ProductCategory","ProductCatalog"];function Vt(e,t=new Set){let{referenceDataObjects:n}=Lo(void 0),r=e.nodes.filter(d=>d.included&&!t.has(d.objectApiName)&&!n.has(d.objectApiName)).map(d=>d.objectApiName),o=new Set(r),s=new Set(e.nodes.map(d=>d.objectApiName)),i=Object.entries(xn).filter(([d,{object:f}])=>o.has(d)&&!s.has(f)&&!t.has(f)).map(([,{object:d}])=>d),a=yr(e,t),u=d=>e.edges.some(f=>f.required===!0&&d.includes(f.sourceObject)&&a.has(f.sourceObject)&&o.has(f.targetObject)),c=i.length>0||u(Vo);return[...new Set([...r,...i,...c?Vo.filter(d=>a.has(d)):[],...u(Ho)?Ho.filter(d=>a.has(d)):[]])]}var Qo=class{deps;constructor(t){this.deps=t}async readForGraph(t,n,r=new Set){return this.read(t,Vt(n,r))}async read(t,n,r={}){let o=[],s=0,i=new Map(n.map(l=>[l.toLowerCase(),l])),a=l=>l===void 0?void 0:i.get(l.toLowerCase()),u=(l,h)=>async()=>{try{let O=await h();return s+=O.requests,O.records}catch(O){return s++,o.push(en(l,O)),[]}},c=l=>()=>this.deps.query(t,l),d=l=>()=>this.deps.toolingQuery(t,l),f=async()=>[],g=n.some(l=>/^(case|lead)$/i.test(l)),[p,m,w,b,R,E]=await pt([u("flows",c(bu)),u("triggers",d(Ru)),u("processes",c(Su)),u("workflowRules",d(Au)),g?u("assignmentRules",c(Eu)):f,u("duplicateRules",c(Tu))],Be),P=p.map(Ku).filter(l=>l!==void 0).flatMap(l=>{let h=a(l.objectApiName);return h?[{...l,objectApiName:h}]:[]}),j=m.map(Xu).filter(l=>l!==void 0).flatMap(l=>{let h=a(l.objectApiName),O=l.trigger.events.some(x=>x!=="afterUndelete"||r.undeletes===!0);return h&&O?[{...l,objectApiName:h}]:[]}),T=w.map(Yu),L=T.filter(l=>l.objectApiName===void 0&&l.id!==null).map(l=>l.id),C=n.filter(l=>l.includes("__")&&rn.test(l)),ce=b.some(l=>/^01I/.test(y(l.TableEnumOrId))),[J,_e]=await pt([L.length>0?u("processes",c(Iu(L))):f,ce&&C.length>0?u("workflowRules",c(ju(C))):f],Be),Ee=new Map(J.filter(l=>y(l.ApiName).toLowerCase()===Uu).map(l=>[y(l.FlowVersionViewId),y(l.ObjectType)]));for(let l of T)l.objectApiName===void 0&&l.id!==null&&(l.objectApiName=Ee.get(l.id)||void 0);let Ie=new Map(_e.map(l=>[y(l.DurableId),y(l.QualifiedApiName)])),S=b.flatMap(l=>{let h=y(l.TableEnumOrId),O=a(Ie.get(h)??h),x=y(l.Name),W=y(l.Id);if(!O||!x)return[];let Y=y(l.NamespacePrefix),me=Y?`${Y}.${x}`:x;return[{objectApiName:O,id:ne.test(W)?W:null,flow:un(me,me,"afterSave","createAndUpdate")}]}),N=T.filter(l=>l.objectApiName===void 0||a(l.objectApiName)!==void 0),k=new Map(n.map((l,h)=>[l,h])),v=l=>k.get(a(l.objectApiName)??"")??n.length,_=P.filter(l=>l.id!==null).sort((l,h)=>Uo(l.flow)-Uo(h.flow)||v(l)-v(h)||l.flow.label.localeCompare(h.flow.label)),M=this.deps.toolingQueries,re=M?this.deps.toolingRetrieves:void 0,U=re?yt:ht,V=M?tn*U:wu,K=M?nn*U:Jo,oe=_.slice(0,V),je=[...N.map(l=>({read:l,kind:"process"})),...S.map(l=>({read:l,kind:"rule"}))].filter(({read:l})=>l.id!==null).sort((l,h)=>v(l.read)-v(h.read)||(l.kind===h.kind?0:l.kind==="process"?-1:1)||l.read.flow.label.localeCompare(h.read.flow.label)),$=je.slice(0,K),D,I,q=new Set,Te=l=>l[0]?.Metadata,hs=(l,h)=>{l.flow.condition="read",wd(l.flow,Te(h))},ys=(l,h)=>{l.flow.condition="unreadable",D??=h},ws=({read:l,kind:h})=>h==="process"?Wo(l.id):_u(l.id),bs=({read:l,kind:h},O)=>{let x=Te(O);if(typeof x!="object"||x===null){l.flow.condition="unreadable";return}if(l.flow.condition="read",h==="process"){let W=bd(l.flow,x);l.objectApiName??=W}else Rd(l.flow,x)||q.add(l.flow)},Rs=({read:l},h)=>{l.flow.condition="unreadable",I??=h},ln=(l,h,O,x,W)=>l.map(Y=>({soql:h(Y),retrieve:O(Y),take:me=>x(Y,me),refused:me=>W(Y,me)})),fn=ln(oe,l=>Wo(l.id),l=>({sobject:"Flow",id:l.id}),hs,ys),gn=ln($,ws,({read:l,kind:h})=>({sobject:h==="process"?"Flow":"WorkflowRule",id:l.id}),bs,Rs);M?s+=await Cu(l=>M(t,l),[{queries:fn,requests:tn},{queries:gn,requests:nn}],Be,re&&(l=>re(t,l))):await pt([...fn,...gn].map(l=>async()=>{try{let h=await this.deps.toolingQuery(t,l.soql);s+=h.requests,l.take(h.records)}catch(h){s++,l.refused(F(h))}}),Be),D!==void 0&&o.push(en("conditions",D)),I!==void 0&&o.push(en("definitions",I));for(let l of[...P,...N,...S])l.id===null&&(l.flow.condition="unreadable");let pn=N.flatMap(l=>{let h=a(l.objectApiName);return h?[{...l,objectApiName:h}]:[]}),mn=S.filter(l=>!q.has(l.flow)),St=[...P,...pn,...mn].flatMap(l=>l.flow.permissions),hn;if(St.length>0){let[l]=await pt([u("userPermissions",c(Ou))],Be);if(!o.some(h=>h.part==="userPermissions")){let h=new Set(l.map(O=>ps(y(O.NamespacePrefix),y(O.DeveloperName))));hn=h;for(let O of St)O.held=h.has(O.name.toLowerCase())}}let yn=[...new Set(St.filter(l=>l.bypass&&l.held!==!0).map(l=>l.name))],Le=yn.length>0?await Ad(yn,l=>u("permissionSets",c(l))(),()=>o.some(l=>l.part==="permissionSets"),async l=>{try{let h=await this.deps.query(t,l);return s+=h.requests,h.records}catch(h){throw s++,h}}):void 0,De={};if(Le?.some(l=>l.permissionSets.length>0)){let{toolingQueries:l,toolingRetrieves:h}=this.deps;try{let{readValidationRuleBypasses:O}=await import("./chunk-RQW5S67A.mjs"),x=await O(W=>this.deps.toolingQuery(t,W),n,l&&(W=>l(t,W)),h&&(W=>h(t,W)));s+=x.requests,De.validationRuleBypasses=x.rules.flatMap(W=>W.permissions.some(Y=>hn?.has(Y.toLowerCase()))?[]:[W]),x.notRead>0&&(De.validationRulesNotRead=x.notRead)}catch(O){s++,De.validationRulesUnread=F(O)}}let wn=!1;if(Le?.some(l=>l.permissionSets.length>0))try{let l=await this.deps.query(t,rt);s+=l.requests;let[h]=l.records;wn=h!==void 0&&!ot(h)}catch{s++}let Ss=l=>R.filter(h=>y(h.SobjectType).toLowerCase()===l.toLowerCase()).map(h=>({name:y(h.Name)})).sort((h,O)=>h.name.localeCompare(O.name)),As=l=>E.filter(h=>y(h.SobjectType).toLowerCase()===l.toLowerCase()).map(h=>({name:y(h.MasterLabel)||y(h.DeveloperName),developerName:y(h.DeveloperName)})).sort((h,O)=>h.name.localeCompare(O.name)),Es=(l,h)=>l.label.localeCompare(h.label),At=(l,h)=>l.filter(O=>O.objectApiName===h).map(O=>O.flow).sort(Es),Et=new Map;for(let l of _.slice(oe.length))Et.set(l.objectApiName,(Et.get(l.objectApiName)??0)+1);let bn=n.flatMap(l=>{let h=Et.get(l);return h?[{objectApiName:l,flows:h}]:[]}),Ts=n.map(l=>({objectApiName:l,flows:At(P,l),triggers:j.filter(h=>h.objectApiName===l).map(h=>h.trigger).sort((h,O)=>h.name.localeCompare(O.name)),processes:At(pn,l),workflowRules:At(mn,l),assignmentRules:Ss(l),duplicateRules:As(l)})).filter(l=>l.flows.length>0||l.triggers.length>0||l.processes.length>0||l.workflowRules.length>0||l.assignmentRules.length>0||l.duplicateRules.length>0);return{objectsRead:[...n],objects:Ts,unread:Sd(o),conditionsNotRead:_.length-oe.length,conditionsBound:V,...bn.length>0?{conditionsNotReadOn:bn}:{},definitionsNotRead:je.length-$.length,definitionsBound:K,...Le?{bypassGrants:Le}:{},...wn?{cannotAssign:!0}:{},...De,requests:s}}};function te(e){return e.slice(0,15)}async function Ad(e,t,n,r){let o=e.flatMap(p=>{let m=p.indexOf("__"),w=m>0?p.slice(0,m):"",b=m>0?p.slice(m+2):p;return rn.test(b)&&(!w||rn.test(w))?[{name:p,developerName:b}]:[]});if(o.length===0)return;let s=await t(Lu([...new Set(o.map(p=>p.developerName))]));if(n())return;let i=new Map;for(let p of s){let m=y(p.Id);ne.test(m)&&i.set(ps(y(p.NamespacePrefix),y(p.DeveloperName)),m)}let a=o.flatMap(p=>{let m=i.get(p.name.toLowerCase());return m?[m]:[]}),u=a.length>0?await t(Du(a)):[];if(n())return;let c=[...new Set(u.map(p=>y(p.ParentId)).filter(p=>ne.test(p)))],d=new Map;for(let p of["SetupEntityAccess","ObjectPermissions"]){if(c.length===0)break;let m=await t(Wu(p,c));if(n())return;for(let w of m){let b=te(y(w.ParentId)),R=typeof w.n=="number"?w.n:Number(w.n);d.set(b,(d.get(b)??0)+(Number.isFinite(R)?R:0))}}let f=new Map;for(let p of s){let m=y(p.Id);ne.test(m)&&f.set(te(m),ms(y(p.NamespacePrefix),y(p.DeveloperName)))}let g=r&&c.length>0?await Od(c,f,r):void 0;return o.map(({name:p})=>{let m=i.get(p.toLowerCase()),w=new Map;for(let b of u){if(!m||te(y(b.SetupEntityId))!==te(m))continue;let R=te(y(b.ParentId)),E=b.Parent,P=y(A(E,"Name"));if(!P||w.has(R))continue;let j=y(A(E,"NamespacePrefix"));w.set(R,{name:j?`${j}__${P}`:P,label:y(A(E,"Label"))||P,grants:d.get(R)??0,...g===void 0?{}:"refused"in g?{customPermissionsUnread:g.refused}:{customPermissions:g.bySet.get(R)??[]}})}return{permission:p,permissionSets:[...w.values()].sort((b,R)=>b.grants-R.grants||b.name.localeCompare(R.name))}})}function ms(e,t){return e?`${e}__${t}`:t}function Ed(e){return`SELECT ParentId, SetupEntityId FROM SetupEntityAccess WHERE SetupEntityType = 'CustomPermission' AND ParentId IN (${e.map(n=>`'${n}'`).join(", ")})`}function Td(e){return`SELECT Id, DeveloperName, NamespacePrefix FROM CustomPermission WHERE Id IN (${e.map(n=>`'${n}'`).join(", ")})`}async function Od(e,t,n){try{let r=await n(Ed(e)),o=new Map(t),s=[...new Set(r.map(a=>y(a.SetupEntityId)).filter(a=>ne.test(a)&&!o.has(te(a))))];if(s.length>0)for(let a of await n(Td(s))){let u=y(a.Id);ne.test(u)&&o.set(te(u),ms(y(a.NamespacePrefix),y(a.DeveloperName)))}let i=new Map;for(let a of r){let u=te(y(a.ParentId)),c=o.get(te(y(a.SetupEntityId)));if(!c)continue;let d=i.get(u)??[];d.includes(c)||d.push(c),i.set(u,d)}for(let a of i.values())a.sort((u,c)=>u.localeCompare(c));return{bySet:i}}catch(r){return{refused:F(r)}}}var kd={insert:"on insert",update:"on update",delete:"on delete"},Pd={insert:{before:"before save",after:"after save",beforeAndAfter:"before and after save"},update:{before:"before save",after:"after save",beforeAndAfter:"before and after save"},delete:{before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"}},Md={flow:e=>`flow "${e}"`,trigger:e=>`Apex trigger ${e}`,process:e=>`process "${e}"`,workflowRule:e=>`workflow rule "${e}"`},$d={flows:"the flows",triggers:"the Apex triggers",conditions:"the start conditions of some flows",processes:"the Process Builder processes",workflowRules:"the workflow rules",definitions:"the definitions of some processes or workflow rules",assignmentRules:"the assignment rules",duplicateRules:"the duplicate rules",userPermissions:"the custom permissions of the user the run writes as",permissionSets:"the permission sets that hold a bypass the user the run writes as does not"},Fd={email:"email",notification:"custom notification",outbound:"outbound message",sms:"text message"};function vd(e){let t=e.guessed?" (guessed from the name of an Apex action)":"";return`${Fd[e.kind]} "${e.name}"${t}`}function Nd(e){let t=e.label?` "${e.label}"`:"";if(e.kind==="async")return`asynchronous path${t}`;if(e.offset===void 0||e.unit===void 0)return`scheduled path${t}`;let n=Math.abs(e.offset),r=n===1?e.unit.replace(/s$/,""):e.unit,o=e.offset<0?"before":"after";return`scheduled path${t} (${n} ${r} ${o} ${e.field??"the save"})`}function Bd(e){let t=e.value===void 0?"true":`'${e.value}'`;return e.where==="decision"?`its first decision ends it when ${e.reference} is ${t}`:`not when ${e.reference} is ${t}`}function xd(e,t){let n=e.flow,r=n?.permissions??[],o=n?.switches??[],s=n?.messages??[],i=n?.paths??[],a=p=>p.held===!0?" (held)":p.held===!1?" (not held)":"",u=r.filter(p=>p.bypass&&p.where!=="decision"),c=r.filter(p=>p.bypass&&p.where==="decision"),d=r.filter(p=>!p.bypass&&p.where!=="decision"),f=[...r.filter(p=>!p.bypass&&p.where==="decision").map(p=>p.name),...o.filter(p=>!p.bypass).map(p=>p.reference)],g=e.kind==="flow"?"start condition":"definition";return[Pd[t][e.when],...s.length>0?[`SENDS MESSAGES: ${s.map(vd).join(", ")}`]:[],...i.length>0?[`then after commit: ${i.map(Nd).join(", ")}`]:[],...u.length>0?[`not for a user with ${u.map(p=>p.name+a(p)).join(", ")}`]:[],...c.length>0?[`its first decision ends it for a user with ${c.map(p=>p.name+a(p)).join(", ")}`]:[],...o.filter(p=>p.bypass).map(Bd),...e.keptQuiet?["quiet for this run"]:[],...d.length>0?[`its start condition names ${d.map(p=>p.name).join(", ")}`]:[],...f.length>0?[`its decisions test ${f.join(", ")}`]:[],...n?.condition==="notRead"?[`${g} not read`]:[],...n?.condition==="unreadable"?[`${g} unreadable`]:[]]}function af(e,t,n={}){let r=[`target automation: what ${t} runs on the ${e.objectsRead.length} object(s) the run writes`];for(let i of e.objects){r.push(` ${i.objectApiName}`);for(let{write:c,fired:d}of ze(i)){let f=d.map(g=>`${Md[g.kind](g.name)} (${xd(g,c).join("; ")})`);r.push(` ${kd[c]}: ${f.join(", ")}`)}let a=n.mayApplyAssignmentRules!==!1;for(let c of i.assignmentRules??[])r.push(n.applyAssignmentRules?` assignment rule "${c.name}": applied${a?" (--apply-assignment-rules)":""}: it can give the records it routes another owner, and mail that owner`:` assignment rule "${c.name}": not applied: the run sends Sforce-Auto-Assign: FALSE and keeps the owner it sets${a?" (--apply-assignment-rules applies it)":""}`);let u=i.duplicateRules??[];u.length>0&&r.push(` duplicate rules: ${u.map(c=>`"${c.name}"`).join(", ")}: the run saves a record a rule only alerts on; a rule that blocks still refuses it`)}e.objects.length===0&&r.push(Dn(e.unread)?" nothing found in what could be read":" no active flow, process, workflow rule, Apex trigger, assignment rule or duplicate rule runs on them");let o=Ve(e),s=Ln(e).filter(i=>!o.includes(i));if(s.length>0){r.push(` bypass: assign ${s.join(", ")} to the user the run writes as, and the flows whose start condition excludes them stay quiet`+(n.mayMute===!1?"":e.cannotAssign===!0?`; --mute-automation would be refused: ${Pe}`:"; --mute-automation assigns them for the run alone, and takes them back as it ends"));for(let{permission:i,permissionSet:a,others:u}of Qe(e,s)){if(!a){r.push(` ${i}: no permission set of ${t} holds it: an admin creates one that includes it`);continue}let c=u.length>0?`; also held by ${u.map(f=>f.name).join(", ")}`:"",d=n.username?`: ${Je(a.name,t,n.username)}`:"";r.push(` ${i}: held by permission set ${a.name}, the smallest${c}${d}`)}}if(o.length>0&&r.push(` bypass held: the user the run writes as holds ${o.join(", ")}, and what excludes them stays quiet for this run`),e.conditionsNotRead>0){let i=(e.conditionsNotReadOn??[]).map(({objectApiName:a,flows:u})=>`${a} (${u})`).join(", ");r.push(` ${e.conditionsNotRead} start condition(s) not read: the read takes ${e.conditionsBound} at most`+(i?`; left unread on ${i}`:""))}(e.definitionsNotRead??0)>0&&r.push(` ${e.definitionsNotRead} process or workflow rule definition(s) not read: the read takes ${e.definitionsBound??Jo} at most`);for(let{part:i,reason:a}of e.unread)r.push(` ${$d[i]} could not be read: ${a}`);return r.push(` read in ${e.requests} request(s) to ${t}`),r}export{to as a,Ti as b,yc as c,no as d,Sc as e,Ac as f,Ec as g,Tc as h,Oc as i,Gd as j,Ns as k,Pe as l,zd as m,ti as n,Lt as o,ii as p,Vd as q,Hd as r,Qd as s,Jd as t,di as u,Kd as v,Yd as w,Xd as x,nc as y,rc as z,oc as A,Qr as B,sc as C,Jr as D,Ri as E,ic as F,fc as G,gc as H,Xr as I,pc as J,mc as K,Io as L,vl as M,Nl as N,Bl as O,xl as P,fu as Q,Cl as R,_l as S,gu as T,_o as U,Il as V,jl as W,Ll as X,Dl as Y,Wl as Z,Ul as _,ql as $,Gl as aa,zl as ba,Lo as ca,Do as da,wu as ea,Jo as fa,ht as ga,yt as ha,tn as ia,nn as ja,go as ka,bu as la,Ru as ma,Su as na,Au as oa,Eu as pa,Tu as qa,Ou as ra,Wo as sa,ku as ta,Pu as ua,Nu as va,Bu as wa,xu as xa,sf as ya,Cu as za,_u as Aa,Iu as Ba,ju as Ca,Lu as Da,Du as Ea,Wu as Fa,Xo as Ga,Zo as Ha,Zu as Ia,ls as Ja,fs as Ka,yd as La,ps as Ma,en as Na,pt as Oa,Vt as Pa,Qo as Qa,Ad as Ra,Ed as Sa,Td as Ta,af as Ua,Lc as Va,Dc as Wa,Oi as Xa,Wc as Ya,Ht as Za,po as _a,Qt as $a,Ut as ab,ho as bb,Uc as cb,Ni as db,qc as eb,oo as fb,Ci as gb,Gc as hb,zc as ib,Vc as jb,Hc as kb,ji as lb,Li as mb,so as nb,Di as ob,Wi as pb,qi as qb,Wt as rb,Me as sb,Vi as tb,Hi as ub,ct as vb,Qi as wb,Ji as xb,Ki as yb,Qc as zb,lt as Ab,na as Bb,ra as Cb,oa as Db,ia as Eb,aa as Fb,ua as Gb,da as Hb,ca as Ib,la as Jb,ga as Kb,pa as Lb,ma as Mb,So as Nb,ie as Ob,Re as Pb,ya as Qb,gt as Rb,wa as Sb,ba as Tb,Ra as Ub,Sa as Vb,Jc as Wb,Aa as Xb,Ao as Yb,Ea as Zb,Eo as _b,Gt as $b,Ta as ac,Pa as bc,Kc as cc,Yc as dc,xa as ec,To as fc,Ca as gc,_a as hc,Ia as ic,ja as jc,Xc as kc,La as lc,Da as mc,Zc as nc,el as oc,Po as pc,tl as qc,nl as rc,Mo as sc,rl as tc,ol as uc,sl as vc,Qa as wc,il as xc,al as yc,ul as zc,dl as Ac,cl as Bc,Z as Cc,No as Dc,Ka as Ec,Ya as Fc,ll as Gc,Xa as Hc,fl as Ic,gl as Jc,Ne as Kc,pl as Lc,ml as Mc,ge as Nc,hl as Oc,yl as Pc,tu as Qc,wl as Rc,nu as Sc,bl as Tc,Yt as Uc,Rl as Vc,Sl as Wc,Al as Xc,El as Yc,Tl as Zc};
@@ -0,0 +1,9 @@
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 T,b as B,g as J,h as x,k as Y,q as Q,r as ee,s as te,t as re,u as E,v as oe}from"./chunk-YTOTMJTY.mjs";import{Aa as X,Ac as k,Ca as W,Da as K,Kc as Z,j as y,o as g,t as G}from"./chunk-CJAWKLAL.mjs";import{d as H}from"./chunk-7O6EFNQS.mjs";import{g as q}from"./chunk-TYUYPFDJ.mjs";import{a as S}from"./chunk-GP5J3DGS.mjs";import{r as $}from"./chunk-OT2NHL2V.mjs";import{k as D}from"./chunk-TQ6HEJ73.mjs";import{q as h}from"./chunk-SZOJ7BEJ.mjs";import{Sd as V,ib as C,jb as F,kd as N,pd as U,sd as O}from"./chunk-J347SPU6.mjs";import{b as A,e as _,l as I,u as j}from"./chunk-WZQEK4WT.mjs";function Re(o){let e=o.fieldPattern.indexOf(".");return e>0?o.fieldPattern.slice(0,e):void 0}function se(o,e){let t=`${e.toLowerCase()}.`;return new Set(o.filter(r=>r.fieldPattern.toLowerCase().startsWith(t)).map(r=>r.fieldPattern.slice(t.length).toLowerCase()))}function Ie(o){let e=0,t=new Map;return{session:{describe:r=>{let s=t.get(r);return s===void 0&&(e+=1,s=o.describe(r),t.set(r,s)),s},query:r=>(e+=1,o.query(r))},requests:()=>e}}async function $e(o){try{let e=await o.describe(h),t=typeof e=="object"&&e!==null&&"fields"in e?e.fields:void 0;return Array.isArray(t)&&t.some(r=>typeof r=="object"&&r!==null&&"name"in r&&r.name===J)}catch{return!1}}function Se(o,e,t){let r=se(e,o.objectApiName),s=t&&o.objectApiName.toLowerCase()===h.toLowerCase();if(s)for(let a of se(x(e),h))r.add(a);let i=o.fields.filter(a=>r.has(a.fieldApiName.toLowerCase())?!1:!(s&&U(a.fieldApiName)&&a.detectedBy!=="content"&&a.suggestedRule!==void 0)),n=i.flatMap(a=>a.suggestedRule===void 0?[]:[{fieldPattern:`${o.objectApiName}.${a.fieldApiName}`,ruleType:a.suggestedRule.ruleType,...a.suggestedRule.config?{config:a.suggestedRule.config}:{}}]),d=(o.hiddenClassified??[]).filter(a=>!r.has(a.fieldApiName.toLowerCase()));return{uncovered:i,proposed:n,hidden:d}}async function ie(o,e,t,r=()=>new Date,s){let{session:i,requests:n}=Ie(o),d=t.template.rules,a=[];for(let u of d){let f=Re(u);f&&!a.some(we=>we.toLowerCase()===f.toLowerCase())&&a.push(f)}let l=a.some(u=>u.toLowerCase()===h.toLowerCase()),c=x(d).length>0,p=t.objects?.map(u=>a.find(f=>f.toLowerCase()===u.toLowerCase())??u),m=p??[...a],w=(m.some(u=>u.toLowerCase()===h.toLowerCase())||p===void 0&&c&&!l)&&await $e(i);p===void 0&&c&&!l&&w&&m.push(h);let be=m.slice(0,10),R=await B(i,e,{orgId:t.orgId,objects:be},r,s),z=[],ve=R.objects.map(u=>{if(u.status==="failed")return u;let f=Se(u,d,w);return z.push(...f.proposed),{status:"scanned",objectApiName:u.objectApiName,label:u.label,sampled:u.sampled,personal:u.fields.length,uncovered:f.uncovered,...f.hidden.length>0?{hiddenClassified:f.hidden}:{},...u.sampleError!==void 0?{sampleError:u.sampleError}:{},...u.classificationError!==void 0?{classificationError:u.classificationError}:{}}});return{orgId:t.orgId,templateId:t.template.id,scannedAt:R.scannedAt,sampleSize:R.sampleSize,objects:ve,notRead:m.slice(10),proposed:z,requests:n()+(R.classificationRequests??0)}}function de(o,e){if(!Array.isArray(o))return;let t=o[e];if(!(typeof t!="object"||t===null||!("fieldPattern"in t)))return typeof t.fieldPattern=="string"?t.fieldPattern:void 0}function ae(o){if(o.code==="unrecognized_keys"&&o.keys.some(r=>/salt/i.test(r)))return`A template carries no salt: the run draws its key as it starts. Take ${o.keys.filter(r=>/salt/i.test(r)).join(", ")} out of the file`;let[e,t]=o.path;if(e==="rules"&&t===void 0){if(o.code==="too_small")return"The file holds no rule: a template masks one field at least";if(o.code==="too_big")return`A template holds ${F} rules at most`}return o.path.length===0?o.code==="unrecognized_keys"?o.message:'The file holds a template\u2019s name and its rules: { "name": \u2026, "rules": [ \u2026 ] }':o.path.length>0&&typeof t!="number"?`${o.path.join(".")}: ${o.message}`:o.message}function Ee(o){if(!Array.isArray(o))return[];let e=new Map,t=[];return o.forEach((r,s)=>{let i=de(o,s);if(i===void 0)return;let n=e.get(i.toLowerCase());if(n===void 0){e.set(i.toLowerCase(),s);return}t.push({rule:s+1,field:i,message:`Rule ${n+1} masks this field already: a field takes one rule`})}),t}function le(o,e){if(o.length>O)return{ok:!1,problems:[{message:`The file holds ${o.length} characters; a template file holds ${O} at most`}]};let t;try{t=JSON.parse(o)}catch(l){return{ok:!1,problems:[{message:`Not JSON: ${l instanceof Error?l.message:String(l)}`}]}}let r=Array.isArray(t)?{rules:t}:t,s=typeof r=="object"&&r!==null&&!("name"in r)?{...r,name:`Rules from ${e}`}:r,i=typeof s=="object"&&s!==null&&"rules"in s?s.rules:void 0,n=X.safeParse(s),d=Ee(i);if(n.success&&d.length===0)return{ok:!0,template:n.data};let a=[];for(let l of n.success?[]:n.error.issues){if(l.path.length===1&&l.path[0]==="rules"&&l.code==="custom")continue;let[c,p]=l.path;if(c==="rules"&&typeof p=="number"){let m=de(i,p);a.push({rule:p+1,...m?{field:m}:{},message:ae(l)})}else a.push({message:ae(l)})}return a.push(...d),a.sort((l,c)=>(l.rule??0)-(c.rule??0)),{ok:!1,problems:a}}function pe(o,e){let t=e.map(r=>`${r.rule===void 0?"":`Rule ${r.rule}${r.field?` (${r.field})`:""}: `}${r.message}.`);return`${o} is not a masking template SandForge can import. ${t.join(" ")}`}function ce(o,e){let t=o.trim(),r=new Set(e.map(s=>s.trim().toLowerCase()));if(!r.has(t.toLowerCase()))return t;for(let s=2;;s++){let i=` (${s})`,n=`${t.slice(0,C-i.length).trimEnd()}${i}`;if(!r.has(n.toLowerCase()))return n}}var Me=new Set(["dataops:anonymize:gaps","dataops:anonymization-template:import"]),Ne="TEMPLATE_NOT_FOUND",Oe="TEMPLATE_FILE_INVALID",ue=class{constructor(e){this.deps=e}deps;get savedTemplates(){return new E(this.deps.configStore)}findTemplate(e){return T.find(t=>t.id===e)??this.savedTemplates.load(e)??this.heldTemplates.get(e)}heldTemplates=new Map;holdTemplate(e){this.heldTemplates.set(e.id,e)}async handle(e){return Me.has(e.type)?(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type==="dataops:anonymize:gaps"?await this.handleGaps(e):this.handleImport(e),!0):!1}async handleGaps(e){let t=k(K,e,"dataops:error",this.deps);if(!t)return;let r=this.findTemplate(t.templateId);if(!r){g(this.deps,"dataops:anonymize:gaps","dataops:error",e,new Error(`Template "${t.templateId}" not found.`),{code:Ne});return}try{let s=await $(t.orgId,this.deps.orgRegistry,this.deps.orgManager),i=await ie(S(s,"dataops:anonymize:gaps"),this.deps.infraServices?.piiDetector??new q,{orgId:t.orgId,template:r,...t.objects?{objects:t.objects}:{}},void 0,H(s)),n=y(this.deps,e,"dataops:anonymize:gaps:response",{...i});this.deps.broker.postToWebview(n);let d=i.objects.reduce((a,l)=>a+(l.status==="scanned"?l.uncovered.length:0),0);this.deps.log(`[TX] ${n.type} id=${n.id} objects=${i.objects.length} uncovered=${d} requests=${i.requests}`)}catch(s){g(this.deps,"dataops:anonymize:gaps","dataops:error",e,s)}}handleImport(e){let t=k(W,e,"dataops:error",this.deps);if(!t)return;let r=le(t.content,t.fileName);if(!r.ok){g(this.deps,"dataops:anonymization-template:import","dataops:error",e,new Error(pe(t.fileName,r.problems)),{code:Oe,extraPayload:{problems:r.problems}});return}try{let s=[...T,...this.savedTemplates.list()].map(l=>l.name),i=r.template.name.trim(),n=ce(i,s),d=this.savedTemplates.create(n,r.template.rules),a=y(this.deps,e,"dataops:anonymization-template:import:response",{template:d,...n!==i?{renamedFrom:i}:{}});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} rules=${d.rules.length}${n!==i?" renamed":""}`)}catch(s){g(this.deps,"dataops:anonymization-template:import","dataops:error",e,s)}}};import{randomUUID as Ce}from"node:crypto";var M=class{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{openExternal:t=>e.env.openExternal(t),parseUri:t=>e.Uri.parse(t,!0)}}async open(e){let t=this.host??await this.defaultHost();try{return await t.openExternal(t.parseUri(e))?{status:"opened"}:{status:"error",message:"VS Code did not open the page."}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}};import{createHash as xe}from"node:crypto";var Pe=1;function fe(o){return{sandforgeMaskingAttestation:Pe,verificationId:o.verificationId,verifiedAt:o.verifiedAt,verdict:o.verdict,org:{...o.org},template:o.template?{...o.template}:null,anonymizationMode:o.template?o.template.id===V?"everything":"standard":null,rules:o.rules.map(e=>({...e})),run:o.runId!==void 0?{id:o.runId}:{},backup:{id:o.backupId,from:o.from,...o.keptAt!==void 0?{keptAt:o.keptAt}:{}},totals:{...o.totals},objects:o.objects.map(e=>({objectApiName:e.objectApiName,kept:e.kept,verified:e.verified,gone:e.gone,notRead:e.notRead,...e.notReadCode!==void 0?{notReadCode:e.notReadCode}:{},...e.fieldsUnseen!==void 0?{fieldsUnseen:[...e.fieldsUnseen]}:{},textFields:e.textFields,fields:e.fields.map(t=>({fieldApiName:t.fieldApiName,...t.method!==void 0?{method:t.method}:{},compared:t.compared,left:t.left,asItsRuleWrites:t.asItsRuleWrites})),elsewhere:e.elsewhere.map(t=>({fieldApiName:t.fieldApiName,as:t.as,records:t.records}))})),...o.slices?{slices:{...o.slices}}:{},reads:{...o.reads},history:o.history?o.history.map(e=>({...e})):null}}function P(o){let e=`${JSON.stringify(fe(o),null,2)}
8
+ `;return{text:e,sha256:xe("sha256").update(e,"utf8").digest("hex")}}var Le={clean:"No value left: every record kept was read, and none holds a value it held before.",left:"Values left: records still hold a value they held before the masking, in a field or in their field history.",incomplete:"Incomplete: no value was found left, but records were not read, or no slice kept them."},ze={email:"email address",phone:"phone number (last 8 digits)",name:"full name"};function me(o){return String(o).replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\s+/g," ")}function b(o,e){return[`| ${o.map(me).join(" | ")} |`,`| ${o.map(()=>"---").join(" | ")} |`,...e.map(t=>`| ${t.map(me).join(" | ")} |`)]}function ge(o){let e=fe(o),{sha256:t}=P(o),{totals:r,reads:s}=e,i=["# Masking attestation","",`- Org: ${e.org.name}${e.org.type?` (${e.org.type})`:""}`,`- Template: ${e.template?.name??"not recorded"}`,`- Anonymization: ${e.anonymizationMode==="everything"?"everything, every personal field of its objects":e.anonymizationMode==="standard"?"standard, the template's rules":"not recorded"}`,`- Masking run: ${e.run.id??"not recorded"}`,`- Values kept in: ${e.backup.from==="slices"?"set of slices":"snapshot"} ${e.backup.id}${e.backup.keptAt?`, taken ${e.backup.keptAt}`:""}`,`- Verified: ${e.verifiedAt}, ${s.requests} request(s) of at most ${s.maxRequests}, in ${Math.round(s.durationMs/1e3)} s`+(s.stoppedAtBound?", stopped at that bound":""),`- Verdict: ${Le[e.verdict]}`,"","## Counts","",...b(["Records kept","Verified","Values left","Found elsewhere","Gone since","Not read","Not kept","History lines left"],[[r.kept,r.verified,r.valuesLeft,r.foundElsewhere,r.gone,r.notRead,r.notKept,e.history?r.historyLeft:"not read"]]),""];e.slices&&i.push(`Slices read: ${e.slices.read}; restored since, not read: ${e.slices.restored}; never backed up: ${e.slices.notTaken}.`,""),i.push("## Rules","",...b(["Object","Field","Method"],e.rules.map(n=>[n.objectApiName,n.fieldApiName,n.method??"not recorded"])),"");for(let n of e.objects)i.push(`## ${n.objectApiName}`,"",`Kept ${n.kept}, verified ${n.verified}, gone since ${n.gone}, not read ${n.notRead}${n.notReadCode?` (${n.notReadCode})`:""}; ${n.textFields} text field(s) read for values found elsewhere.`,""),n.fieldsUnseen&&n.fieldsUnseen.length>0&&i.push(`Masked fields the org no longer shows, not compared: ${n.fieldsUnseen.join(", ")}.`,""),i.push(...b(["Field","Method","Compared","Left","As its rule writes"],n.fields.map(d=>[d.fieldApiName,d.method??"not recorded",d.compared,d.left,d.asItsRuleWrites])),""),n.elsewhere.length>0&&i.push("Found elsewhere:","",...b(["Field","Found as","Records"],n.elsewhere.map(d=>[d.fieldApiName,ze[d.as],d.records])),"");return i.push("## Field history",""),e.history?i.push("Lines of field history still holding a value of a masked field, for the records verified:","",...b(["Object","History","Lines left"],e.history.map(n=>[n.objectApiName,n.notTracked?"not tracked":n.historyObject??"",n.notTracked?0:n.unread!==void 0?`not read (${n.unread})`:n.left??0])),""):i.push("Not read: this attestation says nothing of what the field history keeps.",""),i.push(`SHA-256 of the JSON attestation: \`${t}\``,""),i.join(`
9
+ `)}function he(o){let e;try{e=new URL(o)}catch{return{ok:!1,reason:"invalid"}}return e.protocol!=="https:"?{ok:!1,reason:"not-https",protocol:e.protocol}:{ok:!0,url:e}}var _e=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,je=/^[A-Za-z][A-Za-z0-9_]*$/;function ye(o,e,t){if(!_e.test(t)||!je.test(e))return{ok:!1,reason:"not-a-record"};let r=he(o);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var Fe=new Set(["dataops:anonymize:verify","dataops:anonymize:verify:export","dataops:anonymize:verify:open"]),Ue=1e6,Ve=I({orgId:G,backupId:A().min(1).max(240),maxRequests:_().int().positive().max(Ue).optional()}),De=I({verificationId:A().min(1).max(200),format:j(["markdown","json"])}),He=I({verificationId:A().min(1).max(200),recordId:A().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id")}).strict(),ke="RECORD_NOT_LISTED",qe="MASKING_STILL_RUNNING",Ae="VERIFICATION_NOT_FOUND",Be=20,v=class extends Error{constructor(t,r){super(t);this.code=r;this.name="VerifyRefusedError"}code},Te=class{constructor(e,t,r){this.deps=e;this.saveDialog=t??new oe,this.externalBrowser=r??new M}deps;backupRecords;held=new Map;orgOf=new Map;saveDialog;externalBrowser;setBackupRecordStore(e){this.backupRecords=e}async handle(e){return Fe.has(e.type)?(e.type==="dataops:anonymize:verify"?await this.handleVerify(e):e.type==="dataops:anonymize:verify:open"?await this.handleOpen(e):await this.handleExport(e),!0):!1}async handleVerify(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=k(Ve,e,"dataops:error",this.deps);if(t)try{let r=await this.verify(t),s=y(this.deps,e,"dataops:anonymize:verify:response",{...r});this.deps.broker.postToWebview(s),this.deps.log(`[TX] ${s.type} id=${s.id} verdict=${r.verdict} requests=${r.reads.requests}`)}catch(r){g(this.deps,e.type,"dataops:error",e,r,{...r instanceof v?{code:r.code}:{}})}}async verify(e,t){let r=re(this.keptStores(),e);if("refused"in r)throw new v(r.refused.message,r.refused.code);let{toVerify:s}=r;if((s.runId?this.deps.infraServices?.backgroundRegistry?.get(s.runId):void 0)?.status==="running")throw new v(`The masking run of backup ${e.backupId} is still under way: verify it once it has ended.`,qe);let n=this.deps.orgManager.getOrg(e.orgId),d=await $(e.orgId,this.deps.orgRegistry,this.deps.orgManager),a=S(d,"dataops:anonymize:verify"),l=Ce(),c=await ee({describe:m=>a.describe(m),query:m=>a.query(m),history:Y(d),kept:(m,L,w)=>this.kept(m,L,w)},s,{verificationId:l,org:{name:n?N(n,e.orgId):e.orgId,...n?.orgType?{type:n.orgType}:{}},maxRequests:e.maxRequests??Q,...t?{signal:t}:{}});this.hold(c),this.orgOf.set(l,e.orgId);let{totals:p}=c;return D(this.deps,{action:"masking_verify",module:"dataops",operationId:l,orgId:e.orgId,outcome:te(c.verdict),objects:[],details:{backup:c.backupId,...c.template?{template:c.template.name}:{},verified:p.verified,valuesLeft:p.valuesLeft,foundElsewhere:p.foundElsewhere,...c.history?{historyLeft:p.historyLeft}:{},recordsGone:p.gone,recordsNotRead:p.notRead+p.notKept,requests:c.reads.requests}}),this.deps.log(`[INFO] dataops:anonymize:verify ${e.backupId}: ${c.verdict}, ${p.verified} of ${p.kept} record(s) verified, ${p.valuesLeft} value(s) left, ${p.foundElsewhere} found elsewhere, ${c.reads.requests} request(s)`),c}verification(e){return this.held.get(e)}async handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=k(De,e,"dataops:error",this.deps);if(!t)return;let r=this.held.get(t.verificationId);if(!r){g(this.deps,e.type,"dataops:error",e,new Error("This verification is no longer held by this window: verify the masking again, then export its attestation."),{code:Ae});return}let s=t.format,{text:i,sha256:n}=P(r),d=`sandforge-masking-attestation-${r.verifiedAt.slice(0,10)}`,a=s==="json"?await this.saveDialog.save(`${d}.json`,i,["json"]):await this.saveDialog.save(`${d}.md`,ge(r),["md"]);if(a.status==="error"){g(this.deps,e.type,"dataops:error",e,new Error(a.message));return}let l=y(this.deps,e,"dataops:anonymize:verify:export:response",{verificationId:r.verificationId,format:s,sha256:n,saved:a});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} ${s} ${a.status}`)}hold(e){for(this.held.set(e.verificationId,e);this.held.size>Be;){let t=this.held.keys().next().value;if(t===void 0)break;this.held.delete(t),this.orgOf.delete(t)}}async handleOpen(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=k(He,e,"dataops:error",this.deps);if(!t)return;let r=(p,m)=>{g(this.deps,e.type,"dataops:error",e,new Error(p),{code:m})},s=this.held.get(t.verificationId),i=this.orgOf.get(t.verificationId);if(!s||i===void 0){r("This verification is no longer held by this window: verify the masking again, then open its records.",Ae);return}let n=Ge(s,t.recordId);if(!n){r("This record is not one the verification found a value on.",ke);return}let d=this.deps.orgManager.getOrg(i);if(!d){r("The org this verification read is no longer connected.","ORG_NOT_FOUND");return}let a=ye(d.instanceUrl,n.objectApiName,n.id);if(!a.ok){let p=a.reason==="not-https"?`its instance URL must use HTTPS, got "${a.protocol}"`:a.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${N(d,i)}": ${p}.`,a.reason==="not-a-record"?ke:"INVALID_INSTANCE_URL");return}let l=await this.externalBrowser.open(a.url),c=y(this.deps,e,"dataops:anonymize:verify:open:response",l);this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} status=${l.status}`)}keptStores(){let e=this.deps.configStore,t=new Z(e),r=new E(e);return{meta:s=>e.get(`backup:${s}`),set:s=>t.get(s),template:s=>T.find(i=>i.id===s)??r.load(s)}}async kept(e,t,r){let s=await this.backupRecords?.batches(e,t,r);if(s)return s;let i=this.deps.configStore.get(`backup:${e}:${t}`);if(!Array.isArray(i))return null;let n=i;return{async*[Symbol.asyncIterator](){for(let d=0;d<n.length;d+=r)yield n.slice(d,d+r)}}}};function Ge(o,e){let t=e.slice(0,15);for(let r of o.objects){let i=[...r.fields.flatMap(n=>n.leftIds??[]),...r.elsewhere.flatMap(n=>n.ids??[])].find(n=>n.slice(0,15)===t);if(i)return{objectApiName:r.objectApiName,id:i}}}export{fe as a,P as b,ge as c,he as d,M as e,ye as f,ue as g,Te as h};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-3Q353S2R.mjs";import"./chunk-M6K34KGF.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{r as BEFORE_RUN_DELETED_WORDS,e as BEFORE_RUN_DISK_ROOM,a as WRITE_PATH_STEPS,j as beforeRunAskedOf,f as beforeRunDiskRefusal,d as beforeRunEstimateOf,q as beforeRunFailedWords,i as beforeRunKeepDaysOf,h as beforeRunNameOf,l as beforeRunOutcomeOf,s as beforeRunProgressWords,p as beforeRunRefusedWords,c as beforeRunScopeOf,k as beforeRunTakenOf,g as freeBytesOf,m as scopeBeforeRun,o as settleBeforeRun,n as takeBeforeRun,b as writePathOrderDefects};
7
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-6HHSAPIM.mjs";import"./chunk-DAUX63UB.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{r as BEFORE_RUN_DELETED_WORDS,e as BEFORE_RUN_DISK_ROOM,a as WRITE_PATH_STEPS,j as beforeRunAskedOf,f as beforeRunDiskRefusal,d as beforeRunEstimateOf,q as beforeRunFailedWords,i as beforeRunKeepDaysOf,h as beforeRunNameOf,l as beforeRunOutcomeOf,s as beforeRunProgressWords,p as beforeRunRefusedWords,c as beforeRunScopeOf,k as beforeRunTakenOf,g as freeBytesOf,m as scopeBeforeRun,o as settleBeforeRun,n as takeBeforeRun,b as writePathOrderDefects};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{f as $}from"./chunk-W6PN6TJG.mjs";import{a as N}from"./chunk-4TLYUZD5.mjs";import{a as F}from"./chunk-Q7TLC3I2.mjs";import{b as O}from"./chunk-CA5NAXSU.mjs";import{bd as k,k as M}from"./chunk-PMWAFDUB.mjs";var x=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,r){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=r?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=r?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,r,n){let s=this.connections.get(t);if(s&&s.active)return s.lastUsedAt=Date.now(),s.accessToken=n,s;this.connections.size>=this.config.maxConnections&&this.evictOldest();let i={orgId:t,instanceUrl:r,accessToken:n,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,i),i}release(t){let r=this.connections.get(t);r&&(r.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,r){if(!Number.isFinite(r)||r<0)return;let n=this.latencySamples.get(t);n||(n=[],this.latencySamples.set(t,n)),n.push(r),n.length>1e3&&n.splice(0,n.length-1e3)}getLatencyMetrics(t){let r=this.latencySamples.get(t);if(!r||r.length===0)return;let n=[...r].sort((a,c)=>a-c),s=n.reduce((a,c)=>a+c,0),i=Math.floor(n.length*.95),u=Math.floor(n.length*.99);return{min:n[0],max:n[n.length-1],avg:Math.round(s/n.length),p95:n[Math.min(i,n.length-1)],p99:n[Math.min(u,n.length-1)],sampleCount:n.length}}getAllLatencyMetrics(){let t=new Map;for(let r of this.latencySamples.keys()){let n=this.getLatencyMetrics(r);n&&t.set(r,n)}return t}cleanupIdle(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(n),r++);return r}recycleStale(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.createdAt>this.recycleIntervalMs&&(s.active=!1,this.connections.delete(n),r++);return r}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,r=1/0;for(let[n,s]of this.connections)s.lastUsedAt<r&&(r=s.lastUsedAt,t=n);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var S=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var B=0;function we(){return B}async function I(e,t){let r=$(e);try{return await t()}finally{B+=r()}}var C=class extends Error{constructor(r,n,s){super(`${r}: ${s}`);this.code=r;this.orgId=n;this.name="OrgConnectionError"}code;orgId};import{homedir as ee,userInfo as te}from"node:os";var ne=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],V=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function X(e){return ne.some(t=>t.test(e))}function P(e=process.env){let t={};for(let[r,n]of Object.entries(e))X(r)||(t[r]=n);return t.NO_COLOR="1",t}function Ee(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),r=V.filter(c=>t.some(d=>d.toUpperCase()===c)),n=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),s=t.filter(c=>X(c)),i=s.filter(c=>c.startsWith("ELECTRON_")).sort(),u=s.length-i.length,a=s.length===0?"none":[...i,...u>0?[`${u} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${r.length>0?r.join(", "):"none of "+V.join(", ")}; SF_/SFDX_: ${n.length>0?n.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${a}`}function re(){try{return te().username}catch{return process.env.USERNAME??process.env.USER??""}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,t=ee(),r=re()){let n=e;return t.length>3&&(n=n.replace(new RegExp(H(t),"gi"),"~")),r.length>=2&&(n=n.replace(new RegExp(`(?<=[\\\\/])${H(r)}(?=[\\\\/]|$)`,"gim"),"<user>")),n.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function ve(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function se(e,t){if(process.platform!=="win32")return e[0];let n=(Object.entries(t).find(([s])=>s.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);return e.find(s=>{let i=s.lastIndexOf(".");return i>Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))&&n.includes(s.slice(i).toLowerCase())})}async function Oe(e=1e4){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=process.platform==="win32"?"where sf node":"which -a sf node",s=P(),i,u;try{let l=await r(t)(n,{timeout:e,windowsHide:!0,env:s});i=String(l.stdout)}catch(l){let o=l;i=String(o.stdout??""),i.trim()===""&&(u=j(o.message??String(l)))}let a=i.split(/\r?\n/).map(l=>l.trim()).filter(l=>l.length>0).map(l=>j(l)),c=l=>a.filter(o=>new RegExp(`(^|[\\\\/])${l}(\\.[A-Za-z0-9]+)?$`,"i").test(o)),d=c("sf"),p=se(d,s);return{sf:d,node:c("node"),...p!==void 0?{runs:p}:{},...u?{failure:u}:{}}}function R(e,t){let r=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return r===""?void 0:r}function ie(e,t){if(t===void 0)return!1;let r=e.hostname.toLowerCase(),n=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(s=>s!=="").some(s=>{if(s==="*")return!0;let[,i="",u]=/^(.*?)(?::(\d+))?$/.exec(s.toLowerCase())??[];if(u!==void 0&&u!==n)return!1;let a=i.replace(/^\*?\.?/,"");return a!==""&&(r===a||r.endsWith(`.${a}`))})}function G(e,t=process.env){let r;try{r=new URL(e)}catch{return}let n=r.protocol==="https:"?R(t,"https_proxy")??R(t,"http_proxy"):R(t,"http_proxy");if(n!==void 0)return ie(r,R(t,"no_proxy"))?void 0:n}var oe="https://login.salesforce.com";async function v(e,t=process.env){let{jsforce:r,HttpProxyTransport:n}=await import("./chunk-L5FGY6YA.mjs"),s=G(e.instanceUrl??e.loginUrl??oe,t),i=new r.Connection({...e,...s!==void 0?{httpProxy:s}:{}});return s===void 0&&(i._transport=new n("")),i}var ae=10*1024*1024,L=3e4,q=L+2e3,A=`sf did not answer within ${L/1e3} s \u2014 check the Salesforce CLI`;function J(e){return e instanceof Error&&e.message===A}var D=2e4;function U(e,t,r){let n,s=new Promise((i,u)=>{n=setTimeout(()=>u(new Error(r)),t)});return Promise.race([e,s]).finally(()=>clearTimeout(n))}var E=new x,ce=300*1e3,_=new Map,le={failureThreshold:3,resetTimeout:3e4},z=new Map;function Ne(){return E}function ue(e){let t=z.get(e);return t||(t=new S({...le}),z.set(e,t)),t}var Y;var b="panel";function Be(e){b=e}function fe(e,t=b){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function W(e=b){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function K(e,t){let r=t?.organization_id;if(!(!Y||typeof r!="string"))try{Y(e,{organizationId:r})}catch(n){N.warn("Identity observer threw",{orgId:e,error:O(n)})}}var de="[REDACTED]";function Z(e){return typeof e=="string"&&e.length>0&&!e.startsWith(de)&&!/\s/.test(e)}async function pe(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:r}=await import("child_process"),{promisify:n}=await import("util"),s={maxBuffer:ae,timeout:L,windowsHide:!0,env:P()},i=o=>U(n(t)("sf",o,s),q,A),u=o=>{let f=!1,h,y=new Promise((T,m)=>{h=r(o,s,(g,w)=>{f=!0,g?m(g):T({stdout:w})})});return U(y,q,A).catch(T=>{throw!f&&h?.pid!==void 0&&t("taskkill",["/pid",String(h.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},a=(o,f)=>process.platform==="win32"?u(o):i(f),c=(o,f)=>{let h=o.replace(/\[[0-9;]*m/g,""),y=h.search(/[{[]/);if(y===-1)throw new Error(`Failed to parse "${f}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(h.slice(y)).result??{}},d;try{let{stdout:o}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),f=c(o,"sf org display");d=typeof f.instanceUrl=="string"?f.instanceUrl:void 0}catch(o){if(J(o))throw o;d=void 0}try{let{stdout:o}=await a(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),f=c(o,"sf org auth show-access-token");if(Z(f.accessToken))return{accessToken:f.accessToken,instanceUrl:d}}catch(o){if(J(o))throw o}let{stdout:p}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),l=c(p,"sf org display");if(!Z(l.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof l.instanceUrl=="string"&&(d=l.instanceUrl),{accessToken:l.accessToken,instanceUrl:d}}async function Ve(e,t){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function He(e){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function je(e,t,r){let n=e,s=r.getOrg(e);if(!s)throw new Error(`Org not found: ${e}`);let i=await t.getCredentials(e);if(!i?.accessToken||!i.instanceUrl)throw new Error(`No credentials for org "${s.alias}" (${e}). Reconnect the org.`);let u=s.metadata.apiVersion||M.DEFAULT_API_VERSION,a=E.get(n),c=Date.now()-(_.get(e)??0)<ce;if(a&&a.active&&a.accessToken===i.accessToken&&c)return a.lastUsedAt=Date.now(),v({instanceUrl:a.instanceUrl,accessToken:a.accessToken,version:u});let d=await v({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:u}),p=ue(e);if(!p.acquirePermit())throw new C("ORG_TEMPORARILY_UNREACHABLE",e,`"${s.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let l=Date.now(),o=`identity check did not answer within ${D/1e3} s`;try{let f=await I(d,()=>U(d.identity(),D,o)),h=Date.now()-l;return p.recordSuccess(),E.acquire(n,i.instanceUrl,i.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,f),d}catch(f){let h=Date.now()-l;if(E.remove(n),_.delete(e),F(f))try{let m=await pe(s.username),g=m.instanceUrl??i.instanceUrl;if(m.accessToken===i.accessToken&&g===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let w=await v({instanceUrl:g,accessToken:m.accessToken,version:u}),Q=await I(w,()=>U(w.identity(),D,o));return await t.saveOrg(s,{...i,accessToken:m.accessToken,instanceUrl:g}),p.recordSuccess(),E.acquire(n,g,m.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,Q),w}catch(m){p.recordFailure();let g=O(m);r.updateStatus(e,"expired");let w=k(s,new Date().toISOString().slice(0,10));throw w!==void 0?new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${w}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${g})`):new C("ORG_AUTH_EXPIRED",e,`The session with "${s.alias}" has expired and could not be renewed. ${fe(s.alias)} (cause: ${g})`)}p.recordFailure();let y=O(f),T=k(s,new Date().toISOString().slice(0,10));throw T!==void 0?(r.updateStatus(e,"expired"),new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${y})`)):new Error(`Connection failed for "${s.alias}": ${y}`)}finally{p.releasePermit()}}export{we as a,I as b,C as c,P as d,Ee as e,j as f,ve as g,Oe as h,G as i,v as j,U as k,Ne as l,Be as m,Z as n,pe as o,Ve as p,He as q,je as r};
7
+ import{f as $}from"./chunk-65AMXOQU.mjs";import{a as N}from"./chunk-4TLYUZD5.mjs";import{a as F}from"./chunk-Q7TLC3I2.mjs";import{b as O}from"./chunk-CA5NAXSU.mjs";import{id as k,k as M}from"./chunk-J347SPU6.mjs";var x=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,r){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=r?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=r?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,r,n){let s=this.connections.get(t);if(s&&s.active)return s.lastUsedAt=Date.now(),s.accessToken=n,s;this.connections.size>=this.config.maxConnections&&this.evictOldest();let i={orgId:t,instanceUrl:r,accessToken:n,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,i),i}release(t){let r=this.connections.get(t);r&&(r.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,r){if(!Number.isFinite(r)||r<0)return;let n=this.latencySamples.get(t);n||(n=[],this.latencySamples.set(t,n)),n.push(r),n.length>1e3&&n.splice(0,n.length-1e3)}getLatencyMetrics(t){let r=this.latencySamples.get(t);if(!r||r.length===0)return;let n=[...r].sort((a,c)=>a-c),s=n.reduce((a,c)=>a+c,0),i=Math.floor(n.length*.95),u=Math.floor(n.length*.99);return{min:n[0],max:n[n.length-1],avg:Math.round(s/n.length),p95:n[Math.min(i,n.length-1)],p99:n[Math.min(u,n.length-1)],sampleCount:n.length}}getAllLatencyMetrics(){let t=new Map;for(let r of this.latencySamples.keys()){let n=this.getLatencyMetrics(r);n&&t.set(r,n)}return t}cleanupIdle(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(n),r++);return r}recycleStale(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.createdAt>this.recycleIntervalMs&&(s.active=!1,this.connections.delete(n),r++);return r}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,r=1/0;for(let[n,s]of this.connections)s.lastUsedAt<r&&(r=s.lastUsedAt,t=n);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var S=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var B=0;function we(){return B}async function I(e,t){let r=$(e);try{return await t()}finally{B+=r()}}var C=class extends Error{constructor(r,n,s){super(`${r}: ${s}`);this.code=r;this.orgId=n;this.name="OrgConnectionError"}code;orgId};import{homedir as ee,userInfo as te}from"node:os";var ne=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],V=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function X(e){return ne.some(t=>t.test(e))}function P(e=process.env){let t={};for(let[r,n]of Object.entries(e))X(r)||(t[r]=n);return t.NO_COLOR="1",t}function Ee(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),r=V.filter(c=>t.some(d=>d.toUpperCase()===c)),n=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),s=t.filter(c=>X(c)),i=s.filter(c=>c.startsWith("ELECTRON_")).sort(),u=s.length-i.length,a=s.length===0?"none":[...i,...u>0?[`${u} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${r.length>0?r.join(", "):"none of "+V.join(", ")}; SF_/SFDX_: ${n.length>0?n.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${a}`}function re(){try{return te().username}catch{return process.env.USERNAME??process.env.USER??""}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,t=ee(),r=re()){let n=e;return t.length>3&&(n=n.replace(new RegExp(H(t),"gi"),"~")),r.length>=2&&(n=n.replace(new RegExp(`(?<=[\\\\/])${H(r)}(?=[\\\\/]|$)`,"gim"),"<user>")),n.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function ve(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function se(e,t){if(process.platform!=="win32")return e[0];let n=(Object.entries(t).find(([s])=>s.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);return e.find(s=>{let i=s.lastIndexOf(".");return i>Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))&&n.includes(s.slice(i).toLowerCase())})}async function Oe(e=1e4){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=process.platform==="win32"?"where sf node":"which -a sf node",s=P(),i,u;try{let l=await r(t)(n,{timeout:e,windowsHide:!0,env:s});i=String(l.stdout)}catch(l){let o=l;i=String(o.stdout??""),i.trim()===""&&(u=j(o.message??String(l)))}let a=i.split(/\r?\n/).map(l=>l.trim()).filter(l=>l.length>0).map(l=>j(l)),c=l=>a.filter(o=>new RegExp(`(^|[\\\\/])${l}(\\.[A-Za-z0-9]+)?$`,"i").test(o)),d=c("sf"),p=se(d,s);return{sf:d,node:c("node"),...p!==void 0?{runs:p}:{},...u?{failure:u}:{}}}function R(e,t){let r=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return r===""?void 0:r}function ie(e,t){if(t===void 0)return!1;let r=e.hostname.toLowerCase(),n=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(s=>s!=="").some(s=>{if(s==="*")return!0;let[,i="",u]=/^(.*?)(?::(\d+))?$/.exec(s.toLowerCase())??[];if(u!==void 0&&u!==n)return!1;let a=i.replace(/^\*?\.?/,"");return a!==""&&(r===a||r.endsWith(`.${a}`))})}function G(e,t=process.env){let r;try{r=new URL(e)}catch{return}let n=r.protocol==="https:"?R(t,"https_proxy")??R(t,"http_proxy"):R(t,"http_proxy");if(n!==void 0)return ie(r,R(t,"no_proxy"))?void 0:n}var oe="https://login.salesforce.com";async function v(e,t=process.env){let{jsforce:r,HttpProxyTransport:n}=await import("./chunk-L5FGY6YA.mjs"),s=G(e.instanceUrl??e.loginUrl??oe,t),i=new r.Connection({...e,...s!==void 0?{httpProxy:s}:{}});return s===void 0&&(i._transport=new n("")),i}var ae=10*1024*1024,L=3e4,q=L+2e3,A=`sf did not answer within ${L/1e3} s \u2014 check the Salesforce CLI`;function J(e){return e instanceof Error&&e.message===A}var D=2e4;function U(e,t,r){let n,s=new Promise((i,u)=>{n=setTimeout(()=>u(new Error(r)),t)});return Promise.race([e,s]).finally(()=>clearTimeout(n))}var E=new x,ce=300*1e3,_=new Map,le={failureThreshold:3,resetTimeout:3e4},z=new Map;function Ne(){return E}function ue(e){let t=z.get(e);return t||(t=new S({...le}),z.set(e,t)),t}var Y;var b="panel";function Be(e){b=e}function fe(e,t=b){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function W(e=b){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function K(e,t){let r=t?.organization_id;if(!(!Y||typeof r!="string"))try{Y(e,{organizationId:r})}catch(n){N.warn("Identity observer threw",{orgId:e,error:O(n)})}}var de="[REDACTED]";function Z(e){return typeof e=="string"&&e.length>0&&!e.startsWith(de)&&!/\s/.test(e)}async function pe(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:r}=await import("child_process"),{promisify:n}=await import("util"),s={maxBuffer:ae,timeout:L,windowsHide:!0,env:P()},i=o=>U(n(t)("sf",o,s),q,A),u=o=>{let f=!1,h,y=new Promise((T,m)=>{h=r(o,s,(g,w)=>{f=!0,g?m(g):T({stdout:w})})});return U(y,q,A).catch(T=>{throw!f&&h?.pid!==void 0&&t("taskkill",["/pid",String(h.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},a=(o,f)=>process.platform==="win32"?u(o):i(f),c=(o,f)=>{let h=o.replace(/\[[0-9;]*m/g,""),y=h.search(/[{[]/);if(y===-1)throw new Error(`Failed to parse "${f}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(h.slice(y)).result??{}},d;try{let{stdout:o}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),f=c(o,"sf org display");d=typeof f.instanceUrl=="string"?f.instanceUrl:void 0}catch(o){if(J(o))throw o;d=void 0}try{let{stdout:o}=await a(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),f=c(o,"sf org auth show-access-token");if(Z(f.accessToken))return{accessToken:f.accessToken,instanceUrl:d}}catch(o){if(J(o))throw o}let{stdout:p}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),l=c(p,"sf org display");if(!Z(l.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof l.instanceUrl=="string"&&(d=l.instanceUrl),{accessToken:l.accessToken,instanceUrl:d}}async function Ve(e,t){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function He(e){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function je(e,t,r){let n=e,s=r.getOrg(e);if(!s)throw new Error(`Org not found: ${e}`);let i=await t.getCredentials(e);if(!i?.accessToken||!i.instanceUrl)throw new Error(`No credentials for org "${s.alias}" (${e}). Reconnect the org.`);let u=s.metadata.apiVersion||M.DEFAULT_API_VERSION,a=E.get(n),c=Date.now()-(_.get(e)??0)<ce;if(a&&a.active&&a.accessToken===i.accessToken&&c)return a.lastUsedAt=Date.now(),v({instanceUrl:a.instanceUrl,accessToken:a.accessToken,version:u});let d=await v({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:u}),p=ue(e);if(!p.acquirePermit())throw new C("ORG_TEMPORARILY_UNREACHABLE",e,`"${s.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let l=Date.now(),o=`identity check did not answer within ${D/1e3} s`;try{let f=await I(d,()=>U(d.identity(),D,o)),h=Date.now()-l;return p.recordSuccess(),E.acquire(n,i.instanceUrl,i.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,f),d}catch(f){let h=Date.now()-l;if(E.remove(n),_.delete(e),F(f))try{let m=await pe(s.username),g=m.instanceUrl??i.instanceUrl;if(m.accessToken===i.accessToken&&g===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let w=await v({instanceUrl:g,accessToken:m.accessToken,version:u}),Q=await I(w,()=>U(w.identity(),D,o));return await t.saveOrg(s,{...i,accessToken:m.accessToken,instanceUrl:g}),p.recordSuccess(),E.acquire(n,g,m.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,Q),w}catch(m){p.recordFailure();let g=O(m);r.updateStatus(e,"expired");let w=k(s,new Date().toISOString().slice(0,10));throw w!==void 0?new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${w}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${g})`):new C("ORG_AUTH_EXPIRED",e,`The session with "${s.alias}" has expired and could not be renewed. ${fe(s.alias)} (cause: ${g})`)}p.recordFailure();let y=O(f),T=k(s,new Date().toISOString().slice(0,10));throw T!==void 0?(r.updateStatus(e,"expired"),new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${y})`)):new Error(`Connection failed for "${s.alias}": ${y}`)}finally{p.releasePermit()}}export{we as a,I as b,C as c,P as d,Ee as e,j as f,ve as g,Oe as h,G as i,v as j,U as k,Ne as l,Be as m,Z as n,pe as o,Ve as p,He as q,je as r};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a}from"./chunk-6PD6K7LP.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-TNT27RBG.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as readSyncRecordTypes};
7
+ import{a}from"./chunk-SUIPDW5O.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-SZOJ7BEJ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as readSyncRecordTypes};