sandforge 1.80.0 → 1.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-pipeline.mjs +12 -0
  3. package/bin/sandforge-users.mjs +12 -0
  4. package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
  5. package/lib/chunk-2JZGCCPG.mjs +9 -0
  6. package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
  7. package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
  8. package/lib/chunk-3C2ZZIFN.mjs +7 -0
  9. package/lib/chunk-3CX7GPCR.mjs +7 -0
  10. package/lib/chunk-3HEMJTAP.mjs +925 -0
  11. package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
  12. package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  13. package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
  14. package/lib/chunk-3XG25GTF.mjs +7 -0
  15. package/lib/chunk-42BFLWHR.mjs +7 -0
  16. package/lib/chunk-466F37VD.mjs +7 -0
  17. package/lib/chunk-47UHTN3Q.mjs +7 -0
  18. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  19. package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
  20. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  21. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  22. package/lib/chunk-5K2I2DMP.mjs +11 -0
  23. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  24. package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  25. package/lib/chunk-6KP6WETK.mjs +9 -0
  26. package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
  27. package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
  28. package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
  29. package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
  30. package/lib/chunk-7PY3VQP3.mjs +7 -0
  31. package/lib/chunk-7SDZR6SR.mjs +7 -0
  32. package/lib/chunk-7WSLT5VX.mjs +8 -0
  33. package/lib/chunk-A32ISQ6M.mjs +28 -0
  34. package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
  35. package/lib/chunk-A7JJWOLT.mjs +7 -0
  36. package/lib/chunk-AUS6NFLZ.mjs +8 -0
  37. package/lib/chunk-BMTNTBBM.mjs +7 -0
  38. package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
  39. package/lib/chunk-BNKT3R3F.mjs +7 -0
  40. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  41. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  42. package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
  43. package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  44. package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
  45. package/lib/chunk-CCEH7L53.mjs +7 -0
  46. package/lib/chunk-CELEBWEZ.mjs +7 -0
  47. package/lib/chunk-CV47FDQW.mjs +7 -0
  48. package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
  49. package/lib/chunk-DBBPDSFN.mjs +7 -0
  50. package/lib/chunk-DIL62SUN.mjs +7 -0
  51. package/lib/chunk-DIS254AN.mjs +7 -0
  52. package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
  53. package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
  54. package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
  55. package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
  56. package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
  57. package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  58. package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  59. package/lib/chunk-FOIWWK7G.mjs +156 -0
  60. package/lib/chunk-FZF23M6R.mjs +7 -0
  61. package/lib/chunk-G2JR3F63.mjs +7 -0
  62. package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
  63. package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
  64. package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
  65. package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
  66. package/lib/chunk-GHPR5UVV.mjs +7 -0
  67. package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  68. package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
  69. package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
  70. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  71. package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
  72. package/lib/chunk-HIHCYMSL.mjs +7 -0
  73. package/lib/chunk-HKUWHVI7.mjs +9 -0
  74. package/lib/chunk-HQQVANWQ.mjs +20 -0
  75. package/lib/chunk-ICIYL45C.mjs +7 -0
  76. package/lib/chunk-IRZJU2PG.mjs +22 -0
  77. package/lib/chunk-ISSP2FZ5.mjs +7 -0
  78. package/lib/chunk-IVZJSDJD.mjs +7 -0
  79. package/lib/chunk-J24TIGSI.mjs +10 -0
  80. package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
  81. package/lib/chunk-JFNLKHY6.mjs +8 -0
  82. package/lib/chunk-JH27IKCO.mjs +9 -0
  83. package/lib/chunk-JJITOWZK.mjs +7 -0
  84. package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  85. package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
  86. package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
  87. package/lib/chunk-JQZTMFO7.mjs +7 -0
  88. package/lib/chunk-KIMQQ6JQ.mjs +7 -0
  89. package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
  90. package/lib/chunk-KKOA62S4.mjs +474 -0
  91. package/lib/chunk-KP5G6FUC.mjs +7 -0
  92. package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  93. package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
  94. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  95. package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
  96. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  97. package/lib/chunk-LXDSRP2W.mjs +7 -0
  98. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  99. package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
  100. package/lib/chunk-MUEQRIK7.mjs +9 -0
  101. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
  102. package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
  103. package/lib/chunk-O2PUGRNW.mjs +10 -0
  104. package/lib/chunk-O4BROUGM.mjs +7 -0
  105. package/lib/chunk-OETEC3P7.mjs +7 -0
  106. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  107. package/lib/chunk-P55MKIZX.mjs +37 -0
  108. package/lib/chunk-P63WJMXQ.mjs +7 -0
  109. package/lib/chunk-PBE44M2Y.mjs +7 -0
  110. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  111. package/lib/chunk-PE435FVH.mjs +15 -0
  112. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  113. package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
  114. package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
  115. package/lib/chunk-PWVDNN2C.mjs +7 -0
  116. package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
  117. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  118. package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  119. package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  120. package/lib/chunk-QAPVKPEC.mjs +7 -0
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
  123. package/lib/chunk-RLWB7F26.mjs +7 -0
  124. package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
  125. package/lib/chunk-RYRMUPMY.mjs +7 -0
  126. package/lib/chunk-SAMWHL22.mjs +13 -0
  127. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
  128. package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
  129. package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
  130. package/lib/chunk-SZGGFST2.mjs +272 -0
  131. package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
  132. package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
  133. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  134. package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
  135. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  136. package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
  137. package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
  138. package/lib/chunk-UV74P4H2.mjs +7 -0
  139. package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
  140. package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
  141. package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
  142. package/lib/chunk-VV3B6IC3.mjs +7 -0
  143. package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
  144. package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  145. package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WEMLDUQA.mjs +7 -0
  148. package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
  149. package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
  150. package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
  151. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  152. package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
  153. package/lib/chunk-XK5W7BVE.mjs +7 -0
  154. package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
  155. package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
  156. package/lib/chunk-XU25YA46.mjs +9 -0
  157. package/lib/chunk-XZISAZA6.mjs +7 -0
  158. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  159. package/lib/chunk-YAIIRFKJ.mjs +8 -0
  160. package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
  161. package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
  162. package/lib/chunk-YH4DYI6D.mjs +7 -0
  163. package/lib/chunk-YMDFF657.mjs +10 -0
  164. package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
  165. package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  166. package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  167. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
  170. package/lib/chunk-ZUOPC4W2.mjs +7 -0
  171. package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  172. package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  173. package/lib/sandforge-autopilot.mjs +11 -11
  174. package/lib/sandforge-backup.mjs +63 -32
  175. package/lib/sandforge-checkpoint.mjs +1 -348
  176. package/lib/sandforge-cleanup.mjs +1 -1
  177. package/lib/sandforge-clone.mjs +1 -1
  178. package/lib/sandforge-compare.mjs +1 -1
  179. package/lib/sandforge-dataops.mjs +1 -1
  180. package/lib/sandforge-empty.mjs +11 -11
  181. package/lib/sandforge-env.mjs +186 -140
  182. package/lib/sandforge-frozen.mjs +1 -266
  183. package/lib/sandforge-mcp.mjs +33 -14
  184. package/lib/sandforge-monitor.mjs +1 -1
  185. package/lib/sandforge-pipeline.mjs +88 -0
  186. package/lib/sandforge-seed.mjs +1 -1
  187. package/lib/sandforge-sync.mjs +1 -1
  188. package/lib/sandforge-users.mjs +157 -0
  189. package/lib/sandforge.mjs +1 -22
  190. package/lib/sf/sandforge/autopilot.mjs +20 -0
  191. package/lib/sf/sandforge/backup.mjs +20 -0
  192. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  193. package/lib/sf/sandforge/cleanup.mjs +20 -0
  194. package/lib/sf/sandforge/clone.mjs +20 -0
  195. package/lib/sf/sandforge/compare.mjs +20 -0
  196. package/lib/sf/sandforge/dataops.mjs +20 -0
  197. package/lib/sf/sandforge/empty.mjs +20 -0
  198. package/lib/sf/sandforge/env.mjs +20 -0
  199. package/lib/sf/sandforge/frozen.mjs +20 -0
  200. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  201. package/lib/sf/sandforge/index.mjs +20 -0
  202. package/lib/sf/sandforge/mcp.mjs +20 -0
  203. package/lib/sf/sandforge/monitor.mjs +20 -0
  204. package/lib/sf/sandforge/pipeline.mjs +20 -0
  205. package/lib/sf/sandforge/seed.mjs +20 -0
  206. package/lib/sf/sandforge/sync.mjs +20 -0
  207. package/lib/sf/sandforge/users.mjs +20 -0
  208. package/lib/sfHelpHook.mjs +7 -0
  209. package/lib/sfPlugin.mjs +11 -0
  210. package/oclif.manifest.json +1 -0
  211. package/package.json +18 -3
  212. package/lib/chunk-2CNCDM56.mjs +0 -7
  213. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  214. package/lib/chunk-4VS2V6WU.mjs +0 -25
  215. package/lib/chunk-5P4PHJRL.mjs +0 -9
  216. package/lib/chunk-5TC3QB4U.mjs +0 -10
  217. package/lib/chunk-7ABODJ4G.mjs +0 -7
  218. package/lib/chunk-7EGQP6S4.mjs +0 -7
  219. package/lib/chunk-7FFGJWHN.mjs +0 -7
  220. package/lib/chunk-7YDNUBO5.mjs +0 -7
  221. package/lib/chunk-A527W53V.mjs +0 -7
  222. package/lib/chunk-ADOAS63R.mjs +0 -7
  223. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  224. package/lib/chunk-CION3VMZ.mjs +0 -7
  225. package/lib/chunk-CSBS5U5I.mjs +0 -7
  226. package/lib/chunk-DB7RBE5D.mjs +0 -7
  227. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  228. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  229. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  230. package/lib/chunk-EQNW3UC2.mjs +0 -7
  231. package/lib/chunk-F43REJDZ.mjs +0 -10
  232. package/lib/chunk-GSG7WZHM.mjs +0 -7
  233. package/lib/chunk-HOJYWTP7.mjs +0 -20
  234. package/lib/chunk-HS4YRX4J.mjs +0 -7
  235. package/lib/chunk-I7O6C2B5.mjs +0 -8
  236. package/lib/chunk-IFETCRWE.mjs +0 -10
  237. package/lib/chunk-IQXHJEYB.mjs +0 -7
  238. package/lib/chunk-JPUR2CFX.mjs +0 -10
  239. package/lib/chunk-K327QKMD.mjs +0 -7
  240. package/lib/chunk-KRCA6IPH.mjs +0 -8
  241. package/lib/chunk-LPBMBW3O.mjs +0 -13
  242. package/lib/chunk-LWW4U276.mjs +0 -7
  243. package/lib/chunk-MFG4MUIO.mjs +0 -9
  244. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  245. package/lib/chunk-OAZRPP4I.mjs +0 -7
  246. package/lib/chunk-OO6CLPEH.mjs +0 -7
  247. package/lib/chunk-OPXCV2KL.mjs +0 -7
  248. package/lib/chunk-P33PSCXK.mjs +0 -7
  249. package/lib/chunk-Q3DM32KF.mjs +0 -11
  250. package/lib/chunk-QR3WELJQ.mjs +0 -7
  251. package/lib/chunk-QWT2C74M.mjs +0 -7
  252. package/lib/chunk-R3X3LV64.mjs +0 -14
  253. package/lib/chunk-RMBPOTD7.mjs +0 -7
  254. package/lib/chunk-SIHORWVK.mjs +0 -7
  255. package/lib/chunk-T62WNR54.mjs +0 -7
  256. package/lib/chunk-TTFDUKUS.mjs +0 -47
  257. package/lib/chunk-VE6XKGGD.mjs +0 -7
  258. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  259. package/lib/chunk-VS7ZXUII.mjs +0 -824
  260. package/lib/chunk-VXQLDM4R.mjs +0 -7
  261. package/lib/chunk-VYXMVJL5.mjs +0 -7
  262. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  263. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  264. package/lib/chunk-YS4G22C2.mjs +0 -7
  265. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  266. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{D as w,Mb as v,Xa as k,d as m,e as h,h as $,hb as j,i as y}from"./chunk-TTFDUKUS.mjs";var R=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,T=new Set(["static","random","sequence","formula","reference","picklist_random","ai_generate","faker","regex","from_csv"]),A=class{validate(n){let t=[],a=[];return S(n,t),N(n,t,a),P(n,t),n.objects?.length&&C(n,t),M(n,t),q(n,t),{valid:t.length===0,errors:t,warnings:a}}};function S(e,n){(!e.name||e.name.trim().length===0)&&n.push({field:"name",message:"Template name is required"})}function N(e,n,t){if(!e.objects||e.objects.length===0){n.push({field:"objects",message:"Template must have at least one object"});return}for(let a of e.objects)E(a,n,t,$(a.objectApiName,e.relations))}function E(e,n,t,a){let i=`objects[${e.objectApiName}]`;(!e.objectApiName||e.objectApiName.trim().length===0)&&n.push({field:i,message:"Object API name is required"}),e.recordCount<=0&&n.push({field:`${i}.recordCount`,message:"Record count must be positive"}),e.recordCount>0&&e.fieldRules.length===0&&!a&&!V(e.rows)&&n.push({field:`${i}.fieldRules`,message:`${e.objectApiName} asks for ${e.recordCount} record(s) and names no field to fill: add at least one field rule`}),e.recordCount>1e5&&t.push({field:`${i}.recordCount`,message:"Record count exceeds 100,000 \u2014 consider using grappe mode"}),e.batchSize<=0&&n.push({field:`${i}.batchSize`,message:"Batch size must be positive"});for(let s of e.fieldRules)F(s,i,n);e.rows!==void 0&&x(e.rows,i,n)}function V(e){return Array.isArray(e)&&e.some(n=>b(n?.values)&&Object.keys(n.values).length>0)}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x(e,n,t){if(!Array.isArray(e)||e.length===0){t.push({field:`${n}.rows`,message:"Rows, when given, are at least one"});return}let a=new Set,i=h.maxKeyLength;for(let[s,o]of e.entries()){let r=`${n}.rows[${s}]`,c=b(o)?o:{},{key:d,parentKey:l,values:f}=c;if(typeof d!="string"||d.length===0||d.length>i?t.push({field:`${r}.key`,message:`A row is named by a key of 1 to ${i} characters`}):a.has(d)?t.push({field:`${r}.key`,message:`The key "${d}" names more than one row: each row is named once`}):a.add(d),l!==void 0&&(typeof l!="string"||l.length===0||l.length>i)&&t.push({field:`${r}.parentKey`,message:`A row names its parent by a key of 1 to ${i} characters`}),!b(f)){t.push({field:`${r}.values`,message:"A row gives its values as fields and values"});continue}for(let[u,g]of Object.entries(f))O(g)||t.push({field:`${r}.values[${u}]`,message:`${u} is given a value no field takes: a text of at most ${h.maxTextLength} characters, a number, true or false, or null`})}}function O(e){return e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.length<=h.maxTextLength}function C(e,n){let t=i=>{let[s,o,...r]=i,c=s==="objects"?e.objects[Number(o)]:void 0,d=s==="relations"?e.relations?.[Number(o)]:void 0,l=c?`objects[${c.objectApiName}]`:d?`relations[${d.childObject}.${d.lookupField}]`:`${String(s)}[${String(o)}]`;return r.reduce((f,u)=>typeof u=="number"?`${f}[${u}]`:`${f}.${u}`,l)};if(e.objects.every(i=>i.rows===void 0||Array.isArray(i.rows)&&i.rows.every(b)))for(let i of w(e))n.push({field:t(i.path),message:i.message})}function F(e,n,t){let a=`${n}.fieldRules[${e.fieldApiName}]`;(!e.fieldApiName||e.fieldApiName.trim().length===0)&&t.push({field:a,message:"Field API name is required"}),T.has(e.ruleType)||t.push({field:`${a}.ruleType`,message:`Invalid rule type: ${e.ruleType}`}),I(e,a,t)}function I(e,n,t){switch(e.ruleType){case"reference":e.config.referenceObject||t.push({field:`${n}.config.referenceObject`,message:"Reference rule requires a referenceObject"});break;case"picklist_random":(!e.config.picklistValues||e.config.picklistValues.length===0)&&t.push({field:`${n}.config.picklistValues`,message:"Picklist rule requires at least one value"});break;case"faker":e.config.fakerMethod?j(e.config.fakerMethod)||t.push({field:`${n}.config.fakerMethod`,message:`Faker method "${e.config.fakerMethod}" in ${n} is not implemented: choose a method SandForge generates. No record was written.`}):t.push({field:`${n}.config.fakerMethod`,message:"Faker rule requires a fakerMethod"});break;case"ai_generate":e.fieldType!==void 0&&!k(e.fieldType)&&t.push({field:`${n}.ruleType`,message:`AI generation in ${n} writes text, which a "${e.fieldType}" field cannot hold: choose another rule for this field. No record was written.`});break;case"regex":e.config.regexPattern||t.push({field:`${n}.config.regexPattern`,message:"Regex rule requires a regexPattern"});break;case"from_csv":e.config.csvColumn||t.push({field:`${n}.config.csvColumn`,message:"CSV rule requires a csvColumn"});break}}function P(e,n){let t=new Set(e.objects.map(i=>i.objectApiName)),a=new Set;for(let i of e.relations??[]){let{childObject:s,lookupField:o,parentObject:r}=i,c=`relations[${s}.${o}]`;if(t.has(s)||n.push({field:c,message:`The relation on ${s}.${o} fills an object the template does not write`}),a.has(s)&&n.push({field:c,message:`${s} has more than one relation: an object takes its record count from one relation, so keep one and let the other lookup draw from its field rule`}),a.add(s),i.parents.kind==="generated")r===s?n.push({field:c,message:`${s} records cannot point at ${s} records written by the same insert: draw the parents from records already in the org`}):t.has(r)||n.push({field:c,message:`The relation draws ${s}'s parents from the ${r} records this run writes, and the template writes none`});else if(i.parents.kind==="records"){let d=Array.isArray(i.parents.ids)?i.parents.ids:[],l=m.maxExistingParents;if(d.length<1||d.length>l)n.push({field:`${c}.parents.ids`,message:`The relation on ${s}.${o} names between 1 and ${l} ${r} records by id, not ${d.length}`});else{let f=d.filter(g=>typeof g!="string"||!R.test(g)),u=d.filter(g=>typeof g=="string").map(g=>g.slice(0,15));f.length>0?n.push({field:`${c}.parents.ids`,message:`The relation on ${s}.${o} names ${f.length} parent(s) by something that is not a record id, 15 or 18 letters and digits: ${f.slice(0,3).map(String).join(", ")}`}):new Set(u).size!==u.length&&n.push({field:`${c}.parents.ids`,message:`The relation on ${s}.${o} names the same ${r} record more than once: each parent is given once`})}}else p(i.parents.limit,1,m.maxExistingParents)||n.push({field:`${c}.parents.limit`,message:`The relation on ${s}.${o} reads between 1 and ${m.maxExistingParents} existing ${r} records`});_(i.distribution)||n.push({field:`${c}.distribution`,message:`The relation on ${s}.${o} gives each ${r} a number of children it cannot use`})}}function p(e,n,t){return Number.isInteger(e)&&e>=n&&e<=t}function _(e){let n=m.maxPerParent;switch(e.mode){case"perParent":return p(e.count,1,n);case"range":return p(e.min,0,n)&&p(e.max,1,n)&&e.min<=e.max;case"ratio":return Number.isFinite(e.ratio)&&e.ratio>=m.minRatio&&e.ratio<=n;case"byKey":return!0;default:return!1}}function M(e,n){let t=new Set(e.objects.map(a=>a.objectApiName));for(let a of e.objects){let i=$(a.objectApiName,e.relations);for(let s of a.fieldRules)i&&s.fieldApiName===i.lookupField||v(s,t)||s.ruleType==="reference"&&s.config.referenceObject&&(t.has(s.config.referenceObject)||n.push({field:`objects[${a.objectApiName}].fieldRules[${s.fieldApiName}]`,message:`Reference target "${s.config.referenceObject}" is not in the template`}))}}function q(e,n){let t=new Map;for(let o of e.objects)t.set(o.objectApiName,y(o,e.relations));let a=new Set,i=new Set;function s(o){if(i.has(o))return!0;if(a.has(o))return!1;i.add(o);let r=t.get(o)??[];for(let c of r)if(s(c))return!0;return i.delete(o),a.add(o),!1}for(let o of e.objects)if(s(o.objectApiName)){n.push({field:`objects[${o.objectApiName}]`,message:"Circular dependency detected"});break}}export{A as a};
