sandforge 1.82.0 → 1.84.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 (251) hide show
  1. package/README.md +1 -1
  2. package/lib/chunk-23SEDORH.mjs +11 -0
  3. package/lib/{chunk-7WSLT5VX.mjs → chunk-24RFOFYT.mjs} +1 -1
  4. package/lib/chunk-26POJDIT.mjs +7 -0
  5. package/lib/{chunk-SFGZFB4F.mjs → chunk-2AZQHBEF.mjs} +1 -1
  6. package/lib/{chunk-6VSZNZHH.mjs → chunk-2HVOZUM4.mjs} +1 -1
  7. package/lib/{chunk-XFU3HRUV.mjs → chunk-2JDAOWUW.mjs} +1 -1
  8. package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
  9. package/lib/chunk-2WFIVO4F.mjs +13 -0
  10. package/lib/chunk-2YHZBUZE.mjs +7 -0
  11. package/lib/{chunk-SZGGFST2.mjs → chunk-326AJTIU.mjs} +14 -14
  12. package/lib/{chunk-Q6SXNKV2.mjs → chunk-36JOHEJL.mjs} +1 -1
  13. package/lib/chunk-3PVRGTVK.mjs +7 -0
  14. package/lib/{chunk-VZVICK7Q.mjs → chunk-3Q353S2R.mjs} +1 -1
  15. package/lib/chunk-3TZSBHEY.mjs +7 -0
  16. package/lib/{chunk-UHFLKP26.mjs → chunk-43TOMFV4.mjs} +1 -1
  17. package/lib/{chunk-XK5W7BVE.mjs → chunk-4CVUUVGJ.mjs} +1 -1
  18. package/lib/{chunk-VYOYXTCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
  19. package/lib/{chunk-EOFO3PHS.mjs → chunk-4JE4BYXK.mjs} +1 -1
  20. package/lib/{chunk-7EYQYZJP.mjs → chunk-54WZUS7J.mjs} +1 -1
  21. package/lib/chunk-5CRLRHOJ.mjs +7 -0
  22. package/lib/{chunk-FA4ZKDCU.mjs → chunk-5IZTFMJM.mjs} +1 -1
  23. package/lib/chunk-5M5FQ7RP.mjs +7 -0
  24. package/lib/{chunk-3HROD5RE.mjs → chunk-5SMWFNE7.mjs} +1 -1
  25. package/lib/{chunk-YAIIRFKJ.mjs → chunk-5XTUSN72.mjs} +1 -1
  26. package/lib/chunk-6I6TWNV5.mjs +7 -0
  27. package/lib/{chunk-PYRZFUVU.mjs → chunk-6JWWSDM6.mjs} +1 -1
  28. package/lib/chunk-6O222PW6.mjs +7 -0
  29. package/lib/{chunk-2UU42PTD.mjs → chunk-6PD6K7LP.mjs} +1 -1
  30. package/lib/{chunk-GGUOIDWP.mjs → chunk-6QE6R6RL.mjs} +1 -1
  31. package/lib/{chunk-DJCGURW7.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
  32. package/lib/{chunk-DT3T7FRD.mjs → chunk-6YL7BNYD.mjs} +1 -1
  33. package/lib/chunk-6ZLKIT3H.mjs +7 -0
  34. package/lib/{chunk-CBL42DUU.mjs → chunk-7QYHEHMA.mjs} +1 -1
  35. package/lib/chunk-7SQSWVAU.mjs +9 -0
  36. package/lib/{chunk-ZUBBEP75.mjs → chunk-7UVKIWKV.mjs} +1 -1
  37. package/lib/{chunk-TWV4A5RK.mjs → chunk-7WATA4SB.mjs} +1 -1
  38. package/lib/chunk-7YNM6KFZ.mjs +7 -0
  39. package/lib/chunk-A3MYSOOC.mjs +7 -0
  40. package/lib/chunk-AL4C3GFT.mjs +7 -0
  41. package/lib/chunk-B3FBHVNN.mjs +21 -0
  42. package/lib/{chunk-27Z76O2O.mjs → chunk-B63POIPQ.mjs} +1 -1
  43. package/lib/{chunk-RTWYLOCA.mjs → chunk-BAWCOKRW.mjs} +1 -1
  44. package/lib/{chunk-NWOI25WY.mjs → chunk-BBRWFKS5.mjs} +1 -1
  45. package/lib/chunk-BEA27DLS.mjs +7 -0
  46. package/lib/chunk-BRY3PLIZ.mjs +7 -0
  47. package/lib/chunk-CBH3TOWK.mjs +341 -0
  48. package/lib/chunk-CPQIZGG5.mjs +7 -0
  49. package/lib/chunk-CVHNXJH3.mjs +7 -0
  50. package/lib/{chunk-HFUDCNU5.mjs → chunk-D4GF4FAB.mjs} +1 -1
  51. package/lib/chunk-DGDRQRCW.mjs +7 -0
  52. package/lib/{chunk-YAJQS3OL.mjs → chunk-DPMRIMUC.mjs} +1 -1
  53. package/lib/chunk-DUN2EPRC.mjs +7 -0
  54. package/lib/chunk-E3A3LOCY.mjs +7 -0
  55. package/lib/{chunk-TMA34QMA.mjs → chunk-EAC5QCE3.mjs} +1 -1
  56. package/lib/{chunk-VQJMP3DC.mjs → chunk-EC72TIEG.mjs} +1 -1
  57. package/lib/chunk-EPFCERGL.mjs +7 -0
  58. package/lib/{chunk-3MGMNK3Q.mjs → chunk-ETDCBLGU.mjs} +1 -1
  59. package/lib/{chunk-LXDSRP2W.mjs → chunk-F3AQW6IU.mjs} +1 -1
  60. package/lib/{chunk-A65ADTCR.mjs → chunk-FITPY3L4.mjs} +1 -1
  61. package/lib/chunk-FNJ4SGWO.mjs +7 -0
  62. package/lib/{chunk-SAMWHL22.mjs → chunk-FP7CYB2F.mjs} +1 -1
  63. package/lib/{chunk-JLZRZL5E.mjs → chunk-GKY2JMHY.mjs} +1 -1
  64. package/lib/chunk-GMIGWR6U.mjs +7 -0
  65. package/lib/{chunk-AUS6NFLZ.mjs → chunk-GNRSF65U.mjs} +1 -1
  66. package/lib/chunk-GOOVPVWX.mjs +7 -0
  67. package/lib/{chunk-PPHVWUFY.mjs → chunk-GWZRR3MM.mjs} +1 -1
  68. package/lib/{chunk-JH27IKCO.mjs → chunk-H2BHESDA.mjs} +2 -2
  69. package/lib/chunk-H33DVU3D.mjs +7 -0
  70. package/lib/chunk-H4CGM6YO.mjs +7 -0
  71. package/lib/{chunk-WOOUISSO.mjs → chunk-HCGXK7G7.mjs} +1 -1
  72. package/lib/{chunk-VZT4E2OJ.mjs → chunk-HIDW7FNV.mjs} +1 -1
  73. package/lib/chunk-HSBXRQTI.mjs +7 -0
  74. package/lib/chunk-HUZPBE47.mjs +7 -0
  75. package/lib/chunk-HV7VPEXP.mjs +7 -0
  76. package/lib/chunk-I6E6T6YY.mjs +7 -0
  77. package/lib/chunk-IUM4NFKI.mjs +10 -0
  78. package/lib/chunk-IVFVNNGB.mjs +37 -0
  79. package/lib/{chunk-5K2I2DMP.mjs → chunk-IZGCEOYO.mjs} +1 -1
  80. package/lib/{chunk-ZHIZY3ZC.mjs → chunk-J3DND3BC.mjs} +1 -1
  81. package/lib/{chunk-VPDEJGPS.mjs → chunk-JAEDM4SI.mjs} +1 -1
  82. package/lib/chunk-JCFBFF4Y.mjs +7 -0
  83. package/lib/{chunk-GBGHJTPC.mjs → chunk-JE6SCT6R.mjs} +1 -1
  84. package/lib/chunk-JGZPD4IM.mjs +7 -0
  85. package/lib/{chunk-C3LNYAVJ.mjs → chunk-JKJ74BX5.mjs} +1 -1
  86. package/lib/{chunk-EEFUE2ES.mjs → chunk-JLSIWO4Z.mjs} +1 -1
  87. package/lib/{chunk-3CX7GPCR.mjs → chunk-JSAJS3MY.mjs} +1 -1
  88. package/lib/chunk-JTJK2D36.mjs +7 -0
  89. package/lib/{chunk-V3R45ZWT.mjs → chunk-KAZS5Z6W.mjs} +1 -1
  90. package/lib/chunk-KB4ZHM4Q.mjs +10 -0
  91. package/lib/{chunk-J24TIGSI.mjs → chunk-KGU4SVIT.mjs} +1 -1
  92. package/lib/chunk-KJWFYBMU.mjs +15 -0
  93. package/lib/{chunk-H4JUYUSL.mjs → chunk-KZTZDC7H.mjs} +1 -1
  94. package/lib/chunk-L2E5WBGD.mjs +8 -0
  95. package/lib/{chunk-XU25YA46.mjs → chunk-L53JWJ3S.mjs} +1 -1
  96. package/lib/{chunk-Y4TDVDP2.mjs → chunk-LA4KIATH.mjs} +6 -6
  97. package/lib/chunk-LC3NDW4N.mjs +7 -0
  98. package/lib/{chunk-GCGHHN4K.mjs → chunk-LKTNQEBS.mjs} +1 -1
  99. package/lib/chunk-M2ABR4JM.mjs +7 -0
  100. package/lib/{chunk-3C2ZZIFN.mjs → chunk-M4BLK6HJ.mjs} +1 -1
  101. package/lib/{chunk-L4INJ5TZ.mjs → chunk-M6K34KGF.mjs} +1 -1
  102. package/lib/chunk-MDMPJEV3.mjs +7 -0
  103. package/lib/{chunk-32EUNQT6.mjs → chunk-MJZU3U5O.mjs} +68 -63
  104. package/lib/{chunk-PBE44M2Y.mjs → chunk-MSIEU5MR.mjs} +1 -1
  105. package/lib/{chunk-NLB3RGIY.mjs → chunk-N4WPCWJO.mjs} +1 -1
  106. package/lib/{chunk-SNEOKYV7.mjs → chunk-NCZKWSC7.mjs} +1 -1
  107. package/lib/{chunk-6KP6WETK.mjs → chunk-NED4MBIM.mjs} +1 -1
  108. package/lib/chunk-NOBQTEQD.mjs +7 -0
  109. package/lib/{chunk-RCYEBY42.mjs → chunk-NSQWI7ZY.mjs} +1 -1
  110. package/lib/{chunk-DBBPDSFN.mjs → chunk-O677VOGO.mjs} +1 -1
  111. package/lib/chunk-OFTT7J2M.mjs +7 -0
  112. package/lib/{chunk-C2N2TNEU.mjs → chunk-OLCVHL7I.mjs} +1 -1
  113. package/lib/chunk-OM5NORJG.mjs +7 -0
  114. package/lib/chunk-OMNMLKDT.mjs +7 -0
  115. package/lib/{chunk-CELEBWEZ.mjs → chunk-OPMO6I45.mjs} +1 -1
  116. package/lib/{chunk-LHU6CPGE.mjs → chunk-OUZQPYT3.mjs} +1 -1
  117. package/lib/chunk-OVNMB6Q2.mjs +7 -0
  118. package/lib/{chunk-6GQUZ4IP.mjs → chunk-PAXNWTYK.mjs} +1 -1
  119. package/lib/{chunk-XSKPYGMT.mjs → chunk-PBY2O6OF.mjs} +1 -1
  120. package/lib/chunk-PEDQPM2P.mjs +926 -0
  121. package/lib/chunk-PH7SP4YK.mjs +21 -0
  122. package/lib/{chunk-3SKLBRPL.mjs → chunk-PMN4PAC3.mjs} +1 -1
  123. package/lib/chunk-PMWAFDUB.mjs +48 -0
  124. package/lib/chunk-PPLVFX6N.mjs +7 -0
  125. package/lib/{chunk-STRMWSIQ.mjs → chunk-PR3XCSPO.mjs} +1 -1
  126. package/lib/{chunk-GJ6SZVHT.mjs → chunk-PR42EZSR.mjs} +1 -1
  127. package/lib/{chunk-YMDFF657.mjs → chunk-PWRJRL5U.mjs} +1 -1
  128. package/lib/{chunk-Q3DY7TO2.mjs → chunk-Q7GIJBCD.mjs} +1 -1
  129. package/lib/chunk-Q7TLC3I2.mjs +7 -0
  130. package/lib/{chunk-ZXFL2MSN.mjs → chunk-QAFPQ3YB.mjs} +1 -1
  131. package/lib/{chunk-T7WREYA5.mjs → chunk-QKEKG2LD.mjs} +1 -1
  132. package/lib/chunk-QO53K5W2.mjs +9 -0
  133. package/lib/{chunk-MUEQRIK7.mjs → chunk-QTG6LUZT.mjs} +1 -1
  134. package/lib/{chunk-KP5G6FUC.mjs → chunk-RE7RYF3B.mjs} +1 -1
  135. package/lib/{chunk-FOIWWK7G.mjs → chunk-RGBGUCJA.mjs} +1 -1
  136. package/lib/{chunk-DWMRIWV5.mjs → chunk-RGUQOSBU.mjs} +1 -1
  137. package/lib/{chunk-7PY3VQP3.mjs → chunk-RHNTHGNU.mjs} +1 -1
  138. package/lib/chunk-RKTFFCNS.mjs +7 -0
  139. package/lib/chunk-RMFU4BAL.mjs +28 -0
  140. package/lib/{chunk-KKOA62S4.mjs → chunk-ROV3QXEF.mjs} +14 -13
  141. package/lib/chunk-RT47RKLY.mjs +7 -0
  142. package/lib/{chunk-ZUTUYBNW.mjs → chunk-S42RBRH2.mjs} +1 -1
  143. package/lib/{chunk-Z42PHCVZ.mjs → chunk-SI267LYR.mjs} +1 -1
  144. package/lib/chunk-T3G6VZNS.mjs +7 -0
  145. package/lib/chunk-TNT27RBG.mjs +7 -0
  146. package/lib/chunk-UBIKR5VO.mjs +7 -0
  147. package/lib/chunk-UI3JQVRU.mjs +8 -0
  148. package/lib/{chunk-YT22LMF7.mjs → chunk-UIOMAX56.mjs} +1 -1
  149. package/lib/chunk-UX3BVH2Y.mjs +7 -0
  150. package/lib/chunk-VCUXCK36.mjs +7 -0
  151. package/lib/chunk-VINGECAJ.mjs +10 -0
  152. package/lib/chunk-VOXJHJIE.mjs +7 -0
  153. package/lib/chunk-W6PN6TJG.mjs +7 -0
  154. package/lib/{chunk-FKK5YBGZ.mjs → chunk-WAPSSYMT.mjs} +1 -1
  155. package/lib/{chunk-PR74GYVI.mjs → chunk-WUUKFE2U.mjs} +1 -1
  156. package/lib/chunk-WWTCWWZI.mjs +7 -0
  157. package/lib/chunk-WXDLQT2O.mjs +10 -0
  158. package/lib/chunk-WY5V5PR3.mjs +7 -0
  159. package/lib/chunk-X4BXESMQ.mjs +7 -0
  160. package/lib/chunk-XBQGZGWR.mjs +7 -0
  161. package/lib/chunk-XGGOUNPP.mjs +7 -0
  162. package/lib/chunk-XKWW3GKF.mjs +7 -0
  163. package/lib/{chunk-JJITOWZK.mjs → chunk-Y2DRK37K.mjs} +1 -1
  164. package/lib/{chunk-XZISAZA6.mjs → chunk-YA6ATMTB.mjs} +1 -1
  165. package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
  166. package/lib/chunk-YHR4WQPR.mjs +7 -0
  167. package/lib/{chunk-KJYEQHYP.mjs → chunk-YTLUYSMF.mjs} +1 -1
  168. package/lib/chunk-YWEQQL3C.mjs +8 -0
  169. package/lib/{chunk-PWVDNN2C.mjs → chunk-Z4LKKOFY.mjs} +1 -1
  170. package/lib/chunk-ZBAWJUG2.mjs +7 -0
  171. package/lib/{chunk-XO5FBOQF.mjs → chunk-ZJW6YOMV.mjs} +1 -1
  172. package/lib/chunk-ZQQXSCVI.mjs +7 -0
  173. package/lib/{chunk-47UHTN3Q.mjs → chunk-ZQWIVYVM.mjs} +1 -1
  174. package/lib/chunk-ZV7ZFQQC.mjs +9 -0
  175. package/lib/sandforge-autopilot.mjs +25 -25
  176. package/lib/sandforge-backup.mjs +1 -1
  177. package/lib/sandforge-checkpoint.mjs +1 -1
  178. package/lib/sandforge-cleanup.mjs +1 -1
  179. package/lib/sandforge-clone.mjs +1 -1
  180. package/lib/sandforge-compare.mjs +52 -21
  181. package/lib/sandforge-dataops.mjs +1 -1
  182. package/lib/sandforge-empty.mjs +4 -4
  183. package/lib/sandforge-env.mjs +106 -107
  184. package/lib/sandforge-frozen.mjs +1 -1
  185. package/lib/sandforge-mcp.mjs +12 -12
  186. package/lib/sandforge-monitor.mjs +1 -1
  187. package/lib/sandforge-pipeline.mjs +1 -1
  188. package/lib/sandforge-seed.mjs +1 -1
  189. package/lib/sandforge-sync.mjs +1 -1
  190. package/lib/sandforge-users.mjs +21 -23
  191. package/lib/sandforge.mjs +1 -1
  192. package/lib/sf/sandforge/compare.mjs +2 -2
  193. package/lib/sfPlugin.mjs +1 -1
  194. package/oclif.manifest.json +1 -1
  195. package/package.json +1 -1
  196. package/lib/chunk-2JZGCCPG.mjs +0 -9
  197. package/lib/chunk-3HEMJTAP.mjs +0 -925
  198. package/lib/chunk-3XG25GTF.mjs +0 -7
  199. package/lib/chunk-42BFLWHR.mjs +0 -7
  200. package/lib/chunk-466F37VD.mjs +0 -7
  201. package/lib/chunk-4JKR4PTZ.mjs +0 -8
  202. package/lib/chunk-52EXDVPN.mjs +0 -7
  203. package/lib/chunk-7CVDVBEE.mjs +0 -7
  204. package/lib/chunk-7LKI7OAS.mjs +0 -7
  205. package/lib/chunk-7SDZR6SR.mjs +0 -7
  206. package/lib/chunk-A32ISQ6M.mjs +0 -28
  207. package/lib/chunk-A7JJWOLT.mjs +0 -7
  208. package/lib/chunk-BMTNTBBM.mjs +0 -7
  209. package/lib/chunk-BN33LVPQ.mjs +0 -7
  210. package/lib/chunk-BZ24IAP5.mjs +0 -7
  211. package/lib/chunk-CCEH7L53.mjs +0 -7
  212. package/lib/chunk-CV47FDQW.mjs +0 -7
  213. package/lib/chunk-CZLJZQCS.mjs +0 -7
  214. package/lib/chunk-DIL62SUN.mjs +0 -7
  215. package/lib/chunk-DIS254AN.mjs +0 -7
  216. package/lib/chunk-FZF23M6R.mjs +0 -7
  217. package/lib/chunk-G2JR3F63.mjs +0 -7
  218. package/lib/chunk-GGNUACTY.mjs +0 -7
  219. package/lib/chunk-GHPR5UVV.mjs +0 -7
  220. package/lib/chunk-HIHCYMSL.mjs +0 -7
  221. package/lib/chunk-HKUWHVI7.mjs +0 -9
  222. package/lib/chunk-HQQVANWQ.mjs +0 -20
  223. package/lib/chunk-IRZJU2PG.mjs +0 -22
  224. package/lib/chunk-ISSP2FZ5.mjs +0 -7
  225. package/lib/chunk-IVZJSDJD.mjs +0 -7
  226. package/lib/chunk-JESRFE2Z.mjs +0 -11
  227. package/lib/chunk-JFNLKHY6.mjs +0 -8
  228. package/lib/chunk-JKT5YAQ2.mjs +0 -7
  229. package/lib/chunk-JQZTMFO7.mjs +0 -7
  230. package/lib/chunk-KIMQQ6JQ.mjs +0 -7
  231. package/lib/chunk-LAUOSXMN.mjs +0 -341
  232. package/lib/chunk-MKTXJCXN.mjs +0 -10
  233. package/lib/chunk-O2PUGRNW.mjs +0 -10
  234. package/lib/chunk-O4BROUGM.mjs +0 -7
  235. package/lib/chunk-P55MKIZX.mjs +0 -37
  236. package/lib/chunk-P63WJMXQ.mjs +0 -7
  237. package/lib/chunk-PE435FVH.mjs +0 -15
  238. package/lib/chunk-PPGDAUEQ.mjs +0 -7
  239. package/lib/chunk-QAPVKPEC.mjs +0 -7
  240. package/lib/chunk-RLWB7F26.mjs +0 -7
  241. package/lib/chunk-RYRMUPMY.mjs +0 -7
  242. package/lib/chunk-SCKUIE3R.mjs +0 -7
  243. package/lib/chunk-SU65Z2BA.mjs +0 -7
  244. package/lib/chunk-TCBAE65A.mjs +0 -7
  245. package/lib/chunk-WEMLDUQA.mjs +0 -7
  246. package/lib/chunk-WSUKC2U3.mjs +0 -7
  247. package/lib/chunk-WT3SCUHS.mjs +0 -7
  248. package/lib/chunk-YGJF55VJ.mjs +0 -7
  249. package/lib/chunk-YH4DYI6D.mjs +0 -7
  250. package/lib/chunk-ZQO5PDX5.mjs +0 -48
  251. package/lib/chunk-ZUOPC4W2.mjs +0 -7
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Se}from"./chunk-YYZL7UGV.mjs";import{a as be,f as we,i as ke,j as ve,l as te}from"./chunk-54HYHHVL.mjs";import{a as Le,b as je,c as $e,d as Pe,e as _,f as _e,g as xe,h as D,i as ne,l as Me,o as Je}from"./chunk-WSUKC2U3.mjs";import{a as E}from"./chunk-4TLYUZD5.mjs";import{c as Oe}from"./chunk-HF6LAK3G.mjs";import{a as P,b as Fe,d as Be,e as Ce,f as ee,h as Ne,i as We,j as Ee}from"./chunk-HFUDCNU5.mjs";import{Y as ce,Z as fe,_ as he,a as X,ba as pe,ca as ge,d as Q,fa as ye,ha as me,ia as Re}from"./chunk-KIMQQ6JQ.mjs";import{b as I}from"./chunk-CA5NAXSU.mjs";import{d as Ie,e as Z,f as Ae,k as Te}from"./chunk-ZUTUYBNW.mjs";import{Bc as le,dd as ue,gc as Y}from"./chunk-ZQO5PDX5.mjs";function Ye(a){return Array.isArray(a)?a.length:(a.successfulResults?.length??0)+(a.failedResults?.length??0)}function Ue(a,e){let t=!1,n=!1,s,r={},o=0,i=0,d=(c,p)=>(i+=c,e?.(c),p()),l=async c=>{let p=await d(We,c);return o=Ye(p),p},u={createJob:c=>{let p=a.bulk2.createJob(c);return{get id(){return p.id},open:async()=>{await d(1,()=>p.open()),s=Ce(p)},uploadData:w=>d(1,()=>p.uploadData(w)),close:async()=>{t=!0,await d(1,()=>p.close()),n=!0},abort:()=>d(1,()=>p.abort()),check:async()=>{let w=await d(1,()=>p.check());return r={state:w.state,message:w.errorMessage},w},getAllResults:()=>l(()=>p.getAllResults())}}};if("job"in a.bulk2){let c=a.bulk2;u.job=(p,w)=>{let R=c.job(p,w);return{check:async()=>{let y=await d(1,()=>R.check());return r={state:y.state,message:y.errorMessage??void 0},y},getSuccessfulResults:()=>d(1,()=>R.getSuccessfulResults()),getAllResults:()=>l(()=>R.getAllResults()),abort:()=>d(1,()=>R.abort())}}}return{connection:{bulk2:u},closeSent:()=>t,closed:()=>n,jobId:()=>s,last:()=>r,processed:()=>o,requests:()=>i}}var L=class extends Error{constructor(t,n,s=0,r=[]){super(`Bulk API job ${t||"(no id)"} was closed, and what it wrote could not be read back: ${n}`);this.jobId=t;this.requests=s;this.twins=r;this.name="BulkJobLostError"}jobId;requests;twins},M=1e4,q=50*1024*1024,Xe=10,Qe=/not supported by the Bulk API|InvalidEntity/i,Ze={unprocessed:"The Bulk API job did not write this row.",twin:"Kept out of the Bulk API job: another row carries the same values, and the job's results could not tell them apart.","may-have-written":"The Bulk API job may have written this row without saying so: it is not sent again."};async function Pt(a,e,t,n,s,r={}){let o=n==="insert"?s.map(nt):s,i=Fe(P(n,o,r.externalIdField)),d=[];o.forEach((k,A)=>{i.has(A)||d.push(A)});let l=d.map(k=>o[k]),u=o.map((k,A)=>i.has(A)?"twin":"unprocessed"),c=k=>({answers:u.map(A=>x(A==="twin"?"twin":"unprocessed")),rows:u,unmatchedIds:[],...k});if(l.length===0)return c({requests:0});let p=P(n,l,r.externalIdField),w=Buffer.byteLength(p.text,"utf8");if(l.length>M||w>q)return c({requests:0,untouched:{reason:`${l.length} rows, ${w} bytes of CSV: past what one job takes (${M} rows, ${q} bytes)`}});let R=(k,A,h,v)=>{let F={requests:k.requests,...k.jobId?{jobId:k.jobId}:{}};if(k.info.state!=="JobComplete"&&k.processed===0&&v===0)return c({...F,untouched:re(ee(k.info)??"job not complete")});let W=new Map(A.map(m=>[m.recordIndex,m])),f=u.map(m=>x(m==="twin"?"twin":"unprocessed"));return d.forEach((m,S)=>{let N=tt(W.get(S),v>0);u[m]=N.state,f[m]=N.answer}),{answers:f,rows:u,unmatchedIds:[...h],...F}},y=Ue(a),b,T=()=>b?{jobId:b}:{},B=r.pollDelay??Ee,g;try{g=await new Ne().executeBulk({connection:y.connection,bulkManager:e,pollIntervalMs:B,...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{},onOpened:k=>{b=k,r.onOpened?.(k)}},t,n,l,r.externalIdField)}catch(k){let A=I(k);if(!y.closeSent())return c({requests:y.requests(),...T(),untouched:re(A)});if(b===void 0)throw new L("",A,y.requests(),[...i]);let h=await et(y.connection,b,B);if(h.state==="never-closed")return c({requests:y.requests(),jobId:b,untouched:re(A)});if(h.state!=="ended")throw new L(b,h.state==="unread"?h.reason:"still running",y.requests(),[...i]);let v=Be(h.results,p,ee(h.info));return R({info:h.info,processed:y.processed(),requests:y.requests(),jobId:b},v.outcomes,v.unattributedSuccessIds,v.unattributedSuccesses)}if(g.aborted)return c({requests:y.requests(),...T(),aborted:!0});let C=y.last();return R({info:{state:C.state??"JobComplete",...C.message?{errorMessage:C.message}:{}},processed:y.processed(),requests:y.requests(),...T()},g.outcomes,g.unmatchedIds??[],g.unmatchedWrites??0)}async function et(a,e,t){let n=await te(a,e,{openGraceMs:0});for(let s=1;s<Xe;s++){if(n.state==="ended"||n.state==="never-closed")return n;await new Promise(r=>setTimeout(r,t(s-1))),n=await te(a,e,{openGraceMs:0})}return n}function re(a){return Qe.test(a)?{reason:a,unsupported:!0}:{reason:a}}function x(a){return{id:"",success:!1,errors:[Ze[a]]}}function tt(a,e){if(a===void 0||a.state==="no-result"){let s=e?"may-have-written":"unprocessed";return{state:s,answer:x(s)}}if(a.state==="unprocessed")return{state:"unprocessed",answer:x("unprocessed")};if(a.success)return a.id?{state:"answered",answer:{id:a.id,success:!0,errors:[],...a.created!==void 0?{created:a.created}:{}}}:{state:"may-have-written",answer:x("may-have-written")};let t=a.error??"Unknown error",n=Ie(t);return{state:"answered",answer:n?{id:"",success:!1,errors:[Ae(n)],errorDetails:[n]}:{id:"",success:!1,errors:[t]}}}function nt(a){let e;for(let[t,n]of Object.entries(a))n===""&&(e??={...a},e[t]=null);return e??a}var ae={rest:200,bulk:1e4},Ke=3,ot=3,De=3,it=2e3;function at(a){return new Promise(e=>setTimeout(e,a))}function dt(a,e,t={bulk:!1}){let n=t.bulk&&a.api==="bulk"&&e>=2e3?"bulk":"rest",s=Math.min(a.batchSize,ae[n]);return{api:n,batchSize:s,batchCount:Math.ceil(e/s),clamped:s<a.batchSize}}function z(a){return a.refusals.flatMap(e=>e.leftOut)}function se(a){let e=a.built?.source.Id;return typeof e=="string"?e:void 0}function qe(a){return(a.built?.nullifiedFks??[]).map(({field:e,sourceRefId:t,insertOnly:n})=>({field:e,sourceRefId:t,...n?{insertOnly:n}:{}}))}function lt(a){let e=a.RecordTypeId;return typeof e=="string"&&e!==""}function oe(a){return a.refusals.length===0?a.payload:D(a.payload,z(a))}function He(a,e){let t=new Map;return e?.refusedIn?.answers.forEach((n,s)=>{let r=a[s];n&&r&&t.set(r,n.errors)}),t}var ut=new Set,ct=new Map;function H(a){return{objectApiName:a.objectApiName,op:a.upsertField?"upsert":"insert"}}function Ve(a){return a!==void 0&&!a.success?ue(a.errors):void 0}function ft(a){let e=a.automation??"the target's automation";E.warn(`[forge] ${a.objectApiName}: ${e} hit ${a.limit??"a Salesforce limit"} on a call of ${a.from} \u2014 sending a record on its own, then smaller calls`+(a.op==="upsert"?" (upsert).":"."))}var V={"validation-rule":"a validation rule","restricted-picklist":"a restricted picklist","lookup-filter":"a lookup filter","inactive-owner":"the target, the owner being inactive there"};function ht(a){let e=new Set(a.map(o=>o.refusedBy)),t=Object.keys(V).filter(o=>o!=="inactive-owner"&&e.has(o)).map(o=>V[o]),n=t.length>1?`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`:t[0],s=n===void 0?void 0:`${n} of the target`;if(!e.has("inactive-owner"))return s??`${V["validation-rule"]} of the target`;let r=`${V["inactive-owner"]},`;return s===void 0?r:`${s} or ${r}`}function ie(a,e){if(!a.ownersMapped||a.ownersMapped.size===0)return!1;let t=_(e,"OwnerId"),n=t===void 0?void 0:e[t];return typeof n=="string"&&a.ownersMapped.has(n.slice(0,15))}function pt(a,e,t,n,s){let r=a.errorDetails??[];if(r.length===a.errors.length)return _e(r,e,t,n,s)}function ze(a){a.linkedToCreatedCount=(a.linkedToCreatedCount??0)+1}function gt(a){let e=a.errorDetails??[];return Je(a.errors,e.length===a.errors.length?e:void 0)}function G(a){return a.map(e=>e.field).join(", ")}function yt(a,e){return`Sent again without ${G(a)} after the first refusal: ${e.join("; ")}`}var mt=["first","second","third"];function J(a){return a.map(({leftOut:e,errors:t},n)=>n===0?yt(e,t):`Sent again without ${G(e)} too after the ${mt[n]} refusal: `+t.join("; "))}function U(a){let e=(t,n)=>t.length===0?[]:[`Sent without ${G(t)}: ${n} earlier in the run, `+[...new Set(t.map(s=>s.reason))].join("; ")];return[...e(a.filter(t=>t.refusedBy!=="inactive-owner"),"the target refused the same value under the same record type"),...e(a.filter(t=>t.refusedBy==="inactive-owner"),"the target refused the same owner, inactive there,")]}function O(a){return`${a} record${a===1?"":"s"}`}var Rt="The call was sent and its answer never came back: the target may hold any of these records, and which of them is unknown. Counted as failed and never sent again, they are not among the records the run created, which removing its records takes back.",bt="Counted as failed and never sent again, they are not among the records the run created; the records the job wrote that no row was matched to are, and removing the run's records takes them back.",wt="DUPLICATES_DETECTED";function kt(a,e){if(a==="twin"||a==="unprocessed")return!0;if(a!=="answered"||e.success)return!1;let t=e.errorDetails;return t?.length!==1||t[0].statusCode===wt}function vt(a,e){let t=i=>i.reduce((d,l)=>d+Math.max(Buffer.byteLength(l,"utf8"),4)+(l.split('"').length-1)+3,1),n=t(e.columns),s=[],r=0,o=n;return e.rows.forEach((i,d)=>{let l=t(i);d>r&&o+l>a&&(s.push([r,d]),r=d,o=n),o+=l}),e.rows.length>r&&s.push([r,e.rows.length]),s}function It(a,e,t){let n=a.find(r=>r.isReference&&r.nillable===!1&&r.name!=="OwnerId"&&e.has(r.name))?.name;if(n===void 0)return;let s=r=>{let o=t[r][n];return typeof o=="string"?o:""};if(t.some((r,o)=>s(o)!==""))return t.map((r,o)=>o).sort((r,o)=>{let i=s(r),d=s(o);return i===d?r-o:i===""?1:d===""||i<d?-1:1})}var At="The target refused the call for its API request limit, which no retry gets past: the node stopped there.",Tt="A validation rule of the target, or a trigger with its code, refused the row without naming a field: there was none to send it again without.";function Ft(){return{successCount:0,updatedCount:0,linkedExistingCount:0,failureCount:0,alreadyExistsCount:0,unidentifiedExistingCount:0,errorSamples:[],pendingFkUpdates:[]}}var Ge=class{constructor(e,t,n=at,s=be()){this.deps=e;this.wait=n;this.splitting=s;this.batchStrategy=t??new Oe}deps;wait;splitting;batchStrategy;refusedValues=new Map;refusedOwners=new Map;backoff=new Me({initialDelay:it});async writeNode(e,t=Ft()){let{node:n,fieldInfos:s,creatableFields:r,targetOrgId:o,remapper:i}=e,d=await this.heldBeforeInsert(n.objectApiName,o,e.records);for(let[h,v]of d){let F=e.cleanedRecords[h]?.source,W=F?.Id;if(typeof W!="string")continue;i.addExisting(W,v,n.objectApiName);let f=F?.ContactId;n.objectApiName===X&&typeof f=="string"&&i.wasCreated(f)&&(t.withTheirRecord=[...t.withTheirRecord??[],W])}t.linkedExistingCount+=d.size;let l=await this.giveFlagsBack(n.objectApiName,o,e,d);l&&(t.flagsNotKept=pe(t.flagsNotKept,l));let u=e.records.filter((h,v)=>!d.has(v)),c=e.cleanedRecords.filter((h,v)=>!d.has(v)),p=this.batchStrategy.resolve(n.batchStrategy,u.length),{api:w,batchSize:R,batchCount:y,clamped:b}=dt(p,u.length,{bulk:this.jobsCanCarry(e.bulk,n.objectApiName)});if(b&&E.warn(`[forge] ${n.objectApiName}: batch strategy asked for ${p.batchSize} records per call (api="${p.api}") but the write path is "${w}" (max ${ae[w]}) \u2014 using ${R} per call (${y} batch(es)).`),w==="bulk"){let h=It(s,r,u);if(h){let v={records:u,cleanedRecords:c};u=h.map(F=>v.records[F]),c=h.map(F=>v.cleanedRecords[F])}}e.onProgress({objectName:n.objectApiName,status:"running",progress:0,recordCount:u.length,fieldCount:s.length,createableFieldCount:r.size,message:`Inserting ${u.length} ${n.objectApiName} records in ${y} batch(es)...`});let T=0,B=this.pickUpsertField(s,r,u,e.upsertMode==="auto"&&this.deps.upsertRecords?"auto":"off",e.tableKeys),g={objectApiName:n.objectApiName,targetOrgId:o,targetKeyPrefix:e.targetKeyPrefix,remapper:i,tally:t,oweLookups:e.oweLookups,onWritten:e.onWritten,onCreatedWithoutRecordType:e.onCreatedWithoutRecordType,calls:e.calls,bulk:e.bulk,byNaturalKey:[],refusedOnTheirFields:[],locked:[],upsertField:B,ownersMapped:e.ownersMapped,remembered:new Set([...e.picklistFields??[]].filter(([,h])=>h.controllerName===void 0).map(([h])=>h.toLowerCase()))},{byNaturalKey:C}=g,k=h=>{let v=I(h);this.leaveLockedAsFailed(g,g.locked.splice(0),v),this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),v),this.settleByNaturalKey(n.objectApiName,C,[],i,t,`The record the target holds under the same key was not looked up: ${v}`)};for(let h=0;h<y;h++){let v=u.slice(h*R,(h+1)*R).map((m,S)=>{let{sent:N,before:$}=this.withoutRefusedValues(g,m);return{payload:N,built:c[T+S],before:$,refusals:[],lockResends:0}}),F=`${n.objectApiName} batch ${h+1}/${y}`,W;try{W=await this.sendRows(g,e,v,F,u.length-T-v.length)}catch(m){throw k(m),m}if(W){let m=I(W.thrown);this.leaveLockedAsFailed(g,g.locked.splice(0),m),this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),m);break}T+=v.length;let f;try{f=await this.sendLockedAgain(g,e,u.length-T)}catch(m){throw k(m),m}if(f){this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),I(f.thrown));break}e.onProgress({objectName:n.objectApiName,status:"running",progress:Math.round((h+1)/y*100),message:`batch ${h+1}/${y} \u2014 ${Math.min((h+1)*R,u.length)}/${u.length} records`})}try{await this.writeAgainWithoutTheirFields(g,e,Math.min(R,ae.rest))}catch(h){throw k(h),h}let A=Q[n.objectApiName];if(A&&C.length>0){let h,v;try{h=await this.recordsByNaturalKey(o,n.objectApiName,A,C.map(F=>F.payload))}catch(F){h=[],v=`The record the target holds under the same key could not be looked up: ${I(F)}`}this.settleByNaturalKey(n.objectApiName,C,h,i,t,v)}return t}send(e,t){return e.upsertField&&this.deps.upsertRecords?this.deps.upsertRecords(e.targetOrgId,e.objectApiName,e.upsertField,t):this.deps.insertRecords(e.targetOrgId,e.objectApiName,t)}jobsCanCarry(e,t){return e!==void 0&&this.deps.bulkWriteRecords!==void 0&&!e.restOnly.has(t)&&!e.bulkUnsupported.has(t)}goesSmallerByRest(e){return this.splitting.sizes.of(e)<200}async sendRows(e,t,n,s,r,o){let{bulk:i}=e;if(!i||!this.jobsCanCarry(i,e.objectApiName)||n.length<2e3)return this.sendByRest(e,t,n,s,r,o);for(let d=0;d<n.length;d+=M){let l=n.slice(d,d+M),u=n.length-d-l.length+r,c;try{c=l.length>=2e3?await this.writeAsJobs(e,t,i,l,s,u,o):await this.sendByRest(e,t,l,s,u,o)}catch(p){throw o?.(n.slice(d+l.length),I(p)),p}if(c)return c}}async sendByRest(e,t,n,s,r,o,i){if(n.length===0)return;try{await t.waitIfPaused()}catch(l){let u=I(l);throw o?o(n,u):this.leaveLimitedAsFailed(e,n,He(n,i),u),l}let d=await this.callAndSettle(e,t,n,o,i);if(d)return this.settleThrown(e,d.threw,d.rows,s,d.rest.length+r),d.threw}async writeAsJobs(e,t,n,s,r,o,i){let d=this.deps.bulkWriteRecords;if(!d)return this.sendByRest(e,t,s,r,o,i);let l=H(e);if(this.goesSmallerByRest(l))return this.sendJobByRest(e,t,n,s,r,o,i);let u=e.upsertField?"upsert":"insert",c=s.map(oe),p=vt(q,P(u,c,e.upsertField));for(let[w,R]of p){let y=s.slice(w,R),b=s.length-R+o;if(this.goesSmallerByRest(l)){let f;try{f=await this.sendJobByRest(e,t,n,y,r,b,i)}catch(m){throw i?.(s.slice(R),I(m)),m}if(f)return f;continue}try{await t.waitIfPaused()}catch(f){throw i?.(s.slice(w),I(f)),f}let T=c.slice(w,R),B=e.calls?.sending(e.objectApiName,y.map((f,m)=>({sourceId:se(f),payload:T[m],owes:qe(f)})),e.upsertField,!0),g;try{g=await d(e.targetOrgId,e.objectApiName,u,T,{bulkManager:n.manager,signal:n.signal,...e.upsertField?{externalIdField:e.upsertField}:{},onOpened:f=>{B!==void 0&&e.calls?.opened?.(B,f)}})}catch(f){if(f instanceof L){let m={thrown:f,left:"may-have-written",tries:1},S=new Set(f.twins),N=y.filter(($,de)=>!S.has(de));return this.settleThrown(e,m,N,`${r} (Bulk API job)`,b),this.leaveTwinsUnsent(e,y.length-N.length,r,f),m}g={answers:[],rows:[],unmatchedIds:[],untouched:{reason:I(f)},requests:0}}if(g.aborted){try{await t.waitIfPaused()}catch(f){throw B!==void 0&&e.calls?.answered(B),i?.(s.slice(w),I(f)),f}g={...g,untouched:{reason:"the job was aborted"}}}if(g.untouched){B!==void 0&&e.calls?.answered(B),g.untouched.unsupported&&n.bulkUnsupported.add(e.objectApiName),E.warn(`[forge] ${e.objectApiName}: a Bulk API job of ${O(y.length)} wrote nothing (${g.untouched.reason}) \u2014 sent by REST`+(g.untouched.unsupported?", as every write of the object in the run.":"."));let f;try{f=await this.sendByRest(e,t,y,r,b,i)}catch(m){throw i?.(s.slice(R),I(m)),m}if(f)return f;continue}g.unmatchedIds.length>0&&(e.calls?.unattributed?.(e.objectApiName,g.unmatchedIds),E.warn(`[forge] ${e.objectApiName}: Bulk API job ${g.jobId??""} wrote ${O(g.unmatchedIds.length)} no row was matched to \u2014 kept for removal.`));let C=[],k=[],A=[],h=[],v=[],F=[],W;if(y.forEach((f,m)=>{let S=g.rows[m]??"unprocessed",N=g.answers[m],$=S==="answered"?Ve(N):void 0;S==="may-have-written"?F.push(f):$!==void 0&&N!==void 0?(W??=$,h.push(f),v.push(N)):!N||kt(S,N)?A.push(f):(C.push(f),k.push(N))}),this.settleMayHaveBeenWritten(e,F,r,g.jobId),await this.settleAnswers(e,C,B===void 0?{answers:k}:{answers:k,callId:B}),A.length>0){let f;try{f=await this.sendByRest(e,t,A,`${r}, by REST`,h.length+b,i)}catch(m){throw i?.([...h,...s.slice(R)],I(m)),m}if(f)return f}if(h.length>0){let f;try{f=await this.sendByRest(e,t,h,`${r}, by REST`,b,i,{refusedIn:{from:200,answers:v,...W?{cause:W}:{}}})}catch(m){throw i?.(s.slice(R),I(m)),m}if(f)return f}}}async sendJobByRest(e,t,n,s,r,o,i){let d=H(e),{sizes:l,allowance:u}=this.splitting,c=l.of(d),p=Math.ceil(s.length/c),w=u.take(d,p);l.countExtraCalls(d,w);let R=s.slice(0,w*c),y=s.slice(R.length);if(R.length>0){let b;try{b=await this.sendByRest(e,t,R,r,y.length+o,i,{pricedAs:"job",paid:{calls:w}})}catch(T){throw i?.(y,I(T)),T}finally{w<p&&l.spend(d)}if(b)return b}else w<p&&l.spend(d);if(y.length!==0)return y.length>=2e3?this.writeAsJobs(e,t,n,y,r,o,i):this.sendByRest(e,t,y,r,o,i)}leaveTwinsUnsent(e,t,n,s){t!==0&&(e.tally.failureCount+=t,this.sample(e.tally,{recordSummary:`${n}: ${O(t)} not written`,messages:[I(s),"Kept out of the Bulk API job as twins of other rows, to be written by REST once it answered: never sent, the target holds none of them."]}))}settleMayHaveBeenWritten(e,t,n,s){if(t.length===0)return;let{tally:r}=e;r.failureCount+=t.length;let o=t.map(se).filter(i=>i!==void 0);r.mayHaveBeenWritten=[...r.mayHaveBeenWritten??[],...o],this.sampleAhead(r,{recordSummary:`${n}: ${O(t.length)} may have been written`,messages:[`Bulk API job ${s??""} gave them no result of their own, and wrote records no row was matched to: the target may hold any of these records, and which of them is unknown.`,bt]})}async call(e,t,n){let s=n.map(oe);for(let r=0;;r++){let o=e.calls?.sending(e.objectApiName,n.map((i,d)=>({sourceId:se(i),payload:s[d],owes:qe(i)})),e.upsertField);try{let i=await this.send(e,s);return o===void 0?{answers:i}:{answers:i,callId:o}}catch(i){let d=Se(i);if(o!==void 0&&d!=="may-have-written"&&e.calls?.answered(o),d!=="not-received"||r===Ke)return{thrown:i,left:d,tries:r+1};let l=this.backoff.calculateDelay(r);E.warn(`[forge] ${e.objectApiName}: a call of ${O(s.length)} never reached the target (${I(i)}) \u2014 sent again in ${l} ms (${r+1}/${Ke}).`),await this.wait(l),await t.waitIfPaused()}}}async callAndSettle(e,t,n,s,r){let o,i={answers:[]},d=He(n,r),{stopped:l}=await ve(n,{key:H(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,...r,beforeEachSend:()=>t.waitIfPaused(),send:async u=>{let c=await this.call(e,t,u);return"thrown"in c?(o=c,"stop"):(i=c,{answers:c.answers})},limited:(u,c)=>{let p=Ve(u);return p&&u&&d.set(c,u.errors),p},settle:(u,c,p,w,R)=>this.settleAnswers(e,u,R?{answers:c}:i,p,w),onThrow:(u,c)=>{let p=I(c);s?s(u,p):this.leaveLimitedAsFailed(e,u,d,p)},onFirstRefusal:ft});if(!(!l||o===void 0))return{threw:o,rows:l.part,rest:l.rest}}sample(e,t){e.errorSamples.length<3&&e.errorSamples.push(t)}sampleAhead(e,t){e.errorSamples.unshift(t),e.errorSamples.splice(3)}async settleAnswers(e,t,{answers:n,callId:s},r=ut,o=ct){t.forEach((i,d)=>{let l=n[d];l?.success&&!r.has(d)&&this.settle(e,l,i)}),e.remapper.persist(),await this.readWhatMayBeEmpty(e,n.filter(i=>i!==void 0)),t.forEach((i,d)=>{if(r.has(d))return;let l=n[d];if(l){l.success||this.settle(e,l,i,o.get(d));return}e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(i.payload),messages:[`No result returned for record (API truncated batch: ${n.length}/${t.length})`,...J(i.refusals),...U(i.before)]})}),e.remapper.persist(),s!==void 0&&e.calls?.answered(s)}async readWhatMayBeEmpty(e,t){if(e.mayBeEmpty!==void 0||!t.some(r=>(r.errorDetails??[]).some(o=>o.statusCode===je)))return;let s=await this.deps.describeFields?.(e.targetOrgId,e.objectApiName).catch(()=>{});e.mayBeEmpty=new Set((s??[]).filter(r=>r.nillable===!0).map(r=>r.name.toLowerCase()))}settleThrown(e,t,n,s,r){let{tally:o}=e,i=I(t.thrown);if(o.failureCount+=n.length+r,t.left==="may-have-written"){let l=n.map(u=>u.built?.source.Id).filter(u=>typeof u=="string");o.mayHaveBeenWritten=[...o.mayHaveBeenWritten??[],...l],this.sampleAhead(o,{recordSummary:`${s}: ${O(n.length)} may have been written`,messages:[i,Rt,...r>0?[`${O(r)} after them not sent.`]:[]]});return}let d=n.length+r;this.sample(o,{recordSummary:`${s}: ${O(d)} not written`,messages:[i,...t.left==="request-limit"?[At]:[],...t.left==="not-received"?[`Sent ${t.tries} times, the call never reached the target: it holds none of them.`]:[]]})}async sendLockedAgain(e,t,n){for(let s=0;e.locked.length>0;s++){let r=this.backoff.calculateDelay(s);E.warn(`[forge] ${e.objectApiName}: the target could not lock a record for ${O(e.locked.length)} \u2014 sent again in ${r} ms.`),await this.wait(r),await t.waitIfPaused();let o=e.locked.splice(0),i=o.map(({row:u})=>({...u,lockResends:u.lockResends+1})),d=new Map(i.map((u,c)=>[u,o[c]])),l=await this.callAndSettle(e,t,i,(u,c)=>this.leaveLockedAsFailed(e,u.flatMap(p=>d.get(p)??[]),c));if(l)return this.settleThrown(e,l.threw,l.rows,`${e.objectApiName}, sent again`,n+l.rest.length),this.leaveLockedAsFailed(e,e.locked.splice(0),I(l.threw.thrown)),l.threw}}settle(e,t,n,s){let{tally:r,remapper:o,objectApiName:i}=e,{built:d,before:l}=n,u=oe(n);if(t.success){let b=d?.source.Id,T=t.created===!1;if(T?r.updatedCount++:r.successCount++,typeof b=="string"&&(T?o.addUpdated(b,t.id,i):o.add(b,t.id,i)),d&&e.onWritten?.(d,t.id),!T&&!lt(u)&&e.onCreatedWithoutRecordType?.(d,t.id),d&&d.nullifiedFks.length>0){let g=typeof d.source.Id=="string"?d.source.Id:void 0,C=d.nullifiedFks.map(k=>({objectApiName:i,newId:t.id,sourceId:g,fieldName:k.field,sourceRefId:k.sourceRefId,...k.insertOnly?{insertOnly:!0}:{}}));e.oweLookups?e.oweLookups(C):r.pendingFkUpdates.push(...C)}let B=[...l,...z(n)];B.length>0&&(r.writtenWithoutFields=ne(r.writtenWithoutFields,{rows:1,fields:B.map(g=>({...g,rows:1}))}));for(let{field:g,refusedBy:C}of B)C!=="lookup-filter"||!t.id||(r.leftEmptyByFilter??=[]).push({field:g,recordId:t.id});return}this.rememberRefusedValues(e,t,u),this.rememberRefusedOwners(e,t,u);let c=Te(t,e.targetKeyPrefix);if(c.kind==="linked"){r.linkedExistingCount++,o.createdTarget(c.id)&&ze(r);let b=d?.source.Id;typeof b=="string"&&o.addExisting(b,c.id,i);return}if(c.kind==="unidentified"&&Q[i]){e.byNaturalKey.push({payload:u,sourceId:d?.source.Id,errors:t.errors});return}let p=gt(t);if(p&&n.lockResends<ot){e.locked.push({row:n,errors:t.errors});return}let w=b=>e.mayBeEmpty?.has(b.toLowerCase())??!1,R=pt(t,u,e.upsertField,w,{inactiveOwner:!ie(e,u)}),y=n.refusals.length<De;if(R&&y){e.refusedOnTheirFields.push({...n,refusals:[...n.refusals,{errors:t.errors,leftOut:R}]});return}r.failureCount++,c.kind==="unidentified"&&r.unidentifiedExistingCount++,t.errors.every(b=>Y(b))&&r.alreadyExistsCount++,this.sample(r,{recordSummary:j(n.payload),messages:[...t.errors,...J(n.refusals),...p?[`Sent again ${n.lockResends} times, the target still could not lock a record the write needed.`]:[],...R&&!y?[`Not sent again: a row goes again without the fields the target refused ${De} times at most.`]:[],...xe(t.errorDetails)?[Tt]:[],...s?[we(s,ke(this.splitting.allowance,H(e)),"run")]:[],...U(l)]})}refusedValueKey(e,t,n){let s=t.RecordTypeId,r=t[n];if(typeof s!="string"||s===""||typeof r!="string"||r==="")return;let o=n.toLowerCase();if(!(!e.remembered.has(o)||o===e.upsertField?.toLowerCase()))return[e.objectApiName,s,o,r].join("\0")}rememberRefusedValues(e,t,n){for(let s of t.errorDetails??[])if(s.statusCode===Le)for(let r of s.fields){let o=_(n,r),i=o===void 0?void 0:this.refusedValueKey(e,n,o);o===void 0||i===void 0||this.refusedValues.has(i)||this.refusedValues.set(i,{field:o,refusedBy:"restricted-picklist",reason:Z(s)})}}rememberRefusedOwners(e,t,n){let s=_(n,"OwnerId");if(!(s===void 0||s.toLowerCase()===e.upsertField?.toLowerCase())&&!ie(e,n))for(let r of t.errorDetails??[]){if(r.statusCode!==$e)continue;let o=Pe(r,n);o===void 0||this.refusedOwners.has(o)||this.refusedOwners.set(o,{field:"OwnerId",refusedBy:"inactive-owner",reason:Z(r)})}}withoutRefusedValues(e,t){let n=[];if(this.refusedValues.size===0&&this.refusedOwners.size===0)return{sent:t,before:n};for(let o of Object.keys(t)){let i=this.refusedValueKey(e,t,o),d=i===void 0?void 0:this.refusedValues.get(i);d&&n.push({...d,field:o})}let s=_(t,"OwnerId"),r=s===void 0?void 0:t[s];if(s!==void 0&&typeof r=="string"&&s.toLowerCase()!==e.upsertField?.toLowerCase()&&!ie(e,t)){let o=this.refusedOwners.get(r.slice(0,15));o&&n.push({...o,field:s})}return n.length===0?{sent:t,before:n}:{sent:D(t,n),before:n}}leaveRefusedAsFailed(e,t,n){for(let s of t){let r=s.refusals[s.refusals.length-1];e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r?.errors??[],...J(s.refusals.slice(0,-1)),`Not written again without ${G(z(s))}: ${n}`,...U(s.before)]})}}leaveLimitedAsFailed(e,t,n,s){for(let r of t){let o=n.get(r);o&&(e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(r.payload),messages:[...o,...J(r.refusals),`Not sent again in a smaller call: ${s}`,...U(r.before)]}))}}leaveLockedAsFailed(e,t,n){for(let{row:s,errors:r}of t)e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r,...J(s.refusals),`Not sent again: ${n}`,...U(s.before)]})}async writeAgainWithoutTheirFields(e,t,n){for(;e.refusedOnTheirFields.length>0;){let s=e.refusedOnTheirFields.splice(0);if(t.onProgress({objectName:e.objectApiName,status:"running",progress:100,message:`Writing ${s.length} ${e.objectApiName} record${s.length===1?"":"s"} again without the fields ${ht(s.flatMap(z))} refused...`}),this.jobsCanCarry(e.bulk,e.objectApiName)&&s.length>=2e3){let r=`${e.objectApiName}, sent again`,o=await this.sendRows(e,t,s,r,0,(i,d)=>this.leaveRefusedAsFailed(e,i,d));if(o??=await this.sendLockedAgain(e,t,0),o){let i=I(o.thrown);this.leaveLockedAsFailed(e,e.locked.splice(0),i),this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),i);return}continue}for(let r=0;r<s.length;r+=n){let o=s.slice(r,r+n),i;try{await t.waitIfPaused()}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r),I(l)),l}try{i=await this.callAndSettle(e,t,o,(l,u)=>this.leaveRefusedAsFailed(e,l,u))}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),I(l)),l}let d;if(i){d=i.threw;let l=I(i.threw.thrown),u=[...i.rest,...s.slice(r+n)];i.threw.left==="may-have-written"?(this.settleThrown(e,i.threw,i.rows,`${e.objectApiName}, sent again`,0),this.leaveRefusedAsFailed(e,u,l)):this.leaveRefusedAsFailed(e,[...i.rows,...u],l)}else{try{d=await this.sendLockedAgain(e,t,0)}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),I(l)),l}d&&this.leaveRefusedAsFailed(e,s.slice(r+n),I(d.thrown))}if(d){this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),I(d.thrown));return}}}}settleByNaturalKey(e,t,n,s,r,o){t.forEach((i,d)=>{let l=n[d];if(l&&typeof i.sourceId=="string"){s.createdTarget(l)&&ze(r),s.addExisting(i.sourceId,l,e),r.linkedExistingCount++;return}r.failureCount++,r.unidentifiedExistingCount++,i.errors.every(u=>Y(u))&&r.alreadyExistsCount++,r.errorSamples.length<3&&r.errorSamples.push({recordSummary:j(i.payload),messages:o?[...i.errors,o]:i.errors})})}async recordsByNaturalKey(e,t,n,s){let r=this.deps.queryRecords;return r?Re(o=>r(e,o),t,n,s):s.map(()=>{})}async giveFlagsBack(e,t,n,s){let r=this.deps.updateRecords;if(!r||s.size===0||!he[e])return;let o=[];for(let[d,l]of s){let u=n.cleanedRecords[d]?.source;u&&o.push([u,l])}let i=await this.deps.describeFields?.(t,e).catch(()=>{});return ge(e,o,d=>i?.find(l=>l.name===d)?.updateable!==!1,d=>r(t,e,d),n.stopped)}async heldBeforeInsert(e,t,n){let s=this.deps.queryRecords;if(!s)return new Map;let r=o=>s(t,o);return e===X?ye(r,n):ce[e]!==void 0?fe(r,e,n):e===le?me(r,n):new Map}pickUpsertField(e,t,n,s,r){if(s==="off"||!this.deps.upsertRecords)return;let o=e.filter(i=>i.externalId&&t.has(i.name)).sort((i,d)=>i.name.localeCompare(d.name));if(r)return this.tableKeyOfThePage(o,n,r);if(o.length!==0){for(let i of o){let d=new Set,l=!0;for(let u of n){let c=u[i.name];if(typeof c!="string"||c.length===0){l=!1;break}if(d.has(c)){l=!1;break}d.add(c)}if(l)return E.info(`[forge] upsert: using "${i.name}" as external Id (unique across ${n.length} records)`),i.name}E.warn(`[forge] upsert: no externalId candidate is non-null+unique across batch (${o.map(i=>i.name).join(", ")}) \u2014 falling back to insert`)}}tableKeyOfThePage(e,t,n){let s=e.find(o=>n.unique.has(o.name))?.name;if(s===void 0){e.length>0&&E.warn(`[forge] upsert: no externalId candidate is non-null+unique across the rows read (${e.map(o=>o.name).join(", ")}) \u2014 falling back to insert`);return}let r=new Set;for(let o of t){let i=o[s];if(typeof i!="string"||i.length===0||r.has(i)){E.warn(`[forge] upsert: a row of this page leaves "${s}" empty or repeats it \u2014 inserting the page`);return}if(n.sent.has(i)){E.warn(`[forge] upsert: a row of this page repeats a "${s}" an earlier page sent \u2014 inserting the page`);return}r.add(i)}n.sent.size===0&&E.info(`[forge] upsert: using "${s}" as external Id (unique across the rows read of the object)`);for(let o of r)n.sent.add(o);return s}};function j(a){let e=Object.keys(a).slice(0,4),t=[];for(let n of e){let s=a[n],r;if(s===null)r="null";else if(s===void 0)r="undefined";else if(typeof s=="string")r=s.length>30?s.slice(0,30)+"\u2026":s;else if(typeof s=="object")try{let o=JSON.stringify(s);r=o.length>30?o.slice(0,30)+"\u2026":o}catch{r="<unserializable>"}else r=String(s);t.push(`${n}=${r}`)}return t.join(" ")||"(empty)"}export{L as a,M as b,Pt as c,ae as d,dt as e,lt as f,pt as g,yt as h,Ft as i,Ge as j,j as k};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-QAPVKPEC.mjs";import"./chunk-Q3DY7TO2.mjs";import"./chunk-3XG25GTF.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-WSUKC2U3.mjs";import"./chunk-JFNLKHY6.mjs";import"./chunk-VZVICK7Q.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-7PY3VQP3.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{h as ACTIVE_DUPLICATE_RULES_SOQL,a as FORMULAS_BOUND,c as FORMULAS_IN_COMPOSITES_BOUND,b as FORMULA_REQUESTS_BOUND,o as TargetGapReader,i as bypassesOf,j as callsEstimateOf,f as fieldLabelsSoql,p as gapAnsweredBy,d as gapFieldOf,r as gapLines,q as gapsWithAnswers,l as readActiveValidationRules,m as readValidationRuleBypasses,k as toolingQueriesOver,n as toolingValidationRules,g as validationFormulaSoql,e as validationRulesSoql};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as b}from"./chunk-YGJF55VJ.mjs";import"./chunk-JESRFE2Z.mjs";import{a}from"./chunk-CBL42DUU.mjs";import"./chunk-MKTXJCXN.mjs";import"./chunk-RCYEBY42.mjs";import"./chunk-AUS6NFLZ.mjs";import"./chunk-DBBPDSFN.mjs";import"./chunk-GBGHJTPC.mjs";import"./chunk-YMDFF657.mjs";import"./chunk-7WSLT5VX.mjs";import"./chunk-YT22LMF7.mjs";import"./chunk-ZXFL2MSN.mjs";import"./chunk-PE435FVH.mjs";import"./chunk-PWVDNN2C.mjs";import"./chunk-6VSZNZHH.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import"./chunk-ISSP2FZ5.mjs";import"./chunk-XU25YA46.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-IVZJSDJD.mjs";import"./chunk-VZT4E2OJ.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-O2PUGRNW.mjs";import"./chunk-7SDZR6SR.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-QIRO4HTE.mjs";import"./chunk-3SKLBRPL.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAMWHL22.mjs";import"./chunk-6KP6WETK.mjs";import"./chunk-4JKR4PTZ.mjs";import"./chunk-J24TIGSI.mjs";import"./chunk-HKUWHVI7.mjs";import"./chunk-VPDEJGPS.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-PBE44M2Y.mjs";import"./chunk-ZUOPC4W2.mjs";import"./chunk-JQZTMFO7.mjs";import"./chunk-JFNLKHY6.mjs";import"./chunk-VZVICK7Q.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-7PY3VQP3.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-XZISAZA6.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-PR74GYVI.mjs";import"./chunk-TMA34QMA.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as objectsWrittenBy,b as previewCheckpoint};
@@ -1,8 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{closeSync as D,fstatSync as J,openSync as W,readSync as $,writeSync as G}from"node:fs";function at(a){let e=W(a,"a+"),t=J(e).size;return{size:()=>t,append:n=>{let i=Buffer.from(n,"utf8"),r=0;for(;r<i.length;)r+=G(e,i,r);t+=i.length},read:(n,i)=>{let r=Buffer.alloc(i),s=0;for(;s<i;){let o=$(e,r,s,i-s,n+s);if(o===0)break;s+=o}return r.subarray(0,s)},close:()=>D(e)}}function j(a,e){return e===void 0?a:`${a}/${e}`}var E=/^[A-Za-z][A-Za-z0-9]*$/,T=/^[0-9a-f]{64}$/,K=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function M(a){if(typeof a!="object"||a===null)return;let{objectApiName:e,ids:t,sha256:n,readAt:i,query:r}=a;if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(e)||!Array.isArray(t)||!t.every(o=>typeof o=="string"&&K.test(o))||typeof n!="string"||!T.test(n)||typeof i!="string"||!Number.isFinite(Date.parse(i)))return;let s;if(typeof r=="object"&&r!==null){let{where:o,orderBy:c,limit:u}=r;s={...typeof o=="string"?{where:o}:{},...typeof c=="string"?{orderBy:c}:{},...typeof u=="number"&&Number.isInteger(u)?{limit:u}:{}}}return{objectApiName:e,ids:t,sha256:n,readAt:i,...s?{query:s}:{}}}var y=1,k=2,v=3,S=4,H={created:y,existing:k,updated:v},P={[y]:"created",[k]:"existing",[v]:"updated"},_={[y]:"c",[k]:"e",[v]:"u",[S]:"i"},N={c:y,e:k,u:v,i:S},Y="x",Z="a",q="j",z="d",R="n",O="t",U="found",V="found-owed";function dt(a,e,t,n){return JSON.stringify([z,a,e,t,n])}function ct(a){if(!a.startsWith(`["${z}"`))return;let e;try{e=JSON.parse(a)}catch{return}if(!Array.isArray(e))return;let[,,,t,n]=e;if(!(typeof t!="string"||!Number.isFinite(Date.parse(t)))&&!(typeof n!="string"||!Number.isFinite(Date.parse(n))))return{orgAt:t,at:n}}function Q(a,e=!1){return JSON.stringify([e?"w":"o",a.objectApiName,a.newId,a.sourceId??"",a.fieldName,a.sourceRefId,a.insertOnly?1:0])}var X=1024*1024,tt=1024*1024,et=2e4,nt=2e4,it=.6,rt=3;function l(a){let e=2166136261;for(let t=0;t<a.length;t++)e^=a.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function p(a){let e=2538058380;for(let t=0;t<a.length;t++)e=Math.imul(e^a.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var x=class{constructor(e){this.keyAt=e}keyAt;capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);at=new Float64Array(this.capacity);len=new Uint16Array(this.capacity);code=new Uint8Array(this.capacity);get size(){return this.used}get slots(){return this.capacity}find(e,t,n,i){let r=this.capacity-1,s=n&r;for(;;){let o=this.at[s];if(o===0)return~s;if(this.h1[s]===t&&this.h2[s]===n&&(i===o-1||this.keyAt(o-1,this.len[s])===e))return s;s=s+1&r}}offsetOf(e){return this.at[e]-1}lengthOf(e){return this.len[e]}codeOf(e){return this.code[e]}put(e,t,n,i,r,s){let o=e;e<0&&(this.used+1>this.capacity*it?(this.grow(),o=this.freeSlotFor(n)):o=~e,this.used++,this.h1[o]=t,this.h2[o]=n),this.at[o]=i+1,this.len[o]=r,this.code[o]=s}freeSlotFor(e){let t=this.capacity-1,n=e&t;for(;this.at[n]!==0;)n=n+1&t;return n}grow(){let{h1:e,h2:t,at:n,len:i,code:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.at=new Float64Array(this.capacity),this.len=new Uint16Array(this.capacity),this.code=new Uint8Array(this.capacity);for(let s=0;s<n.length;s++){if(n[s]===0)continue;let o=this.freeSlotFor(t[s]);this.h1[o]=e[s],this.h2[o]=t[s],this.at[o]=n[s],this.len[o]=i[s],this.code[o]=r[s]}}};function F(a){return a?a[0]==="p"&&a.length>=3?B(String(a[1]),String(a[2])):a[0]==="g"&&a.length>=3?C(String(a[2])):a[0]===O&&a.length>=2?I(String(a[1])):"":""}function I(a){return`t\0${a}`}function B(a,e){return`p\0${a}\0${e}`}function C(a){return`g\0${a}`}function*st(a){let e=a.size(),t=0,n=Buffer.alloc(0),i=0;for(;t<e;){let r=a.read(t,Math.min(tt,e-t));if(r.length===0)break;t+=r.length;let s=n.length>0?Buffer.concat([n,r]):r,o=0;for(;;){let c=s.indexOf(10,o);if(c<0)break;c>o&&(yield{offset:i+o,length:c-o,text:s.toString("utf8",o,c)}),o=c+1}n=s.subarray(o),i+=o}}var L=class a{constructor(e){this.file=e;this.index=new x((t,n)=>this.idOfLine(t,n)),this.marks=new x((t,n)=>F(m(this.lineAt(t,n)))),this.createdTargets=new x((t,n)=>{let i=m(this.lineAt(t,n));return i?A(String(i[2]??"")):""})}file;index;cache=new Map;pending=[];pendingBytes=0;flushQueued=!1;partStart=Number.POSITIVE_INFINITY;parts=0;mappedCount=0;counts=new Map;earlierByObject=new Map;earlierPastCheckpoint=new Map;checkpointsByObject=new Map;owedCount=0;statuses=new Map;given=new Map;marks;createdTargets;createdUnattributedKeys=new Set;readsHeld=[];withTheirRecordMarked=0;callsSent=0;foundAfterStop=new Set;foundOwingUntold=new Set;plan;rootsNamed;static open(e){let t=new a(e);return t.readWhatIsThere(),t}get partCount(){return this.parts}get resumes(){return this.checkpointsByObject.size>0||this.earlierByObject.size>0||this.owedCount>0}get earlierMapped(){return this.partStart===Number.POSITIVE_INFINITY?this.mappedCount:this.mappedBeforePart}mappedBeforePart=0;beginPart(e){this.flush(),this.mappedBeforePart=this.mappedCount,this.withTheirRecordMarked=0,this.partStart=this.file.size(),this.write({part:{n:this.parts,startedAt:e.toISOString()}}),this.parts++,this.flush()}nameSamplePlan(e){if(!T.test(e.sha256))throw new Error("Not the SHA-256 of a plan.");this.write({sample:{dir:e.dir,sha256:e.sha256}}),this.plan={dir:e.dir,sha256:e.sha256},this.flush()}get samplePlan(){return this.plan?{...this.plan}:void 0}nameRoots(e){let t=M(e);if(!t)throw new Error("Not the roots of a clone from records.");this.write({roots:t}),this.rootsNamed=t,this.flush()}get roots(){return this.rootsNamed?{...this.rootsNamed,ids:[...this.rootsNamed.ids]}:void 0}setMapping(e,t,n,i){let r=H[e],s=l(t),o=p(t),c=this.cache.get(t),u=this.index.find(t,s,o,c?.at),g=u>=0&&this.index.codeOf(u)!==S;g&&this.uncount(t,u,c);let d=JSON.stringify([_[r],t,n,i??""]),f=this.write(d);if(this.index.put(u,s,o,f,Buffer.byteLength(d),r),r===y&&this.indexCreated(n,f,Buffer.byteLength(d)),g||this.mappedCount++,i){let h=this.countsOf(i);r===y?h.created++:r===k?h.linked++:h.updated++}this.remember(t,{at:f,code:r,targetId:n,objectApiName:i??""})}uncount(e,t,n){let i=this.index.offsetOf(t);if(i<this.partStart)return;let r=this.index.codeOf(t),s=n?.at===i?n:this.recordAt(e,t),o=s?.objectApiName?this.counts.get(s.objectApiName):void 0;o&&(r===y?o.created--:r===k?o.linked--:o.updated--)}countsOf(e){let t=this.counts.get(e);return t||(t={created:0,linked:0,updated:0},this.counts.set(e,t)),t}mapping(e){let t=this.lookUp(e);if(!(!t||t.code===S))return{kind:P[t.code],sourceId:e,targetId:t.targetId,...t.objectApiName?{objectApiName:t.objectApiName}:{},earlier:t.at<this.partStart}}createdTarget(e){let t=A(e);if(this.createdUnattributedKeys.has(t))return!0;if(this.createdTargets.size===0)return!1;let n=this.createdTargets.find(t,l(t),p(t));if(n<0)return!1;let i=this.createdTargets.offsetOf(n),r=m(this.lineAt(i,this.createdTargets.lengthOf(n)));if(!r)return!1;let s=String(r[1]),o=this.index.find(s,l(s),p(s));return o>=0&&this.index.offsetOf(o)===i&&this.index.codeOf(o)===y}indexCreated(e,t,n){let i=A(e);if(!i)return;let r=l(i),s=p(i);this.createdTargets.put(this.createdTargets.find(i,r,s),r,s,t,n,y)}targetOf(e){let t=this.lookUp(e);return t&&t.code!==S?t.targetId:void 0}get mappedSize(){return this.mappedCount}countsByObject(){let e=[];for(let[t,{created:n,linked:i,updated:r}]of this.counts)n+i+r!==0&&e.push(r>0?{objectApiName:t,created:n,linked:i,updated:r}:{objectApiName:t,created:n,linked:i});return e}linkedToCreatedCount(){let e=0;for(let d of this.counts.values())e+=d.linked;if(e===0)return 0;let t=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart,n=(d,f)=>{let h=m(this.lineAt(d,f));return h?String(h[2]).slice(0,15):""},i=(d,f)=>{if(d.offset<t)return;let h=N[String(f[0])];if(h===void 0||h===S||!f[3])return;let b=String(f[1]),w=this.index.find(b,l(b),p(b),d.offset);return w>=0&&this.index.offsetOf(w)===d.offset?h:void 0},r=(d,f,h)=>{let b=l(f),w=p(f);d.put(d.find(f,b,w),b,w,h.offset,h.length,0)},s=(d,f)=>d.size>0&&d.find(f,l(f),p(f))>=0,o=new x(n);for(let d of this.lines()){if(!d.text.startsWith('["'))continue;let f=m(d.text);!f||i(d,f)!==k||this.markedWithTheirRecord(String(f[1]))||r(o,String(f[2]).slice(0,15),d)}if(o.size===0)return 0;let c=new x(n),u=new Set;for(let d of this.lines()){if(!d.text.startsWith('["')||d.offset<t)continue;let f=m(d.text);if(!f)continue;if(f[0]===R&&Array.isArray(f[2])){for(let b of f[2]){let w=String(b).slice(0,15);s(o,w)&&u.add(w)}continue}if(i(d,f)!==y)continue;let h=String(f[2]).slice(0,15);s(o,h)&&r(c,h,d)}if(c.size===0&&u.size===0)return 0;let g=0;for(let d of this.lines()){if(!d.text.startsWith('["'))continue;let f=m(d.text);if(!f||i(d,f)!==k||this.markedWithTheirRecord(String(f[1])))continue;let h=String(f[2]).slice(0,15);(s(c,h)||u.has(h))&&g++}return g}earlierRecordsOf(e,t=!1){return(t?this.earlierPastCheckpoint:this.earlierByObject).get(e)??0}*mappings(){for(let e of this.lines()){if(!e.text.startsWith('["'))continue;let t=m(e.text);if(!t)continue;let n=N[String(t[0])];if(n===void 0||n===S)continue;let i=String(t[1]),r=this.index.find(i,l(i),p(i),e.offset);if(r<0||this.index.offsetOf(r)!==e.offset)continue;let s=String(t[3]??"");yield{kind:P[n],sourceId:i,targetId:String(t[2]),...s?{objectApiName:s}:{},earlier:e.offset<this.partStart}}}noteRead(e){this.readsHeld.push(e),this.readsHeld.length>=nt&&this.settleReads()}settleReads(){let e=this.readsHeld;this.readsHeld=[];for(let t of e){let n=l(t),i=p(t),r=this.index.find(t,n,i,this.cache.get(t)?.at);if(r>=0)continue;let s=JSON.stringify([_[S],t]),o=this.write(s);this.index.put(r,n,i,o,Buffer.byteLength(s),S)}}wasRead(e){return this.readsHeld.includes(e)?!0:this.index.find(e,l(e),p(e),this.cache.get(e)?.at)>=0}checkpoint(e,t,n){if(n!==void 0&&!E.test(n))throw new Error(`Not the name of a pass: ${JSON.stringify(n.slice(0,40))}`);this.settleReads(),this.write({at:{object:e,...n!==void 0?{pass:n}:{},...t}}),this.checkpointsByObject.set(j(e,n),{...t}),this.flush()}checkpoints(){return new Map(this.checkpointsByObject)}owe(e,t=!1){this.owedCount++,this.write(Q(e,t))}get owed(){return this.owedCount}*owedPages(e){let t=[];for(let n of this.lines()){if(!n.text.startsWith('["o"')&&!n.text.startsWith('["w"'))continue;let i=m(n.text);if(!i||i.length<7)continue;let[r,s,o,c,u,g,d]=i;t.push({update:{objectApiName:String(s),newId:String(o),sourceId:c?String(c):void 0,fieldName:String(u),sourceRefId:String(g),...d===1?{insertOnly:!0}:{}},toRowWrittenBefore:r==="w"}),t.length>=e&&(yield t,t=[])}t.length>0&&(yield t)}patched(e,t){this.mark(JSON.stringify(["p",e,t]),B(e,t))}wasPatched(e,t){return this.hasMark(B(e,t))}mark(e,t){let n=l(t),i=p(t),r=this.marks.find(t,n,i),s=this.write(e);this.marks.put(r,n,i,s,Buffer.byteLength(e),0)}hasMark(e){return this.marks.size>0&&this.marks.find(e,l(e),p(e))>=0}owedLeftByEarlierParts(){let e=new Set;for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["p"'))continue;let i=m(n.text);i&&i.length>=3&&e.add(`${String(i[1])}\0${String(i[2])}`)}let t=[];for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["o"'))continue;let i=m(n.text);if(!i||i.length<7)continue;let[,r,s,o,c,u,g]=i;e.has(`${String(s)}\0${String(c)}`)||t.push({objectApiName:String(r),newId:String(s),sourceId:o?String(o):void 0,fieldName:String(c),sourceRefId:String(u),...g===1?{insertOnly:!0}:{}})}return t}oweStatus(e,t,n){this.write(JSON.stringify(["s",e,t,n])),this.tallyStatus({objectApiName:e,id:t,status:n})}tallyStatus(e){let t=this.statuses.get(e.objectApiName);t||(t={count:0,samples:[]},this.statuses.set(e.objectApiName,t)),t.count++,t.samples.length<rt&&t.samples.push(e)}gaveStatus(e,t){this.statusGiven(t)||(this.mark(JSON.stringify(["g",e,t]),C(t)),this.given.set(e,(this.given.get(e)??0)+1))}statusGiven(e){return this.hasMark(C(e))}statusesOwed(){let e=new Map;for(let[t,n]of this.statuses){let i=n.count-(this.given.get(t)??0);i<=0||e.set(t,{count:i,samples:n.samples.filter(({id:r})=>!this.statusGiven(r))})}return e}*statusLines(){for(let e of this.lines()){if(!e.text.startsWith('["s"'))continue;let t=m(e.text);!t||t.length<4||(yield{objectApiName:String(t[1]),id:String(t[2]),status:String(t[3])})}}withTheirRecord(e){let t=I(e),n=l(t),i=p(t),r=this.marks.find(t,n,i),s=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;if(r>=0&&this.marks.offsetOf(r)>=s)return;let o=JSON.stringify([O,e]),c=this.write(o);this.marks.put(r,n,i,c,Buffer.byteLength(o),0),this.withTheirRecordMarked++}get withTheirRecordCount(){return this.withTheirRecordMarked}markedWithTheirRecord(e){if(this.withTheirRecordMarked===0)return!1;let t=I(e),n=this.marks.find(t,l(t),p(t)),i=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;return n>=0&&this.marks.offsetOf(n)>=i}*withTheirRecordIds(){if(this.withTheirRecordMarked!==0)for(let e of this.lines()){if(e.offset<this.partStart||!e.text.startsWith(`["${O}"`))continue;let t=m(e.text);t&&t.length>=2&&(yield String(t[1]))}}sent(e,t,n,i=new Date,r){this.callsSent++;let s=`${Math.max(0,this.parts-1)}.${this.callsSent}`;return this.write(JSON.stringify([Y,s,e,i.toISOString(),t,n.map(({sourceId:o,fingerprint:c,externalKey:u,jobKey:g})=>r!==void 0&&u!==void 0?[o,c,u]:g!==void 0?[o,c,"",g]:[o,c]),n.flatMap(({owes:o},c)=>(o??[]).map(({field:u,sourceRefId:g,insertOnly:d})=>[c,u,g,d?1:0])),...r!==void 0?[r]:[]])),this.flush(),s}answered(e){this.write(JSON.stringify([Z,e]))}jobOpened(e,t){this.write(JSON.stringify([q,e,t])),this.flush()}createdUnattributed(e,t){if(t.length!==0){this.write(JSON.stringify([R,e,[...t]]));for(let n of t)this.createdUnattributedKeys.add(A(n))}}wasFoundAfterStop(e){return this.foundAfterStop.has(e)}owesUntold(e){return this.foundOwingUntold.has(e)}flush(){if(this.pending.length===0)return;let e=this.pending.join("");this.pending=[],this.pendingBytes=0,this.file.append(e)}close(){this.settleReads(),this.flush(),this.file.close()}write(e){let t=typeof e=="string"?e:JSON.stringify(e),n=this.file.size()+this.pendingBytes,i=`${t}
8
- `;return this.pending.push(i),this.pendingBytes+=Buffer.byteLength(i),this.pendingBytes>=X?this.flush():this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()})),n}lineAt(e,t){return e+t>this.file.size()&&this.flush(),this.file.read(e,t).toString("utf8")}idOfLine(e,t){let n=m(this.lineAt(e,t));return n?String(n[1]):""}lookUp(e){let t=this.cache.get(e);if(t)return this.cache.delete(e),this.cache.set(e,t),t;let n=this.index.find(e,l(e),p(e));if(n<0)return;let i=this.recordAt(e,n);return i&&this.remember(e,i),i}recordAt(e,t){let n=this.index.offsetOf(t),i=m(this.lineAt(n,this.index.lengthOf(t)));if(!(!i||String(i[1])!==e))return{at:n,code:this.index.codeOf(t),targetId:String(i[2]??""),objectApiName:String(i[3]??"")}}remember(e,t){if(this.cache.delete(e),this.cache.set(e,t),this.cache.size>et){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}}*lines(){this.flush(),yield*st(this.file)}readWhatIsThere(){for(let e of this.lines()){if(e.text.startsWith('["')){let n=m(e.text);n&&this.readRegistration(e,n);continue}let t;try{t=JSON.parse(e.text)}catch{continue}if(!(typeof t!="object"||t===null)){if("part"in t)this.parts++;else if("sample"in t){let n=t.sample;if(typeof n!="object"||n===null)continue;let{dir:i,sha256:r}=n;if(typeof i!="string"||i===""||typeof r!="string"||!T.test(r))continue;this.plan={dir:i,sha256:r}}else if("roots"in t){let n=M(t.roots);n&&(this.rootsNamed=n)}else if("at"in t){let n=t.at;if(typeof n!="object"||n===null)continue;let{object:i,pass:r,lastId:s,read:o,done:c}=n;if(typeof i!="string"||typeof s!="string"||typeof o!="number"||r!==void 0&&(typeof r!="string"||!E.test(r)))continue;this.checkpointsByObject.set(j(i,r),{lastId:s,read:o,...c===!0?{done:c}:{}}),r===void 0&&this.earlierPastCheckpoint.delete(i)}}}}readRegistration(e,t){let n=String(t[0]);if(n==="o"||n==="w"){this.owedCount++;return}if(n==="s"){t.length>=4&&this.tallyStatus({objectApiName:String(t[1]),id:String(t[2]),status:String(t[3])});return}if(n==="p"||n==="g"||n===O){let d=F(t);if(!d)return;let f=l(d),h=p(d),b=this.marks.find(d,f,h);if(n==="g"&&b<0){let w=String(t[1]);this.given.set(w,(this.given.get(w)??0)+1)}this.marks.put(b,f,h,e.offset,e.length,0);return}if(n===R){if(Array.isArray(t[2]))for(let d of t[2])this.createdUnattributedKeys.add(A(String(d)));return}let i=N[n];if(i===void 0)return;let r=String(t[1]);i===y&&(t[4]===U||t[4]===V)&&(this.foundAfterStop.add(r),t[4]===U&&this.foundOwingUntold.add(r));let s=l(r),o=p(r),c=this.index.find(r,s,o),u=c>=0&&this.index.codeOf(c)!==S;if(i===S&&c>=0||(this.index.put(c,s,o,e.offset,e.length,i),i===S))return;i===y&&this.indexCreated(String(t[2]??""),e.offset,e.length),u||this.mappedCount++;let g=String(t[3]??"");g&&(this.earlierByObject.set(g,(this.earlierByObject.get(g)??0)+1),this.earlierPastCheckpoint.set(g,(this.earlierPastCheckpoint.get(g)??0)+1))}};function A(a){return a.slice(0,15)}function m(a){try{let e=JSON.parse(a);return Array.isArray(e)?e:void 0}catch{return}}export{at as a,j as b,M as c,Y as d,Z as e,q as f,z as g,R as h,O as i,U as j,V as k,dt as l,ct as m,Q as n,l as o,p,x as q,st as r,L as s};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ce}from"./chunk-GMY5427L.mjs";import{h as Re,i as be,j as Se,k as ke,n as Te,o as Fe}from"./chunk-TEIBWMJM.mjs";import{c as Oe}from"./chunk-BWWQXU2B.mjs";import{f as he,i as me,o as we}from"./chunk-WSUKC2U3.mjs";import{b as fe,c as q,m as pe}from"./chunk-HFSBDM7B.mjs";import{d as K}from"./chunk-OHEOJISY.mjs";import{G as se,q as te,s as ne,t as re,u as oe}from"./chunk-KIMQQ6JQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{a as z,l as ie,o as ae,q as de,t as ce,u as ue,v as le}from"./chunk-ICIYL45C.mjs";import{b as ye,e as ge}from"./chunk-PR74GYVI.mjs";import{Fc as X,Xc as B}from"./chunk-ZQO5PDX5.mjs";var H=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function b(t){return t.slice(0,15)}var We=class{constructor(e=new Map){this.earlier=e}earlier;written=new Map;refused=new Map;deleted=new Set;ownersRefused=new Set;contactsSentWith=new Map;noteSentWithContact(e,n){this.contactsSentWith.set(b(e),n)}contactSentWith(e){return this.contactsSentWith.get(b(e))}roleLinkedFor(e){this.contactsSentWith.delete(b(e))}get sentWithAContact(){return this.contactsSentWith.size>0}noteOwnerRefused(e){this.ownersRefused.add(b(e))}isOwnerRefused(e){return this.ownersRefused.has(b(e))}noteDeleted(e){for(let n of e)this.deleted.add(b(n))}standing(e){return e!==void 0&&this.deleted.has(b(e))?void 0:e}noteMatched(e,n){this.noteWritten(e,n)}noteWritten(e,n){this.written.set(b(e),n),this.refused.delete(b(e))}noteRefused(e,n){this.written.has(b(e))||this.refused.set(b(e),n)}targetOf(e){return this.standing(this.written.get(b(e)))??this.standing(this.earlier.get(b(e)))}refusedObjectOf(e){if(this.standing(this.earlier.get(b(e)))===void 0)return this.refused.get(b(e))}};function Ae(t,e,n){if(e.length===0||!n.some(o=>!o.master))return;let r={};for(let o of e)r[o]=(r[o]??0)+1;let s=Se(be(n));return{objectApiName:t,rows:e.length,why:r,...s?{predicted:s}:{}}}function Ie(t,e){return q(t,e?.target??[])}function Y(t){switch(t.operation){case"insert":return null;case"upsert":return t.externalIdField??"Id";case"update":case"delete":return"Id"}}function ze(t,e,n,r,s){let o=ge(t,e);for(let i of n)(!(i.fieldApiName in o)||i.overwriteExisting)&&(o[i.fieldApiName]=i.value);if(!r)return o;let a={};for(let i of Object.keys(o))i!=="attributes"&&(r.has(i)||i===s)&&(a[i]=o[i]);return a}function ve(t,e){return`${t} ${e} record${t===1?"":"s"}`}function Ue(t,e,n){let r=a=>e.find(i=>b(i.recordTypeId)===b(a)),s=t;if(!r(t)&&n){let a=n.mappings.find(i=>b(i.sourceId)===b(t));if(!a){let i=n.source.find(c=>b(c.id)===b(t)),y=i?(n.target??[]).filter(c=>c.sobjectType===i.sobjectType&&c.developerName===i.developerName):[];return{unmapped:i?K(i):"",namesakes:y.map(K)}}s=a.targetId}let o=q(e.filter(a=>b(a.recordTypeId)===b(s)),n?.target??[])[0];return o&&!o.available&&!o.master?{unavailable:o}:o?{sent:s,info:o}:{sent:s}}function Ge(t,e,n){if(t?.personAccounts===!1)return!0;if(!n)return!1;let r=e??Te(t?.recordTypes);return r!==void 0&&!n.has(b(r))}function Le(t,e,n){return{group:`parent:${e}:${n}`,reason:`PARENT_REFUSED: the ${n} record its ${e} names was refused in this run.`,say:r=>`PARENT_REFUSED: ${ve(r,t)} held back, not sent: the ${n} record their ${e} names was refused in this run, and written without it they would stand without their ${n}.`}}function Ee(t){let{config:e,records:n,target:r,run:s}=t,o=e.objectApiName,a=Y(e),i=r?.recordTypes??[],y=r?.references??new Set,c={payloads:[],sentAt:[],settled:[],held:[],deferred:[],deferredAcross:[],notes:[],currencies:[],withoutRecordType:new Map},h=new Map,m=new Map,T=(d,l,g,k)=>{c.held.push({index:d,reason:g}),h.delete(d);let I=m.get(l);I?I.count++:m.set(l,{count:1,say:k})},w=e.operation==="insert"||e.operation==="upsert",W=w&&i.some(d=>!d.master),f=new Map;s&&w&&s.sources.forEach((d,l)=>{let g=d?.Id;typeof g=="string"&&H.test(g)&&f.set(b(g),l)});let v=new Set([...s&&w?s.later??[]:[]].map(d=>d.toLowerCase())),R=new Set(v.size===0?[]:(r?.fields??[]).flatMap(d=>d.isReference&&(d.referenceTo??[]).some(l=>v.has(l.toLowerCase()))&&!(d.nillable===!1&&d.defaultedOnCreate!==!0)?[d.name]:[]));n.forEach((d,l)=>{let g=ze(d,e.fieldMappings,e.addOnFields,r?.creatable??null,a);if(e.operation==="delete"){h.set(l,{payload:g,settled:new Set});return}let k=new Set;if(s)for(let p of Object.keys(g)){let C=g[p];if(p==="RecordTypeId"||!y.has(p)||typeof C!="string"||!H.test(C))continue;if(f.has(b(C))){delete g[p],c.deferred.push({index:l,field:p,parent:C});continue}let _=s.links.targetOf(C);if(_){g[p]=_,k.add(p);continue}let M=s.links.refusedObjectOf(C);if(M===void 0){R.has(p)&&(delete g[p],c.deferredAcross.push({index:l,field:p,parent:C}));continue}let G=Le(o,p,M);T(l,G.group,G.reason,G.say);return}let I=g.RecordTypeId,E,j=Oe(I);if(j)delete g.RecordTypeId;else if(typeof I=="string"&&H.test(I)){let p=Ue(I,i,s?.recordTypes);if("unmapped"in p){let C=p.unmapped,_=p.namesakes.length>0?` The target org's ${p.namesakes.join(" and ")} carries its DeveloperName under another namespace, and a record type is mapped to one of the same namespace only.`:"";T(l,`unmapped:${C}`,"RECORD_TYPE_UNMAPPED: its record type has no counterpart in the target org.",M=>`RECORD_TYPE_UNMAPPED: ${ve(M,o)} held back, not sent: `+(C?`their record type ${C} has no active ${o} record type of that API name in the target org.${_} Create or activate record type ${C} on ${o} in the target org.`:"their record type is inactive in the source org, and has no counterpart in the target org."));return}if("unavailable"in p){let C=p.unavailable;T(l,`unavailable:${C.recordTypeId}`,`RECORD_TYPE_UNAVAILABLE: record type ${C.developerName} is closed to the running user in the target org.`,_=>`${pe({objectApiName:o,recordTypeId:C.recordTypeId,developerName:C.developerName,name:C.name,inactive:!C.active,recordCount:_})} Held back, not sent.`);return}g.RecordTypeId=p.sent,E=p.sent,p.info&&k.add("RecordTypeId")}let $=s?.sources[l]??d;if(re($)){let p=oe($,Ge(r,E,s?.recordTypes?.personTypes));for(let C of Object.keys(g))B(o,C,p)&&delete g[C]}else for(let p of Object.keys(g))B(o,p,"business")&&delete g[p];W&&!("RecordTypeId"in g)&&c.withoutRecordType.set(l,j?"masterInSource":"notRead"),h.set(l,{payload:g,settled:k})});let L=!0;for(;L;){L=!1;for(let{index:d,field:l,parent:g}of c.deferred){let k=f.get(b(g));if(!h.has(d)||k===void 0||h.has(k)||s?.links.targetOf(g)!==void 0)continue;let I=Le(o,l,o);T(d,I.group,I.reason,I.say),L=!0}}c.deferred=c.deferred.filter(({index:d})=>h.has(d)),c.deferredAcross=c.deferredAcross.filter(({index:d})=>h.has(d));for(let d of[...c.withoutRecordType.keys()])h.has(d)||c.withoutRecordType.delete(d);c.held.sort((d,l)=>d.index-l.index);let S=e.operation==="delete"?void 0:s?.currencies,O=r?.creatable.has(z)===!0,u=!O&&(s?.currencyChangesById?.size??0)>0&&r?.fields?.some(d=>d.name===z)===!0,F=S&&(O||u)?ae(r?.fields??[]):void 0,P=[...r?.references??[]],A=new le;for(let[d,{payload:l,settled:g}]of[...h].sort(([k],[I])=>k-I)){for(let k of X(o,l))delete l[k];if(S&&F){let k=s?.sources[d]??n[d],I=k?.[z],E=O?de(l,{read:I,currencyFields:F,ratesOn:ie(o,k)},S):ue(l,{read:I,parent:k?ce(o,k,P,$=>s?.currencyChangesById?.get($)):void 0,currencyFields:F},S);A.add(o,E);let j=k?.Id;E&&typeof j=="string"&&s?.currencyChangesById?.set(j,E)}c.payloads.push(l),c.sentAt.push(d),c.settled.push(g)}return c.notes=[...m.values()].map(({count:d,say:l})=>l(d)),c.currencies=A.list(),c}function V(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}function Be(t){let e=V(t.length),n=V(t.precision),r=V(t.digits);return{name:t.name,queryable:t.queryable!==!1,createable:t.createable===!0,isReference:t.type==="reference",...t.type!==void 0?{type:t.type}:{},...e!==void 0?{length:e}:{},...t.nillable!==void 0?{nillable:t.nillable}:{},...t.defaultedOnCreate!==void 0?{defaultedOnCreate:t.defaultedOnCreate}:{},...t.calculated===!0?{calculated:!0}:{},...n!==void 0?{precision:n}:{},...n!==void 0&&typeof t.scale=="number"&&t.scale>=0?{scale:t.scale}:{},...r!==void 0?{digits:r}:{},...t.unique===!0?{unique:!0}:{},...t.referenceTo?{referenceTo:[...t.referenceTo]}:{}}}function yt(t){let e=t.fields.filter(r=>r.createable===!0),n=t.fields.some(r=>typeof r.idLookup=="boolean");return{creatable:new Set(e.map(r=>r.name)),references:new Set(e.filter(r=>r.type==="reference").map(r=>r.name)),...typeof t.createable=="boolean"?{objectCreateable:t.createable}:{},...typeof t.updateable=="boolean"?{objectUpdateable:t.updateable}:{},recordTypes:fe(t.recordTypeInfos),...t.name===te?{personAccounts:t.fields.some(r=>r.name===ne)}:{},fields:t.fields.map(Be),...n?{upsertKeys:new Set(t.fields.filter(r=>r.externalId===!0||r.idLookup===!0).map(r=>r.name.toLowerCase()))}:{}}}function Z(t,e,n){switch(e){case"notInTarget":return`Object is not in the target org, or the user the run writes as cannot see it: ${t}. None of its records were sent.`;case"notCreateable":return`Object is not createable on target org: the user the run writes as may not create ${t} records there. None of its records were sent.`;case"notUpdateable":return`Object is not updateable on target org: the user the run writes as may not edit ${t} records there. None of its records were sent.`;case"unread":return`The target org did not describe ${t}${n?` (${n})`:""}, so what it takes could not be told and none of its records were sent.`;case"notAKey":return`The upsert of ${t} matches on ${n??"a field"}, which the target org does not match an upsert on: it takes an External ID field, the Id, or a field its describe marks idLookup. None of its records were sent.`}}function gt(t,e){let n=t.externalIdField?.trim().toLowerCase();if(t.operation!=="upsert"||!n)return t;let r=e.fields?.find(s=>s.name.toLowerCase()===n)?.name;return r===void 0?t:{...t,externalIdField:r}}function ht(t,e){if(t.operation==="delete"||t.query===void 0)return t;let n=Ce(t.query);if(!("list"in n))return t;let r=new Set([...n.list,t.externalIdField??"",...t.fieldMappings.filter(o=>ye.has(o.type)).map(o=>o.sourceField)].map(o=>o.toLowerCase())),s=[...e.creatable].filter(o=>!r.has(o.toLowerCase()));return s.length===0?t:{...t,excludedFields:[...new Set([...t.excludedFields??[],...s])]}}async function Pe(t,e,n,r){let s;try{s=await t(e)}catch(c){if(n==="delete")return{notAsked:!0};let h=Fe(c)?"notInTarget":"unread";return{refused:{why:h,message:Z(e,h,ee(c))}}}let o=n==="insert"||n==="upsert",a=n==="update"||n==="upsert",i=o&&s.objectCreateable===!1?"notCreateable":a&&s.objectUpdateable===!1?"notUpdateable":void 0;if(i)return{refused:{why:i,message:Z(e,i)},target:s};let y=r?.trim()||"Id";return n==="upsert"&&s.upsertKeys&&!s.upsertKeys.has(y.toLowerCase())?{refused:{why:"notAKey",message:Z(e,"notAKey",y),key:y},target:s}:{target:s}}function Rt(t){return t.keepContactPoints===!0?void 0:new Re}function Ot(t,e){if(!t)return e?{neutralized:!1,fields:[],values:0}:void 0;let n=t.report();return n.values>0?n:void 0}function xe(t,e,n,r,s){let o=s?n.filter(i=>i.name!==s):n,a=t.forObject(e,o);if(a)for(let i of r)a(i)}var x=class extends Error{constructor(n,r=[],s=[],o=[],a){super(r.length===0?`The write of ${n} was cancelled before any of its records was written.`:`The write of ${n} was cancelled after ${r.length} of its records were sent.`);this.objectApiName=n;this.written=r;this.notes=s;this.lookupsLeftOut=o;this.writtenWithoutFields=a;this.name="WriteCancelledError"}objectApiName;written;notes;lookupsLeftOut;writtenWithoutFields};var Ne=class{deps;constructor(e){this.deps=e}async sync(e,n,r){let{outcomes:s,notes:o,currencies:a,lookupsLeftOut:i,writtenWithoutFields:y}=await this.write(e,n,r);return Je(Qe(e.objectApiName,e.operation,s,o,i,y),a)}updateRecords(e,n,r){return this.executeOperation(e,"update",n,r)}async write(e,n,r){let s=null;if(this.deps.describeTargetFields){let u=await Pe(this.deps.describeTargetFields,e.objectApiName,e.operation,e.externalIdField);if("refused"in u){let F=n.map(()=>({success:!1,errors:[u.refused.message]}));return r&&$e(e,F,r),{outcomes:F,notes:[],currencies:[],lookupsLeftOut:[]}}"target"in u&&u.target.creatable.size>0&&(s=u.target)}let o=Ee({config:e,records:n,target:s,run:r}),a=r?r.contactPoints:this.deps.contactPoints;a&&s?.fields&&xe(a,e.objectApiName,s.fields,o.payloads,e.externalIdField);let i=He(o.payloads,o.settled,r),y=new Map(o.held.map(({index:u,reason:F})=>[u,F])),c=u=>{let F=[],P=0;for(let A=0;A<n.length;A++){let d=y.get(A);if(d!==void 0){F.push({success:!1,errors:[d],heldBack:!0});continue}if(P>=u.length)break;F.push(u[P++])}return F},h,m=o.sentAt.filter(u=>u<(r?.standardFirst??0)).length,T=u=>this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField);try{h=o.payloads.length===0&&n.length>0?[]:m>0&&m<o.payloads.length?await Ve(e.objectApiName,T,o.payloads.slice(0,m),o.payloads.slice(m)):await T(o.payloads)}catch(u){if(!(u instanceof x))throw u;let F=je(i,u.written),P=c(u.written);throw De(e,o.withoutRecordType,P,s,r),new x(e.objectApiName,P,[...o.notes,...u.notes],[...F?[F]:[],...u.lookupsLeftOut,...Q(U([...o.deferred,...o.deferredAcross],P))],u.writtenWithoutFields)}let w=await this.retryRefused(e,o.payloads,h,s?.references??null,o.settled);if(r)for(let u of w.ownersRefused)r.links.noteOwnerRefused(u);let W=c(w.outcomes);De(e,o.withoutRecordType,W,s,r);let f=je(i,w.outcomes),v=[...o.notes,...w.notes],R=[...f?[f]:[],...w.lookupsLeftOut],{writtenWithoutFields:L}=w,S=U(o.deferredAcross,W),O=0;if(w.cancelled)throw new x(e.objectApiName,W,v,[...R,...Q([...U(o.deferred,W),...S])],L);if(r){$e(e,W,r),Ze(e,o.payloads,w.outcomes,r.links);let u=await this.setLookups(e,U(o.deferred,W),r.links,!1);if(R.push(...u.leftOut),O=u.unset,u.cancelled)throw new x(e.objectApiName,W,v,[...R,...Q(S)],L)}return{outcomes:W,notes:v,currencies:o.currencies,lookupsLeftOut:R,...L?{writtenWithoutFields:L}:{},...S.length>0?{lookupsToSet:S}:{},...O>0?{lookupsUnset:O}:{}}}async setLookups(e,n,r,s){let o=e.objectApiName,a=new Map,i=new Map,y=new D;for(let{id:f,field:v,parent:R}of n){let L=r.targetOf(R),S=L!==void 0?a:s&&r.refusedObjectOf(R)===void 0?i:void 0;if(!S){y.add(f,v);continue}let O=S.get(f)??{Id:f};O[v]=L??R,S.set(f,O)}let c=new D,h=new D,m=new D,T=new D,w=!1;for(let f of[[...a.values()],[...i.values()]]){if(f.length===0)continue;if(w){for(let R of f)T.addRow(R);continue}let v;try{v=await this.executeOperation(o,"update",f,e.batchSize)}catch(R){if(!(R instanceof x)){let L=R instanceof Error?R.message:String(R);for(let S of f)m.addRow(S,L);continue}v=R.written,w=!0}f.forEach((R,L)=>{let S=v[L];S===void 0?T.addRow(R):S.success?c.addRow(R):S.errors.some(O=>J(O))?h.addRow(R):m.addRow(R,S.errors[0])})}let W=[y,h,m,T];return{...c.records>0?{set:{records:c.records,fields:c.fields()}}:{},leftOut:[y.leftOut("parentRefused"),h.leftOut("notInTarget"),m.leftOut("notSet"),T.leftOut("notReached")].flatMap(f=>f?[f]:[]),unset:new Set(W.flatMap(f=>[...f.recordIds])).size,cancelled:w}}async retryRefused(e,n,r,s,o){let a=Y(e)??void 0,i=[...r],y=[...n],c=n.map(()=>new Set),h=n.map(()=>[]),m=n.map(()=>[]),T=[],w,W=new Set;for(let S=0;S<2&&!w;S++){let O=[],u=[],F=[];if(i.forEach((A,d)=>{if(A.success)return;let l=y[d],g=o[d]??new Set;if(A.errors.some(E=>J(E))){let E=n[d]?.[N];if(typeof E=="string"&&!g.has(N)&&(A.errorDetails??[]).some(p=>J(p.statusCode)&&p.fields.includes(N))&&W.add(E),c[d].has("lookup")||!s||s.size===0)return;let j={},$=!1;for(let p of Object.keys(l)){if(s.has(p)&&!g.has(p)&&l[p]!==null&&l[p]!==void 0){$=!0;continue}j[p]=l[p]}if(!$)return;O.push(d),u.push(j),F.push(null);return}if(c[d].has("fields"))return;let k=he(A.errorDetails,l,a);if(!k||k.some(({field:E})=>g.has(E)))return;let I=new Set(k.map(({field:E})=>E));O.push(d),u.push(Object.fromEntries(Object.entries(l).filter(([E])=>!I.has(E)))),F.push(k)}),O.length===0)break;let P;try{P=await this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField)}catch(A){if(!(A instanceof x)){T.push(...Ye(O,y,u,F,A));break}P=A.written,w=A}P.forEach((A,d)=>{let l=O[d],g=F[d];c[l].add(g===null?"lookup":"fields"),g===null?h[l].push(...Object.keys(y[l]).filter(k=>!(k in u[d]))):m[l].push(...g),y[l]=u[d],i[l]=A})}let f=new Set,v=0,R,L=new Set(W);return i.forEach((S,O)=>{if(!(!S.success||c[O].size===0)){if(h[O].length>0){v++;for(let F of h[O])f.add(F);let u=n[O]?.[N];typeof u=="string"&&h[O].length===1&&h[O][0]===N&&L.add(u)}m[O].length>0&&(R=me(R,{rows:1,fields:m[O].map(u=>({...u,rows:1}))}))}}),{outcomes:i,notes:[...T,...w?.notes??[]],...R?{writtenWithoutFields:R}:{},cancelled:w!==void 0,ownersRefused:[...L],lookupsLeftOut:[...v>0?[{records:v,fields:[...f].sort(),reason:"notInTarget"}]:[],...w?.lookupsLeftOut??[]]}}async executeOperation(e,n,r,s,o){if(this.deps.crudFlsGuard){let a=r.length>0?Object.keys(r[0]):[],i=await this.deps.crudFlsGuard.checkCrudAndFls(e,n,a);if(!i.allowed)throw new Error(`CRUD/FLS check failed for ${n} on ${e}: ${i.reason}`)}switch(n){case"insert":return this.deps.insert(e,r,s);case"update":return this.deps.update(e,r,s);case"upsert":return this.deps.upsert(e,o??"Id",r,s);case"delete":{let a=r.map(i=>i.Id).filter(i=>typeof i=="string");return this.deps.delete(e,a,s)}}}},Ke=["INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY","INVALID_CROSS_REFERENCE_KEY"],qe=/cross[- ]reference id|r[ée]f[ée]rence crois[ée]e/i;function J(t){return Ke.some(e=>t.includes(e))||qe.test(t)}var N="OwnerId";function He(t,e,n){let r=new Set;return n&&t.forEach((s,o)=>{let a=s[N];typeof a!="string"||e[o]?.has(N)||n.links.isOwnerRefused(a)&&(delete s[N],r.add(o))}),r}function je(t,e){let n=0;for(let r of t)e[r]?.success&&n++;if(n!==0)return{records:n,fields:[N],reason:"ownerRefusedEarlier"}}function Ye(t,e,n,r,s){let o=s instanceof Error?s.message:String(s),a=new Set,i=new Set,y=0;return r.forEach((c,h)=>{if(c===null){y++;let m=n[h];for(let T of Object.keys(e[t[h]]))T in m||a.add(T)}else for(let{field:m}of c)i.add(m)}),[...y>0?[`${y} record(s) the target refused for a lookup it does not have could not be written again without ${[...a].sort().join(", ")}: ${o}`]:[],...i.size>0?[`${t.length-y} record(s) the target refused on fields it named could not be written again without ${[...i].sort().join(", ")}: ${o}`]:[]]}var D=class{ids=new Set;named=new Set;said;add(e,n){this.ids.add(e),this.named.add(n)}addRow(e,n){let r=String(e.Id);for(let s of Object.keys(e))s!=="Id"&&this.add(r,s);n!==void 0&&n!==""&&(this.said??=n)}get records(){return this.ids.size}get recordIds(){return this.ids}fields(){return[...this.named].sort()}leftOut(e){if(this.ids.size!==0)return{records:this.ids.size,fields:this.fields(),reason:e,...this.said!==void 0?{refusal:this.said}:{}}}};function U(t,e){return t.flatMap(({index:n,field:r,parent:s})=>{let o=e[n];return o?.success&&typeof o.id=="string"&&o.id!==""?[{id:o.id,field:r,parent:s}]:[]})}function vt(t){return new Set(t.map(({id:e})=>e)).size}function Q(t){let e=new D;for(let{id:r,field:s}of t)e.add(r,s);let n=e.leftOut("notReached");return n?[n]:[]}function Me(t,e){if(!(e.success||t!=="insert"&&t!=="upsert"))return e.existingId!==void 0&&e.existingId!==""?e.existingId:void 0}async function Ve(t,e,n,r){let s=await e(n);try{return[...s,...await e(r)]}catch(o){throw o instanceof x?new x(t,[...s,...o.written],o.notes,o.lookupsLeftOut,o.writtenWithoutFields):o}}function De(t,e,n,r,s){if(!s?.createdWithoutRecordType||e.size===0)return;let o=[],a=[];for(let[c,h]of e){let m=n[c];!m?.success||typeof m.id!="string"||m.id===""||t.operation!=="insert"&&m.created!==!0||(o.push(h),a.length<ke&&a.push(m.id))}let i=Ie(s.recordTypesUnderTheLease??r?.recordTypes??[],s.recordTypes),y=Ae(t.objectApiName,o,i);y&&s.createdWithoutRecordType.set(t.objectApiName,{given:y,types:i,ids:a})}function Ze(t,e,n,r){t.objectApiName==="Opportunity"&&(t.operation!=="insert"&&t.operation!=="upsert"||e.forEach((s,o)=>{let a=n[o],i=s[se];!a?.success||typeof a.id!="string"||a.id===""||t.operation!=="insert"&&a.created!==!0||typeof i=="string"&&i!==""&&r.noteSentWithContact(a.id,i)}))}function $e(t,e,n){if(t.operation==="delete")return;let r=t.operation==="insert"||t.operation==="upsert";e.forEach((s,o)=>{let a=n.sources[o]?.Id;if(typeof a!="string"||a==="")return;let i=Me(t.operation,s);s.success&&typeof s.id=="string"&&s.id!==""?n.links.noteWritten(a,s.id):i!==void 0?n.links.noteWritten(a,i):!s.success&&r&&n.links.noteRefused(a,t.objectApiName)})}function Je(t,e){return e.length>0?{...t,currenciesReplaced:[...e]}:t}var _e=1e3;function Qe(t,e,n,r=[],s=[],o){let a=0,i=0,y=0,c,h=[],m=0,T={created:0,updated:0},w={rows:0,written:0,stillLocked:0};for(let f of n)f.lockResends!==void 0&&(w.rows++,f.success?w.written++:we(f.errors,f.errorDetails)&&w.stillLocked++),f.success?(a++,f.created===!0?T.created++:f.created===!1&&T.updated++):Me(e,f)!==void 0?(y++,c??=f.errors[0]):(i++,!f.heldBack&&m++<_e&&h.push(...f.errors));let W=Math.max(0,m-_e);return{objectApiName:t,operation:e,processed:n.length,success:a,failed:i,skipped:y,conflictCount:0,errors:[...h,...r],...y>0?{linkedToExisting:{records:y,...c?{refusal:c}:{}}}:{},...s.length>0?{lookupsLeftOut:[...s]}:{},...o?{writtenWithoutFields:o}:{},...w.rows>0?{sentAgainForALock:w}:{},...W>0?{refusalsDropped:W}:{},...e==="upsert"?{upsertSplit:T}:{}}}export{We as a,Ae as b,Ie as c,Ee as d,yt as e,gt as f,ht as g,Pe as h,Rt as i,Ot as j,xe as k,x as l,Ne as m,vt as n,Q as o,Me as p,Je as q,_e as r,Qe as s};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-Z42PHCVZ.mjs";import"./chunk-V3R45ZWT.mjs";import"./chunk-NWOI25WY.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-JKT5YAQ2.mjs";import"./chunk-3SKLBRPL.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SCENARIO_SIDECAR_SUFFIX,f as compiledForSidecar,g as nodeScenarioSidecarFiles,j as readScenarioRunSidecar,c as scenarioPackFingerprint,d as scenarioRunSidecar,b as scenarioRunSidecarSchema,h as scenarioSidecarPath,e as withAgentChoice,i as writeScenarioRunSidecar};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i}from"./chunk-H4JUYUSL.mjs";import"./chunk-Z42PHCVZ.mjs";import"./chunk-V3R45ZWT.mjs";import"./chunk-NWOI25WY.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-JKT5YAQ2.mjs";import"./chunk-3SKLBRPL.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SCENARIO_PACK_FILE_SUFFIX,b as SCENARIO_PACK_SEARCH,i as findScenarioPack,e as findScenarioPackFiles,f as listScenarioPacks,c as nodeScenarioPackFiles,d as readScenarioPackText,h as saveScenarioPack,g as scenarioPackText};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Tt,d as _t,e as Bt,g as xt,h as Ft,i as Ut,j as $t,k as et}from"./chunk-54HYHHVL.mjs";import{a as Ce,b as q,d as H,e as vt,f as Xe,h as j}from"./chunk-VPDEJGPS.mjs";import{e as Ht,h as Jt,i as zt}from"./chunk-HFUDCNU5.mjs";import{da as me,e as te,ea as Ze,ga as pe,ja as Pe}from"./chunk-KIMQQ6JQ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{Bc as Ye,Cc as Lt,dd as jt,lc as Nt,qc as Mt,rc as ee,vc as Ee,yc as ge,zc as Ge}from"./chunk-ZQO5PDX5.mjs";import{b as x,e as Ke,f as L,i as Pt,k as ae,l as X,o as Ie,s as Ct}from"./chunk-WZQEK4WT.mjs";var Ne=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function $n(r,e){let t=et(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Me(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>$n(Ht(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>et(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var qt=100,tt=2e3,Wt=20,Qt=20,Jn=X({name:x(),label:x(),type:x(),createable:L().optional(),updateable:L().optional(),nillable:L().optional(),defaultedOnCreate:L().optional(),aggregatable:L().optional(),groupable:L().optional(),filterable:L().optional(),nameField:L().optional(),autoNumber:L().optional(),calculated:L().optional(),referenceTo:ae(x()).optional()}).loose(),G=X({name:x(),label:x(),queryable:L().optional(),updateable:L().optional(),deletable:L().optional(),fields:ae(Jn),childRelationships:ae(X({childSObject:x(),field:x(),cascadeDelete:L().optional(),restrictedDelete:L().optional()}).loose()).optional()}).loose(),zn=Ct(x(),Pt()),qn=X({k:Ie([x(),Ke(),L()]).nullable(),n:Ke().int().nonnegative()}).loose();function Vt(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function Wn(r){return r.groupable===!0&&(Vt(r)||r.nameField===!0)}function Qn(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Nt(r,e.name)}function Le(r,e,t){let n=P(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Vn(r,e,t,n){let o=new Map,s=[],a=[],i=(f,u)=>{s.push({fieldApiName:f.name,label:f.label,reason:u})},d=t.filter(f=>f.aggregatable===!0),l=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&i(f,"not-countable");if(n===0)for(let f of[...d,...l])o.set(f.name,0);else{for(let f=0;f<d.length;f+=qt){let u=d.slice(f,f+qt);try{let g=u.map(R=>`COUNT(${N(R.name)})`).join(", "),m=await r.query(`SELECT ${g} FROM ${e}`),h=zn.parse(m.records[0]??{});u.forEach((R,b)=>{let w=h[`expr${b}`];if(typeof w!="number")throw new Error(`The org answered no count for ${e}.${R.name}.`);o.set(R.name,w)})}catch(g){Le(a,"fill",g);for(let m of u)o.delete(m.name),i(m,"refused")}}for(let[f,u]of l.entries()){if(f>=Qt){i(u,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${N(u.name)} != null`);o.set(u.name,g.totalSize)}catch(g){Le(a,"fill",g),i(u,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Qn(e,f)})).sort((f,u)=>f.filled-u.filled||f.fieldApiName.localeCompare(u.fieldApiName)),unmeasured:s,errors:a}}async function Kn(r,e,t,n,o){let s=[],a=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!a)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let i={keyField:a.name,keyLabel:a.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:i,errors:s};try{let d=await Gn(r,e,a.name),l=d.rows.map(c=>({value:String(c.value),count:c.count}));return{duplicates:{...i,groups:l.slice(0,Wt),groupCount:l.length,recordCount:l.reduce((c,f)=>c+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Le(s,"duplicates",d),{duplicates:null,errors:s}}}async function Gn(r,e,t){let n=N(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${tt}`),s=[];for(let a of o.records){let i=qn.safeParse(a);!i.success||i.data.k===null||s.push({value:i.data.k,count:i.data.n})}return{rows:s,truncated:o.records.length>=tt}}async function Yn(r,e,t,n,o){let s=[];if(!t.some(a=>a.name==="LastModifiedDate"&&a.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let a=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:a.totalSize},errors:s}}catch(a){return Le(s,"stale",a),{stale:null,errors:s}}}async function Zn(r,e,t){let n,o,s;try{if(n=G.parse(await r.describe(N(e.objectApiName))),o=N(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(c){return{status:"failed",objectApiName:e.objectApiName,message:P(c)}}let a=n.fields.filter(Wn).sort((c,f)=>c.label.localeCompare(f.label)),[i,d,l]=await Promise.all([Vn(r,o,n.fields.filter(Vt),s),Kn(r,o,a,e.duplicateKey,s),Yn(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:i.fields,unmeasured:i.unmeasured,duplicates:d.duplicates,stale:l.stale,keyFields:a.map(c=>({fieldApiName:c.name,label:c.label})),errors:[...i.errors,...d.errors,...l.errors]}}async function oo(r,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Zn(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:tt,duplicateSample:Wt,singleFieldQueries:Qt},objects:o}}var nt=1e4,ve=5e4,Kt="DELETE_FAILED",rt="UNABLE_TO_LOCK_ROW",Gt=3,Xn=2e3,Yt="FEATURENOTENABLED",ot="ContentVersion",Zt="ContentDocument",st=new Set([ot,Zt]);async function he(r,e,t,n,o="delete"){let s=!1,a={},i=0,d=0,l=(g,m)=>(d+=g,m()),c={bulk2:{createJob:g=>{let m=r.bulk2.createJob(g);return{get id(){return m.id},open:()=>l(1,()=>m.open()),uploadData:h=>l(1,()=>m.uploadData(h)),close:async()=>{await l(1,()=>m.close()),s=!0},abort:()=>l(1,()=>m.abort()),check:async()=>{let h=await l(1,()=>m.check());return a={state:h.state,message:h.errorMessage},h},getAllResults:async()=>{let h=await l(zt,()=>m.getAllResults());return i=Array.isArray(h)?h.length:(h.successfulResults?.length??0)+(h.failedResults?.length??0),h}}}}},f;try{f=await new Jt().executeBulk({connection:c,bulkManager:new Ne(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let m=g?.errorCode;return{kind:"untouched",reason:P(g),...typeof m=="string"&&m!==""?{code:m}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(a.state!=="JobComplete"&&i===0)return{kind:"untouched",reason:a.message||`job ${a.state??"not complete"}`,requests:d};let u=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,m)=>{let h=u.get(m);return h?.success?{success:!0}:{success:!1,error:h?.error??"The job gave no result for it."}})}}function yo(r,e){let t=Me(r);return{...Ce(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>he(t,n,o,s),bulkHardDestroy:(n,o,s)=>he(t,n,o,s,"hardDelete")}}var it=X({success:L(),errors:ae(Ie([X({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ne(r){return r.slice(0,15)}function je(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function at(r){if(typeof r=="string")return r;let e=je(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function de(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function er(r){return new Promise(e=>setTimeout(e,r))}function tr(r){let e=Xn*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Xt(r,e,t,n){let o=[...t];for(let s=0;s<Gt;s++){let a=o.flatMap((d,l)=>d.kind==="refused"&&d.locked===!0?[l]:[]);if(a.length===0||n.stopped?.()===!0||(await(n.wait??er)(tr(s)),n.stopped?.()===!0))break;let i=await e(a.map(d=>r[d]));if(i===void 0)break;a.forEach((d,l)=>{let c=i[l];c&&(o[d]={...c,lockResends:s+1})})}return o}async function dt(r,e,t,n={}){if(e===ot)return dr(r,t,n);let o=s=>nr(r,e,s);return Xt(t,o,await o(t),n)}async function nr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let a=P(s);return t.map(()=>({kind:"refused",reason:a,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,a)=>{let i=it.safeParse(o[a]);if(i.success&&i.data.success)return{kind:"deleted"};let d=i.success?i.data.errors??[]:[];if(d.some(c=>je(c)==="ENTITY_IS_DELETED"))return{kind:"gone"};let l=d.length>0&&d.every(c=>je(c)===rt);return{kind:"refused",reason:d.length>0?at(d[0]):"The org gave no reason.",dependency:d.some(c=>je(c)===Kt),...l?{locked:!0}:{}}})}async function rr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:or}:"untouched";let a=async d=>{let l;try{l=await s(e,d,o.signal)}catch(f){let u=P(f);return d.map(()=>({kind:"refused",reason:u,dependency:!1}))}if(l.kind==="aborted")return"aborted";if(l.kind==="untouched"){if(n!=="hard")return"untouched";if(l.code===Yt)return{hardRefused:sr(l.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${l.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:c}=l;return d.map((f,u)=>{let g=c[u];if(g?.success===!0)return{kind:"deleted"};let{code:m,message:h}=ar(g?.error??"");return m==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:m&&h?`${m}: ${h}`:g?.error||m||h||"The org gave no reason.",dependency:m===Kt,...m===rt?{locked:!0}:{}}})},i=await a(t);return Array.isArray(i)?Xt(t,async d=>{let l=await a(d);return Array.isArray(l)?l:void 0},i,o):i}var or="Records cannot be deleted for good through this connection: nothing was sent.";function sr(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${Yt}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var ir="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function ar(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function dr(r,e,t){let n;try{n=await j(r,ot,["ContentDocumentId"],e)}catch(d){let l=P(d);return e.map(()=>({kind:"refused",reason:l,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ne(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],a=s.length>0?await dt(r,Zt,s,t):[],i=new Map(s.map((d,l)=>[d,a[l]]));return e.map(d=>{let l=o.get(ne(d));return l===void 0?{kind:"gone"}:i.get(l)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function en(r){let e=[];for(let t=0;t<r.length;t+=q)e.push({ids:r.slice(t,t+q),byJob:!1});return e}function tn(r,e,t,n="recycle"){return st.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=nt}async function cr(r,e,t,n="recycle"){let o=[],s=!st.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),a=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<nt){o.push(...en(d));return}let l=Math.ceil(d.length/Math.ceil(d.length/ve));for(let c=0;c<d.length;c+=l)o.push({ids:d.slice(c,c+l),byJob:!0})};if(!Ee(e)||t.length===0)return a(t),o;let i=new Set;try{i=new Set([...await pe(de(r),t)].map(ne))}catch{}return a(t.filter(d=>!i.has(ne(d)))),a(t.filter(d=>i.has(ne(d)))),o}function nn(r){return{objectApiName:r,op:"delete"}}async function rn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:a}=await $t(t,{key:nn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async i=>({answers:await dt(r,e,i,s)}),limited:i=>i?.kind==="refused"?jt([i.reason]):void 0,settle:(i,d,l,c)=>{let f=[],u=[];i.forEach((g,m)=>{if(l.has(m))return;let h=d[m]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},R=c.get(m);f.push(g),u.push(R!==void 0&&h.kind==="refused"?{...h,dependency:!1,limit:R}:h)}),f.length>0&&o.settle(f,u)}});return a!==void 0}function ct(r,e){let t=nn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(xt(n)),n.notSplit>0&&o.push(Ft(n.notSplit,Ut(e.allowance,t),"removal")),n.keptWhole>0?o.push(Bt):n.alone>0&&o.push(_t),o}function on(r){let e=0,t=0,n=0,o=0;for(let a of r)e++,a==="deleted"?t++:a==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${rt}), each sent again up to ${Gt} times, a wait before each: ${s.join(", ")}.`]}async function sn(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&st.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:ir,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},a=await cr(r,e,t,o);for(let i=a.shift();i!==void 0;i=a.shift()){let{ids:d,byJob:l}=i;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!l){if(await rn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let c=await rr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(c==="aborted")return{stopped:!0};if(c==="untouched"){a.unshift(...en(d));continue}if(!Array.isArray(c))return{stopped:!0,hardRefused:c.hardRefused};n.settle(d,c)}return{stopped:!1}}async function an(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let a=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>a&&(n=!0)}}return!1}async function Te(r,e){let t=new Set(e.map(a=>a.objectApiName)),n=new Map;for(let{objectApiName:a}of e){let i;try{i=(G.parse(await r.describe(a)).childRelationships??[]).map(l=>l.childSObject)}catch{continue}for(let d of i){if(d===a||!t.has(d))continue;let l=n.get(d)??new Set;l.add(a),n.set(d,l)}}let o=[...e],s=[];for(;o.length>0;){let a=o.findIndex(i=>!o.some(d=>d!==i&&n.get(d.objectApiName)?.has(i.objectApiName)));s.push(...o.splice(a>=0?a:0,1))}return s}async function lt(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(a){return{gone:[],unchecked:[...r],failure:P(a)}}let o=new Set(n.map(a=>ne(String(a.Id)))),s=r.filter(a=>!o.has(ne(a)));return{gone:s.filter(t),unchecked:s.filter(a=>!t(a))}}function lr(r){return r.filter(e=>me[e]!==void 0&&!Ze.has(e))}async function ut(r,e,t,n,o,s){let a=de(r),i=[];for(let{objectApiName:d}of e){let l=me[d];if(!l||Ze.has(d))continue;let c;for await(let f of t.pages(d)){let u=f.filter(w=>n(d,w));if(u.length===0)continue;if(o())return{drafted:i,cancelled:!0};c??=await Pe(a,l);let g=c,m=g?.draft;if(!g||!m)break;let h=await s(d,u),R;try{R=await j(r,d,["Status"],u)}catch{continue}let b=R.filter(w=>typeof w.Id=="string"&&!h.has(w.Id.slice(0,15))).filter(w=>{let k=g.categoryOf.get(String(w.Status));return k!==void 0&&k!=="Draft"}).map(w=>({objectApiName:d,id:String(w.Id),draft:m,status:String(w.Status)}));for(let w=0;w<b.length;w+=q){if(o())return{drafted:i,cancelled:!0};let k=b.slice(w,w+q);i.push(...k);try{await r.update(d,k.map(({id:I})=>({Id:I,Status:m})))}catch{}}}}return{drafted:i,cancelled:!1}}function Oo(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function dn(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(c=>c.objectApiName===o),a=new Map(s.map(c=>[c.id.slice(0,15),c])),i=s.map(c=>c.id),d;try{d=await j(r,o,["Status"],i)}catch(c){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${P(c)}`,!0);continue}let l=d.flatMap(c=>{let f=typeof c.Id=="string"?a.get(c.Id.slice(0,15)):void 0;return f&&c.Status===f.draft?[f]:[]});for(let c=0;c<l.length;c+=q){let f=l.slice(c,c+q),u;try{u=await r.update(o,f.map(({id:m,status:h})=>({Id:m,Status:h})))}catch(m){u=f.map(()=>({success:!1,errors:[P(m)]}))}let g=Array.isArray(u)?u:[u];f.forEach(({draft:m,status:h},R)=>{let b=it.safeParse(g[R]);if(b.success&&b.data.success){t.note(o,`Status set to ${m} for the delete, then back to ${h}.`,!1,f[R]);return}let w=b.success?b.data.errors??[]:[],k=w.length>0?at(w[0]):"The org gave no reason.";t.note(o,`Status set to ${m} for the delete, and left there: the org refused ${h} back \u2014 ${k}`,!0,f[R])})}}}var le="DuplicateRecordSet",ur="DuplicateRecordItem",_e=2e3,fr=999,gr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function T(r){return r.slice(0,15)}function cn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function ft(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function ln(r,e){return(await mr(r,e)).map(t=>({id:t.id,modified:pr(t,e)}))}async function mr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!gr.test(e.user))return[];let t;try{let l=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${le} WHERE CreatedDate >= ${cn(e.start-2e3)} AND CreatedDate <= ${cn(e.end+6e4)} LIMIT ${_e}`);if(l.records.length>=_e)return[];t=l.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);if(n.length===0)return[];let o=new Map,s=new Map,a=new Map;try{for(let l of H(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${ur} WHERE DuplicateRecordSetId IN (${l}) LIMIT ${_e}`);if(c.records.length>=_e)return[];for(let f of c.records){let u=f??{},g=u.DuplicateRecordSetId,m=u.RecordId;if(typeof g!="string")continue;let h=ft(u.CreatedDate);if(Number.isFinite(h)&&!(h<=(a.get(T(g))??Number.NaN))&&a.set(T(g),h),typeof m!="string"||!e.has(T(m))){let R=o.get(T(g))??new Set;R.add(typeof m=="string"?T(m):`item ${String(u.Id)}`),o.set(T(g),R)}else s.set(T(g),[...s.get(T(g))??[],T(m)])}}}catch{return[]}let i=T(e.user),d=(l,c)=>{let f=o.get(l)?.size??0;return s.has(l)?f<=1:f===0&&typeof c=="string"&&T(c)===i};return t.flatMap(l=>typeof l.Id=="string"&&d(T(l.Id),l.LastModifiedById)?[{id:l.Id,created:ft(l.CreatedDate),modified:ft(l.LastModifiedDate),...typeof l.LastModifiedById=="string"?{modifiedBy:l.LastModifiedById}:{},names:s.get(T(l.Id))??[],...a.has(T(l.Id))?{itemsMade:a.get(T(l.Id))}:{}}]:[])}function pr(r,e){if((r.modifiedBy!==void 0?T(r.modifiedBy):"")===T(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+fr)?Math.min(r.modified,e.end):r.modified}async function un(r,e,t,n="recycle"){let o=N(e),s=new Set;try{for(let a of H(t)){let i=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${a}) AND IsDeleted = true`);for(let d of i.records){let l=d?.Id;typeof l=="string"&&s.add(l.slice(0,15))}}}catch(a){return{error:P(a)}}return{deleted:s,inBin:n!=="hard"}}var hr=/__kav$/i;function ye(r){return hr.test(r)}function gn(r){return r.replace(/v$/i,"")}var gt="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",yr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},fn=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",br="An article version is deleted through its article, over REST.",Rr={success:!1,errors:[{message:"The org gave no reason."}]};function J(r){return r.slice(0,15)}function mn(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>ye(n)?wr(r,n):r.describe(n),destroy:(n,o)=>ye(n)?Sr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>ye(n)?Promise.resolve({kind:"untouched",reason:br,requests:0}):t(n,o,s)}:{}}}async function wr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(gn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function pn(r,e,t){let n=N(e),o=new Map,s=new Map,a=(d,l)=>{for(let c of d){let f=c;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;l?.set(J(f.Id),f.KnowledgeArticleId);let u=J(f.KnowledgeArticleId),g=s.get(u)??new Set;g.add(J(f.Id)),s.set(u,g)}};for(let d of["",fn])for(let l of H(t)){let c=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${l})${d}`);a(c.records,o)}let i=[...new Set(o.values())];for(let d of["",fn])for(let l of H(i)){let c=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${l})${d}`);a(c.records)}return{articleOf:o,versions:s}}function hn({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(J)),s=a=>[...e.get(a)??[]].some(i=>!o.has(i));return new Set([...r.values()].map(J).filter(s))}async function yn(r,e,t,n){let o=await pn(r,e,t),s=hn(o,t,n);return new Set(t.map(J).filter(a=>{let i=o.articleOf.get(a);return i!==void 0&&s.has(J(i))}))}async function Sr(r,e,t,n){let o=await pn(r,e,t),{articleOf:s}=o,a=[...new Set(s.values())],i=hn(o,t,n),d=a.filter(c=>!i.has(J(c))),l=new Map;if(d.length>0){let c;try{c=await r.destroy(gn(e),d)}catch(u){let g=P(u);c=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(c)?c:[c];d.forEach((u,g)=>l.set(J(u),f[g]))}return t.map(c=>{let f=s.get(J(c));return f===void 0?{success:!1,errors:[yr]}:i.has(J(f))?{success:!1,errors:[{message:gt}]}:l.get(J(f))??Rr})}var xe="Quote",Re="QuoteLineItem",be="Opportunity",we="OpportunityLineItem",bn=2e3;function kr(r){return r.slice(0,15)}function Rn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function F(r,e){let t=r[e];return typeof t=="string"&&t!==""?kr(t):void 0}function pt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function Or(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let m=F(g,"Id"),h=F(g,"SyncedQuoteId");!m||!h||!pt(e,m)||!e.has(h)||(t.add(h),n.add(m))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let m=F(g,"QuoteId");return m!==void 0&&t.has(m)&&F(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let m=F(g,"OpportunityId");return m!==void 0&&n.has(m)&&F(g,"Id")!==void 0}),a=g=>F(g,"CreatedById"),i=(g,m)=>{let h=F(g,"Id");if(!h||pt(e,h)||!m)return!1;let R=e.user??a(m),b=Rn(g.CreatedDate);return R!==void 0&&a(g)===R&&b>=e.start&&b<=e.end},d=g=>({id:String(g.Id),modified:Rn(g.LastModifiedDate)}),l=new Map(s.flatMap(g=>{let m=F(g,"Id");return m&&e.has(m)?[[m,g]]:[]})),c=new Map;for(let g of o){let m=F(g,"Id"),h=F(g,"OpportunityLineItemId");m&&h&&e.has(m)&&!c.has(h)&&c.set(h,g)}let f=o.filter(g=>{let m=F(g,"OpportunityLineItemId");return i(g,m?l.get(m):void 0)}).map(d),u=s.filter(g=>{let m=F(g,"Id");return i(g,m?c.get(m):void 0)}).map(d);return[...f.length>0?[{objectApiName:Re,copies:f}]:[],...u.length>0?[{objectApiName:we,copies:u}]:[]]}function wn(r,e=[]){let t=new Set(r),n=t.has(be)||new Set(e).has(be);if(!t.has(xe)||!n)return[];let o=t.has(Re),s=t.has(we);return o===s?[]:[o?we:Re]}async function mt(r,e,t,n,o){let s=t.map(N).join(", "),a=[];for(let i of H(o)){let d=await r.query(`SELECT ${s} FROM ${N(e)} WHERE ${N(n)} IN (${i}) LIMIT ${bn}`);if(d.records.length>=bn)throw new Error(`More ${e} records than one read takes.`);for(let l of d.records)typeof l=="object"&&l!==null&&a.push(l)}return a}async function Sn(r,e,t,n){let o=n.has(Re)||n.has(we),s=n.has(be)||e.otherParts?.objects.has(be)===!0;if(t.length===0||!s||!o)return[];try{let i=(await mt(r,be,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(c=>{let f=F(c,"Id");return f!==void 0&&pt(e,f)});if(i.length===0)return[];let d=await mt(r,Re,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(i.map(c=>String(c.SyncedQuoteId)))]),l=await mt(r,we,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",i.map(c=>String(c.Id)));return Or({syncing:i,quoteLines:d,opportunityLines:l},e)}catch{return[]}}var Ar=5,Se=4,Fe=2e3,Dr=4,He=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],yt=1e4,Ir="005",kn="ContentDocumentLink",Er="ContentDocument",Pr="ContentVersion",Cr=5;function Je(r){let e=new Set(r.flatMap(n=>n.ids.map(y))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function re(r){return!Array.isArray(r)}function es(r){return re(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function ts(r){return(re(r)?r.objects:r).map(e=>e.objectApiName)}var ze=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},bt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function ue(r,e){return typeof r=="string"&&e.has(y(r))}var On=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],ht={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return ue(r.ContentDocumentId,e)&&(ue(t,e)||typeof t=="string"&&t.startsWith(Ir))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>ue(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>ue(r.ContentDocumentId,e)},[te.objectApiName]:{ends:[te.parent,te.field],cameWithRun:(r,e)=>r[te.field]===te.value&&ue(r[te.parent],e)}};function ns(r,e){return{...Ce(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>he(Me(r),t,n,o)}}function Rt(r,e,t){let n=new Map;for(let o of r??[]){let s=kt(o.span,[],t);if(Number.isFinite(s.end))for(let a of o[e]??[]){let i=y(a);s.end<=(n.get(i)?.end??Number.NEGATIVE_INFINITY)||n.set(i,s)}}return n}function Nr(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>re(n)?n:Je(n)),Je(e)];return{has:n=>t.some(o=>o.has(n))}}function Mr(r=[],e=[]){return new Set([...r.map(({plan:t})=>re(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function Pn(r,e){return new Map([...Rt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function Cn(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function wt(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function An(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new ke(o,s,t(o)).result,notReached:s}));return r}var rs={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function y(r){return r.slice(0,15)}function Lr(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(P(r))}function jr(r,e){let t=/no such column '(\w+)'/i.exec(P(r))?.[1],n=He.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?He.length:n}function M(r){return typeof r=="string"?Date.parse(r):Number.NaN}function Nn(){return{modified:new bt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var ke=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ze;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(y(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let a of this.secondTry){let i=y(a);this.deletedLater.has(i)?e++:this.goneLater.has(i)?t++:this.refused.has(a)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let a=this.automationHeld.get(y(s));return a?[a]:[]}),t=this.held.filter(s=>{let a=y(s);return this.automationHeld.has(a)&&this.automationHeldAfter.has(a)}).length,n=this.held.filter(s=>{let a=y(s);return this.automationHeld.has(a)&&this.automationHeldAlong.has(a)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...on(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,Ar),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,Cr)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function os(r,e,t){let n=re(e)?e:Je(e),o=n,s=o.objects.reduce((p,S)=>p+S.count,0),a=new Map,i=p=>a.get(p)??0,d=()=>t.signal?.aborted===!0,l=t.splitting??Tt(),c=()=>({objects:An([],o.objects,i),cancelled:!0,gone:[],stamps:{},left:()=>En(n)}),f=new Map,u=new Map;for(let{objectApiName:p}of o.objects){let S=Nn();f.set(p,S);let O=0;for await(let A of o.pages(p)){if(d())return c();let v=A[0];v!==void 0&&!u.has(v.slice(0,3))&&u.set(v.slice(0,3),p);let E=O;if(O+=A.length,S.error!==void 0)continue;let D=await Ur(r,p,A,E,S);if(S.error!==void 0||D.length===0)continue;if(d())return c();let B=await un(r,p,D);if("error"in B)S.binError=B.error;else for(let z of B.deleted)S.binned.add(z)}}let g=new Map,m=!1,h=r.bulkDestroy?.bind(r),R={query:p=>r.query(p),destroy:(p,S)=>(m=!0,r.destroy(p,S)),...h?{bulkDestroy:(p,S)=>(m=!0,h(p,S,t.signal))}:{},update:(p,S)=>(m=!0,r.update(p,S)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:p=>r.queryDeleted(p),describeGlobal:()=>r.describeGlobal(),describe:p=>{let S=g.get(p);return S||(S=r.describe(p),g.set(p,S)),S}},b=mn(R,{includeChanged:t.includeChanged}),w=await Te(b,o.objects),k=await xr(b,w,(p,S)=>S-(f.get(p)?.missing.size??0)),I=new Set(k.map(p=>p.objectApiName));if(k.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return c();if(!await t.onUndeletable(k))return{...c(),objects:[],undeletable:k,stoppedForUndeletable:!0}}let[C,_]=await Promise.all([Jr(b),t.previewOnly===!0?void 0:zr(b)]),{start:Y,end:V}=kt(t,f.values(),C.aheadMs);if(d())return c();let oe=Nr(t.otherParts,t.otherPartRecords),qe=Mr(t.otherParts,t.otherPartRecords),Ae=await $r(b,o,{start:Y,end:V,...t.runUserId?{user:y(t.runUserId)}:{},...oe?{otherParts:{has:p=>oe.has(p),objects:qe}}:{},undeletable:I,snapshots:f}),We=[];if(t.runUserId&&t.alongAccepted!==!0){let p=await ln(b,{has:S=>o.has(S),start:Y,end:V,user:t.runUserId});if(p.length>0&&!o.objects.some(S=>S.objectApiName===le)&&await Mn(b,le)){Ae.push({objectApiName:le,copies:p});for(let S of p)We.push(S.id)}}if(Ae.length>0){o=await Hr(o,Ae,f,u);for(let{objectApiName:p,copies:S}of Ae)a.set(p,S.length);s=o.objects.reduce((p,S)=>p+S.count,0),w=await Te(b,o.objects)}let Tn=new Map(Object.entries(t.removalStamps??{}).map(([p,S])=>[y(p),M(S)])),_n=Pn(t.laterParts,C.aheadMs),se=new Set;for(let{objectApiName:p}of o.objects){let S=f.get(p);if(!S||S.error!==void 0)continue;let O=0;for await(let A of o.pages(p))for(let v of A){let E=S.modified.at(O++),D=y(v);if(S.missing.has(D))continue;E<=V||E<=(Tn.get(D)??Number.NaN)||E<=(_n.get(D)??Number.NaN)||se.add(D)}}if(t.previewOnly===!0){if(d())return c();let p=new Set,S=await Tr(b,o,w,{snapshots:f,changed:se,undeletable:I,includeChanged:t.includeChanged,stopped:d,copiesOf:i,...t.previewHeld===!0?{held:{notSent:p,check:new Oe(b,{runRecords:o,reached:{has:()=>!1},stays:O=>p.has(O),runStart:Y,runEnd:V,removalStart:C.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(O=>({start:M(O.first),end:M(O.last),user:y(O.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:y(t.runUserId)}:{},...t.laterParts?{linkedLater:Rt(t.laterParts,"linked",C.aheadMs)}:{},...oe?{otherPartRecords:oe,otherPartObjects:qe}:{}})}}:{}});return S?{...k.length>0?{undeletable:k}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>En(n),preview:S}:c()}let Ot=await Fr(b,t.otherParts??[],C.aheadMs,d);if(!Ot)return c();let At=new Set,Bn={has:p=>o.has(p)&&At.has(u.get(p.slice(0,3))??"")},Qe=new Oe(b,{runRecords:o,reached:Bn,stays:p=>se.has(p)&&!t.includeChanged,runStart:Y,runEnd:V,removalStart:C.start,removalUser:_,earlierRemovals:(t.removalSpans??[]).map(p=>({start:M(p.first),end:M(p.last),user:y(p.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:y(t.runUserId)}:{},...t.automationMade?{automationMade:vn(t.automationMade)}:{},...t.laterParts?{linkedLater:Rt(t.laterParts,"linked",C.aheadMs)}:{},...oe?{otherPartRecords:oe,otherPartObjects:qe}:{}});if(d())return c();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(l)&&(m=!0);let Z=[],Dt=p=>Z.find(S=>S.result.objectApiName===p);async function*Ve(p,S,O){for(let{objectApiName:A}of S){let v=Dt(A),E=0;for await(let D of p.pages(A)){let B=D.filter(z=>O(A,z,v?.isGone(z,E++)===!0));B.length>0&&(yield{objectApiName:A,ids:B})}}}let xn=()=>Ve(o,w,(p,S,O)=>{let A=f.get(p),v=y(S);return A?.modifiedColumn==="LastModifiedDate"&&!A.missing.has(v)&&!se.has(v)&&!O}),De=[],$=async p=>{await dn(b,De,{note:(D,B,z)=>{let U=Dt(D);if(!U){if(!z)return;let W=o.objects.find(Q=>Q.objectApiName===D);U=new ke(D,W?.count??0,i(D)),Z.push(U)}U.note(B)}});let S=m?await Dn(b,xn(),{start:C.start,user:_}):{},O=[];if(m)for(let D of Ot)O.push(await Dn(b,D.unchanged(),{start:C.start,user:_}));let A=m?qr(C,_):void 0,v=[];if(!re(e))for await(let{ids:D}of Ve(n,w,(B,z,U)=>U))for(let B of D)v.push(B);for(let D of Z)D.limitNotes=ct(D.result.objectApiName,l);let E=Z.map(D=>D.settle());return{...k.length>0?{undeletable:k}:{},objects:p?An(E,w,i):E,cancelled:p,gone:v,left:()=>Ve(n,n.objects,(D,B,z)=>!z),stamps:S,...A?{span:A}:{},...O.length>0?{otherPartStamps:O}:{},...We.length>0?{duplicateSets:We}:{}}};if(d())return m?$(!0):c();let It=async(p,S)=>(await Qe.heldAmong(p,S)).held,Et=await ut(b,w,o,(p,S)=>{let O=y(S),A=f.get(p);return A!==void 0&&A.error===void 0&&!I.has(p)&&!A.missing.has(O)&&!(se.has(O)&&!t.includeChanged)},d,It);if(De=Et.drafted,Et.cancelled)return $(!0);if(t.alongToDraft){let p=await ut(b,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,It);if(De=[...De,...p.drafted],p.cancelled)return $(!0)}let K=0;for(let{objectApiName:p,count:S}of w){if(d())return $(!0);let O=new ke(p,S,i(p));Z.push(O),At.add(p);let A=f.get(p);if(!A||A.error!==void 0){O.unread={reason:A?.error??"The org gave no reason.",count:S},K+=S,t.onProgress?.(K,s,p);continue}if(I.has(p)){let U=0,W=0;for await(let Q of o.pages(p))for(let ie of Q){let fe=y(ie),Un=U++;A.missing.has(fe)?A.binned.has(fe)?(O.result.alreadyGone++,O.goneAt.add(Un)):O.notVisible++:W++}O.notVisible>0&&(O.notVisibleNote=wt(O.notVisible,A.binError)),W>0&&(O.unread={reason:Cn(p,W),count:W}),K+=S,t.onProgress?.(K,s,p);continue}let v=tn(b,p,S),E=[],D=new Map,B=async()=>{let U=E,W=D;return E=[],D=new Map,In(b,Qe,O,U,{stopped:d,splitting:l,placeOf:W,onDeleted:Q=>{K+=Q,t.onProgress?.(K,s,p)},onHeld:Q=>{K+=Q,t.onProgress?.(K,s,p)}})},z=0;for await(let U of o.pages(p)){if(d())return $(!0);let W=E.length;for(let Q of U){let ie=y(Q),fe=z++;A.missing.has(ie)?A.binned.has(ie)?(O.result.alreadyGone++,O.goneAt.add(fe)):O.notVisible++:se.has(ie)&&!t.includeChanged?O.result.keptChanged++:(E.push(Q),D.set(ie,fe))}if(O.notVisible>0&&(O.notVisibleNote=wt(O.notVisible,A.binError)),K+=U.length-(E.length-W),!(v&&E.length<ve)&&await B())return $(!0)}if(v&&E.length>0&&(d()||await B()))return $(!0)}let Fn=Z.some(p=>p.result.deleted>0);if(await an(Z,{stopped:d,idsOf:(p,S)=>{if(S>0)return p.waiting();let O=p.refusedToSendAgain();return O.length>0||Fn?[...O,...p.held]:[]},send:async(p,S,O)=>{let A=new Set(O===0?p.refusedToSendAgain():[]),v=await In(b,Qe,p,S,{stopped:d,splitting:l,onSent:E=>{for(let D of E)A.has(D)&&p.secondTry.add(D)}});for(let E of p.held)A.has(E)&&p.secondTry.add(E);return v},deleted:p=>p.result.deleted}))return $(!0);if(t.afterRemoval){if(d())return $(!0);await t.afterRemoval(l)&&(m=!0)}for(let p of Z){if(d())return $(!0);await Br(b,p,f.get(p.result.objectApiName))}return $(!1)}async function vr(r,e,t,n,o){let{changed:s,includeChanged:a}=o,i=[];for await(let d of e.pages(t))for(let l of d){let c=y(l);!n.has(c)&&(a||!s.has(c))&&i.push(l)}try{return{kept:await yn(r,t,i,{includeChanged:a})}}catch(d){return{kept:new Set,unread:P(d)}}}async function Tr(r,e,t,n){let o=[],s=new Set,a=new Set;for(let{objectApiName:i,count:d}of t){let l=n.copiesOf(i),c={objectApiName:i,planned:d,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...l>0?{platformCopies:l}:{},reasons:[]};o.push(c);let f=n.snapshots.get(i);if(!f||f.error!==void 0){if(c.unread=d,c.reasons.push(f?.error??"The org gave no reason."),n.held)for await(let R of e.pages(i))for(let b of R)n.held.notSent.add(y(b));continue}let u=ye(i)&&!n.undeletable.has(i)?await vr(r,e,i,f.missing,n):void 0,g=[],m=[],h=R=>{n.held?.notSent.add(R)};for await(let R of e.pages(i))for(let b of R){let w=y(b);f.missing.has(w)?f.binned.has(w)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,h(w)):u?.unread!==void 0?(c.unread++,h(w)):n.changed.has(w)?(c.changedSince++,g.push(b),n.includeChanged?(c.toDelete++,m.push(b)):(c.keptChanged++,h(w))):u?.kept.has(w)?(c.changedSince++,c.keptChanged++,h(w)):(c.toDelete++,m.push(b))}if(n.held&&m.length>0){if(n.stopped())return;let R=await n.held.check.heldAmong(i,m),b=m.filter(k=>R.held.has(y(k)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...R.holders];for(let I of b)n.held.notSent.add(y(I));let k=b.filter(I=>R.byAutomation.has(y(I)));k.length>0&&(c.heldByAutomation=k.length)}let w=new Map;for(let k of m)if(!R.held.has(y(k)))for(let[I,C]of R.cameAlong.get(y(k))??[])a.has(I)||(a.add(I),w.set(I,C));w.size>0&&(c.cameAlong={count:w.size,objects:[...new Set(w.values())]}),R.reason!==void 0&&c.reasons.push(R.reason),R.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...R.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(u?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${u.unread}`):u!==void 0&&u.kept.size>0&&c.reasons.push(gt),c.notVisible>0&&c.reasons.push(wt(c.notVisible,f.binError)),c.undeletable>0&&c.reasons.push(Cn(i,c.undeletable)),!(g.length===0||f.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let R=await j(r,i,["LastModifiedById"],g,Se);for(let b of R){let w=b.LastModifiedById;typeof w!="string"||w===""||(c.changedBy[w]=(c.changedBy[w]??0)+1,s.add(w))}}catch(R){c.reasons.push(`Who changed them since the run could not be read: ${P(R)}`)}}}if(!n.stopped())return{objects:o,userNames:await _r(r,[...s])}}async function _r(r,e){let t={};if(e.length===0)return t;try{for(let n of await j(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function Br(r,e,t){let{gone:n,unchecked:o,failure:s}=await lt(e.refusedSent(),a=>j(r,e.result.objectApiName,[],a),a=>t!==void 0&&t.error===void 0&&!t.missing.has(y(a)));for(let a of n)e.refused.delete(a),e.goneLater.add(y(a)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(s?` \u2014 ${s}`:"."))}function ss(r,e=[],t={}){return[...new Set([...r,...wn(r,e),...t.userKept===!0&&r.length>0?[le]:[]])]}async function xr(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===Pr||s===0)continue;let a=t(o,s);if(a!==0)try{let i=G.safeParse(await r.describe(o));i.success&&i.data.deletable===!1&&n.push({objectApiName:o,records:a})}catch{}}return n}async function Dn(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:a,ids:i}of e){let d;try{d=await j(r,a,["LastModifiedDate","LastModifiedById"],i)}catch{continue}for(let l of d)typeof l.Id=="string"&&typeof l.LastModifiedDate=="string"&&typeof l.LastModifiedById=="string"&&y(l.LastModifiedById)===s&&M(l.LastModifiedDate)>=o&&(n[l.Id]=l.LastModifiedDate)}return n}async function Fr(r,e,t,n){let o=[];for(let s of e){let a=re(s.plan)?s.plan:Je(s.plan),{end:i}=kt(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,u])=>[y(f),M(u)])),l=Pn(s.laterParts,t),c=new Map;if(Number.isFinite(i))for(let{objectApiName:f}of a.objects){let u=new ze,g=0,m=!1;for await(let h of a.pages(f)){if(n())return;let R=g;if(g+=h.length,m)continue;let b;try{b=await j(r,f,["LastModifiedDate"],h,Se)}catch{m=!0;continue}let w=new Map;for(let k of b)typeof k.Id=="string"&&w.set(y(k.Id),M(k.LastModifiedDate));h.forEach((k,I)=>{let C=y(k),_=w.get(C);_!==void 0&&(_<=i||_<=(d.get(C)??Number.NaN)||_<=(l.get(C)??Number.NaN))&&u.add(R+I)})}m||c.set(f,u)}o.push({unchanged:async function*(){for(let{objectApiName:f}of a.objects){let u=c.get(f);if(!u)continue;let g=0;for await(let m of a.pages(f)){let h=m.filter(()=>u.has(g++));h.length>0&&(yield{objectApiName:f,ids:h})}}}})}return o}async function In(r,e,t,n,o){let{objectApiName:s}=t.result,a=await e.heldAmong(s,n);a.reason!==void 0&&t.note(a.reason);for(let u of a.unchecked)t.result.unchecked.includes(u)||t.result.unchecked.push(u);let i=n.filter(u=>a.held.has(y(u)));if(o.placeOf){for(let u of i)t.held.push(u);t.result.heldBy=[...new Set([...t.result.heldBy,...a.holders])]}else t.held=i,t.result.heldBy=[...a.holders];for(let u of i)t.refused.delete(u);for(let u of n){let g=y(u),m=a.byAutomation.get(g);m?t.automationHeld.set(g,m):t.automationHeld.delete(g),m&&a.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),m&&a.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(i.length);let d=n.filter(u=>!a.held.has(y(u))),l=new Map,c=(u,g)=>{u.forEach((m,h)=>{let R=g[h],b=y(m);if((R.lockResends!==void 0||t.lockResent.has(b))&&t.lockResent.set(b,R.kind),R.kind==="refused"){t.refused.set(m,{reason:R.reason,dependency:R.dependency,sent:!0,...R.limit?{limit:!0}:{}});return}t.refused.delete(m);let w=o.placeOf?.get(b);if(w!==void 0?t.goneAt.add(w):t.goneLater.add(b),R.kind==="deleted"){t.result.deleted++,w===void 0&&t.deletedLater.add(b);for(let k of l.get(b)??[])t.filesLeft.set(k.key,k.name);for(let[k,I]of a.along.get(b)??[])t.tookAlong.set(k,I);for(let[k,I]of a.cameAlong.get(b)??[])t.cameAlong.set(k,I)}else t.result.alreadyGone++}),o.onSent?.(u),o.onDeleted?.(u.length)},{stopped:f}=await sn(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async u=>{l=await e.filesOn(u)},settle:c});return f}async function Ur(r,e,t,n,o){let s,a=o.modifiedColumn?On.filter(({modified:i})=>i===o.modifiedColumn):On;for(let{created:i,modified:d}of a)try{let c=await j(r,e,i?[i,d]:[d],t,Se),f=new Map;for(let g of c)typeof g.Id=="string"&&f.set(y(g.Id),M(g[d])),i&&(o.firstCreated=Ln(o.firstCreated,M(g[i])),o.lastCreated=St(o.lastCreated,M(g[i])));o.modifiedColumn=d;let u=[];return t.forEach((g,m)=>{let h=y(g),R=f.get(h);R===void 0&&(o.missing.add(h),u.push(g)),o.modified.set(n+m,R??Number.NaN)}),u}catch(l){s??=P(l)}return o.error=s,o.modifiedColumn=void 0,[]}async function*En(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function $r(r,e,t){let n=new Set(e.objects.filter(i=>i.count>0).map(i=>i.objectApiName));if(!n.has(xe))return[];let o=[];for await(let i of e.pages(xe))o.push(...i);let s=await Sn(r,{has:i=>e.has(i),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),a=[];for(let i of s){let{objectApiName:d}=i;if(t.undeletable.has(d))continue;let l=t.snapshots.get(d);if(l){if(l.error!==void 0||l.modifiedColumn!=="LastModifiedDate")continue}else if(!await Mn(r,d))continue;a.push(i)}return a}async function Mn(r,e){try{let t=G.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function Hr(r,e,t,n){let o=new Map(e.map(({objectApiName:i,copies:d})=>[i,d])),s=new Set(e.flatMap(({copies:i})=>i.map(d=>y(d.id)))),a=r.objects.map(i=>{let d=o.get(i.objectApiName);return d?{objectApiName:i.objectApiName,count:i.count+d.length}:i});for(let[i,d]of o){r.objects.some(u=>u.objectApiName===i)||a.push({objectApiName:i,count:d.length});let l=t.get(i);l||(l={...Nn(),modifiedColumn:"LastModifiedDate"},t.set(i,l));let c=0;for await(let u of r.pages(i))c+=u.length;for(let u of d)l.modified.set(c++,u.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,i)}return{objects:a,pages:async function*(i){yield*r.pages(i);let d=o.get(i);d&&d.length>0&&(yield d.map(l=>l.id))},has:i=>r.has(i)||s.has(i)}}async function Jr(r){let e=Date.now(),t=Number.NaN;try{t=M(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function zr(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?y(e):void 0}catch{return}}function qr(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+yt).toISOString(),userId:e}}function Ln(r,e){return Number.isNaN(r)||e<r?e:r}function St(r,e){return Number.isNaN(r)||e>r?e:r}var jn=999;function Wr(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=St(n,o.lastCreated)),n=St(n,o.modified.latestWithin(e,t));return n}function kt(r,e,t){let n=Qr(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+jn;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Qr(r,e,t){let n=[...e],o=Number.NaN;for(let l of n)o=Ln(o,l.firstCreated);let s=r.runDurationMs??0,a=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(a)){let l=a-s-yt,c=a+yt,f=r.endedByItsWrites===!0?Wr(n,l,c):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>l?o:l),end:Number.isFinite(f)?Math.min(f+jn,c):c}}let i=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??i+s;return{start:i,end:d}}function vn(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(y)),t=r.size),e.has(n))}}function is(r,e){let t=new Oe(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:M(n.first),end:M(n.last),user:y(n.userId)})),includeChanged:e.includeChanged,automationMade:vn(e.taken),...e.runUserId?{runUser:y(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var Ue="IsPersonAccount";function Vr(r,e){return{holding:new Set([...r.holding,...e.holding]),automation:[...r.automation,...e.automation],along:[...r.along,...e.along],goes:[...r.goes,...e.goes],unchecked:r.unchecked||e.unchecked}}var Kr=50;function $e(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Oe=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let u=G.parse(await this.org.describe(e)),g=await this.workedObjects(),m=e==="Account"&&u.fields.some(h=>h.name===Ue);s=(u.childRelationships??[]).filter(h=>(h.cascadeDelete===!0||h.restrictedDelete===!0)&&g.has(h.childSObject)).map(h=>({childSObject:h.childSObject,field:h.field,restricted:h.cascadeDelete!==!0,...m&&h.childSObject==="Contact"&&h.field==="AccountId"?{personContacts:!0}:{}}))}catch(u){return o.reason=P(u),t.forEach(g=>this.hold(o,y(g))),o}let a=[];for(let u=0;u<t.length;u+=q)a.push(t.slice(u,u+q));let i=a.length>1?await Xe(s.map(u=>()=>this.anyPointing(u)),Se):s.map(()=>!0),d=s.filter((u,g)=>i[g]).flatMap(u=>a.map(g=>async()=>({relationship:u,...await this.holdingIn(u,g)}))),l=o.mayBeAutomation,c=new Map;for(let{relationship:u,holding:g,unchecked:m,automation:h,along:R,goes:b}of await Xe(d,Se)){m&&o.unchecked.add(u.childSObject),(g.size>0||h.length>0)&&o.holders.add(u.childSObject),g.forEach(w=>this.hold(o,w));for(let w of h)o.held.add(y(w.parent));l.push(...h);for(let{parent:w,key:k}of R){let I=o.along.get(w)??new Map;I.set(k,u.childSObject),o.along.set(w,I)}b.length>0&&c.set(u.childSObject,[...c.get(u.childSObject)??[],...b])}if(await this.heldBelow(c,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),Ee(e)&&await this.standardPricesHeld(t,o),e===Ye&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(l,o);let f=await this.byAutomationOnly(e,l,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,a,i,d)=>{let l=s.get(a)??new Map;l.set(i,d),s.set(a,l)};for(let[s,a]of e){let i=[...new Set(a.map(l=>l.id))],d=n+1<Dr?await this.heldAmong(s,i,n+1):void 0;for(let{parent:l,id:c,came:f}of a){let u=y(c);if(!d||d.held.has(u)){this.hold(t,l),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,l,u,s);for(let[g,m]of d.along.get(u)??[])o(t.along,l,g,m);for(let[g,m]of d.cameAlong.get(u)??[])o(t.cameAlong,l,g,m)}d?.unchecked.forEach(l=>t.unchecked.add(l))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(y(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let a=await this.heldAmong(o,[...new Set(s.map(i=>i.id))],1);for(let i of s){let d=y(i.id),l=a.mayBeAutomation.some(c=>y(c.parent)===d&&c.creator!==i.creator);!a.otherwise.has(d)&&!l||(this.hold(t,y(i.parent)),a.holders.forEach(c=>t.holders.add(c)))}a.unchecked.forEach(i=>t.unchecked.add(i))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,a=t.filter(f=>!n.has(y(f.parent)));if(a.length===0)return{objects:o,after:s,along:new Set};let i;try{let f=await j(this.org,e,["CreatedDate","CreatedById"],[...new Set(a.map(u=>u.parent))]);i=new Map(f.flatMap(u=>typeof u.Id=="string"?[[y(u.Id),u]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,l=new Set;for(let f of a){let u=y(f.parent),g=i.get(u),m=M(g?.CreatedDate),h=g?.CreatedById,R=this.context.runUser??(typeof h=="string"?y(h):void 0),b=f.created-m;if(!(R!==void 0&&f.creator===R&&b>=-2e3&&b<=6e4)){d.add(u);continue}let k=o.get(u)??new Set;k.add(f.object),o.set(u,k),f.created>this.context.runEnd&&s.add(u),f.along||l.add(u)}for(let f of d)o.delete(f),s.delete(f);let c=new Set([...o.keys()].filter(f=>!l.has(f)));return{objects:o,after:s,along:c}}async holdingIn(e,t){let n=N(e.childSObject),o=N(e.field),[s]=H(t,t.length),a=new Set(["Id",o,...ht[n]?.ends??[],...e.personContacts?[Ue]:[]]),i=this.datesKept.get(n)??0;for(;i<He.length;){let d=He[i],l;try{l=await this.org.query(`SELECT ${[...a,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Fe}`)}catch(R){Lr(R)?(i=jr(R,i),this.datesKept.set(n,i)):i++;continue}if(l.records.length>=Fe){if(t.length>1){let R=Math.ceil(t.length/2);return Vr(await this.holdingIn(e,t.slice(0,R)),await this.holdingIn(e,t.slice(R)))}return{holding:new Set(t.map(y)),automation:[],along:[],goes:[],unchecked:!1}}let c=new Set,f=[],u=[],g=[],m=new Map;for(let R of l.records){if(typeof R!="object"||R===null)continue;let b=R,w=b[e.field];if(typeof w!="string"||typeof b.Id!="string"||(n===kn&&o==="LinkedEntityId"&&this.noteFile(b),this.lockedUnder.get(y(b.Id))===y(w)))continue;let k={onlyIncluded:!1};if(!this.stays(b,n,e.restricted,e.personContacts,k)){if(k.onlyIncluded&&u.push({parent:y(w),key:y(b.Id)}),n!==kn&&this.goesAlongUnread(b)){let _=!(ht[n]?.cameWithRun(b,this.context.runRecords)===!0||e.personContacts===!0&&b[Ue]===!0)&&!k.onlyIncluded&&k.byRemoval!==!0&&this.context.goesWithParent?.(b,this.context.runEnd)!==!0;g.push({parent:y(w),id:b.Id,came:_})}continue}let I=this.mayBeAutomation(b);if(I){let C={parent:w,id:b.Id,object:n,along:!e.restricted,...I};f.push(C),e.restricted&&m.set(b.Id,C)}else c.add(y(w))}let h=await this.ofOtherParts(n,[...m.keys()]);for(let[R,b]of m)h.has(y(R))&&(f.splice(f.indexOf(b),1),c.add(y(b.parent)));return{holding:c,automation:f,along:u,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=y(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:a,runEnd:i}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||a?.(e,i)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:a}=this.context;if(t.length===0||!o||!s)return n;let i=this.cascadeEnds.get(e);i||(i=(async()=>{let c=new Set;for(let f of s)try{let u=G.parse(await this.org.describe(f));for(let g of u.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&c.add(g.field)}catch{}return[...c]})(),this.cascadeEnds.set(e,i));let d=await i;if(d.length===0)return n;let l;try{l=await j(this.org,e,d,t)}catch{return n}for(let c of l){if(typeof c.Id!="string")continue;let f=d.flatMap(u=>{let g=c[u];return typeof g=="string"?[y(g)]:[]});f.some(u=>a.has(u))||f.some(u=>o.has(u))&&n.add(y(c.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:a}=this.context;if(typeof e.Id!="string"||t.has(y(e.Id))||a?.has(y(e.Id))===!0||typeof e.CreatedById!="string")return;let i=y(e.CreatedById);if(s!==void 0&&i!==s)return;let d=M(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let l=M(e.LastModifiedDate),c=typeof e.LastModifiedById=="string"?y(e.LastModifiedById):void 0;if(!(l>o&&c!==void 0&&c!==i))return{created:d,creator:i}}async anyPointing(e){try{let t=N(e.childSObject),n=N(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||ue(n,this.context.runRecords))return;let o=this.files.get(y(t))??new Set;o.add(n),this.files.set(y(t),o)}async filesOn(e){let t=new Map;for(let s of e){let a=this.files.get(y(s));a&&a.size>0&&t.set(y(s),[...a])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await j(this.org,Er,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(y(s.Id),s.Title)}catch{}return new Map([...t].map(([s,a])=>[s,a.map(i=>({key:y(i),name:o.get(y(i))??i}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(Mt)){let a=s.find(u=>u.object===e)?.lookup,i=me[o];if(!a||!i)continue;let d=await this.statusCategoriesOf(i);if(!d)continue;let l,c;try{l=await j(this.org,e,[a],t);let u=[...new Set(l.map(g=>g[a]).filter(g=>typeof g=="string"))];c=u.length>0?await j(this.org,o,["Status"],u):[]}catch{continue}let f=new Set(c.filter(u=>{let g=d.categoryOf.get(String(u.Status));return g!==void 0&&g!=="Draft"}).map(u=>y(String(u.Id))));for(let u of l){let g=u[a];typeof u.Id!="string"||typeof g!="string"||f.has(y(g))&&(this.hold(n,y(u.Id)),n.holders.add(o),this.lockedUnder.set(y(u.Id),y(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=Pe(de(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=de(this.org),o=[...await pe(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),a=await j(this.org,ee,s,o),i=await this.pricesOfProducts(a,s),d=i.flatMap(u=>typeof u.Id=="string"?[u.Id]:[]),l=new Set([...await pe(n,d)].map(y)),c=new Set(e.map(y)),f=new Set;for(let u of i){if(typeof u.Id!="string")continue;let g=y(u.Id);if(l.has(g))continue;(c.has(g)?t.held.has(g):this.stays(u,ee,!0))&&f.add($e(u,s))}for(let u of a)typeof u.Id!="string"||!f.has($e(u,s))||(this.hold(t,y(u.Id)),t.holders.add(ee))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ge,Ge];try{let o=await j(this.org,Ye,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),a=new Set(s.filter(i=>typeof i.Id=="string"&&i.IsActive===!0&&this.stays(i,ee,!0)).map(i=>$e(i,n)));for(let i of o)typeof i.Id!="string"||!a.has($e(i,n))||(this.hold(t,y(i.Id)),t.holders.add(ee))}catch{}}async priceKeyFields(){let e=G.parse(await this.org.describe(ee)),t=new Set(e.fields.map(n=>n.name));return[ge,...[Ge,Lt].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(a=>a[ge]).filter(a=>typeof a=="string"))],o=[...new Set(["Id",...t])].map(N).join(", "),s=[];for(let a of H(n,Kr)){let i=await this.org.query(`SELECT ${o} FROM ${ee} WHERE ${ge} IN (${a}) LIMIT ${Fe}`);if(i.records.length>=Fe)throw new Error("More prices than one read takes.");for(let d of i.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let a=y(e.Id),{runRecords:i,reached:d,runStart:l,runEnd:c,removalStart:f,removalUser:u,earlierRemovals:g,includeChanged:m}=this.context;if(i.has(a))return d.has(a)||this.context.stays(a);if(n)return!0;if(this.context.automationMade?.has(a)===!0||this.context.goesWithParent?.(e,c)===!0||this.context.alongToDraft?.has(a)===!0||ht[t]?.cameWithRun(e,i))return!1;if(o&&e[Ue]===!0)return!(M(e.LastModifiedDate??e.SystemModstamp)<=c)&&!m;let h="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!h)return!0;let R=M(e[h]),b=M(h==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(R>=l))return!0;let w=this.context.linkedLater?.get(a);if(w&&(R<=c||R>=w.start)&&b<=w.end)return!1;let k=typeof e.CreatedById=="string"?y(e.CreatedById):void 0,I=(_,Y)=>_!==void 0&&(_===u&&Y>=f||g.some(V=>_===V.user&&Y>=V.start&&Y<=V.end));if(I(k,R))return s&&(s.byRemoval=!0),!1;if(b<=c)return!1;let C=typeof e.LastModifiedById=="string"?y(e.LastModifiedById):void 0;return R<=c&&I(C,b)?!1:(m&&s&&(s.onlyIncluded=!0),!m)}workedObjects(){return this.worked??=vt(this.org),this.worked}};export{Ne as a,tt as b,Wt as c,Qt as d,G as e,Vt as f,Wn as g,Vn as h,Kn as i,Gn as j,Yn as k,oo as l,Me as m,nt as n,ve as o,he as p,yo as q,dt as r,or as s,ir as t,tn as u,rn as v,ct as w,on as x,sn as y,an as z,Te as A,lt as B,lr as C,ut as D,Oo as E,dn as F,Sn as G,le as H,mr as I,yt as J,re as K,es as L,ts as M,ns as N,rs as O,os as P,ss as Q,is as R};
@@ -1,28 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as s}from"./chunk-SCKUIE3R.mjs";import{readFileSync as d}from"node:fs";import{extname as p,join as i}from"node:path";import{pathToFileURL as c}from"node:url";var r={autopilot:"run an Autopilot copy between two orgs",backup:"take and restore DataOps snapshots",checkpoint:"take a checkpoint of an org's data, and rewind the org to it",cleanup:"Bulk delete records you created on a sandbox in a time window",clone:"clone a record, or whole tables, from one org to a sandbox, or remove a run",compare:"compare two orgs the way the Compare page does",dataops:"mask an org's records, and put them back",empty:"empty objects of a sandbox, or the whole of it",env:"apply a sandforge.yaml to an org, and take it back",frozen:"build and replay a Frozen Dataset",mcp:"the MCP server: these scripts as tools for an AI agent, on stdio",monitor:"read an org the way the Monitor page does",pipeline:"plan and run an Automation pipeline exported from VS Code",seed:"fill an org from a seed template",sync:"run a Sync between two orgs",users:"set up the users of a sandbox after its refresh, and take them back"},a=o=>Object.prototype.hasOwnProperty.call(r,o);function m(o){let[e,...n]=o;if(e===void 0)return{kind:"refused",reason:"Name the command to run."};if(e==="--help"||e==="-h"||e==="help")return{kind:"help"};if(e==="--version"||e==="-v")return{kind:"version"};if(a(e))return{kind:"run",tool:e,args:n};let t=e.replace(/^sandforge-/,"");return t!==e&&a(t)?{kind:"refused",reason:`"${e}" is named ${t} here: ${s(t)} \u2026.`}:{kind:"refused",reason:e.startsWith("-")?`"${e}" is not a flag sandforge reads: name a command first.`:`"${e}" is not a command of sandforge.`}}function l(){let o=Math.max(...Object.keys(r).map(n=>n.length));return`sandforge \u2014 SandForge's command lines, without the editor: Seed, Forge's clone, Sync,
8
- Checkpoints, DataOps, Frozen Dataset, the emptying of a sandbox, the users of a sandbox,
9
- sandforge.yaml environments, Automation pipelines, and the MCP server.
10
-
11
- Usage:
12
- sandforge <command> [options]
13
- sandforge <command> --help what the command does, its options and its exit codes
14
-
15
- Commands:
16
- ${Object.entries(r).map(([n,t])=>` ${n.padEnd(o)} ${t}`).join(`
17
- `)}
18
-
19
- Each org is named by its sf CLI alias: the Salesforce CLI (sf) must be installed and logged in
20
- to it. In Claude Code:
21
- claude mcp add sandforge -- npx -y sandforge mcp
22
-
23
- --version the version of SandForge these scripts belong to
24
- --help this text
25
- `}function f(o,e=__dirname,n=__filename){return i(e,`sandforge-${o}${p(n)}`)}function u(o=__dirname){let e=JSON.parse(d(i(o,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}var g=o=>import(c(o).href);async function h(o=process.argv,e=g){let n=m(o.slice(2));switch(n.kind){case"help":process.stdout.write(l());return;case"version":process.stdout.write(`${u()}
26
- `);return;case"refused":process.stderr.write(`${n.reason} Nothing was run. The commands: ${Object.keys(r).join(", ")}. Run with --help.
27
- `),process.exitCode=2;return;case"run":{let t=f(n.tool);process.argv=[o[0]??process.execPath,t,...n.args],await e(t);return}}}/(?:^|[\\/])sandforge\.[cm]?[jt]s$/.test(process.argv[1]??"")&&h().catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
28
- `),process.exit(1)});export{r as a,m as b,l as c,f as d,u as e,h as f};