7
+ import{G as w,Hb as k,Tb as j,e as m,f as h,i as $,j as y,wc as v}from"./chunk-ZQO5PDX5.mjs";var R=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,T=new Set(["static","random","sequence","formula","reference","picklist_random","ai_generate","faker","regex","from_csv"]),A=class{validate(n){let t=[],a=[];return S(n,t),N(n,t,a),P(n,t),n.objects?.length&&C(n,t),M(n,t),q(n,t),{valid:t.length===0,errors:t,warnings:a}}};function S(e,n){(!e.name||e.name.trim().length===0)&&n.push({field:"name",message:"Template name is required"})}function N(e,n,t){if(!e.objects||e.objects.length===0){n.push({field:"objects",message:"Template must have at least one object"});return}for(let a of e.objects)E(a,n,t,$(a.objectApiName,e.relations))}function E(e,n,t,a){let i=`objects[${e.objectApiName}]`;(!e.objectApiName||e.objectApiName.trim().length===0)&&n.push({field:i,message:"Object API name is required"}),e.recordCount<=0&&n.push({field:`${i}.recordCount`,message:"Record count must be positive"}),e.recordCount>0&&e.fieldRules.length===0&&!a&&!V(e.rows)&&n.push({field:`${i}.fieldRules`,message:`${e.objectApiName} asks for ${e.recordCount} record(s) and names no field to fill: add at least one field rule`}),e.recordCount>1e5&&t.push({field:`${i}.recordCount`,message:"Record count exceeds 100,000 \u2014 consider using grappe mode"}),e.batchSize<=0&&n.push({field:`${i}.batchSize`,message:"Batch size must be positive"});for(let s of e.fieldRules)F(s,i,n);e.rows!==void 0&&x(e.rows,i,n)}function V(e){return Array.isArray(e)&&e.some(n=>b(n?.values)&&Object.keys(n.values).length>0)}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x(e,n,t){if(!Array.isArray(e)||e.length===0){t.push({field:`${n}.rows`,message:"Rows, when given, are at least one"});return}let a=new Set,i=h.maxKeyLength;for(let[s,o]of e.entries()){let r=`${n}.rows[${s}]`,c=b(o)?o:{},{key:d,parentKey:l,values:f}=c;if(typeof d!="string"||d.length===0||d.length>i?t.push({field:`${r}.key`,message:`A row is named by a key of 1 to ${i} characters`}):a.has(d)?t.push({field:`${r}.key`,message:`The key "${d}" names more than one row: each row is named once`}):a.add(d),l!==void 0&&(typeof l!="string"||l.length===0||l.length>i)&&t.push({field:`${r}.parentKey`,message:`A row names its parent by a key of 1 to ${i} characters`}),!b(f)){t.push({field:`${r}.values`,message:"A row gives its values as fields and values"});continue}for(let[u,g]of Object.entries(f))O(g)||t.push({field:`${r}.values[${u}]`,message:`${u} is given a value no field takes: a text of at most ${h.maxTextLength} characters, a number, true or false, or null`})}}function O(e){return e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.length<=h.maxTextLength}function C(e,n){let t=i=>{let[s,o,...r]=i,c=s==="objects"?e.objects[Number(o)]:void 0,d=s==="relations"?e.relations?.[Number(o)]:void 0,l=c?`objects[${c.objectApiName}]`:d?`relations[${d.childObject}.${d.lookupField}]`:`${String(s)}[${String(o)}]`;return r.reduce((f,u)=>typeof u=="number"?`${f}[${u}]`:`${f}.${u}`,l)};if(e.objects.every(i=>i.rows===void 0||Array.isArray(i.rows)&&i.rows.every(b)))for(let i of w(e))n.push({field:t(i.path),message:i.message})}function F(e,n,t){let a=`${n}.fieldRules[${e.fieldApiName}]`;(!e.fieldApiName||e.fieldApiName.trim().length===0)&&t.push({field:a,message:"Field API name is required"}),T.has(e.ruleType)||t.push({field:`${a}.ruleType`,message:`Invalid rule type: ${e.ruleType}`}),I(e,a,t)}function I(e,n,t){switch(e.ruleType){case"reference":e.config.referenceObject||t.push({field:`${n}.config.referenceObject`,message:"Reference rule requires a referenceObject"});break;case"picklist_random":(!e.config.picklistValues||e.config.picklistValues.length===0)&&t.push({field:`${n}.config.picklistValues`,message:"Picklist rule requires at least one value"});break;case"faker":e.config.fakerMethod?j(e.config.fakerMethod)||t.push({field:`${n}.config.fakerMethod`,message:`Faker method "${e.config.fakerMethod}" in ${n} is not implemented: choose a method SandForge generates. No record was written.`}):t.push({field:`${n}.config.fakerMethod`,message:"Faker rule requires a fakerMethod"});break;case"ai_generate":e.fieldType!==void 0&&!k(e.fieldType)&&t.push({field:`${n}.ruleType`,message:`AI generation in ${n} writes text, which a "${e.fieldType}" field cannot hold: choose another rule for this field. No record was written.`});break;case"regex":e.config.regexPattern||t.push({field:`${n}.config.regexPattern`,message:"Regex rule requires a regexPattern"});break;case"from_csv":e.config.csvColumn||t.push({field:`${n}.config.csvColumn`,message:"CSV rule requires a csvColumn"});break}}function P(e,n){let t=new Set(e.objects.map(i=>i.objectApiName)),a=new Set;for(let i of e.relations??[]){let{childObject:s,lookupField:o,parentObject:r}=i,c=`relations[${s}.${o}]`;if(t.has(s)||n.push({field:c,message:`The relation on ${s}.${o} fills an object the template does not write`}),a.has(s)&&n.push({field:c,message:`${s} has more than one relation: an object takes its record count from one relation, so keep one and let the other lookup draw from its field rule`}),a.add(s),i.parents.kind==="generated")r===s?n.push({field:c,message:`${s} records cannot point at ${s} records written by the same insert: draw the parents from records already in the org`}):t.has(r)||n.push({field:c,message:`The relation draws ${s}'s parents from the ${r} records this run writes, and the template writes none`});else if(i.parents.kind==="records"){let d=Array.isArray(i.parents.ids)?i.parents.ids:[],l=m.maxExistingParents;if(d.length<1||d.length>l)n.push({field:`${c}.parents.ids`,message:`The relation on ${s}.${o} names between 1 and ${l} ${r} records by id, not ${d.length}`});else{let f=d.filter(g=>typeof g!="string"||!R.test(g)),u=d.filter(g=>typeof g=="string").map(g=>g.slice(0,15));f.length>0?n.push({field:`${c}.parents.ids`,message:`The relation on ${s}.${o} names ${f.length} parent(s) by something that is not a record id, 15 or 18 letters and digits: ${f.slice(0,3).map(String).join(", ")}`}):new Set(u).size!==u.length&&n.push({field:`${c}.parents.ids`,message:`The relation on ${s}.${o} names the same ${r} record more than once: each parent is given once`})}}else p(i.parents.limit,1,m.maxExistingParents)||n.push({field:`${c}.parents.limit`,message:`The relation on ${s}.${o} reads between 1 and ${m.maxExistingParents} existing ${r} records`});_(i.distribution)||n.push({field:`${c}.distribution`,message:`The relation on ${s}.${o} gives each ${r} a number of children it cannot use`})}}function p(e,n,t){return Number.isInteger(e)&&e>=n&&e<=t}function _(e){let n=m.maxPerParent;switch(e.mode){case"perParent":return p(e.count,1,n);case"range":return p(e.min,0,n)&&p(e.max,1,n)&&e.min<=e.max;case"ratio":return Number.isFinite(e.ratio)&&e.ratio>=m.minRatio&&e.ratio<=n;case"byKey":return!0;default:return!1}}function M(e,n){let t=new Set(e.objects.map(a=>a.objectApiName));for(let a of e.objects){let i=$(a.objectApiName,e.relations);for(let s of a.fieldRules)i&&s.fieldApiName===i.lookupField||v(s,t)||s.ruleType==="reference"&&s.config.referenceObject&&(t.has(s.config.referenceObject)||n.push({field:`objects[${a.objectApiName}].fieldRules[${s.fieldApiName}]`,message:`Reference target "${s.config.referenceObject}" is not in the template`}))}}function q(e,n){let t=new Map;for(let o of e.objects)t.set(o.objectApiName,y(o,e.relations));let a=new Set,i=new Set;function s(o){if(i.has(o))return!0;if(a.has(o))return!1;i.add(o);let r=t.get(o)??[];for(let c of r)if(s(c))return!0;return i.delete(o),a.add(o),!1}for(let o of e.objects)if(s(o.objectApiName)){n.push({field:`objects[${o.objectApiName}]`,message:"Circular dependency detected"});break}}export{A as a};
@@ -0,0 +1,9 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{o as m}from"./chunk-4JKR4PTZ.mjs";import{H as d,d as w,z as b}from"./chunk-J24TIGSI.mjs";import{Hc as u}from"./chunk-ZQO5PDX5.mjs";import{b as R,e as A,k as j,l as p,v as P}from"./chunk-WZQEK4WT.mjs";import{randomBytes as O}from"node:crypto";import{createReadStream as T}from"node:fs";import{appendFile as C,open as $,readFile as D,rename as F,rm as _}from"node:fs/promises";import{join as k}from"node:path";import{createInterface as M}from"node:readline";var U=2e3,a=15,x=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,W=2e3,z="spool.json",h="a rewind";function v(r){return typeof r=="string"&&x.test(r)?r.slice(0,a):void 0}var g=class{bytes=Buffer.alloc(a*1024);flags=new Uint16Array(1024);slots=new Uint32Array(2048);used=0;get size(){return this.used}find(t){let e=this.slots.length-1;for(let s=m(t)&e;;s=s+1&e){let n=this.slots[s];if(n===0)return-1;if(this.holds(n-1,t))return n-1}}holds(t,e){let s=t*a;for(let n=0;n<a;n++)if(this.bytes[s+n]!==e.charCodeAt(n))return!1;return!0}keyAt(t){let e=t*a;return this.bytes.toString("latin1",e,e+a)}place(t,e){let s=this.slots.length-1,n=m(e)&s;for(;this.slots[n]!==0;)n=n+1&s;this.slots[n]=t+1}add(t,e=0){let s=v(t);if(s===void 0)throw new RangeError(`Not a Salesforce id: ${String(t)}`);let n=this.find(s);if(n>=0)return this.flags[n]|=e,!1;if((this.used+1)*2>this.slots.length){let o=this.slots;this.slots=new Uint32Array(o.length*2);for(let i of o)i!==0&&this.place(i-1,this.keyAt(i-1))}if((this.used+1)*a>this.bytes.length){let o=Buffer.alloc(this.bytes.length*2);this.bytes.copy(o),this.bytes=o;let i=new Uint16Array(this.flags.length*2);i.set(this.flags),this.flags=i}return this.bytes.write(s,this.used*a,a,"latin1"),this.flags[this.used]=e,this.place(this.used,s),this.used++,!0}has(t){let e=v(t);return e!==void 0&&this.find(e)>=0}count(t){let e=0;for(let s=0;s<this.used;s++)t(this.flags[s])&&e++;return e}flagsOf(t){let e=v(t);if(e===void 0)return 0;let s=this.find(e);return s<0?0:this.flags[s]}},B=p({version:P(1),objects:j(p({objectApiName:R().min(1),count:A().int().nonnegative()}))});function S(r,t){return k(r,`${u(t)}.ids`)}async function G(r,t){let e=`${r}.${process.pid}-${O(4).toString("hex")}.tmp`,s=await $(e,"wx",w);try{try{await s.writeFile(t,"utf8"),await s.sync()}finally{await s.close()}await F(e,r)}catch(n){throw await _(e,{force:!0}),n}}async function J(r){let t=await $(r,"r+");try{await t.sync()}finally{await t.close()}}async function L(r,t,e=h){for(let{objectApiName:s,count:n}of t)n>0&&await J(S(r,s));return await G(k(r,z),`${JSON.stringify({version:1,objects:t})}
8
+ `),new y(r,t,e)}var I=class{constructor(t,e=h){this.dir=t;this.act=e}dir;act;order=[];counts=new Map;lines=new Map;written=new Set;keys=new g;made=!1;async add(t,e){if(!this.keys.add(e))return!1;let s=this.lines.get(t);return s||(u(t),s=[],this.lines.set(t,s),this.order.push(t)),s.push(e),this.counts.set(t,(this.counts.get(t)??0)+1),s.length>=W&&await this.flush(t),!0}async flush(t){let e=this.lines.get(t)??[];this.made||(await b(this.dir),this.made=!0);let s=!this.written.has(t);e.length===0&&!s||(await C(S(this.dir,t),e.map(n=>`${n}
9
+ `).join(""),{encoding:"utf8",mode:w,flag:s?"w":"a"}),this.written.add(t),this.lines.set(t,[]))}get objects(){return this.order.map(t=>({objectApiName:t,count:this.counts.get(t)??0}))}async finish(t){this.made||(await b(this.dir),this.made=!0);for(let e of this.order)await this.flush(e);return L(this.dir,t?t(this.objects):this.objects,this.act)}},y=class r{constructor(t,e,s=h){this.dir=t;this.objects=e;this.act=s}dir;objects;act;get count(){return this.objects.reduce((t,e)=>t+e.count,0)}static async open(t,e=h){let s;try{s=JSON.parse(await D(k(t,z),"utf8"))}catch{throw new d("damaged",`The list of what ${e} sets out to do is not on this machine.`)}let n=B.safeParse(s);if(!n.success)throw new d("damaged",`The list of what ${e} sets out to do does not read as one.`);for(let{objectApiName:o}of n.data.objects)u(o);return new r(t,n.data.objects,e)}async*pages(t,e=U){let s=this.objects.find(c=>c.objectApiName===t);if(!s||s.count===0)return;let n=()=>new d("damaged",`The ${t} records ${this.act} sets out to act on are not as they were written.`),o=Math.max(1,Math.floor(e)),i=T(S(this.dir,t),{encoding:"utf8"}),f=M({input:i,crlfDelay:1/0}),E=0,l=[];try{for await(let c of f)if(c!==""){if(!x.test(c))throw n();E++,l.push(c),l.length>=o&&(yield l,l=[])}}catch(c){throw c.code==="ENOENT"?n():c}finally{f.close(),i.destroy()}if(E!==s.count)throw n();l.length>0&&(yield l)}},N=class r{constructor(t,e){this.spool=t;this.keys=e}spool;keys;static async of(t,e){return new r(await t.finish(e),t.keys)}static async open(t,e=h){let s=await y.open(t,e),n=new g;for(let{objectApiName:o}of s.objects)for await(let i of s.pages(o))for(let f of i)n.add(f);return new r(s,n)}get objects(){return this.spool.objects}pages(t){return this.spool.pages(t)}has(t){return this.keys.has(t)}};export{U as a,g as b,S as c,L as d,I as e,y as f,N as g};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{od as s,pd as d}from"./chunk-TTFDUKUS.mjs";function c(l,e){return l.type==="condition"&&e.status==="completed"&&e.output?.conditionMet===!1}var f=class{evaluate(e,n){return d(e,n)}check(e){return s(e)}evaluateGroup(e,n){return e.length===0?!0:e.some(t=>t.logicalGroup==="or")?e.some(t=>this.evaluate(t,n)):e.every(t=>this.evaluate(t,n))}getNextStep(e,n){if(n.status==="completed")return c(e,n)?e.onFailure:e.onSuccess;if(n.status==="failed")return e.onFailure}endsRun(e,n){return c(e,n)&&!e.onFailure}findBranch(e,n,o){let t=new Map(e.map(r=>[r.id,r])),u=[],a=new Set,i=n,p=t.get(i);if(!p)return u;for(i=o?p.onSuccess:p.onFailure;i&&!a.has(i);){a.add(i);let r=t.get(i);if(!r)break;u.push(r),i=o?r.onSuccess:r.onFailure}return u}};export{f as a};
7
+ import{Zd as s,_d as d}from"./chunk-ZQO5PDX5.mjs";function c(l,e){return l.type==="condition"&&e.status==="completed"&&e.output?.conditionMet===!1}var f=class{evaluate(e,n){return d(e,n)}check(e){return s(e)}evaluateGroup(e,n){return e.length===0?!0:e.some(t=>t.logicalGroup==="or")?e.some(t=>this.evaluate(t,n)):e.every(t=>this.evaluate(t,n))}getNextStep(e,n){if(n.status==="completed")return c(e,n)?e.onFailure:e.onSuccess;if(n.status==="failed")return e.onFailure}endsRun(e,n){return c(e,n)&&!e.onFailure}findBranch(e,n,o){let t=new Map(e.map(r=>[r.id,r])),u=[],a=new Set,i=n,p=t.get(i);if(!p)return u;for(i=o?p.onSuccess:p.onFailure;i&&!a.has(i);){a.add(i);let r=t.get(i);if(!r)break;u.push(r),i=o?r.onSuccess:r.onFailure}return u}};export{f as a};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.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};
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};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{i as c}from"./chunk-TTFDUKUS.mjs";var a=/__kav$/i,d="Campaign";function u(e){return a.test(e)?"Salesforce Knowledge is not turned on in it: tick Knowledge User on your user (Setup > Users), then enable it in Setup > Knowledge Settings":void 0}var b="a campaign needs the Marketing User box ticked on the user, in Setup > Users",f=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;function m(e){let n,t;return async s=>{n??=e.describeGlobal().then(o=>new Map(o.sobjects.map(i=>[i.name.toLowerCase(),i.createable===!0])));let r=(await n).get(s.toLowerCase());if(r===void 0){let o=u(s);return{access:"absent",...o?{reason:o}:{}}}return s===d&&(t??=l(e),!r||!await t)?{access:"readOnly",reason:b}:r?{access:"createable"}:{access:"readOnly"}}}async function j(e,n){let t=new Set;for(let{objectApiName:s,optional:r}of e.objects)if(r===!0)try{(await n(s)).access!=="createable"&&t.add(s)}catch{}if(t.size===0)return e;for(let s=!0;s;){s=!1;for(let r of e.objects)t.has(r.objectApiName)||c(r,e.relations).some(o=>t.has(o))&&(t.add(r.objectApiName),s=!0)}return{...e,objects:e.objects.filter(s=>!t.has(s.objectApiName)),...e.relations?{relations:e.relations.filter(({childObject:s,parentObject:r})=>!t.has(s)&&!t.has(r))}:{}}}async function l(e){try{let{user_id:n}=await e.identity();return f.test(n)?(await e.query(`SELECT UserPermissionsMarketingUser FROM User WHERE Id = '${n}'`)).records[0]?.UserPermissionsMarketingUser!==!1:!0}catch{return!0}}export{m as a,j as b};
7
+ import{j as c}from"./chunk-ZQO5PDX5.mjs";var a=/__kav$/i,d="Campaign";function u(e){return a.test(e)?"Salesforce Knowledge is not turned on in it: tick Knowledge User on your user (Setup > Users), then enable it in Setup > Knowledge Settings":void 0}var b="a campaign needs the Marketing User box ticked on the user, in Setup > Users",f=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;function m(e){let n,t;return async s=>{n??=e.describeGlobal().then(o=>new Map(o.sobjects.map(i=>[i.name.toLowerCase(),i.createable===!0])));let r=(await n).get(s.toLowerCase());if(r===void 0){let o=u(s);return{access:"absent",...o?{reason:o}:{}}}return s===d&&(t??=l(e),!r||!await t)?{access:"readOnly",reason:b}:r?{access:"createable"}:{access:"readOnly"}}}async function j(e,n){let t=new Set;for(let{objectApiName:s,optional:r}of e.objects)if(r===!0)try{(await n(s)).access!=="createable"&&t.add(s)}catch{}if(t.size===0)return e;for(let s=!0;s;){s=!1;for(let r of e.objects)t.has(r.objectApiName)||c(r,e.relations).some(o=>t.has(o))&&(t.add(r.objectApiName),s=!0)}return{...e,objects:e.objects.filter(s=>!t.has(s.objectApiName)),...e.relations?{relations:e.relations.filter(({childObject:s,parentObject:r})=>!t.has(s)&&!t.has(r))}:{}}}async function l(e){try{let{user_id:n}=await e.identity();return f.test(n)?(await e.query(`SELECT UserPermissionsMarketingUser FROM User WHERE Id = '${n}'`)).records[0]?.UserPermissionsMarketingUser!==!1:!0}catch{return!0}}export{m as a,j as b};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i}from"./chunk-W622GUAW.mjs";import"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.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};
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};
@@ -0,0 +1,7 @@
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 j,c as M}from"./chunk-INIT2UKJ.mjs";import{d as K}from"./chunk-KIMQQ6JQ.mjs";import{a as T,h as N}from"./chunk-TZE3Y7IQ.mjs";import{Ac as $,Bc as F,mc as z,nc as J,oc as Q,rc as C,sc as v,zc as H}from"./chunk-ZQO5PDX5.mjs";var ee="Id = NULL",B="no parent in cache and not the root",Y=class{build(t){let n=this.buildMeasured(t);return{...n,statements:_(n.statements,t.node.objectApiName,t.selectFields)}}buildMeasured(t){let n=N(t.node.objectApiName),o=k(M(t.selectFields)),r=t.extraWhere?` AND (${t.extraWhere})`:"",i=t.extraWhere?" + extra filter":"",l=`SELECT ${o} FROM ${n} WHERE `,u=t.node.objectApiName===t.rootObjectApiName&&!t.under;if(u&&!(t.rootReadAgain&&t.cache.has(t.node.objectApiName))){if(t.rootRecordIds!==void 0)return{statements:L({prefix:l,suffix:r,wrap:!1,objectApiName:t.node.objectApiName},[{field:"Id",ids:t.rootRecordIds}]),scoped:t.rootRecordIds.size>0,scope:"root",reason:`${t.rootRecordIds.size} root records${i}`,parentObjectsUsed:[t.rootObjectApiName],scopeIdCount:t.rootRecordIds.size,byIdCount:0};let b=T(t.rootRecordId??"");return{statements:[`${l}Id = '${b}'${r}`],scoped:!0,scope:"root",reason:`root record${i}`,parentObjectsUsed:[t.rootObjectApiName],scopeIdCount:1,byIdCount:0}}let d=t.under?void 0:t.cache.get(t.node.objectApiName),s=d?.size??0,a=d&&s>0?L({prefix:l,suffix:r,wrap:!1,objectApiName:t.node.objectApiName},[{field:"Id",ids:d}]):[],h=`${s} ID(s) cached from earlier wave`,f={statements:a,scoped:!0,scope:"self-cached",reason:`${h}${i}`,parentObjectsUsed:[],scopeIdCount:s,byIdCount:a.length};if(s>0&&(!t.everyEdge||u))return f;let g=[],I=[],y=0;for(let b of t.edges){if(b.targetObject!==t.node.objectApiName||t.under&&!t.under.has(b.sourceObject)||b.sourceObject===b.targetObject)continue;let O=t.fromAboveOnly||t.catalog?.has(b.sourceObject)?t.cache.reachedOf(b.sourceObject):t.cache.scopeOf(b.sourceObject);if(!O||O.size===0)continue;let S=t.fields.filter(c=>c.type==="reference"&&c.referenceTo.includes(b.sourceObject));if(S.length!==0){for(let c of S)g.push({field:N(c.name),ids:O});I.includes(b.sourceObject)||(I.push(b.sourceObject),y+=O.size)}}let R=[];for(let b of t.fields){if(b.type!=="reference"||b.nillable!==!1)continue;let O=new Set;for(let S of b.referenceTo){if(!t.readObjects?.has(S))continue;let c=t.catalog?.has(S)===!0;if(c&&!t.cache.isRead(S))continue;let m=c?t.cache.scopeOf(S):t.cache.get(S);if(m)for(let p of m)O.add(p)}O.size!==0&&R.push({field:N(b.name),ids:O})}let x=R.length>0?" + required parents in scope":"";if(g.length===0)return s>0?f:{statements:[`${l}${ee}`],scoped:!1,scope:"unscoped",reason:B,parentObjectsUsed:[],scopeIdCount:0,byIdCount:1};let w=Z({prefix:l,extraSuffix:r,objectApiName:t.node.objectApiName},g,R),A=`via ${I.join(", ")}${i}${x}`;return s===0?{statements:w,scoped:!0,scope:"parent-fk",reason:A,parentObjectsUsed:I,scopeIdCount:y,byIdCount:0}:{statements:[...a,...w],scoped:!0,scope:"self-and-parent-fk",reason:`${h}, and ${A}`,parentObjectsUsed:I,scopeIdCount:s+y,byIdCount:a.length}}buildJoining(t){let n=N(t.objectApiName),r=`SELECT ${k(M(t.selectFields))} FROM ${n} WHERE `,i=t.extraWhere?` AND (${t.extraWhere})`:"";return _(Z({prefix:r,extraSuffix:i,objectApiName:t.objectApiName},[{field:N(t.split.field),ids:t.split.ids}],[{field:N(t.whole.field),ids:t.whole.ids}]),t.objectApiName,t.selectFields)}buildById(t){let n=N(t.objectApiName);return _(L({prefix:`SELECT ${k(M(t.selectFields))} FROM ${n} WHERE `,suffix:t.extraWhere?` AND (${t.extraWhere})`:"",wrap:!1,objectApiName:t.objectApiName},[{field:"Id",ids:t.ids}]),t.objectApiName,t.selectFields)}};function k(e){return e.length===0?"Id":e.map(t=>N(t)).join(", ")}function _(e,t,n){let o=N(t),r=`SELECT ${k(M(n))} FROM ${o} `,i=`SELECT ${k(n)} FROM ${o} `;return r===i?[...e]:e.map(l=>l.startsWith(r)?i+l.slice(r.length):l)}var te=500;function W(e,t){let n=[...t].map(o=>`'${T(o)}'`).join(", ");return` AND (${e.field} IN (${n}))`}function ne(e,t){if(e.field!==t.field)return!1;for(let n of e.ids)if(!t.ids.has(n))return!1;return!0}function oe(e,t,n){let o=j(W(e,[])),r=j(", "),i=[],l=[],u=o;for(let d of e.ids){let s=j(`'${T(d)}'`);if(l.length>0&&u+r+s>t&&(i.push(l),l=[],u=o),l.length===0&&o+s>t)throw X(n);u+=(l.length>0?r:0)+s,l.push(d)}return l.length>0&&i.push(l),i}function re(e,t,n){let o=[""];for(let r of e){let i=oe(r,t/e.length,n);o=o.flatMap(l=>i.map(u=>l+W(r,u)))}return o}function Z(e,t,n){let o=(d,s)=>L({prefix:e.prefix,suffix:d,wrap:d!=="",objectApiName:e.objectApiName},s),r=n.map(d=>W(d,d.ids)).join(""),i=14e3-j(`${e.prefix}()${e.extraSuffix}`);if(j(r)<=i/2)return o(`${r}${e.extraSuffix}`,t);let l=new Map;for(let d of t){let s=n.filter(f=>!ne(d,f)),a=s.map(f=>f.field).join("|"),h=l.get(a)??{needed:s,clauses:[]};h.clauses.push(d),l.set(a,h)}let u=[];for(let d of l.values())for(let s of re(d.needed,i/2,e.objectApiName))u.push(...o(`${s}${e.extraSuffix}`,d.clauses));return u}function X(e){return new Error(`Scoped clone for ${e}: its filter leaves a Salesforce query URI no room for a single record Id. Shorten the filter on this object and run it again.`)}function L(e,t){let n=e.wrap?"(":"",o=e.wrap?")":"",r=j(e.prefix+n+o+e.suffix),i=j(", "),l=j(" OR "),u=[],d=[],s=r,a=0,h=()=>{let f=d.map(g=>`${g.field} IN (${g.values.join(", ")})`).join(" OR ");u.push(`${e.prefix}${n}${f}${o}${e.suffix}`),d=[],s=r,a=0};for(let f of t){let g=j(`${f.field} IN ()`),I=!1;for(let y of f.ids){let R=`'${T(y)}'`,x=j(R),w=I?i+x:(d.length>0?l:0)+g+x,A=s+w>14e3||a>=te;if(d.length>0&&A&&(h(),I=!1,w=g+x),d.length===0&&s+w>14e3)throw X(e.objectApiName);I?d[d.length-1].values.push(R):(d.push({field:f.field,values:[R]}),I=!0),s+=w,a++}}return d.length>0&&h(),u}var G="Product2",U=[C,G,$,F,v,"ProductCategory","ProductCatalog"],Ne=new Set(U);function je(e,t){return z(e,t.name,t.nillable)||e===C&&t.name===H}function xe(e,t=new Set){let n=new Set(e.nodes.map(o=>o.objectApiName));return new Set(U.filter(o=>!n.has(o)&&!t.has(o)))}function we(e,t){return e.nodes.some(n=>n.included&&t.has(n.objectApiName))?{...e,nodes:e.nodes.map(n=>n.included&&t.has(n.objectApiName)?{...n,included:!1}:n)}:e}function se(e,t,n){if(t.length<2)return t;let o=e.slice(0,3),r=t.find(i=>n.get(i)===o);return r!==void 0?[r]:t.filter(i=>!n.has(i))}function Ae(e,t){let n=q(e);return t?he(n,t):n}function Ee(e,t,n){let o=U.flatMap(f=>t.filter(({node:g})=>g.objectApiName===f)),r=new Set(o.flatMap(({fieldInfos:f})=>f.flatMap(g=>g.isReference?g.referenceTo??[]:[]))),i=new Map,l=new Map,u=(f,g,I)=>{let y=f.get(g);y?y.push(I):f.set(g,[I])};for(let{sourceObject:f,targetObject:g}of n)u(i,g,f),u(l,f,g);let d=[],s=new Set,a=[...e],h=a.filter(f=>r.has(f.objectApiName));for(;h.length>0;){for(let f of h)s.add(f.objectApiName),d.push(f);a=a.filter(f=>!s.has(f.objectApiName)),h=a.filter(({objectApiName:f})=>(i.get(f)??[]).some(g=>s.has(g))||(l.get(f)??[]).some(g=>s.has(g)))}return[...a,...o.map(({node:f})=>f),...d]}function V(e){return e.settable!==!1}function Ce(e,t){let n=!1,o=e.edges.map(r=>{let i=(t.get(r.targetObject)??[]).filter(s=>s.isReference&&(s.referenceTo??[]).includes(r.sourceObject));if(i.length===0)return r;let l=i.some(s=>J(s)),u=i.some(s=>Q(s));if(l===V(r)&&u===(r.insertOnly===!0))return r;n=!0;let d={...r};return l?delete d.settable:d.settable=!1,u?d.insertOnly=!0:delete d.insertOnly,d});return n?{...e,edges:o}:e}function Fe(e,t=[]){let n=e.edges.filter(V),o=[...n.filter(c=>c.required===!0),...t],r=n.filter(c=>c.insertOnly===!0&&c.required!==!0);if(o.length===0&&r.length===0)return q(e,n);let i=new Set(e.nodes.map(c=>c.objectApiName)),l=q(e,n),u=new Map(l.map((c,m)=>[c.objectApiName,m])),d=new Map,s=new Map,a=new Map,h=(c,m,p)=>{let E=c.get(m)??new Set;E.add(p),c.set(m,E)};for(let c of o){let{sourceObject:m,targetObject:p}=c;m===p||!i.has(m)||!i.has(p)||(h(d,p,m),h(s,m,p))}for(let c of n){let{sourceObject:m,targetObject:p}=c;m===p||!i.has(m)||!i.has(p)||d.get(p)?.has(m)||h(a,p,m)}let f=new Map;for(let[c,m]of a)for(let p of m)h(f,p,c);let g=new Map,I=new Map;for(let{sourceObject:c,targetObject:m}of r)c===m||!i.has(c)||!i.has(m)||d.get(m)?.has(c)||(h(g,m,c),h(I,c,m));let y=new Map,R=new Map,x=new Map;for(let c of i)y.set(c,d.get(c)?.size??0),R.set(c,g.get(c)?.size??0),x.set(c,a.get(c)?.size??0);let w=(c,m)=>{for(let p of[R,x,u]){let E=p.get(c)??0,D=p.get(m)??0;if(E!==D)return E<D}return!1},A=new Set([...i].filter(c=>y.get(c)===0)),b=new Map(e.nodes.map(c=>[c.objectApiName,c])),O=[],S=new Set;for(;A.size>0;){let c;for(let p of A)(c===void 0||w(p,c))&&(c=p);if(c===void 0)break;A.delete(c),S.add(c);let m=b.get(c);m&&O.push(m);for(let p of s.get(c)??[]){let E=(y.get(p)??1)-1;y.set(p,E),E===0&&!S.has(p)&&A.add(p)}for(let p of I.get(c)??[])R.set(p,(R.get(p)??1)-1);for(let p of f.get(c)??[])x.set(p,(x.get(p)??1)-1)}for(let c of e.nodes)S.has(c.objectApiName)||O.push(c);return O}function $e(e,t){return[[G,F],[$,F],[G,C],[$,C],[F,C],[v,C],...t.map(o=>[C,o])].filter(([o,r])=>o!==r&&e.has(o)&&e.has(r)).map(([o,r])=>({sourceObject:o,targetObject:r,relationshipName:`${o}Before${r}`,type:"lookup",required:!0}))}var ie=new Set(["Id","Name","CurrencyIsoCode","IsPersonAccount","IsActive","Status","IsWhat","IsInvitee","Response","RespondedDate",...Object.values(K).flat()]);function de(e,t){let n=new Set(t??[]);return e.filter(o=>o.queryable&&(!n.has(o.name)||o.isReference||ie.has(o.name))).map(o=>o.name)}var ce=2;function ae(e,t){let n=Array.from({length:t.length+1},(o,r)=>r);for(let o=1;o<=e.length;o++){let r=[o];for(let i=1;i<=t.length;i++)r[i]=Math.min(n[i]+1,r[i-1]+1,n[i-1]+(e[o-1]===t[i-1]?0:1));n=r}return n[t.length]}function le(e,t){let n=e.toLowerCase(),o;for(let r of t){let i=ae(n,r.toLowerCase());i<=ce&&i<n.length&&(!o||i<o.edits)&&(o={name:r,edits:i})}return o?.name}function Te(e,t,n){let o={},r=[];for(let[i,l]of Object.entries(e)){let u=t.find(a=>a.toLowerCase()===i.toLowerCase())??i,d=n(u),s=o[u]??=[];for(let a of l){let h=d?.find(g=>g.toLowerCase()===a.toLowerCase());if(h===void 0&&d!==null){let g=d===void 0?void 0:le(a,d);r.push({objectApiName:u,field:a,missing:d===void 0?"object":"field",...g!==void 0?{nearest:g}:{}})}let f=h??a;s.includes(f)||s.push(f)}}return{exclusions:o,unmatched:r}}function Me(e){let t=de(e.fieldInfos,e.fieldsLeftOut);t.length===0&&t.push("Id");let n,o=0,r=[],i=!1,l=!!e.rootRecordId||e.rootRecordIds!==void 0;if(e.scopedBuilder&&e.scopeCache&&e.rootObjectApiName&&l&&e.node.objectApiName===F&&e.node.objectApiName!==e.rootObjectApiName&&e.catalog?.has(F)){let d=ge(e.scopedBuilder,e.scopeCache,t,e.extraWhere);if(!d)return{kind:"skip",reason:B};n=d,o=n.length}else if(e.scopedBuilder&&e.scopeCache&&e.rootObjectApiName&&l){let d=e.fieldInfos.filter(a=>a.isReference).map(a=>({name:a.name,type:"reference",referenceTo:a.referenceTo??[],nillable:a.nillable})),s=e.scopedBuilder.build({node:e.node,fields:d,selectFields:t,edges:e.edges,cache:e.scopeCache,rootObjectApiName:e.rootObjectApiName,...e.rootRecordIds!==void 0?{rootRecordIds:e.rootRecordIds}:{rootRecordId:e.rootRecordId},extraWhere:e.extraWhere,everyEdge:!0,readObjects:e.readObjects,catalog:e.catalog,rootReadAgain:e.rootReadAgain,under:e.under});if(!s.scoped)return{kind:"skip",reason:s.reason};n=s.statements,o=s.byIdCount,i=s.scope==="root"&&e.rootRecordIds!==void 0,e.rootRecordIds!==void 0&&(s.scope==="parent-fk"||s.scope==="self-and-parent-fk")&&(r=s.parentObjectsUsed)}else{let d=[...e.extraWhere?[`(${e.extraWhere})`]:[],...e.inIdOrder?.afterId!==void 0?[`Id > ${ue(e.inIdOrder.afterId)}`]:[]],s=d.length>0?` WHERE ${d.join(" AND ")}`:"",a=e.inIdOrder?" ORDER BY Id":"";n=[`SELECT ${t.join(", ")} FROM ${N(e.node.objectApiName)}${s}${a}`]}let u={...o>0?{byIdCount:o}:{},...r.length>0?{readUnder:[...r]}:{}};if(!i&&e.maxRecordsPerObject&&e.maxRecordsPerObject>0){let d=Math.floor(e.maxRecordsPerObject);if(d>0)return fe(n,d,u)}return{kind:"query",statements:n,...u}}function fe(e,t,n={}){return{kind:"query",statements:e.map(o=>`${o} LIMIT ${t+1}`),limit:t,...n}}function ue(e){if(!/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(e))throw new Error(`Not a record id to resume after: ${JSON.stringify(e.slice(0,40))}`);return`'${e}'`}function ge(e,t,n,o){let r=t.scopeOf(G),i=t.scopeOf($);if(!(!r||r.size===0||!i||i.size===0))return e.buildJoining({objectApiName:F,selectFields:n,split:{field:"Product2Id",ids:r},whole:{field:"ProductSellingModelId",ids:i},extraWhere:o})}function ke(e){return(e.byIdCount??0)<e.statements.length}async function Le(e,t,n,o){let r=e.byIdCount??0,i=e.limit,l=s=>{if(i===void 0||s.length<=i)return s;for(let a of s.slice(i))typeof a.Id=="string"&&n?.delete(a.Id);return o?.(),s.slice(0,i)};if(e.statements.length===1){let s=await t(e.statements[0]);if(n&&r===0)for(let a of s)typeof a.Id=="string"&&n.add(a.Id);return l(s)}let u=[],d=new Set;for(let[s,a]of e.statements.entries())for(let h of await t(a)){let f=h.Id;if(typeof f=="string"){if(n&&s>=r&&n.add(f),d.has(f))continue;d.add(f)}if(u.push(h),i!==void 0&&u.length>i)return l(u)}return u}function pe(e,t,n,{settle:o=!0}={}){let r=[];for(let i of n){let l=i.Id;typeof l=="string"&&l&&r.push(l)}o?e.addRead(t,r):e.add(t,r)}function Ge(e,t,n,o,r={}){pe(e,t,n,r);let i=r.keyPrefixes??new Map,l=o.filter(u=>u.isReference&&u.referenceTo&&u.referenceTo.length>0);for(let u of l){let d=u.referenceTo??[];for(let s of n){let a=s[u.name];if(!(typeof a!="string"||!a))for(let h of se(a,d,i))e.add(h,[a])}}}function he(e,t){let n=e.findIndex(l=>l.objectApiName===t);if(n<0)throw new Error(`Cannot run scoped clone with root "${t}" missing from the graph. The root node was excluded or filtered out \u2014 re-include it before executing.`);let o=e[n];if(!o.included)throw o.status==="error"?new Error(`Cannot run scoped clone: root "${t}" could not be measured during discovery (${o.errors[0]??"unknown discovery error"}), and nothing was read or written. Run discovery again once the org answers for it; if it refuses again, the user the clone reads as may not read ${t}: start from a record the user can read.`):new Error(`Cannot run scoped clone with root "${t}" excluded: the clone starts from its record, and the records that point at it would be written without it. Include it again, or clone from a query instead of a record.`);if(n===0)return e;let r=[...e],[i]=r.splice(n,1);return r.unshift(i),r}function q(e,t){let n=t??e.edges,o=new Map;for(let s of e.nodes)o.set(s.objectApiName,s);let r=new Map,i=new Map;for(let s of e.nodes)r.set(s.objectApiName,0);for(let s of n){r.has(s.targetObject)&&r.set(s.targetObject,(r.get(s.targetObject)??0)+1);let a=i.get(s.sourceObject);a?a.push(s.targetObject):i.set(s.sourceObject,[s.targetObject])}let l=[];for(let[s,a]of r)a===0&&l.push(s);let u=[],d=new Set;for(;l.length>0;){let s=l.shift();if(d.has(s))continue;d.add(s);let a=o.get(s);a&&u.push(a);let h=i.get(s);if(h){for(let f of h)if(r.has(f)){let g=(r.get(f)??1)-1;r.set(f,g),g===0&&!d.has(f)&&l.push(f)}}}for(let s of e.nodes)d.has(s.objectApiName)||u.push(s);return u}export{B as a,Y as b,te as c,G as d,U as e,Ne as f,je as g,xe as h,we as i,se as j,Ae as k,Ee as l,V as m,Ce as n,Fe as o,$e as p,de as q,Te as r,Me as s,fe as t,ke as u,Le as v,pe as w,Ge as x};
@@ -0,0 +1,7 @@
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};
@@ -0,0 +1,8 @@
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{e as C,f as I}from"./chunk-YT22LMF7.mjs";import{e as T,r as S,z as O}from"./chunk-SAMWHL22.mjs";import{H as A,d as P,r as b}from"./chunk-J24TIGSI.mjs";import{b as w}from"./chunk-CA5NAXSU.mjs";import{a as u}from"./chunk-ZUTUYBNW.mjs";import{_a as h}from"./chunk-ZQO5PDX5.mjs";import{b as i,f as R,l as m}from"./chunk-WZQEK4WT.mjs";import{randomBytes as q}from"node:crypto";import{open as U,readFile as F,rename as $,rm as M}from"node:fs/promises";import{promisify as N}from"node:util";import{gunzip as L,gzip as _}from"node:zlib";var D=N(_),Q=N(L),G=200,E="005",j="User",z="Group",H=new Set(["Pricebook2","PricebookEntry"]);function Re(e,n){let t=new Set(n);return e.fields.filter(o=>t.has(o.name)&&!C.includes(o.name)&&o.type==="reference"&&o.createable===!0&&(o.referenceTo??[]).some(r=>r===j||r===z)).map(o=>o.name)}async function Ae(e,n,t){let o=new Set;for(let{objectApiName:r,userLookups:s}of t){if(s.length===0)continue;let c=await S.read(e,n,r);for await(let l of c.records())for(let y of s){let a=l[y];if(typeof a!="string")continue;let p=u(a,E);p!==void 0&&o.add(p)}}return[...o].sort()}function ke(e){for(let n of e)if((n.name==="Account"||n.name==="Contact")&&n.fields.some(t=>t.name===I))return!0;return!1}function be(e){for(let n of e)if(H.has(n))return!0;return!1}function J(e){return e.map(n=>{if(u(n,E)!==n)throw new Error(`Not a user id: ${n}`);return`'${n}'`}).join(", ")}function W(e,n){let t=[];for(let o=0;o<e.length;o+=n)t.push(e.slice(o,o+n));return t}function B(e,n){return[...v(e),...W(n,G).map(t=>({part:"users",objectApiName:j,soql:`SELECT Id, Username, Name, IsActive, UserType FROM User WHERE Id IN (${J(t)})`,scanAll:!1}))]}function v(e){let n=[{part:"recordTypes",objectApiName:"RecordType",soql:`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${e.personAccounts?", IsPersonType":""} FROM RecordType`,scanAll:!1},{part:"queues",of:"groups",objectApiName:z,soql:"SELECT Id, DeveloperName, Name FROM Group WHERE Type = 'Queue'",scanAll:!1},{part:"queues",of:"objects",objectApiName:"QueueSobject",soql:"SELECT QueueId, SobjectType FROM QueueSobject",scanAll:!1}];return e.catalog&&n.push({part:"standardPricebook",objectApiName:"Pricebook2",soql:"SELECT Id FROM Pricebook2 WHERE IsStandard = true LIMIT 1",scanAll:!1}),n}function xe(e){return Math.ceil((v(e).length+1)/T)}var K=m({Id:i(),SobjectType:i(),DeveloperName:i(),NamespacePrefix:i().nullish(),Name:i(),IsActive:R(),IsPersonType:R().nullish()}).loose(),X=m({Id:i(),DeveloperName:i(),Name:i().nullish()}).loose(),V=m({QueueId:i(),SobjectType:i()}).loose(),Y=m({Id:i(),Username:i(),Name:i().nullish(),IsActive:R(),UserType:i()}).loose(),f="the org answered with rows this SandForge does not read";function Z(e,n){let t=[];for(let o of e){let r=K.safeParse(o);if(!r.success)return{unread:f};let s=r.data;t.push({id:u(s.Id)??s.Id,sobjectType:s.SobjectType,developerName:s.DeveloperName,...s.NamespacePrefix?{namespacePrefix:s.NamespacePrefix}:{},name:s.Name,isActive:s.IsActive,...n&&typeof s.IsPersonType=="boolean"?{isPersonType:s.IsPersonType}:{}})}return{rows:t.sort((o,r)=>x(`${o.sobjectType}.${o.developerName}`,`${r.sobjectType}.${r.developerName}`))}}function ee(e,n){let t=new Map;for(let r of n){let s=V.safeParse(r);if(!s.success)return{unread:f};let c=s.data.QueueId.slice(0,15);t.set(c,[...t.get(c)??[],s.data.SobjectType])}let o=[];for(let r of e){let s=X.safeParse(r);if(!s.success)return{unread:f};let c=s.data;o.push({id:u(c.Id)??c.Id,developerName:c.DeveloperName,name:c.Name??"",sobjectTypes:[...t.get(c.Id.slice(0,15))??[]].sort()})}return{rows:o.sort((r,s)=>x(r.developerName,s.developerName))}}function ne(e){let n=[];for(let t of e){let o=Y.safeParse(t);if(!o.success)return{unread:f};let r=o.data;n.push({id:u(r.Id)??r.Id,username:r.Username,name:r.Name??"",isActive:r.IsActive,userType:r.UserType})}return{rows:n.sort((t,o)=>x(t.id,o.id))}}async function we(e){let n=B(e,e.users),t=n.map(()=>[]),o=await O(e.reader,n,(a,p)=>{t[a].push(...p)},e.signal),r=new Map;o.forEach((a,p)=>{let{part:d}=n[p];!a.read&&!r.has(d)&&r.set(d,a.reason)});let s=(a,p)=>n.flatMap((d,g)=>d.part===a&&(p===void 0||d.of===p)?t[g]:[]),c={version:1,organizationId:u(e.organizationId)??e.organizationId,recordTypes:[],users:[],queues:[],unread:[]},l=(a,p,d)=>{let g=r.get(a);if(g!==void 0){c.unread.push({part:a,reason:oe(g)});return}let k=p();"unread"in k?c.unread.push({part:a,reason:k.unread}):d(k.rows)};l("recordTypes",()=>Z(s("recordTypes"),e.personAccounts),a=>{c.recordTypes=a}),l("queues",()=>ee(s("queues","groups"),s("queues","objects")),a=>{c.queues=a}),e.catalog&&l("standardPricebook",()=>{let[a]=s("standardPricebook"),p=typeof a?.Id=="string"?u(a.Id,"01s"):void 0;return a!==void 0&&p===void 0?{unread:f}:{rows:p}},a=>{a!==void 0&&(c.standardPricebookId=a)}),l("users",()=>ne(s("users")),a=>{c.users=a});let y=h.safeParse(c);return y.success?y.data:re(c,y.error.issues)}function re(e,n){let t=new Set;for(let r of n){let[s]=r.path;(s==="recordTypes"||s==="users"||s==="queues")&&t.add(s),s==="standardPricebookId"&&t.add("standardPricebook")}let o={...e,unread:[...e.unread]};for(let r of t)r==="recordTypes"&&(o.recordTypes=[]),r==="users"&&(o.users=[]),r==="queues"&&(o.queues=[]),r==="standardPricebook"&&delete o.standardPricebookId,o.unread.push({part:r,reason:f});return h.parse(o)}function x(e,n){return e<n?-1:e>n?1:0}function oe(e){let n=e.trim()===""?"the org gave no reason":e.trim();return n.length<=500?n:`${n.slice(0,499)}\u2026`}function te(e){let n=[...new Set(e.unread.map(t=>t.part))];return{recordTypes:e.recordTypes.length,users:e.users.length,queues:e.queues.length,standardPricebook:e.standardPricebookId!==void 0,...n.length>0?{unread:n}:{}}}async function Te(e,n){let t=h.safeParse(n);if(!t.success)throw new A("invalid",`Not a replay annex: ${t.error.message}`);let o=b(e),r=`${o}.${process.pid}-${q(4).toString("hex")}.tmp`,s=await U(r,"wx",P);try{try{await s.writeFile(await D(`${JSON.stringify(t.data)}
8
+ `)),await s.sync()}finally{await s.close()}await $(r,o)}catch(c){throw await M(r,{force:!0}),c}return te(t.data)}async function Pe(e){let n;try{n=await F(b(e))}catch(r){if(r.code==="ENOENT")return;throw r}let t;try{t=JSON.parse((await Q(n)).toString("utf8"))}catch(r){throw new A("damaged",`The checkpoint\u2019s replay annex cannot be read: ${w(r)}`)}let o=h.safeParse(t);if(!o.success)throw new A("damaged","The checkpoint\u2019s replay annex does not parse");return o.data}export{Re as a,Ae as b,ke as c,be as d,xe as e,we as f,te as g,Te as h,Pe as i};
@@ -0,0 +1,28 @@
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};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{b as S,d as z}from"./chunk-GSKCGQIP.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{yb as R}from"./chunk-TTFDUKUS.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-7EANH5PY.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};
7
+ import{b as S,d as z}from"./chunk-VPDEJGPS.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{ic as R}from"./chunk-ZQO5PDX5.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-WZQEK4WT.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};