sandforge 1.80.0 → 1.81.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 (239) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-EMNC6YI4.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-3RZQZHEB.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/{chunk-AEKONPF4.mjs → chunk-2OIRJEYE.mjs} +1 -1
  5. package/lib/{chunk-BV6VTP3J.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-JEERQRLW.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-FKG7Q3WH.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-HLWMJF6Y.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-GGD7ON3M.mjs → chunk-3B5H24ZG.mjs} +1 -1
  11. package/lib/chunk-43K2C6H2.mjs +7 -0
  12. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  13. package/lib/chunk-4L7FBOJS.mjs +8 -0
  14. package/lib/chunk-5344TZBT.mjs +11 -0
  15. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  16. package/lib/chunk-55LQD3Y3.mjs +7 -0
  17. package/lib/chunk-56MPPWLA.mjs +7 -0
  18. package/lib/chunk-5C5XEVZN.mjs +11 -0
  19. package/lib/chunk-5CKWGZX4.mjs +9 -0
  20. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  21. package/lib/{chunk-BKDV4ENO.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/{chunk-XAMBCQPU.mjs → chunk-5WGA5CZB.mjs} +1 -1
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/{chunk-UCD54V2M.mjs → chunk-67CC7RAE.mjs} +1 -1
  26. package/lib/{chunk-TSLJUSLW.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-FPKYYFM7.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-XUWL6ZPC.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-PJ5I73CK.mjs → chunk-742SSN7I.mjs} +1 -1
  33. package/lib/chunk-7DALDJMO.mjs +7 -0
  34. package/lib/chunk-7PK5QDQI.mjs +7 -0
  35. package/lib/chunk-AELFEK3G.mjs +7 -0
  36. package/lib/chunk-AITNZWLB.mjs +9 -0
  37. package/lib/{chunk-2UZPIMUC.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-GSKCGQIP.mjs → chunk-BNO5GIJ6.mjs} +1 -1
  39. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  40. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  41. package/lib/chunk-BZFIOZS3.mjs +156 -0
  42. package/lib/{chunk-J525F5KI.mjs → chunk-C4YGSK6W.mjs} +1 -1
  43. package/lib/chunk-CAFUNR6D.mjs +7 -0
  44. package/lib/chunk-CULAOP3U.mjs +7 -0
  45. package/lib/chunk-D62KWDDT.mjs +7 -0
  46. package/lib/{chunk-OHWNPXWW.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/{chunk-COFG7Q6R.mjs → chunk-DHGPDSXS.mjs} +1 -1
  48. package/lib/{chunk-WU3GLFZO.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-6XYKJSGX.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/{chunk-BY2HJFFG.mjs → chunk-DQR5NDMI.mjs} +1 -1
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/{chunk-YRQGKDHM.mjs → chunk-E2OBAWSH.mjs} +1 -1
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/{chunk-JWTSEDIQ.mjs → chunk-EAFLDSQ2.mjs} +1 -1
  56. package/lib/{chunk-MILU7WFN.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-BGUEWRK2.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-MYW5QNGI.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-NTFIRZP6.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-CHYDMRSV.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-MJVTDA5Q.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/{chunk-SOU4FRYN.mjs → chunk-FTA5LOVX.mjs} +1 -1
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-BTWDMNN3.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-SE4QEZUG.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-3TJON4F3.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-NZC67CGR.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-XLXIPIEW.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/{chunk-KDGMAGQR.mjs → chunk-HVC5CYIB.mjs} +1 -1
  73. package/lib/{chunk-WR4Q363I.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-5K5VLULK.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-QR3WELJQ.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-IWDREM66.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-2BA2XKAY.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-MHMH6MTP.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-M3ROUWDX.mjs → chunk-K77NR3UK.mjs} +1 -1
  84. package/lib/chunk-KE2PGD6C.mjs +7 -0
  85. package/lib/chunk-KGYXLSQ5.mjs +37 -0
  86. package/lib/{chunk-E5AHXLS6.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-L77FJZEP.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  90. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  91. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-LO527YLT.mjs} +1 -1
  92. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  93. package/lib/{chunk-F6GUDTOB.mjs → chunk-MHW6DV6T.mjs} +1 -1
  94. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  95. package/lib/{chunk-FGRG7ANU.mjs → chunk-MKNAZPOT.mjs} +1 -1
  96. package/lib/{chunk-PZPJKATS.mjs → chunk-MNITSYI2.mjs} +8 -8
  97. package/lib/{chunk-OLSGVAIL.mjs → chunk-MO3N5XVV.mjs} +53 -53
  98. package/lib/chunk-MWLFFVQV.mjs +8 -0
  99. package/lib/chunk-N6HHNR6J.mjs +7 -0
  100. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  101. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  102. package/lib/chunk-NWPQF5XR.mjs +7 -0
  103. package/lib/{chunk-IG2MTQRP.mjs → chunk-NWVVCZUK.mjs} +1 -1
  104. package/lib/{chunk-2NBYT7GR.mjs → chunk-O6ADMP36.mjs} +1 -1
  105. package/lib/chunk-O7DAFE6M.mjs +14 -0
  106. package/lib/chunk-OEHVAJAB.mjs +7 -0
  107. package/lib/chunk-OETEC3P7.mjs +7 -0
  108. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  109. package/lib/chunk-OIIL4NVI.mjs +7 -0
  110. package/lib/chunk-OMZJ37JI.mjs +15 -0
  111. package/lib/{chunk-CEX3NEZL.mjs → chunk-ONMBSACW.mjs} +1 -1
  112. package/lib/chunk-OQQHNYR7.mjs +272 -0
  113. package/lib/{chunk-SOGQW4IG.mjs → chunk-OU5W7SCB.mjs} +1 -1
  114. package/lib/{chunk-O2HDYYUV.mjs → chunk-OVOLG3AL.mjs} +1 -1
  115. package/lib/{chunk-DYFALGRT.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  116. package/lib/{chunk-2GTBABKU.mjs → chunk-OZNLOV4U.mjs} +1 -1
  117. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  118. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  119. package/lib/{chunk-IGYH7GMA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  120. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-BXU6WFMH.mjs → chunk-QXLZINZB.mjs} +1 -1
  123. package/lib/chunk-R2BJWO5N.mjs +20 -0
  124. package/lib/chunk-R6TF26V4.mjs +10 -0
  125. package/lib/{chunk-YKKRIEH4.mjs → chunk-RKALOKAU.mjs} +1 -1
  126. package/lib/chunk-SQGP46QS.mjs +7 -0
  127. package/lib/chunk-SW2NUKQL.mjs +9 -0
  128. package/lib/{chunk-MFG4MUIO.mjs → chunk-T26C576X.mjs} +1 -1
  129. package/lib/{chunk-LKQ5RKIV.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  130. package/lib/chunk-T5VAULLQ.mjs +7 -0
  131. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  132. package/lib/chunk-TKQQVB2D.mjs +9 -0
  133. package/lib/{chunk-ELFXJHU7.mjs → chunk-TPHXRHOA.mjs} +1 -1
  134. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  135. package/lib/{chunk-RPI7LRTW.mjs → chunk-TQM2XJ27.mjs} +1 -1
  136. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  137. package/lib/{chunk-G35N4P7D.mjs → chunk-UIUPPEFB.mjs} +1 -1
  138. package/lib/{chunk-DBB3EMIN.mjs → chunk-UT27HXE7.mjs} +1 -1
  139. package/lib/{chunk-KBJ5VERV.mjs → chunk-UUSLTW5V.mjs} +1 -1
  140. package/lib/chunk-V2QO6KOE.mjs +19 -0
  141. package/lib/chunk-V473C7LY.mjs +7 -0
  142. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  143. package/lib/chunk-VSU74RQ3.mjs +9 -0
  144. package/lib/chunk-VV3B6IC3.mjs +7 -0
  145. package/lib/chunk-W2AAGIZF.mjs +7 -0
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WD47PGUS.mjs +10 -0
  148. package/lib/{chunk-HEKAZJRH.mjs → chunk-WEZLXE34.mjs} +1 -1
  149. package/lib/{chunk-W622GUAW.mjs → chunk-WI4HYWV6.mjs} +1 -1
  150. package/lib/{chunk-WA7EYLAQ.mjs → chunk-WM5JI4JI.mjs} +1 -1
  151. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  152. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  153. package/lib/{chunk-FXXLX4O6.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  154. package/lib/{chunk-ZVAED4QV.mjs → chunk-XC2QKQT5.mjs} +1 -1
  155. package/lib/chunk-XC54KKKC.mjs +7 -0
  156. package/lib/chunk-XEB6HZ34.mjs +7 -0
  157. package/lib/chunk-XGKSSCW7.mjs +7 -0
  158. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  159. package/lib/{chunk-74Q6DORA.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  160. package/lib/{chunk-UNJA4J37.mjs → chunk-YCSFP6ER.mjs} +4 -4
  161. package/lib/{chunk-X5JYBPXP.mjs → chunk-YHIOS2PU.mjs} +1 -1
  162. package/lib/chunk-YIGFYZQY.mjs +7 -0
  163. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  164. package/lib/{chunk-TTKXMDBN.mjs → chunk-YOGMP72T.mjs} +4 -4
  165. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  166. package/lib/{chunk-CU2INBND.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  167. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  168. package/lib/{chunk-N652NMZ4.mjs → chunk-ZWZXQTAK.mjs} +52 -52
  169. package/lib/sandforge-autopilot.mjs +11 -11
  170. package/lib/sandforge-backup.mjs +63 -32
  171. package/lib/sandforge-checkpoint.mjs +1 -348
  172. package/lib/sandforge-cleanup.mjs +1 -1
  173. package/lib/sandforge-clone.mjs +1 -1
  174. package/lib/sandforge-compare.mjs +1 -1
  175. package/lib/sandforge-dataops.mjs +1 -1
  176. package/lib/sandforge-empty.mjs +11 -11
  177. package/lib/sandforge-env.mjs +104 -104
  178. package/lib/sandforge-frozen.mjs +1 -266
  179. package/lib/sandforge-mcp.mjs +33 -14
  180. package/lib/sandforge-monitor.mjs +1 -1
  181. package/lib/sandforge-pipeline.mjs +88 -0
  182. package/lib/sandforge-seed.mjs +1 -1
  183. package/lib/sandforge-sync.mjs +1 -1
  184. package/lib/sandforge.mjs +6 -6
  185. package/package.json +2 -1
  186. package/lib/chunk-2CNCDM56.mjs +0 -7
  187. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  188. package/lib/chunk-4VS2V6WU.mjs +0 -25
  189. package/lib/chunk-5P4PHJRL.mjs +0 -9
  190. package/lib/chunk-5TC3QB4U.mjs +0 -10
  191. package/lib/chunk-7ABODJ4G.mjs +0 -7
  192. package/lib/chunk-7EGQP6S4.mjs +0 -7
  193. package/lib/chunk-7FFGJWHN.mjs +0 -7
  194. package/lib/chunk-7YDNUBO5.mjs +0 -7
  195. package/lib/chunk-A527W53V.mjs +0 -7
  196. package/lib/chunk-ADOAS63R.mjs +0 -7
  197. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  198. package/lib/chunk-CION3VMZ.mjs +0 -7
  199. package/lib/chunk-CSBS5U5I.mjs +0 -7
  200. package/lib/chunk-DB7RBE5D.mjs +0 -7
  201. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  202. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  203. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  204. package/lib/chunk-EQNW3UC2.mjs +0 -7
  205. package/lib/chunk-F43REJDZ.mjs +0 -10
  206. package/lib/chunk-GSG7WZHM.mjs +0 -7
  207. package/lib/chunk-HOJYWTP7.mjs +0 -20
  208. package/lib/chunk-HS4YRX4J.mjs +0 -7
  209. package/lib/chunk-I7O6C2B5.mjs +0 -8
  210. package/lib/chunk-IFETCRWE.mjs +0 -10
  211. package/lib/chunk-IQXHJEYB.mjs +0 -7
  212. package/lib/chunk-JPUR2CFX.mjs +0 -10
  213. package/lib/chunk-K327QKMD.mjs +0 -7
  214. package/lib/chunk-KRCA6IPH.mjs +0 -8
  215. package/lib/chunk-LPBMBW3O.mjs +0 -13
  216. package/lib/chunk-LWW4U276.mjs +0 -7
  217. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  218. package/lib/chunk-OAZRPP4I.mjs +0 -7
  219. package/lib/chunk-OO6CLPEH.mjs +0 -7
  220. package/lib/chunk-OPXCV2KL.mjs +0 -7
  221. package/lib/chunk-P33PSCXK.mjs +0 -7
  222. package/lib/chunk-Q3DM32KF.mjs +0 -11
  223. package/lib/chunk-QROPNEGY.mjs +0 -14
  224. package/lib/chunk-QWT2C74M.mjs +0 -7
  225. package/lib/chunk-R3X3LV64.mjs +0 -14
  226. package/lib/chunk-RMBPOTD7.mjs +0 -7
  227. package/lib/chunk-SIHORWVK.mjs +0 -7
  228. package/lib/chunk-T62WNR54.mjs +0 -7
  229. package/lib/chunk-TTFDUKUS.mjs +0 -47
  230. package/lib/chunk-VE6XKGGD.mjs +0 -7
  231. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  232. package/lib/chunk-VS7ZXUII.mjs +0 -824
  233. package/lib/chunk-VXQLDM4R.mjs +0 -7
  234. package/lib/chunk-VYXMVJL5.mjs +0 -7
  235. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  236. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  237. package/lib/chunk-YS4G22C2.mjs +0 -7
  238. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  239. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ const [major, minor] = process.versions.node.split('.').map(Number);
3
+ if (major < 20 || (major === 20 && minor < 19)) {
4
+ process.stderr.write(
5
+ 'sandforge needs Node.js 20.19 or later, and this is ' + process.versions.node + '. Nothing was run.\n',
6
+ );
7
+ process.exit(1);
8
+ }
9
+ const { fileURLToPath } = await import('node:url');
10
+ const entry = new URL('../lib/sandforge-pipeline.mjs', import.meta.url);
11
+ process.argv[1] = fileURLToPath(entry);
12
+ await import(entry.href);
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a}from"./chunk-BV6VTP3J.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SeedValidator};
7
+ import{a}from"./chunk-2OZG6GRW.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SeedValidator};
@@ -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{l as i}from"./chunk-F43REJDZ.mjs";function u(o,t){let n=e=>e==="production"?`${t} is taken for a production org, and this command writes to none`:void 0;return new i({requestConfirmation:(e,d)=>{let r=n(d);return r===void 0?Promise.resolve(!0):(o(`refused: ${r} (${e})`),Promise.resolve(!1))},declinesWithoutAsking:n})}export{u as a};
7
+ import{l as i}from"./chunk-6SEDOIO3.mjs";function u(o,t){let n=e=>e==="production"?`${t} is taken for a production org, and this command writes to none`:void 0;return new i({requestConfirmation:(e,d)=>{let r=n(d);return r===void 0?Promise.resolve(!0):(o(`refused: ${r} (${e})`),Promise.resolve(!1))},declinesWithoutAsking:n})}export{u 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{g as m,h as S,i as E,j as x}from"./chunk-JWTSEDIQ.mjs";import{b as C}from"./chunk-CA5NAXSU.mjs";import{Cd as T,x as R}from"./chunk-TTFDUKUS.mjs";import{statfs as q}from"node:fs/promises";var re=["reads","leasePlan","stillRunning","deliverabilityRead","question","checkpointTake","leaseAcquire","afterLeaseCheck","write","leaseRelease","recordTypeReadBack","result"];function ie(e){let t=[],n=s=>e.indexOf(s),r=s=>e.lastIndexOf(s),o=(s,c,d,p=r(s),l=n(c))=>{p>=0&&l>=0&&p>l&&t.push(d)};o("leasePlan","stillRunning","what still runs was computed before the lease was planned"),o("stillRunning","deliverabilityRead","the deliverability was read before what still runs was known"),o("deliverabilityRead","question","the deliverability was read after the question it belongs to",n("deliverabilityRead")),o("question","checkpointTake","the checkpoint was taken before the last question"),o("question","leaseAcquire","the lease was taken before the last question"),o("checkpointTake","leaseAcquire","the lease was taken before the checkpoint"),o("leaseAcquire","afterLeaseCheck","the lease was checked before it was taken"),o("checkpointTake","write","a record was written before the checkpoint was taken"),o("leaseAcquire","write","a record was written before the lease was taken"),o("afterLeaseCheck","write","a record was written before the lease was checked"),o("write","leaseRelease","the lease was given back before the last write"),o("write","recordTypeReadBack","the record types were read back before the last write"),o("leaseRelease","recordTypeReadBack","the record types were read back while the lease was held"),n("leaseAcquire")>=0&&n("leaseRelease")<0&&t.push("the lease was never given back");let i=n("result");return i>=0&&e.slice(i+1).some(s=>s!=="result")&&t.push("the run went on past its result"),t}var W={insert:"go in",update:"are updated",delete:"are deleted",undelete:"come back"},L={flow:"flow",process:"process",workflowRule:"workflow rule",trigger:"Apex trigger"},h=3,v=/__e$/i;function u(e){return e.toLowerCase()}function A(e){let t=new Set,n=[];for(let r of e)t.has(u(r))||(t.add(u(r)),n.push(r));return n}function F(e){let t=e.slice(0,h),n=e.length-t.length,r=`${t.join("; ")}${n>0?`; and ${n} more`:""}`;return`${r.charAt(0).toUpperCase()}${r.slice(1)}.`}function I(e){let t=A(e.written),n=new Set(t.map(u)),r=new Map;for(let i of e.running.firing)if(i.flow!==void 0)for(let s of i.flow.creates??[]){let c=u(s);if(n.has(c)||v.test(s))continue;let d=r.get(c);d===void 0&&(d={objectApiName:s,clauses:[],by:[]},r.set(c,d));let p=`the target's ${L[i.kind]} '${i.name}' creates ${s} records as ${i.objectApiName} records ${W[i.write]}`;d.clauses.includes(p)||(d.clauses.push(p),d.by.push({kind:i.kind,name:i.name,objectApiName:i.objectApiName,write:i.write}))}let o=[...r.values()].map(({objectApiName:i,clauses:s,by:c})=>({objectApiName:i,code:"createdByAutomation",reason:F(s),creators:c.slice(0,h),...c.length>h?{moreCreators:c.length-h}:{}}));return{written:t,added:o,excluded:A(e.request.excluded??[]),picked:[...t,...o.map(({objectApiName:i})=>i)]}}var M={[u(m)]:{code:"files",reason:"Files, which every checkpoint of picked objects holds: a rewind deletes the files added since to the records it holds."},[u(x)]:{code:"attachments",reason:"Attachments, which every checkpoint of picked objects holds: a rewind deletes the attachments added since."}},K="Held as every checkpoint of picked objects holds it.",U={[u("AccountContactRelation")]:"Account contact relations, which the platform writes with each contact: a rewind deletes those made since with their contacts, and keeps no contact for them."},J=new Set([E,S].map(u)),z="A rewind leaves its records as they are.",k="No record was read.";function w(e,t,n){let r=new Map(t.map(a=>[u(a),a])),o=r.has(u(m)),i=a=>r.has(u(a))||o&&J.has(u(a)),s=[],c=a=>{let f=r.get(u(a));f!==void 0&&!s.includes(f)&&s.push(f)};for(let a of e.written)c(a);for(let{objectApiName:a}of e.added)c(a);for(let a of t)c(a);let d=new Set(e.picked.map(u)),p=[...e.added.flatMap(a=>{let f=r.get(u(a.objectApiName));return f===void 0?[]:[{...a,objectApiName:f}]}),...t.filter(a=>!d.has(u(a))).map(a=>({objectApiName:a,...M[u(a)]??{code:"heldUnasked",reason:U[u(a)]??K}}))],l=n.filter(({objectApiName:a})=>!i(a)).map(({objectApiName:a,reason:f,code:b,detail:y,records:O,limit:B})=>({objectApiName:a,...b!==void 0?{code:b}:{},reason:`${f} ${z}`,...y!==void 0?{detail:y}:{},...O!==void 0?{records:O}:{},...B!==void 0?{limit:B}:{}})),H=new Map(n.map(({objectApiName:a,reason:f})=>[u(a),f]));return{objects:s,added:p,notHeld:l,holds:i,why:a=>H.get(u(a))}}function g(e,t,n){return e.written.some(o=>t.holds(o))?void 0:e.written.length===0?{code:"NOTHING_HELD",message:`The run names no object it writes: a checkpoint before it would hold nothing a rewind could take back. ${n}`}:{code:"NOTHING_HELD",message:`The checkpoint before the run would hold none of the objects the run writes, so a rewind to it could take nothing of the run back. ${e.written.map(o=>`${o}: ${t.why(o)??"The take did not hold it."}`).join(" ")} ${n}`}}function G(e,t,n){let r={state:"planned",estimate:t.estimate,keepDays:n};if(t.objects.length===0&&t.leftOut.length===0&&t.refusal!==void 0)return{...r,objects:[],added:[],notHeld:[],refusal:t.refusal};let o=w(e,t.objects.map(({objectApiName:s})=>s),t.leftOut),i=g(e,o,k)??t.refusal;return{...r,objects:o.objects,added:o.added,notHeld:o.notHeld,...i!==void 0?{refusal:i}:{}}}var V=1.1;function N(e){return`${(e/(1024*1024)).toFixed(1)} MB`}function P(e,t){if(!(t===void 0||t>=Math.ceil(e*V)))return{code:"DISK",message:`The checkpoint before the run takes about ${N(e)} on this machine, and its disk has ${N(t)} free, less than that and a tenth more: make room, or leave objects out of the checkpoint. ${k}`}}async function _(e){try{let t=await q(e);return Number(t.bavail)*Number(t.bsize)}catch{return}}var Y={forge:"Forge run",sync:"Sync run",seed:"Seed run",autopilot:"Autopilot run",frozen:"Frozen Dataset load",empty:"emptying"};function Q(e){return`Before ${Y[e]} ${T}`}function se(e,t){let{min:n,max:r}=R,o=i=>typeof i=="number"&&Number.isInteger(i)&&i>=n&&i<=r;if(e!==void 0){if(!o(e))throw new RangeError(`Not a number of days to keep a checkpoint, ${n} to ${r}: ${e}`);return e}return o(t)?t:R.default}function X(e,t){return{mode:"picked",objects:e.picked,...e.excluded.length>0?{excluded:e.excluded}:{},nameWithDate:Q(t.module),keepDays:t.keepDays,unprovenLeftOut:!0,beforeRun:{module:t.module,operationId:t.operationId,tool:t.tool}}}function j(e,t){let{checkpoint:n}=t,r=w(e,n.objects.map(({objectApiName:o})=>o),n.scope.leftOut);return{state:"taken",checkpointId:n.checkpointId,name:n.name,takenAt:n.takenAt,expiresAt:n.expiresAt,objects:r.objects,records:n.objects.reduce((o,i)=>o+i.records,0),bytes:n.bytes,requests:t.requests?.total??t.estimate.apiRequests,added:r.added,notHeld:r.notHeld}}function D(e){return`${e.operation==="take"?"a checkpoint is being taken":e.operation==="rewind"?"a rewind is writing":e.operation==="undo"?"an undo is writing":e.operation==="empty"?"an emptying of its objects is writing":"SandForge is deleting checkpoints"} (process ${e.pid} on ${e.host})`}async function Z(e,t,n){let r=w(t,n.checkpoint.objects.map(({objectApiName:c})=>c),n.checkpoint.scope.leftOut);if(g(t,r,"")===void 0)return{taken:!0,checkpoint:j(t,n)};let o=await e.delete(n.checkpoint.checkpointId),i=o.outcome==="busy"?`It is kept all the same, as ${D(o.holder)}: delete it from the Checkpoints page once that has ended. Nothing was written.`:"It was deleted again; nothing was written.",s=g(t,r,i);return s===void 0?{taken:!0,checkpoint:j(t,n)}:{taken:!1,refusal:s}}function $(e,t,n){return{...e,...X(t,n)}}async function ae(e,t,n){let{scopeCheckpoint:r}=await import("./chunk-CSBS5U5I.mjs"),o=I(n),i=await r(e,$(t,o,n)),s=G(o,i,n.keepDays);if(s.refusal!==void 0)return s;let c=P(s.estimate.bytes,await(e.freeBytes??_)(e.store.root));return c===void 0?s:{...s,refusal:c}}async function ce(e,t,n,r){let o=await import("./chunk-CSBS5U5I.mjs"),i=I(n);if(r!==void 0){let c=P(r.estimate.bytes,await(e.freeBytes??_)(e.store.root));if(c!==void 0)return{taken:!1,refusal:c}}let s;try{s=await o.takeCheckpoint(e,$(t,i,n))}catch(c){if(c instanceof o.CheckpointTakeStopped)return{taken:!1,stopped:!0};throw c}return s.taken?Z(e.store,i,s):{taken:!1,refusal:s.refusal}}async function ue(e,t,n){if(n)return{info:t};let r=await e.delete(t.checkpointId);return r.outcome==="busy"?{info:t,notDeleted:`The checkpoint '${t.name}' taken before the run is kept, though the run wrote nothing: ${D(r.holder)}. Delete it from the Checkpoints page once that has ended.`}:{info:{state:"deleted",deleted:"nothingWritten"}}}function de(e){return`The checkpoint before the run was refused: ${e.message.endsWith(k)?e.message.slice(0,-k.length).trimEnd():e.message} Nothing was written. Untick Checkpoint first to run without it, or fix what refuses it.`}function fe(e){return`The checkpoint before the run could not be taken: ${C(e).replace(/\.$/,"")}. Nothing was written.`}var pe="The checkpoint taken before the run was deleted: the run wrote nothing.";function le(e){return`Taking the checkpoint first (${Math.round(e)}%)`}export{re as a,ie as b,I as c,G as d,V as e,P as f,_ as g,Q as h,se as i,X as j,j as k,Z as l,ae as m,ce as n,ue as o,de as p,fe as q,pe as r,le as s};
7
+ import{g as m,h as S,i as E,j as x}from"./chunk-EAFLDSQ2.mjs";import{b as C}from"./chunk-CA5NAXSU.mjs";import{$d as T,z as R}from"./chunk-DPYTG6DM.mjs";import{statfs as q}from"node:fs/promises";var re=["reads","leasePlan","stillRunning","deliverabilityRead","question","checkpointTake","leaseAcquire","afterLeaseCheck","write","leaseRelease","recordTypeReadBack","result"];function ie(e){let t=[],n=s=>e.indexOf(s),r=s=>e.lastIndexOf(s),o=(s,c,d,p=r(s),l=n(c))=>{p>=0&&l>=0&&p>l&&t.push(d)};o("leasePlan","stillRunning","what still runs was computed before the lease was planned"),o("stillRunning","deliverabilityRead","the deliverability was read before what still runs was known"),o("deliverabilityRead","question","the deliverability was read after the question it belongs to",n("deliverabilityRead")),o("question","checkpointTake","the checkpoint was taken before the last question"),o("question","leaseAcquire","the lease was taken before the last question"),o("checkpointTake","leaseAcquire","the lease was taken before the checkpoint"),o("leaseAcquire","afterLeaseCheck","the lease was checked before it was taken"),o("checkpointTake","write","a record was written before the checkpoint was taken"),o("leaseAcquire","write","a record was written before the lease was taken"),o("afterLeaseCheck","write","a record was written before the lease was checked"),o("write","leaseRelease","the lease was given back before the last write"),o("write","recordTypeReadBack","the record types were read back before the last write"),o("leaseRelease","recordTypeReadBack","the record types were read back while the lease was held"),n("leaseAcquire")>=0&&n("leaseRelease")<0&&t.push("the lease was never given back");let i=n("result");return i>=0&&e.slice(i+1).some(s=>s!=="result")&&t.push("the run went on past its result"),t}var W={insert:"go in",update:"are updated",delete:"are deleted",undelete:"come back"},L={flow:"flow",process:"process",workflowRule:"workflow rule",trigger:"Apex trigger"},h=3,v=/__e$/i;function u(e){return e.toLowerCase()}function A(e){let t=new Set,n=[];for(let r of e)t.has(u(r))||(t.add(u(r)),n.push(r));return n}function F(e){let t=e.slice(0,h),n=e.length-t.length,r=`${t.join("; ")}${n>0?`; and ${n} more`:""}`;return`${r.charAt(0).toUpperCase()}${r.slice(1)}.`}function I(e){let t=A(e.written),n=new Set(t.map(u)),r=new Map;for(let i of e.running.firing)if(i.flow!==void 0)for(let s of i.flow.creates??[]){let c=u(s);if(n.has(c)||v.test(s))continue;let d=r.get(c);d===void 0&&(d={objectApiName:s,clauses:[],by:[]},r.set(c,d));let p=`the target's ${L[i.kind]} '${i.name}' creates ${s} records as ${i.objectApiName} records ${W[i.write]}`;d.clauses.includes(p)||(d.clauses.push(p),d.by.push({kind:i.kind,name:i.name,objectApiName:i.objectApiName,write:i.write}))}let o=[...r.values()].map(({objectApiName:i,clauses:s,by:c})=>({objectApiName:i,code:"createdByAutomation",reason:F(s),creators:c.slice(0,h),...c.length>h?{moreCreators:c.length-h}:{}}));return{written:t,added:o,excluded:A(e.request.excluded??[]),picked:[...t,...o.map(({objectApiName:i})=>i)]}}var M={[u(m)]:{code:"files",reason:"Files, which every checkpoint of picked objects holds: a rewind deletes the files added since to the records it holds."},[u(x)]:{code:"attachments",reason:"Attachments, which every checkpoint of picked objects holds: a rewind deletes the attachments added since."}},K="Held as every checkpoint of picked objects holds it.",U={[u("AccountContactRelation")]:"Account contact relations, which the platform writes with each contact: a rewind deletes those made since with their contacts, and keeps no contact for them."},J=new Set([E,S].map(u)),z="A rewind leaves its records as they are.",k="No record was read.";function w(e,t,n){let r=new Map(t.map(a=>[u(a),a])),o=r.has(u(m)),i=a=>r.has(u(a))||o&&J.has(u(a)),s=[],c=a=>{let f=r.get(u(a));f!==void 0&&!s.includes(f)&&s.push(f)};for(let a of e.written)c(a);for(let{objectApiName:a}of e.added)c(a);for(let a of t)c(a);let d=new Set(e.picked.map(u)),p=[...e.added.flatMap(a=>{let f=r.get(u(a.objectApiName));return f===void 0?[]:[{...a,objectApiName:f}]}),...t.filter(a=>!d.has(u(a))).map(a=>({objectApiName:a,...M[u(a)]??{code:"heldUnasked",reason:U[u(a)]??K}}))],l=n.filter(({objectApiName:a})=>!i(a)).map(({objectApiName:a,reason:f,code:b,detail:y,records:O,limit:B})=>({objectApiName:a,...b!==void 0?{code:b}:{},reason:`${f} ${z}`,...y!==void 0?{detail:y}:{},...O!==void 0?{records:O}:{},...B!==void 0?{limit:B}:{}})),H=new Map(n.map(({objectApiName:a,reason:f})=>[u(a),f]));return{objects:s,added:p,notHeld:l,holds:i,why:a=>H.get(u(a))}}function g(e,t,n){return e.written.some(o=>t.holds(o))?void 0:e.written.length===0?{code:"NOTHING_HELD",message:`The run names no object it writes: a checkpoint before it would hold nothing a rewind could take back. ${n}`}:{code:"NOTHING_HELD",message:`The checkpoint before the run would hold none of the objects the run writes, so a rewind to it could take nothing of the run back. ${e.written.map(o=>`${o}: ${t.why(o)??"The take did not hold it."}`).join(" ")} ${n}`}}function G(e,t,n){let r={state:"planned",estimate:t.estimate,keepDays:n};if(t.objects.length===0&&t.leftOut.length===0&&t.refusal!==void 0)return{...r,objects:[],added:[],notHeld:[],refusal:t.refusal};let o=w(e,t.objects.map(({objectApiName:s})=>s),t.leftOut),i=g(e,o,k)??t.refusal;return{...r,objects:o.objects,added:o.added,notHeld:o.notHeld,...i!==void 0?{refusal:i}:{}}}var V=1.1;function N(e){return`${(e/(1024*1024)).toFixed(1)} MB`}function P(e,t){if(!(t===void 0||t>=Math.ceil(e*V)))return{code:"DISK",message:`The checkpoint before the run takes about ${N(e)} on this machine, and its disk has ${N(t)} free, less than that and a tenth more: make room, or leave objects out of the checkpoint. ${k}`}}async function _(e){try{let t=await q(e);return Number(t.bavail)*Number(t.bsize)}catch{return}}var Y={forge:"Forge run",sync:"Sync run",seed:"Seed run",autopilot:"Autopilot run",frozen:"Frozen Dataset load",empty:"emptying",replay:"checkpoint replay"};function Q(e){return`Before ${Y[e]} ${T}`}function se(e,t){let{min:n,max:r}=R,o=i=>typeof i=="number"&&Number.isInteger(i)&&i>=n&&i<=r;if(e!==void 0){if(!o(e))throw new RangeError(`Not a number of days to keep a checkpoint, ${n} to ${r}: ${e}`);return e}return o(t)?t:R.default}function X(e,t){return{mode:"picked",objects:e.picked,...e.excluded.length>0?{excluded:e.excluded}:{},nameWithDate:Q(t.module),keepDays:t.keepDays,unprovenLeftOut:!0,beforeRun:{module:t.module,operationId:t.operationId,tool:t.tool}}}function j(e,t){let{checkpoint:n}=t,r=w(e,n.objects.map(({objectApiName:o})=>o),n.scope.leftOut);return{state:"taken",checkpointId:n.checkpointId,name:n.name,takenAt:n.takenAt,expiresAt:n.expiresAt,objects:r.objects,records:n.objects.reduce((o,i)=>o+i.records,0),bytes:n.bytes,requests:t.requests?.total??t.estimate.apiRequests,added:r.added,notHeld:r.notHeld}}function D(e){return`${e.operation==="take"?"a checkpoint is being taken":e.operation==="rewind"?"a rewind is writing":e.operation==="undo"?"an undo is writing":e.operation==="empty"?"an emptying of its objects is writing":"SandForge is deleting checkpoints"} (process ${e.pid} on ${e.host})`}async function Z(e,t,n){let r=w(t,n.checkpoint.objects.map(({objectApiName:c})=>c),n.checkpoint.scope.leftOut);if(g(t,r,"")===void 0)return{taken:!0,checkpoint:j(t,n)};let o=await e.delete(n.checkpoint.checkpointId),i=o.outcome==="busy"?`It is kept all the same, as ${D(o.holder)}: delete it from the Checkpoints page once that has ended. Nothing was written.`:"It was deleted again; nothing was written.",s=g(t,r,i);return s===void 0?{taken:!0,checkpoint:j(t,n)}:{taken:!1,refusal:s}}function $(e,t,n){return{...e,...X(t,n)}}async function ae(e,t,n){let{scopeCheckpoint:r}=await import("./chunk-G4VXPS3A.mjs"),o=I(n),i=await r(e,$(t,o,n)),s=G(o,i,n.keepDays);if(s.refusal!==void 0)return s;let c=P(s.estimate.bytes,await(e.freeBytes??_)(e.store.root));return c===void 0?s:{...s,refusal:c}}async function ce(e,t,n,r){let o=await import("./chunk-G4VXPS3A.mjs"),i=I(n);if(r!==void 0){let c=P(r.estimate.bytes,await(e.freeBytes??_)(e.store.root));if(c!==void 0)return{taken:!1,refusal:c}}let s;try{s=await o.takeCheckpoint(e,$(t,i,n))}catch(c){if(c instanceof o.CheckpointTakeStopped)return{taken:!1,stopped:!0};throw c}return s.taken?Z(e.store,i,s):{taken:!1,refusal:s.refusal}}async function ue(e,t,n){if(n)return{info:t};let r=await e.delete(t.checkpointId);return r.outcome==="busy"?{info:t,notDeleted:`The checkpoint '${t.name}' taken before the run is kept, though the run wrote nothing: ${D(r.holder)}. Delete it from the Checkpoints page once that has ended.`}:{info:{state:"deleted",deleted:"nothingWritten"}}}function de(e){return`The checkpoint before the run was refused: ${e.message.endsWith(k)?e.message.slice(0,-k.length).trimEnd():e.message} Nothing was written. Untick Checkpoint first to run without it, or fix what refuses it.`}function fe(e){return`The checkpoint before the run could not be taken: ${C(e).replace(/\.$/,"")}. Nothing was written.`}var pe="The checkpoint taken before the run was deleted: the run wrote nothing.";function le(e){return`Taking the checkpoint first (${Math.round(e)}%)`}export{re as a,ie as b,I as c,G as d,V as e,P as f,_ as g,Q as h,se as i,X as j,j as k,Z as l,ae as m,ce as n,ue as o,de as p,fe as q,pe as r,le as s};
@@ -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 j,e as m,f as h,i as $,j as y,kc as v,vb as k}from"./chunk-DPYTG6DM.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};
@@ -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{g as v}from"./chunk-JWTSEDIQ.mjs";var x=!0;function D(t){let e=new Map;for(let n of t){let r=n.SobjectType;if(typeof r!="string"||r==="")continue;let o=r.toLowerCase(),c=e.get(o)??{viewAll:!1,modifyAll:!1};e.set(o,{viewAll:c.viewAll||n.PermissionsViewAllRecords===!0,modifyAll:c.modifyAll||n.PermissionsModifyAllRecords===!0})}return e}function E(t){return[...t.values()].some(e=>e.modifyAll)}var I=new Set(["task","event"]),M=new Set(["product2","pricebook2","pricebookentry"]),N=new Set(["user","group"]);function L(t){let e=[];for(let n of t.fields){if(n.type!=="reference")continue;let r=(n.referenceTo??[]).filter(o=>!N.has(o.toLowerCase()));r.length>0&&e.push({field:n.name,targets:r})}return e}function R(t,e){if(I.has(t))return"activities";if(M.has(t))return"catalog";if(t===v.toLowerCase())return"filesNotProven";if(e.has(t))return"settingNotProven"}function G(t,e){let n=j(e.describes),r=k(e.customSettings),o=new Map;for(let c of t){let f=c.toLowerCase();if(R(f,r)!==void 0||e.grants.has(f))continue;let u=n.get(f);if(u!==void 0)for(let{targets:p}of L(u)){if(p.length!==1)continue;let s=p[0],i=s.toLowerCase();!n.has(i)&&!o.has(i)&&o.set(i,s)}}return[...o.values()]}function j(t){return new Map([...t].map(e=>[e.name.toLowerCase(),e]))}function k(t){return new Set([...t??[]].map(e=>e.toLowerCase()))}function P(t,e,n){return(t.childRelationships??[]).some(r=>r.cascadeDelete===!0&&r.childSObject.toLowerCase()===e&&r.field.toLowerCase()===n.toLowerCase())}function $(t,e,n={}){let r=n.byParent??x,o=j(e.describes),c=k(e.customSettings),f=new Map,u=(s,i)=>{let d=s.toLowerCase(),C=f.get(d);if(C!==void 0)return C;let m=R(d,c);if(m!==void 0)return{reason:m};let h=e.grants.get(d);if(h!==void 0)return h.modifyAll?{access:"object"}:{reason:h.viewAll?"noModifyAll":"noViewAll"};if(!r)return{reason:"parentNotSeen",detail:"held through its parents is not proven"};let A=o.get(d);if(A===void 0)return{reason:"parentNotSeen",detail:"it could not be described"};let w=[];for(let{field:l,targets:a}of L(A)){let b=a.filter(y=>!o.has(y.toLowerCase())),g=a.filter(y=>{let S=o.get(y.toLowerCase());return S!==void 0&&P(S,d,l)});if(a.length>1){if(g.length>0||b.length>0)return{reason:"parentNotSeen",detail:`${l} may name a record of ${a.join(", ")}`};continue}if(b.length>0)return{reason:"parentNotSeen",detail:`${b[0]}, which ${l} names, could not be described`};g.length>0&&w.push({field:l,parent:g[0]})}if(w.length===0)return{reason:"parentNotSeen",detail:"it hangs from no record whose delete takes it along"};let O=new Set([...i,d]);for(let{field:l,parent:a}of w){let b=a.toLowerCase(),g=O.has(b)?void 0:u(a,O);if(g===void 0||!("access"in g))return{reason:"parentNotSeen",detail:`${a}, which ${l} names, is not held whole`}}return{access:"parent"}},p=new Map;for(let s of t){let i=u(s,new Set);f.set(s.toLowerCase(),i),p.set(s,i)}return p}export{D as a,E as b,G as c,$ as d};
7
+ import{g as v}from"./chunk-EAFLDSQ2.mjs";var x=!0;function D(t){let e=new Map;for(let n of t){let r=n.SobjectType;if(typeof r!="string"||r==="")continue;let o=r.toLowerCase(),c=e.get(o)??{viewAll:!1,modifyAll:!1};e.set(o,{viewAll:c.viewAll||n.PermissionsViewAllRecords===!0,modifyAll:c.modifyAll||n.PermissionsModifyAllRecords===!0})}return e}function E(t){return[...t.values()].some(e=>e.modifyAll)}var I=new Set(["task","event"]),M=new Set(["product2","pricebook2","pricebookentry"]),N=new Set(["user","group"]);function L(t){let e=[];for(let n of t.fields){if(n.type!=="reference")continue;let r=(n.referenceTo??[]).filter(o=>!N.has(o.toLowerCase()));r.length>0&&e.push({field:n.name,targets:r})}return e}function R(t,e){if(I.has(t))return"activities";if(M.has(t))return"catalog";if(t===v.toLowerCase())return"filesNotProven";if(e.has(t))return"settingNotProven"}function G(t,e){let n=j(e.describes),r=k(e.customSettings),o=new Map;for(let c of t){let f=c.toLowerCase();if(R(f,r)!==void 0||e.grants.has(f))continue;let u=n.get(f);if(u!==void 0)for(let{targets:p}of L(u)){if(p.length!==1)continue;let s=p[0],i=s.toLowerCase();!n.has(i)&&!o.has(i)&&o.set(i,s)}}return[...o.values()]}function j(t){return new Map([...t].map(e=>[e.name.toLowerCase(),e]))}function k(t){return new Set([...t??[]].map(e=>e.toLowerCase()))}function P(t,e,n){return(t.childRelationships??[]).some(r=>r.cascadeDelete===!0&&r.childSObject.toLowerCase()===e&&r.field.toLowerCase()===n.toLowerCase())}function $(t,e,n={}){let r=n.byParent??x,o=j(e.describes),c=k(e.customSettings),f=new Map,u=(s,i)=>{let d=s.toLowerCase(),C=f.get(d);if(C!==void 0)return C;let m=R(d,c);if(m!==void 0)return{reason:m};let h=e.grants.get(d);if(h!==void 0)return h.modifyAll?{access:"object"}:{reason:h.viewAll?"noModifyAll":"noViewAll"};if(!r)return{reason:"parentNotSeen",detail:"held through its parents is not proven"};let A=o.get(d);if(A===void 0)return{reason:"parentNotSeen",detail:"it could not be described"};let w=[];for(let{field:l,targets:a}of L(A)){let b=a.filter(y=>!o.has(y.toLowerCase())),g=a.filter(y=>{let S=o.get(y.toLowerCase());return S!==void 0&&P(S,d,l)});if(a.length>1){if(g.length>0||b.length>0)return{reason:"parentNotSeen",detail:`${l} may name a record of ${a.join(", ")}`};continue}if(b.length>0)return{reason:"parentNotSeen",detail:`${b[0]}, which ${l} names, could not be described`};g.length>0&&w.push({field:l,parent:g[0]})}if(w.length===0)return{reason:"parentNotSeen",detail:"it hangs from no record whose delete takes it along"};let O=new Set([...i,d]);for(let{field:l,parent:a}of w){let b=a.toLowerCase(),g=O.has(b)?void 0:u(a,O);if(g===void 0||!("access"in g))return{reason:"parentNotSeen",detail:`${a}, which ${l} names, is not held whole`}}return{access:"parent"}},p=new Map;for(let s of t){let i=u(s,new Set);f.set(s.toLowerCase(),i),p.set(s,i)}return p}export{D as a,E as b,G as c,$ as d};
@@ -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{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h,m as i,n as j,o as k,p as l,q as m,r as n}from"./chunk-YCSFP6ER.mjs";import"./chunk-GYKNCYES.mjs";import"./chunk-YOGMP72T.mjs";import"./chunk-6CDIIFNX.mjs";import"./chunk-MWLFFVQV.mjs";import"./chunk-YIGFYZQY.mjs";import"./chunk-2Z54GB6X.mjs";import"./chunk-R6TF26V4.mjs";import"./chunk-V4RKM4QZ.mjs";import"./chunk-JU2XEKEO.mjs";import"./chunk-K55LH4ZQ.mjs";import"./chunk-OMZJ37JI.mjs";import"./chunk-43K2C6H2.mjs";import"./chunk-FSZTXLNW.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import"./chunk-CAFUNR6D.mjs";import"./chunk-AITNZWLB.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-OEHVAJAB.mjs";import"./chunk-GWRKS3AL.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-6SEDOIO3.mjs";import"./chunk-ZWCRWF7E.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-QIRO4HTE.mjs";import"./chunk-MNITSYI2.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-ETT5GP4P.mjs";import"./chunk-SW2NUKQL.mjs";import"./chunk-4JKR4PTZ.mjs";import"./chunk-E2YJVSX6.mjs";import"./chunk-T26C576X.mjs";import"./chunk-BNO5GIJ6.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-SQGP46QS.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-6IGEASOF.mjs";import"./chunk-KOQV4WXC.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-CULAOP3U.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-KRNFVAGC.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-2OIRJEYE.mjs";import"./chunk-XEB6HZ34.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-ZUA5BNAO.mjs";import"./chunk-RKALOKAU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-55LQD3Y3.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-EAFLDSQ2.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{d as NOT_REMADE_WORDS,b as OTHERS_DELETION_WORDS,c as OUT_OF_REACH_WORDS,j as REWIND_AUTOMATION_LIFTED_BY,a as REWIND_RESIDUAL_IDS,i as RewindStopped,k as automationUnread,m as counted,h as heldWhile,l as inRewindWords,g as muteOfSteps,e as notAskedWords,n as rewindOrg,f as rewindOrgOf};
@@ -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}from"./chunk-UCD54V2M.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as seedObjectAccess,b as templateTheOrgTakes};
7
+ import{a,b}from"./chunk-67CC7RAE.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as seedObjectAccess,b as templateTheOrgTakes};
@@ -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}from"./chunk-WU3GLFZO.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{c as acquireEnvLock,g as checkpointLockRefusal,a as defaultEnvLocksDir,b as envLockFileOf,d as envLockHolder,f as envLockLine,e as envLockRefusal};
7
+ import{a,b,c,d,e,f,g}from"./chunk-DHIW4IO5.mjs";import"./chunk-E2YJVSX6.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{c as acquireEnvLock,g as checkpointLockRefusal,a as defaultEnvLocksDir,b as envLockFileOf,d as envLockHolder,f as envLockLine,e as envLockRefusal};
@@ -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 as S,b as k}from"./chunk-UNDIBZWG.mjs";import{tb as m,ub as z,vb as E,wb as h}from"./chunk-TTFDUKUS.mjs";import{b as c,f as g,i as f,k as l,l as d}from"./chunk-7EANH5PY.mjs";var D=/\bid\.?\s*:\s*([A-Za-z0-9]{18}|[A-Za-z0-9]{15})(?![A-Za-z0-9])/i;function x(e,s){let t;if(/^[A-Za-z0-9]{15}$/.test(e))t=S(e);else if(k(e))t=e;else return;if(!(s&&!t.startsWith(s)))return t}function v(e){return D.exec(e)?.[1]}var R=d({statusCode:c().optional(),errorCode:c().optional(),message:c().optional(),fields:l(f()).optional(),duplicateResult:f().optional()}).loose(),p="UNKNOWN_ERROR";function y(e){if(typeof e=="string")return{statusCode:p,message:e,fields:[]};let s=R.safeParse(e);return s.success?{statusCode:s.data.statusCode??s.data.errorCode??p,message:s.data.message??"",fields:(s.data.fields??[]).filter(t=>typeof t=="string")}:{statusCode:p,message:"Unknown error",fields:[]}}var _=/^([A-Z][A-Z0-9_]*):([\s\S]*):([A-Za-z0-9_]+(?: [A-Za-z0-9_]+)*)? ?--$/;function M(e){let s=e.trim();if(!s.endsWith("--")||s.slice(0,-2).includes("--"))return;let t=_.exec(s);if(t)return{statusCode:t[1],message:t[2],fields:t[3]===void 0?[]:t[3].split(" ")}}var b=d({matchResults:l(d({entityType:c().optional(),matchRecords:l(d({record:d({Id:c().optional(),attributes:d({type:c().optional()}).loose().optional()}).loose().optional()}).loose()).optional()}).loose()).optional()}).loose(),I=d({id:c().nullish(),success:g(),created:g().optional(),errors:l(f()).optional()}).loose();function P(e){return e.statusCode===p?e.message:`${e.statusCode}: ${e.message}`}function A(e){if(typeof e=="string")return e;let s=R.safeParse(e);if(!s.success)return"Unknown error";let t=s.data.statusCode??s.data.errorCode,n=s.data.message??"",r=t?`${t}: ${n}`:n,i=(s.data.fields??[]).filter(a=>typeof a=="string");if(i.length===0)return r;let o=`[${i.join(", ")}]`;return r.includes(o)?r:r?`${r} ${o}`:o}var C=5;function T(e){let s=(e??[]).map(r=>A(r)).filter(r=>r!==""&&r!=="Unknown error");if(s.length===0)return"Unknown insert error";let t=s.slice(0,C).join("; "),n=s.length-C;return n>0?`${t} (and ${n} more)`:t}function O(e,s){let t=R.safeParse(e);if(!t.success)return[];if((t.data.statusCode??t.data.errorCode)!==m)return[];let n=b.safeParse(t.data.duplicateResult);if(!n.success)return[];let r=[];for(let i of n.data.matchResults??[])for(let{record:o}of i.matchRecords??[]){let a=[i.entityType,o?.attributes?.type].filter(u=>typeof u=="string");a.length===0||a.some(u=>u!==s)||o?.Id&&r.push(o.Id)}return r}function w(e,s){let t=I.safeParse(e);if(!t.success){let i="Salesforce returned a save result of an unexpected shape";return{id:"",success:!1,errors:[i],errorDetails:[y(i)]}}let n=t.data.errors??[],r=n.flatMap(i=>O(i,s));return{id:t.data.id??"",success:t.data.success,...t.data.created!==void 0?{created:t.data.created}:{},errors:n.map(A),errorDetails:n.map(y),...r.length>0?{duplicateMatchIds:r}:{}}}function Z(e,s){return(Array.isArray(e)?e:[e]).map(t=>w(t,s))}function L(e,s){if(e.success||e.errors.length===0)return{kind:"none"};let t=o=>h(o)||z(o);if(!e.errors.every(t))return{kind:"none"};let n=new Set,r=!1;for(let o of e.errors){if(!o.includes(E))continue;let a=v(o),u=a?x(a,s):void 0;u?n.add(u):r=!0}let i=e.duplicateMatchIds??[];e.errors.some(o=>o.includes(m))&&i.length===0&&(r=!0);for(let o of i){let a=x(o,s);a?n.add(a):r=!0}return r||n.size!==1?{kind:"unidentified"}:{kind:"linked",id:[...n][0]}}export{x as a,p as b,y as c,M as d,P as e,A as f,T as g,O as h,w as i,Z as j,L as k};
7
+ import{a as S,b as k}from"./chunk-UNDIBZWG.mjs";import{Tb as m,Ub as z,Vb as E,Wb as h}from"./chunk-DPYTG6DM.mjs";import{b as c,f as g,i as f,k as l,l as d}from"./chunk-WZQEK4WT.mjs";var D=/\bid\.?\s*:\s*([A-Za-z0-9]{18}|[A-Za-z0-9]{15})(?![A-Za-z0-9])/i;function x(e,s){let t;if(/^[A-Za-z0-9]{15}$/.test(e))t=S(e);else if(k(e))t=e;else return;if(!(s&&!t.startsWith(s)))return t}function v(e){return D.exec(e)?.[1]}var R=d({statusCode:c().optional(),errorCode:c().optional(),message:c().optional(),fields:l(f()).optional(),duplicateResult:f().optional()}).loose(),p="UNKNOWN_ERROR";function y(e){if(typeof e=="string")return{statusCode:p,message:e,fields:[]};let s=R.safeParse(e);return s.success?{statusCode:s.data.statusCode??s.data.errorCode??p,message:s.data.message??"",fields:(s.data.fields??[]).filter(t=>typeof t=="string")}:{statusCode:p,message:"Unknown error",fields:[]}}var _=/^([A-Z][A-Z0-9_]*):([\s\S]*):([A-Za-z0-9_]+(?: [A-Za-z0-9_]+)*)? ?--$/;function M(e){let s=e.trim();if(!s.endsWith("--")||s.slice(0,-2).includes("--"))return;let t=_.exec(s);if(t)return{statusCode:t[1],message:t[2],fields:t[3]===void 0?[]:t[3].split(" ")}}var b=d({matchResults:l(d({entityType:c().optional(),matchRecords:l(d({record:d({Id:c().optional(),attributes:d({type:c().optional()}).loose().optional()}).loose().optional()}).loose()).optional()}).loose()).optional()}).loose(),I=d({id:c().nullish(),success:g(),created:g().optional(),errors:l(f()).optional()}).loose();function P(e){return e.statusCode===p?e.message:`${e.statusCode}: ${e.message}`}function A(e){if(typeof e=="string")return e;let s=R.safeParse(e);if(!s.success)return"Unknown error";let t=s.data.statusCode??s.data.errorCode,n=s.data.message??"",r=t?`${t}: ${n}`:n,i=(s.data.fields??[]).filter(a=>typeof a=="string");if(i.length===0)return r;let o=`[${i.join(", ")}]`;return r.includes(o)?r:r?`${r} ${o}`:o}var C=5;function T(e){let s=(e??[]).map(r=>A(r)).filter(r=>r!==""&&r!=="Unknown error");if(s.length===0)return"Unknown insert error";let t=s.slice(0,C).join("; "),n=s.length-C;return n>0?`${t} (and ${n} more)`:t}function O(e,s){let t=R.safeParse(e);if(!t.success)return[];if((t.data.statusCode??t.data.errorCode)!==m)return[];let n=b.safeParse(t.data.duplicateResult);if(!n.success)return[];let r=[];for(let i of n.data.matchResults??[])for(let{record:o}of i.matchRecords??[]){let a=[i.entityType,o?.attributes?.type].filter(u=>typeof u=="string");a.length===0||a.some(u=>u!==s)||o?.Id&&r.push(o.Id)}return r}function w(e,s){let t=I.safeParse(e);if(!t.success){let i="Salesforce returned a save result of an unexpected shape";return{id:"",success:!1,errors:[i],errorDetails:[y(i)]}}let n=t.data.errors??[],r=n.flatMap(i=>O(i,s));return{id:t.data.id??"",success:t.data.success,...t.data.created!==void 0?{created:t.data.created}:{},errors:n.map(A),errorDetails:n.map(y),...r.length>0?{duplicateMatchIds:r}:{}}}function Z(e,s){return(Array.isArray(e)?e:[e]).map(t=>w(t,s))}function L(e,s){if(e.success||e.errors.length===0)return{kind:"none"};let t=o=>h(o)||z(o);if(!e.errors.every(t))return{kind:"none"};let n=new Set,r=!1;for(let o of e.errors){if(!o.includes(E))continue;let a=v(o),u=a?x(a,s):void 0;u?n.add(u):r=!0}let i=e.duplicateMatchIds??[];e.errors.some(o=>o.includes(m))&&i.length===0&&(r=!0);for(let o of i){let a=x(o,s);a?n.add(a):r=!0}return r||n.size!==1?{kind:"unidentified"}:{kind:"linked",id:[...n][0]}}export{x as a,p as b,y as c,M as d,P as e,A as f,T as g,O as h,w as i,Z as j,L as k};
@@ -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{b as f}from"./chunk-CA5NAXSU.mjs";import{Nd as S,Od as h,Sd as g,Td as y,Ud as P}from"./chunk-DPYTG6DM.mjs";var T=576*60*60*1e3,b=T,m=class extends Error{constructor(e){super(e),this.name="StepCancelledError"}},w=Symbol("stopped");function $(t,e,n,i){let r=new Date().toISOString();return{stepId:t.id,stepName:t.name,stepType:t.type,status:"completed",output:e,summary:i,startTime:n,endTime:r,duration:new Date(r).getTime()-new Date(n).getTime()}}function u(t,e,n){let i=new Date().toISOString();return{stepId:t.id,stepName:t.name,stepType:t.type,status:"failed",error:e,startTime:n,endTime:i,duration:new Date(i).getTime()-new Date(n).getTime()}}function v(t){return P(t.type)?`Step "${t.name}" is a ${String(t.type)} step, which SandForge no longer supports: remove it from the pipeline.`:y(t.type)?`Step "${t.name}" is a ${String(t.type)} step, and this step type cannot run in a pipeline yet.`:`Step "${t.name}" is a "${String(t.type)}" step, a step type this release of SandForge does not have: the pipeline was saved by a later release, or written by hand. Remove the step, or update SandForge.`}function H(t){let{timeout:e}=t;if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))return`Step "${t.name}" has a timeout that is not a number of milliseconds: ${JSON.stringify(e)}.`;if(e>b)return`Step "${t.name}" has a timeout of ${e} ms, longer than a step can be given: set at most 24 days (${b} ms).`}}function x(t){let e=t.seconds,n=e===void 0?t.durationMs:e;if(typeof n!="number"||!Number.isFinite(n)||n<0)return;let i=e===void 0?n:n*1e3;return i<=T?i:void 0}function l(t){return String(Math.round(t/100)/10)}function M(t,e){let n=Math.max(t,e),i=n-t;return i<=Math.max(5e3,t/100)?`Waited ${l(n)} s.`:`Waited ${l(n)} s by the wall clock, ${l(i)} s more than the ${l(t)} s asked: the machine's clock or a sleep may account for it.`}function C(t){if(t.config.seconds===void 0&&t.config.durationMs===void 0)return`Delay step "${t.name}" has no duration: set how many seconds it waits.`;if(x(t.config)===void 0)return`Delay step "${t.name}" has no usable duration: set a number of seconds, from 0 up to 24 days.`}function E(t,e,n){let i=`Condition step "${t.name}"`;switch(n){case"noEarlierStep":return`${i} tests how the previous step went, and no step comes before it.`;case"noCompare":return`${i} tests how many differences a comparison found, and no Compare step comes before it.`;case"noPrecheck":return`${i} tests ${e}, which a Pre-check hands on, and no Pre-check before it takes that reading.`}}function k(t){let e=t.condition;if(!e||typeof e.field!="string"||e.field.trim()==="")return`Condition step "${t.name}" has no condition to evaluate.`;let n=S(e);return n===void 0?void 0:`Condition step "${t.name}" ${n}.`}function I(t,e){let n=k(t);if(n!==void 0||!t.condition||!e)return n;let i=t.condition,r=g(i,e.steps.slice(0,e.index),e.declared);return r===void 0?void 0:E(t,i.field,r)}function O(t,e){return e?.aborted?Promise.resolve(!1):new Promise(n=>{let i=()=>{clearTimeout(r),n(!1)},r=setTimeout(()=>{e?.removeEventListener("abort",i),n(!0)},t);e?.addEventListener("abort",i,{once:!0})})}var D=class{handlers=new Map;checks=new Map;constructor(){this.registerDefaults()}async execute(e,n){let i=new Date().toISOString(),r=this.check(e);if(r)return u(e,r,i);let o=this.getExecutor(e.type),c=e.retries??0,a="";for(let p=0;p<=c;p++){let s=await this.attempt(o,e,n);if("result"in s)return s.result;if(s.stopped)return{...u(e,s.error,i),status:"stopped"};a=s.error}return u(e,a,i)}async attempt(e,n,i){let r=i.signal;if(r?.aborted)return{error:`Step "${n.name}" was stopped before it started.`,stopped:!0};let o=new AbortController,c=new Promise(d=>{o.signal.addEventListener("abort",()=>d(w),{once:!0})}),a=()=>o.abort();r?.addEventListener("abort",a,{once:!0});let p=!1,s=n.timeout,R=s!==void 0&&s>0?setTimeout(()=>{p=!0,o.abort()},s):void 0;try{let d=await Promise.race([e(n,{...i,signal:o.signal}),c]);return d!==w?{result:d}:p?{error:`Step "${n.name}" timed out after ${s} ms.`}:{error:`Step "${n.name}" was stopped before it finished.`,stopped:!0}}catch(d){return d instanceof m?{error:d.message,stopped:!0}:{error:f(d)}}finally{clearTimeout(R),r?.removeEventListener("abort",a)}}check(e,n){return this.handlers.has(e.type)?H(e)??this.checks.get(e.type)?.(e,n):v(e)}getExecutor(e){return this.handlers.get(e)??this.refusingHandler}registerHandler(e,n,i){this.handlers.set(e,n),i?this.checks.set(e,i):this.checks.delete(e)}wrapHandler(e,n){let i=this.handlers.get(e);i&&this.handlers.set(e,n(i))}refusingHandler=async e=>u(e,v(e),new Date().toISOString());registerDefaults(){this.handlers.set("delay",this.createDelayHandler()),this.checks.set("delay",C),this.handlers.set("condition",this.createConditionHandler()),this.checks.set("condition",I)}createDelayHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=x(e.config);if(r===void 0)return u(e,C(e)??"No usable duration",i);let o=Date.now();if(!await O(r,n.signal))return u(e,`Delay step "${e.name}" was stopped before its ${r} ms wait ended.`,i);let a=Math.max(r,Date.now()-o);return $(e,{delayed:r,heldMs:a},i,M(r,a))}}createConditionHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=k(e);if(r||!e.condition)return u(e,r??"No condition",i);try{let o=h(e.condition,n.variables);return $(e,{conditionMet:o},i,o?"The condition held.":"The condition did not hold.")}catch(o){return u(e,`Condition step "${e.name}" could not be evaluated: ${f(o)}.`,i)}}}};export{m as a,x as b,M as c,D as d};
@@ -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{closeSync as D,fstatSync as J,openSync as W,readSync as $,writeSync as G}from"node:fs";function at(a){let e=W(a,"a+"),t=J(e).size;return{size:()=>t,append:n=>{let i=Buffer.from(n,"utf8"),r=0;for(;r<i.length;)r+=G(e,i,r);t+=i.length},read:(n,i)=>{let r=Buffer.alloc(i),s=0;for(;s<i;){let o=$(e,r,s,i-s,n+s);if(o===0)break;s+=o}return r.subarray(0,s)},close:()=>D(e)}}function j(a,e){return e===void 0?a:`${a}/${e}`}var E=/^[A-Za-z][A-Za-z0-9]*$/,T=/^[0-9a-f]{64}$/,K=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function M(a){if(typeof a!="object"||a===null)return;let{objectApiName:e,ids:t,sha256:n,readAt:i,query:r}=a;if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(e)||!Array.isArray(t)||!t.every(o=>typeof o=="string"&&K.test(o))||typeof n!="string"||!T.test(n)||typeof i!="string"||!Number.isFinite(Date.parse(i)))return;let s;if(typeof r=="object"&&r!==null){let{where:o,orderBy:c,limit:u}=r;s={...typeof o=="string"?{where:o}:{},...typeof c=="string"?{orderBy:c}:{},...typeof u=="number"&&Number.isInteger(u)?{limit:u}:{}}}return{objectApiName:e,ids:t,sha256:n,readAt:i,...s?{query:s}:{}}}var y=1,k=2,v=3,S=4,H={created:y,existing:k,updated:v},P={[y]:"created",[k]:"existing",[v]:"updated"},_={[y]:"c",[k]:"e",[v]:"u",[S]:"i"},N={c:y,e:k,u:v,i:S},Y="x",Z="a",q="j",z="d",R="n",O="t",U="found",V="found-owed";function dt(a,e,t,n){return JSON.stringify([z,a,e,t,n])}function ct(a){if(!a.startsWith(`["${z}"`))return;let e;try{e=JSON.parse(a)}catch{return}if(!Array.isArray(e))return;let[,,,t,n]=e;if(!(typeof t!="string"||!Number.isFinite(Date.parse(t)))&&!(typeof n!="string"||!Number.isFinite(Date.parse(n))))return{orgAt:t,at:n}}function Q(a,e=!1){return JSON.stringify([e?"w":"o",a.objectApiName,a.newId,a.sourceId??"",a.fieldName,a.sourceRefId,a.insertOnly?1:0])}var X=1024*1024,tt=1024*1024,et=2e4,nt=2e4,it=.6,rt=3;function l(a){let e=2166136261;for(let t=0;t<a.length;t++)e^=a.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function p(a){let e=2538058380;for(let t=0;t<a.length;t++)e=Math.imul(e^a.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var x=class{constructor(e){this.keyAt=e}keyAt;capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);at=new Float64Array(this.capacity);len=new Uint16Array(this.capacity);code=new Uint8Array(this.capacity);get size(){return this.used}get slots(){return this.capacity}find(e,t,n,i){let r=this.capacity-1,s=n&r;for(;;){let o=this.at[s];if(o===0)return~s;if(this.h1[s]===t&&this.h2[s]===n&&(i===o-1||this.keyAt(o-1,this.len[s])===e))return s;s=s+1&r}}offsetOf(e){return this.at[e]-1}lengthOf(e){return this.len[e]}codeOf(e){return this.code[e]}put(e,t,n,i,r,s){let o=e;e<0&&(this.used+1>this.capacity*it?(this.grow(),o=this.freeSlotFor(n)):o=~e,this.used++,this.h1[o]=t,this.h2[o]=n),this.at[o]=i+1,this.len[o]=r,this.code[o]=s}freeSlotFor(e){let t=this.capacity-1,n=e&t;for(;this.at[n]!==0;)n=n+1&t;return n}grow(){let{h1:e,h2:t,at:n,len:i,code:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.at=new Float64Array(this.capacity),this.len=new Uint16Array(this.capacity),this.code=new Uint8Array(this.capacity);for(let s=0;s<n.length;s++){if(n[s]===0)continue;let o=this.freeSlotFor(t[s]);this.h1[o]=e[s],this.h2[o]=t[s],this.at[o]=n[s],this.len[o]=i[s],this.code[o]=r[s]}}};function F(a){return a?a[0]==="p"&&a.length>=3?B(String(a[1]),String(a[2])):a[0]==="g"&&a.length>=3?C(String(a[2])):a[0]===O&&a.length>=2?I(String(a[1])):"":""}function I(a){return`t\0${a}`}function B(a,e){return`p\0${a}\0${e}`}function C(a){return`g\0${a}`}function*st(a){let e=a.size(),t=0,n=Buffer.alloc(0),i=0;for(;t<e;){let r=a.read(t,Math.min(tt,e-t));if(r.length===0)break;t+=r.length;let s=n.length>0?Buffer.concat([n,r]):r,o=0;for(;;){let c=s.indexOf(10,o);if(c<0)break;c>o&&(yield{offset:i+o,length:c-o,text:s.toString("utf8",o,c)}),o=c+1}n=s.subarray(o),i+=o}}var L=class a{constructor(e){this.file=e;this.index=new x((t,n)=>this.idOfLine(t,n)),this.marks=new x((t,n)=>F(m(this.lineAt(t,n)))),this.createdTargets=new x((t,n)=>{let i=m(this.lineAt(t,n));return i?A(String(i[2]??"")):""})}file;index;cache=new Map;pending=[];pendingBytes=0;flushQueued=!1;partStart=Number.POSITIVE_INFINITY;parts=0;mappedCount=0;counts=new Map;earlierByObject=new Map;earlierPastCheckpoint=new Map;checkpointsByObject=new Map;owedCount=0;statuses=new Map;given=new Map;marks;createdTargets;createdUnattributedKeys=new Set;readsHeld=[];withTheirRecordMarked=0;callsSent=0;foundAfterStop=new Set;foundOwingUntold=new Set;plan;rootsNamed;static open(e){let t=new a(e);return t.readWhatIsThere(),t}get partCount(){return this.parts}get resumes(){return this.checkpointsByObject.size>0||this.earlierByObject.size>0||this.owedCount>0}get earlierMapped(){return this.partStart===Number.POSITIVE_INFINITY?this.mappedCount:this.mappedBeforePart}mappedBeforePart=0;beginPart(e){this.flush(),this.mappedBeforePart=this.mappedCount,this.withTheirRecordMarked=0,this.partStart=this.file.size(),this.write({part:{n:this.parts,startedAt:e.toISOString()}}),this.parts++,this.flush()}nameSamplePlan(e){if(!T.test(e.sha256))throw new Error("Not the SHA-256 of a plan.");this.write({sample:{dir:e.dir,sha256:e.sha256}}),this.plan={dir:e.dir,sha256:e.sha256},this.flush()}get samplePlan(){return this.plan?{...this.plan}:void 0}nameRoots(e){let t=M(e);if(!t)throw new Error("Not the roots of a clone from records.");this.write({roots:t}),this.rootsNamed=t,this.flush()}get roots(){return this.rootsNamed?{...this.rootsNamed,ids:[...this.rootsNamed.ids]}:void 0}setMapping(e,t,n,i){let r=H[e],s=l(t),o=p(t),c=this.cache.get(t),u=this.index.find(t,s,o,c?.at),g=u>=0&&this.index.codeOf(u)!==S;g&&this.uncount(t,u,c);let d=JSON.stringify([_[r],t,n,i??""]),f=this.write(d);if(this.index.put(u,s,o,f,Buffer.byteLength(d),r),r===y&&this.indexCreated(n,f,Buffer.byteLength(d)),g||this.mappedCount++,i){let h=this.countsOf(i);r===y?h.created++:r===k?h.linked++:h.updated++}this.remember(t,{at:f,code:r,targetId:n,objectApiName:i??""})}uncount(e,t,n){let i=this.index.offsetOf(t);if(i<this.partStart)return;let r=this.index.codeOf(t),s=n?.at===i?n:this.recordAt(e,t),o=s?.objectApiName?this.counts.get(s.objectApiName):void 0;o&&(r===y?o.created--:r===k?o.linked--:o.updated--)}countsOf(e){let t=this.counts.get(e);return t||(t={created:0,linked:0,updated:0},this.counts.set(e,t)),t}mapping(e){let t=this.lookUp(e);if(!(!t||t.code===S))return{kind:P[t.code],sourceId:e,targetId:t.targetId,...t.objectApiName?{objectApiName:t.objectApiName}:{},earlier:t.at<this.partStart}}createdTarget(e){let t=A(e);if(this.createdUnattributedKeys.has(t))return!0;if(this.createdTargets.size===0)return!1;let n=this.createdTargets.find(t,l(t),p(t));if(n<0)return!1;let i=this.createdTargets.offsetOf(n),r=m(this.lineAt(i,this.createdTargets.lengthOf(n)));if(!r)return!1;let s=String(r[1]),o=this.index.find(s,l(s),p(s));return o>=0&&this.index.offsetOf(o)===i&&this.index.codeOf(o)===y}indexCreated(e,t,n){let i=A(e);if(!i)return;let r=l(i),s=p(i);this.createdTargets.put(this.createdTargets.find(i,r,s),r,s,t,n,y)}targetOf(e){let t=this.lookUp(e);return t&&t.code!==S?t.targetId:void 0}get mappedSize(){return this.mappedCount}countsByObject(){let e=[];for(let[t,{created:n,linked:i,updated:r}]of this.counts)n+i+r!==0&&e.push(r>0?{objectApiName:t,created:n,linked:i,updated:r}:{objectApiName:t,created:n,linked:i});return e}linkedToCreatedCount(){let e=0;for(let d of this.counts.values())e+=d.linked;if(e===0)return 0;let t=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart,n=(d,f)=>{let h=m(this.lineAt(d,f));return h?String(h[2]).slice(0,15):""},i=(d,f)=>{if(d.offset<t)return;let h=N[String(f[0])];if(h===void 0||h===S||!f[3])return;let b=String(f[1]),w=this.index.find(b,l(b),p(b),d.offset);return w>=0&&this.index.offsetOf(w)===d.offset?h:void 0},r=(d,f,h)=>{let b=l(f),w=p(f);d.put(d.find(f,b,w),b,w,h.offset,h.length,0)},s=(d,f)=>d.size>0&&d.find(f,l(f),p(f))>=0,o=new x(n);for(let d of this.lines()){if(!d.text.startsWith('["'))continue;let f=m(d.text);!f||i(d,f)!==k||this.markedWithTheirRecord(String(f[1]))||r(o,String(f[2]).slice(0,15),d)}if(o.size===0)return 0;let c=new x(n),u=new Set;for(let d of this.lines()){if(!d.text.startsWith('["')||d.offset<t)continue;let f=m(d.text);if(!f)continue;if(f[0]===R&&Array.isArray(f[2])){for(let b of f[2]){let w=String(b).slice(0,15);s(o,w)&&u.add(w)}continue}if(i(d,f)!==y)continue;let h=String(f[2]).slice(0,15);s(o,h)&&r(c,h,d)}if(c.size===0&&u.size===0)return 0;let g=0;for(let d of this.lines()){if(!d.text.startsWith('["'))continue;let f=m(d.text);if(!f||i(d,f)!==k||this.markedWithTheirRecord(String(f[1])))continue;let h=String(f[2]).slice(0,15);(s(c,h)||u.has(h))&&g++}return g}earlierRecordsOf(e,t=!1){return(t?this.earlierPastCheckpoint:this.earlierByObject).get(e)??0}*mappings(){for(let e of this.lines()){if(!e.text.startsWith('["'))continue;let t=m(e.text);if(!t)continue;let n=N[String(t[0])];if(n===void 0||n===S)continue;let i=String(t[1]),r=this.index.find(i,l(i),p(i),e.offset);if(r<0||this.index.offsetOf(r)!==e.offset)continue;let s=String(t[3]??"");yield{kind:P[n],sourceId:i,targetId:String(t[2]),...s?{objectApiName:s}:{},earlier:e.offset<this.partStart}}}noteRead(e){this.readsHeld.push(e),this.readsHeld.length>=nt&&this.settleReads()}settleReads(){let e=this.readsHeld;this.readsHeld=[];for(let t of e){let n=l(t),i=p(t),r=this.index.find(t,n,i,this.cache.get(t)?.at);if(r>=0)continue;let s=JSON.stringify([_[S],t]),o=this.write(s);this.index.put(r,n,i,o,Buffer.byteLength(s),S)}}wasRead(e){return this.readsHeld.includes(e)?!0:this.index.find(e,l(e),p(e),this.cache.get(e)?.at)>=0}checkpoint(e,t,n){if(n!==void 0&&!E.test(n))throw new Error(`Not the name of a pass: ${JSON.stringify(n.slice(0,40))}`);this.settleReads(),this.write({at:{object:e,...n!==void 0?{pass:n}:{},...t}}),this.checkpointsByObject.set(j(e,n),{...t}),this.flush()}checkpoints(){return new Map(this.checkpointsByObject)}owe(e,t=!1){this.owedCount++,this.write(Q(e,t))}get owed(){return this.owedCount}*owedPages(e){let t=[];for(let n of this.lines()){if(!n.text.startsWith('["o"')&&!n.text.startsWith('["w"'))continue;let i=m(n.text);if(!i||i.length<7)continue;let[r,s,o,c,u,g,d]=i;t.push({update:{objectApiName:String(s),newId:String(o),sourceId:c?String(c):void 0,fieldName:String(u),sourceRefId:String(g),...d===1?{insertOnly:!0}:{}},toRowWrittenBefore:r==="w"}),t.length>=e&&(yield t,t=[])}t.length>0&&(yield t)}patched(e,t){this.mark(JSON.stringify(["p",e,t]),B(e,t))}wasPatched(e,t){return this.hasMark(B(e,t))}mark(e,t){let n=l(t),i=p(t),r=this.marks.find(t,n,i),s=this.write(e);this.marks.put(r,n,i,s,Buffer.byteLength(e),0)}hasMark(e){return this.marks.size>0&&this.marks.find(e,l(e),p(e))>=0}owedLeftByEarlierParts(){let e=new Set;for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["p"'))continue;let i=m(n.text);i&&i.length>=3&&e.add(`${String(i[1])}\0${String(i[2])}`)}let t=[];for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["o"'))continue;let i=m(n.text);if(!i||i.length<7)continue;let[,r,s,o,c,u,g]=i;e.has(`${String(s)}\0${String(c)}`)||t.push({objectApiName:String(r),newId:String(s),sourceId:o?String(o):void 0,fieldName:String(c),sourceRefId:String(u),...g===1?{insertOnly:!0}:{}})}return t}oweStatus(e,t,n){this.write(JSON.stringify(["s",e,t,n])),this.tallyStatus({objectApiName:e,id:t,status:n})}tallyStatus(e){let t=this.statuses.get(e.objectApiName);t||(t={count:0,samples:[]},this.statuses.set(e.objectApiName,t)),t.count++,t.samples.length<rt&&t.samples.push(e)}gaveStatus(e,t){this.statusGiven(t)||(this.mark(JSON.stringify(["g",e,t]),C(t)),this.given.set(e,(this.given.get(e)??0)+1))}statusGiven(e){return this.hasMark(C(e))}statusesOwed(){let e=new Map;for(let[t,n]of this.statuses){let i=n.count-(this.given.get(t)??0);i<=0||e.set(t,{count:i,samples:n.samples.filter(({id:r})=>!this.statusGiven(r))})}return e}*statusLines(){for(let e of this.lines()){if(!e.text.startsWith('["s"'))continue;let t=m(e.text);!t||t.length<4||(yield{objectApiName:String(t[1]),id:String(t[2]),status:String(t[3])})}}withTheirRecord(e){let t=I(e),n=l(t),i=p(t),r=this.marks.find(t,n,i),s=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;if(r>=0&&this.marks.offsetOf(r)>=s)return;let o=JSON.stringify([O,e]),c=this.write(o);this.marks.put(r,n,i,c,Buffer.byteLength(o),0),this.withTheirRecordMarked++}get withTheirRecordCount(){return this.withTheirRecordMarked}markedWithTheirRecord(e){if(this.withTheirRecordMarked===0)return!1;let t=I(e),n=this.marks.find(t,l(t),p(t)),i=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;return n>=0&&this.marks.offsetOf(n)>=i}*withTheirRecordIds(){if(this.withTheirRecordMarked!==0)for(let e of this.lines()){if(e.offset<this.partStart||!e.text.startsWith(`["${O}"`))continue;let t=m(e.text);t&&t.length>=2&&(yield String(t[1]))}}sent(e,t,n,i=new Date,r){this.callsSent++;let s=`${Math.max(0,this.parts-1)}.${this.callsSent}`;return this.write(JSON.stringify([Y,s,e,i.toISOString(),t,n.map(({sourceId:o,fingerprint:c,externalKey:u,jobKey:g})=>r!==void 0&&u!==void 0?[o,c,u]:g!==void 0?[o,c,"",g]:[o,c]),n.flatMap(({owes:o},c)=>(o??[]).map(({field:u,sourceRefId:g,insertOnly:d})=>[c,u,g,d?1:0])),...r!==void 0?[r]:[]])),this.flush(),s}answered(e){this.write(JSON.stringify([Z,e]))}jobOpened(e,t){this.write(JSON.stringify([q,e,t])),this.flush()}createdUnattributed(e,t){if(t.length!==0){this.write(JSON.stringify([R,e,[...t]]));for(let n of t)this.createdUnattributedKeys.add(A(n))}}wasFoundAfterStop(e){return this.foundAfterStop.has(e)}owesUntold(e){return this.foundOwingUntold.has(e)}flush(){if(this.pending.length===0)return;let e=this.pending.join("");this.pending=[],this.pendingBytes=0,this.file.append(e)}close(){this.settleReads(),this.flush(),this.file.close()}write(e){let t=typeof e=="string"?e:JSON.stringify(e),n=this.file.size()+this.pendingBytes,i=`${t}
8
+ `;return this.pending.push(i),this.pendingBytes+=Buffer.byteLength(i),this.pendingBytes>=X?this.flush():this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()})),n}lineAt(e,t){return e+t>this.file.size()&&this.flush(),this.file.read(e,t).toString("utf8")}idOfLine(e,t){let n=m(this.lineAt(e,t));return n?String(n[1]):""}lookUp(e){let t=this.cache.get(e);if(t)return this.cache.delete(e),this.cache.set(e,t),t;let n=this.index.find(e,l(e),p(e));if(n<0)return;let i=this.recordAt(e,n);return i&&this.remember(e,i),i}recordAt(e,t){let n=this.index.offsetOf(t),i=m(this.lineAt(n,this.index.lengthOf(t)));if(!(!i||String(i[1])!==e))return{at:n,code:this.index.codeOf(t),targetId:String(i[2]??""),objectApiName:String(i[3]??"")}}remember(e,t){if(this.cache.delete(e),this.cache.set(e,t),this.cache.size>et){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}}*lines(){this.flush(),yield*st(this.file)}readWhatIsThere(){for(let e of this.lines()){if(e.text.startsWith('["')){let n=m(e.text);n&&this.readRegistration(e,n);continue}let t;try{t=JSON.parse(e.text)}catch{continue}if(!(typeof t!="object"||t===null)){if("part"in t)this.parts++;else if("sample"in t){let n=t.sample;if(typeof n!="object"||n===null)continue;let{dir:i,sha256:r}=n;if(typeof i!="string"||i===""||typeof r!="string"||!T.test(r))continue;this.plan={dir:i,sha256:r}}else if("roots"in t){let n=M(t.roots);n&&(this.rootsNamed=n)}else if("at"in t){let n=t.at;if(typeof n!="object"||n===null)continue;let{object:i,pass:r,lastId:s,read:o,done:c}=n;if(typeof i!="string"||typeof s!="string"||typeof o!="number"||r!==void 0&&(typeof r!="string"||!E.test(r)))continue;this.checkpointsByObject.set(j(i,r),{lastId:s,read:o,...c===!0?{done:c}:{}}),r===void 0&&this.earlierPastCheckpoint.delete(i)}}}}readRegistration(e,t){let n=String(t[0]);if(n==="o"||n==="w"){this.owedCount++;return}if(n==="s"){t.length>=4&&this.tallyStatus({objectApiName:String(t[1]),id:String(t[2]),status:String(t[3])});return}if(n==="p"||n==="g"||n===O){let d=F(t);if(!d)return;let f=l(d),h=p(d),b=this.marks.find(d,f,h);if(n==="g"&&b<0){let w=String(t[1]);this.given.set(w,(this.given.get(w)??0)+1)}this.marks.put(b,f,h,e.offset,e.length,0);return}if(n===R){if(Array.isArray(t[2]))for(let d of t[2])this.createdUnattributedKeys.add(A(String(d)));return}let i=N[n];if(i===void 0)return;let r=String(t[1]);i===y&&(t[4]===U||t[4]===V)&&(this.foundAfterStop.add(r),t[4]===U&&this.foundOwingUntold.add(r));let s=l(r),o=p(r),c=this.index.find(r,s,o),u=c>=0&&this.index.codeOf(c)!==S;if(i===S&&c>=0||(this.index.put(c,s,o,e.offset,e.length,i),i===S))return;i===y&&this.indexCreated(String(t[2]??""),e.offset,e.length),u||this.mappedCount++;let g=String(t[3]??"");g&&(this.earlierByObject.set(g,(this.earlierByObject.get(g)??0)+1),this.earlierPastCheckpoint.set(g,(this.earlierPastCheckpoint.get(g)??0)+1))}};function A(a){return a.slice(0,15)}function m(a){try{let e=JSON.parse(a);return Array.isArray(e)?e:void 0}catch{return}}export{at as a,j as b,M as c,Y as d,Z as e,q as f,z as g,R as h,O as i,U as j,V as k,dt as l,ct as m,Q as n,l as o,p,x as q,st as r,L as s};
@@ -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{b as $e}from"./chunk-OXKZ4Y3B.mjs";import{a as We}from"./chunk-M6P5ZZLE.mjs";import{c as ke,d as Ge}from"./chunk-SW2NUKQL.mjs";import{d as _e,z as Le}from"./chunk-E2YJVSX6.mjs";import{a as k}from"./chunk-4TLYUZD5.mjs";import{a as re}from"./chunk-PPGDAUEQ.mjs";import{a as Me}from"./chunk-VV3B6IC3.mjs";import{m as qe}from"./chunk-CULAOP3U.mjs";import{a as De}from"./chunk-SU65Z2BA.mjs";import{b as xe}from"./chunk-EADHKH3A.mjs";import{a as Te,h as q}from"./chunk-TZE3Y7IQ.mjs";import{a as H,c as Ae,g as oe,j as Pe,n as Ne}from"./chunk-EAFLDSQ2.mjs";import{a as je,b as x}from"./chunk-CA5NAXSU.mjs";import{ac as Z,bc as ee,ca as Ie,cc as te,ja as Fe,wa as ve,za as ue}from"./chunk-DPYTG6DM.mjs";import{b as Ce,e as Ee,i as Re,k as Se,l as de}from"./chunk-WZQEK4WT.mjs";import{appendFile as tt}from"node:fs/promises";var fe=new Set(["Task","Event"]),rt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ot="an emptying";function nt(t){let e=q(t.objectApiName),o=fe.has(t.objectApiName),r=[...t.filter!==void 0&&t.filter.trim()!==""?[`(${t.filter})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT Id FROM ${e}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,scanAll:o}}async function zt(t,e,o,r={}){let n=()=>r.signal?.aborted===!0,c=[];await Le(e);for(let a of o){let{soql:d,scanAll:u}=nt(a),m={objectApiName:a.objectApiName,count:0};if(c.push(m),n())return{stopped:!0,read:c};let R=ke(e,a.objectApiName),i=!0,h=0,b=await t.query(d,{scanAll:u});for(;;){let S=b.records.map(y=>{let C=y.Id;if(typeof C!="string"||!rt.test(C))throw new Error(`The org answered a ${a.objectApiName} row with no record id: its ids are not read.`);return C});if((S.length>0||i)&&(await tt(R,S.map(y=>`${y}
8
+ `).join(""),{encoding:"utf8",mode:_e,flag:i?"w":"a"}),i=!1),m.count+=S.length,r.onPage?.(a.objectApiName,m.count),h=S.length===0?h+1:0,b.done||!b.nextRecordsUrl)break;if(h>=xe)throw new Error(`The org kept answering empty pages of ${a.objectApiName} without saying it was done: ${m.count} id(s) read, the rest not.`);if(n())return{stopped:!0,read:c};b=await t.queryMore(b.nextRecordsUrl)}}return{stopped:!1,spool:await Ge(e,c,ot)}}function ne(t,e,o){return e.nillable!==!1||e.referenceTo.length!==1?!1:e.isMasterDetail||(o??[]).some(r=>r.isCascadeDelete&&r.childSObject===t&&r.field===e.name)}var V=.001,ge=.01,st=50,it=5,at=2,ct=4;function lt(t){return t.level===0||t.recordCount>0||t.status==="error"||t.recordCountUnknown===!0}function Be(t){return t.inputMode==="record"&&typeof t.recordId=="string"&&t.recordId!==""}function pe(t){if(!Fe(t)||t.inputMode!=="soql")return;let e=Ie(t.soqlQuery??"");return e?{where:e.where,limit:e.limit}:void 0}function dt(t,e,o){let r=[];o===0&&Be(t)&&r.push(`Id = '${Te(t.recordId??"")}'`);let n=o===0?pe(t):void 0;n?.where&&r.push(`(${n.where})`);let c=t.objectSoqlFilters?.[e];return c&&r.push(`(${c})`),`SELECT COUNT() FROM ${q(e)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`}var me=typeof setImmediate=="function"?()=>new Promise(t=>setImmediate(t)):()=>new Promise(t=>setTimeout(t,0)),A=class extends Error{constructor(){super("Discovery cancelled"),this.name="DiscoveryCancelled"}};function M(t,e){return e?e.aborted?Promise.reject(new A):new Promise((o,r)=>{let n=()=>r(new A);e.addEventListener("abort",n,{once:!0}),t().then(c=>{e.removeEventListener("abort",n),o(c)},c=>{e.removeEventListener("abort",n),r(c)})}):t()}function ut(t){return t.fieldCount>0||t.piiFields.length>0}function ft(t,e){if(t.type!=="master-detail")return t;let o=(e.get(t.targetObject)?.fields??[]).filter(n=>n.referenceTo.includes(t.sourceObject)),r=e.get(t.sourceObject)?.childRelationships;return o.some(n=>ne(t.targetObject,n,r))?t:{...t,type:"lookup"}}function Y(){return{nodes:[],edges:[],totalRecords:0,estimatedSizeMB:0,estimatedDurationSeconds:0,truncated:!1}}var Ue=class{deps;constructor(e){this.deps=e}async discover(e,o){if(e.inputMode==="org"||e.depth==="all")return ze(this.deps,e,o);let r=o?.signal;if(r?.aborted)return Y();o?.onProgress?.({phase:"resolving-root",discoveredCount:0,queueRemaining:1});let n=Date.now(),c;try{c=await this.resolveRootObject(e,r)}catch(g){if(g instanceof A)return Y();throw g}let a=Date.now();a-n>2e3&&k.warn(`[forge-discover] resolveRootObject took ${a-n}ms (cold path, consider verifying describeGlobal cache state)`);let d=this.resolveMaxDepth(e),u=o?.maxNodes??st,m=u,R=u*at,i=new Set,h=[],b=u*ct,S=0,y=0,C=new Set,I=[],$=new Map,N=new Map,L=()=>S+y+w.length<m&&I.length+y+w.length<b,W=(g,j)=>{i.has(g)||h.push([g,j]),i.add(g)},D=g=>{i.delete(g)&&(h=h.filter(([j])=>j!==g))},U=new Map,B=(g,j,P,F)=>{if(H(g.sourceObject)||H(g.targetObject)||g.sourceObject===g.targetObject)return;let s=`${g.sourceObject}|${g.targetObject}`,l=U.get(s)??new Map;(P!==void 0||!l.has(j))&&l.set(j,{settable:P,insertOnly:F}),U.set(s,l);let p=$.get(s);if(!p){$.set(s,g);return}let f=g.type==="master-detail"&&p.type==="lookup"?g:p,v=p.required===!0||g.required===!0;$.set(s,v?{...f,required:v}:f)},w=[[c,0]];for(C.add(c);w.length>0&&!r?.aborted;){await me();let g=m-S;if(g<=0)break;let j=Math.min(6,g,w.length),P=w.splice(0,j),F=await Promise.all(P.map(async([s,l])=>{let p,f=!1,v=dt(e,s,l);try{let[E,Q]=await Promise.all([M(()=>this.deps.describeObject(e.sourceOrgId,s,r),r),M(()=>this.deps.queryCount(e.sourceOrgId,v,r),r).catch(_=>{if(_ instanceof A)throw _;return p=x(_),f=se(_),-1})]);return{objectName:s,depth:l,describe:E,recordCount:Q,countError:p,countRefused:f}}catch(E){return E instanceof A||r?.aborted?{objectName:s,depth:l,describe:null,recordCount:-1,cancelled:!0}:{objectName:s,depth:l,describe:null,recordCount:-1,describeError:x(E)}}}));y=F.length;for(let s of F){if(y--,s.cancelled)continue;let{objectName:l,depth:p,describe:f,recordCount:v,countError:E,countRefused:Q,describeError:_}=s;if(!f){I.push({objectApiName:l,recordCount:0,fieldCount:0,status:"error",progress:0,included:!1,piiFields:[],anonymizeFields:[],level:p,successCount:0,failureCount:0,errors:[`Describe unavailable: ${_??"unknown error"}`],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}),S++,o?.onProgress?.({phase:"object",objectApiName:l,discoveredCount:I.length,queueRemaining:w.length});continue}N.set(l,f);let ie=v<0,ae=ie&&Q!==!0,ce=ie&&!ae,le=p===0?pe(e)?.limit:void 0,J=ie?0:typeof le=="number"&&Number.isFinite(le)?Math.min(v,le):v,Je=p===0&&(Be(e)||pe(e)!==void 0),be=this.deps.detectPII(f.fields),Ke=f.fields.filter(O=>O.type!=="id").length,Oe={objectApiName:l,...f.label?{label:f.label}:{},recordCount:J,...ae?{recordCountUnknown:!0}:{},fieldCount:f.fields.length,status:ce?"error":"idle",progress:0,included:ce?!1:ae||Je||!e.skipEmpty||J>0,piiFields:be,anonymizeFields:e.anonymizePII?be:[],level:p,successCount:0,failureCount:0,errors:ce?[`Record count unavailable: ${E??"unknown error"}`]:[],createableFieldCount:Ke,estimatedSizeMB:J*V,estimatedApiCalls:Math.ceil(J/200),batchStrategy:"auto"};I.push(Oe);let ye=lt(Oe);if(ye&&S++,p<d&&ye){for(let O of f.fields){if(O.referenceTo.length===0)continue;let we=ee(O),K=we&&Z(l,O.name,O.nillable),Ze=te(O);for(let T of O.referenceTo){B({sourceObject:T,targetObject:l,relationshipName:O.relationshipName??O.name,type:O.isMasterDetail?"master-detail":"lookup",required:K},O.name,we,Ze);let et=i.has(T);(!C.has(T)||K&&et)&&!H(T)&&(L()?(C.add(T),D(T),K?w.unshift([T,p+1]):w.push([T,p+1])):K&&m<R?(C.add(T),D(T),m++,w.unshift([T,p+1])):(C.add(T),W(T,p+1)))}}for(let O of f.childRelationships)B({sourceObject:l,targetObject:O.childSObject,relationshipName:O.relationshipName,type:O.isCascadeDelete?"master-detail":"lookup"},O.field,void 0,void 0),!C.has(O.childSObject)&&!H(O.childSObject)&&(C.add(O.childSObject),L()?w.push([O.childSObject,p+1]):W(O.childSObject,p+1))}o?.onProgress?.({phase:"object",objectApiName:l,discoveredCount:I.length,queueRemaining:w.length})}for(;h.length>0&&L();){let[s,l]=h.shift();i.delete(s),w.push([s,l])}}let z=I.reduce((g,j)=>g+j.recordCount,0),G=[...$].map(([g,j])=>{let P=[...U.get(g)?.values()??[]],F=ft(j,N);return P.length>0&&P.every(s=>s.settable===!1)&&(F={...F,settable:!1}),P.some(s=>s.insertOnly===!0)&&(F={...F,insertOnly:!0}),F});return{nodes:I,edges:G,totalRecords:z,estimatedSizeMB:z*V,estimatedDurationSeconds:z*ge,truncated:h.length>0}}personalFields(e){return this.deps.detectPII(e)}async readPersonalFields(e,o,r){let n=e.nodes.filter(a=>!ut(a)&&a.status!=="error"),c=new Map;for(let a=0;a<n.length&&!r?.aborted;a+=6)await Promise.all(n.slice(a,a+6).map(async({objectApiName:d})=>{try{let u=await this.deps.describeObject(o.sourceOrgId,d,r),m=this.deps.detectPII(u.fields);m.length>0&&c.set(d,m)}catch(u){k.warn(`[forge] personal fields of ${d} not read: ${x(u)}`)}}));return c.size===0?e:{...e,nodes:e.nodes.map(a=>{let d=c.get(a.objectApiName);return d?{...a,piiFields:d,anonymizeFields:o.anonymizePII?[...d]:[]}:a})}}async resolveRootObject(e,o){if(e.inputMode==="record"&&e.recordId){let r=e.recordId.substring(0,3),c=(await M(()=>this.deps.describeGlobal(e.sourceOrgId,o),o)).find(a=>a.keyPrefix===r);if(!c)throw new Error(`No object found for record ID prefix "${r}". The ID may not belong to any accessible object in this org.`);return c.name}if(e.inputMode==="soql"&&e.soqlQuery)return pt(e.soqlQuery);throw new Error(`Cannot resolve root object for inputMode "${e.inputMode}". Provide a valid recordId (for "record" mode) or soqlQuery (for "soql" mode).`)}resolveMaxDepth(e){switch(e.depth){case"direct":return 1;case"full":return it;case"custom":return Math.max(1,Math.min(10,e.customDepth??3));case"all":throw new Error("A clone of the whole org is discovered without a walk (WholeOrgDiscovery)")}}};function pt(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--[^\n]*/g,"");for(let r=0;r<32;r++){let n=e.replace(/\([^()]*\)/g,"");if(n===e)break;e=n}let o=/\bFROM\s+(\w+)/i.exec(e);if(!o)throw new Error('Could not parse object name from SOQL query. Ensure the query uses standard "SELECT ... FROM ObjectName" syntax.');return q(o[1])}var gt={clone:"write",empty:"delete"},mt=["settings","definition"],ht=new Set(["contentworkspace"]);function bt(t){if(t.name.includes("__"))return!1;let e=t.name.toLowerCase();return ht.has(e)||mt.some(o=>e.endsWith(o))?!0:t.createable===!1&&e!==oe.toLowerCase()}function Ot(t,e){return t.objectApiName<e.objectApiName?-1:t.objectApiName>e.objectApiName?1:0}function yt(t,e,o,r={}){let n=Ne(t,{mode:"everything",access:gt[o],...r.excluded!==void 0?{excluded:r.excluded}:{},...r.customSettings!==void 0?{customSettings:r.customSettings}:{}},e),c=new Map(t.map(u=>[u.name.toLowerCase(),u])),a=[],d=[];for(let u of n.candidates){let m=c.get(u.toLowerCase());m!==void 0&&bt(m)?d.push({objectApiName:u,reason:"configuration"}):a.push(u)}return d.length===0?n:{...n,candidates:a,leftOut:[...n.leftOut,...d].sort(Ot)}}var wt=new Set([oe,Pe].map(t=>t.toLowerCase())),Qe="withTheirRecords",Ct="noLayout";function Et(t){switch(t){case"configuration":return{reason:"setup"};case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"files":case"setup":case"platformCreated":case"metadata":case"notWritable":case"excludedByUser":return{reason:t};case"heldWithFiles":return{reason:"files",detail:Qe};case"notFound":case"notCustomSetting":return{reason:"missingInTarget"}}}function Rt(t){switch(t){case"platform":return{reason:"platformCreated"};case"setup":return{reason:"setup"};case"feature":case"parent":return{reason:"notWritable",detail:t};case"user":return{reason:"notWritable"}}}function St(t){if(t.createable!==!0||t.queryable!==!0)return;let e=t.updateable===!0,o=t.deletable===!0;if(!(e&&o))return!e&&!o?{reason:"createOnly"}:{reason:"createOnly",detail:e?Ft:It}}var It="noEdit",Ft="noDelete";function vt(t,e){return t.objectApiName<e.objectApiName?-1:t.objectApiName>e.objectApiName?1:0}function He(t,e,o,r={}){let n=yt(e,o,"clone",r),c=new Map(t.map(i=>[i.name.toLowerCase(),i])),a=new Map(e.map(i=>[i.name.toLowerCase(),i])),d=[],u=[],m=new Set,R=(i,h,b)=>{m.add(i.toLowerCase()),u.push({objectApiName:i,reason:h,...b!==void 0?{detail:b}:{}})};for(let i of t)a.has(i.name.toLowerCase())||R(i.name,"missingInTarget");for(let i of n.leftOut){let h=i.objectApiName.toLowerCase(),b=c.get(h);if(!b||m.has(h))continue;let S=a.get(h),y=Et(i.reason),C=h!==oe.toLowerCase();y.reason==="notWritable"&&C&&S?.createable!==!0&&r.createFacts&&(y=Rt(We(b.name,r.createFacts))),y.reason==="notWritable"&&C&&S&&(y=St(S)??y);let I=i.reason==="setup"&&S?.layoutable===!1&&!Ae(i.objectApiName);R(b.name,y.reason,I?Ct:y.detail??i.detail)}for(let i of n.candidates){let h=i.toLowerCase(),b=c.get(h);b&&(b.queryable!==!0?R(b.name,"notQueryable"):wt.has(h)?R(b.name,"files",Qe):d.push(b.name))}return d.sort(),u.sort(vt),{candidates:d,leftOut:u}}var he=1950,Xe=2e4,jt=1e6,Dt=18,Tt=200,At=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE","REQUEST_LIMIT_EXCEEDED","REQUEST_RUNNING_TOO_LONG","SERVER_UNAVAILABLE","UNKNOWN_EXCEPTION"]);function se(t){if(t instanceof Me||De(t))return!1;let e=je(x(t));return e===void 0?!1:!At.has(e)&&!e.startsWith("ERROR_HTTP_")}function Pt(t,e){let o=fe.has(t),r=[...e?[`(${e})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT COUNT() FROM ${q(t)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,all:o}}async function Ve(t,e){let o=0,r=!1,n=()=>r,c=async()=>{for(;!r&&o<t.length;){let a=o++;try{await e(t[a],a,n)}catch(d){throw r=!0,d}}};await Promise.all(Array.from({length:Math.min(6,t.length)},c))}async function Nt(t,e){try{return await t()}catch(o){if(o instanceof A||re(o)||se(o))throw o;return k.warn(`[forge-discover] whole org: describe of ${e} unanswered, asked again: ${x(o)}`),t()}}function Ye(t){if(!(t<=ue))throw new Error(`The source org lists ${t} objects a clone of the whole org leaves out, more than the ${ue} one graph says. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`)}var xt=de({name:Ce().min(1),count:Ee().int().nonnegative()});function Mt(t){let e=de({sObjects:Se(Re())}).safeParse(t);if(!e.success)return;let o=new Map;for(let r of e.data.sObjects){let n=xt.safeParse(r);n.success&&o.set(n.data.name,n.data.count)}return o}function _t(t){let e=new Map;for(let[o,r]of t)for(let n of r.fields){if(n.referenceTo.length===0)continue;let c=ee(n),a=c&&Z(o,n.name,n.nillable),d=te(n);for(let u of n.referenceTo){if(u===o||!t.has(u))continue;let m=`${u}|${o}`,R={sourceObject:u,targetObject:o,relationshipName:n.relationshipName??n.name,type:ne(o,n,t.get(u)?.childRelationships)?"master-detail":"lookup",required:a},i=e.get(m);if(!i){e.set(m,{edge:R,noneSettable:!c,insertOnly:d});continue}let h=R.type==="master-detail"&&i.edge.type==="lookup"?R:i.edge;i.edge={...h,required:i.edge.required===!0||a},i.noneSettable=i.noneSettable&&!c,i.insertOnly=i.insertOnly||d}}return[...e.values()].map(({edge:o,noneSettable:r,insertOnly:n})=>({...o,...r?{settable:!1}:{},...n?{insertOnly:!0}:{}}))}function Lt(t,e){let o=e.filter(qe),r=$e(t,o).reverse(),n=new Map;r.forEach((d,u)=>{for(let m of d)n.set(m,u)});let c=new Map;for(let d of o){let u=c.get(d.targetObject)??[];u.push(d.sourceObject),c.set(d.targetObject,u)}let a=r.map(()=>0);return r.forEach((d,u)=>{for(let m of d)for(let R of c.get(m)??[]){let i=n.get(R);i!==void 0&&i!==u&&(a[u]=Math.max(a[u],a[i]+1))}}),new Map(t.map(d=>[d,Math.min(Dt,1+a[n.get(d)??0])]))}async function ze(t,e,o){let r=ve(e);if(r!==void 0)throw new Error(r);let n=o?.signal;if(n?.aborted)return Y();try{return await kt(t,e,o)}catch(c){if(c instanceof A||n?.aborted)return Y();throw c}}async function kt(t,e,o){let r=o?.signal,n=s=>o?.onProgress?.(s),c=Date.now(),a=s=>l=>{if(l instanceof A)throw l;return k.warn(`[forge-discover] whole org: ${x(l)}`),s},{toolingObjects:d,recordCounts:u,createFacts:m}=t;n({phase:"listing",discoveredCount:0,queueRemaining:0});let[R,i,h,b,S]=await Promise.all([M(()=>t.describeGlobal(e.sourceOrgId,r),r),M(()=>t.describeGlobal(e.targetOrgId,r),r),d?M(()=>d(e.targetOrgId,r),r).catch(a([])):Promise.resolve([]),m?M(()=>m(e.targetOrgId),r).catch(a(void 0)):Promise.resolve(void 0),u?M(()=>u(e.sourceOrgId,r),r).catch(a(void 0)):Promise.resolve(void 0)]),y=Mt(S),C=e.excludedObjects??[],{candidates:I,leftOut:$}=He(R,i,h,{...b?{createFacts:b}:{},...C.length>0?{excluded:C}:{}}),N=[...$];Ye(N.length);let L=I.map(()=>{}),W=0;n({phase:"counting",discoveredCount:0,queueRemaining:I.length,total:I.length}),await Ve(I,async(s,l,p)=>{let f=y?.get(s),v=e.objectSoqlFilters?.[s];if(f!==void 0&&f>jt&&!v)L[l]={objectApiName:s,rows:f,approximate:!0};else try{let{soql:E,all:Q}=Pt(s,v),_=await M(()=>t.queryCount(e.sourceOrgId,E,r,Q?{all:!0}:void 0),r);if(p())return;_>0?L[l]={objectApiName:s,rows:_}:N.push({objectApiName:s,reason:"empty"})}catch(E){if(E instanceof A||re(E))throw E;if(p())return;se(E)?N.push({objectApiName:s,reason:"unreadable",detail:x(E)}):(k.warn(`[forge-discover] whole org: ${s} not counted, kept: ${x(E)}`),L[l]=f!==void 0&&f>0&&!v?{objectApiName:s,rows:f,approximate:!0}:{objectApiName:s,rows:0,unknown:!0})}W++,n({phase:"counting",objectApiName:s,discoveredCount:W,queueRemaining:I.length-W,total:I.length})});let D=L.filter(s=>s!==void 0);if(D.length>he)throw new Error(`The source org holds records in ${D.length} objects a clone of the whole org would take, more than the ${he} one run writes. Nothing was written. Leave ${D.length-he} of them out or more, or clone the org in parts instead: a run from a record or from a query for each part.`);let U=D.map(()=>{}),B=0;n({phase:"describing",discoveredCount:0,queueRemaining:D.length,total:D.length}),await Ve(D,async({objectApiName:s},l,p)=>{try{let f=await Nt(()=>M(()=>t.describeObject(e.sourceOrgId,s,r),r),s);if(p())return;U[l]=f}catch(f){if(f instanceof A||re(f))throw f;if(p())return;N.push({objectApiName:s,reason:"notDescribed",detail:x(f)})}B++,n({phase:"describing",objectApiName:s,discoveredCount:B,queueRemaining:D.length-B,total:D.length})}),await me();let w=new Map,z=new Map;D.forEach((s,l)=>{let p=U[l];p&&(w.set(s.objectApiName,p),z.set(s.objectApiName,s))});let G=_t(w);if(G.length>Xe)throw new Error(`The ${w.size} objects of the source org a clone of the whole org would take relate ${G.length} pairs of objects, more than the ${Xe} one run writes in order. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`);let g=[...w.keys()],j=Lt(g,G),P=g.map(s=>{let l=w.get(s),p=z.get(s),f=p.rows,v=t.detectPII(l.fields);return{objectApiName:s,...l.label?{label:l.label}:{},recordCount:f,...p.approximate?{recordCountApproximate:!0}:{},...p.unknown?{recordCountUnknown:!0}:{},fieldCount:l.fields.length,status:"idle",progress:0,included:!0,piiFields:v,anonymizeFields:e.anonymizePII?[...v]:[],level:j.get(s)??1,successCount:0,failureCount:0,errors:[],createableFieldCount:l.fields.filter(E=>E.type!=="id").length,estimatedSizeMB:f*V,estimatedApiCalls:Math.ceil(f/Tt),batchStrategy:"auto"}});Ye(N.length);let F=P.reduce((s,l)=>s+l.recordCount,0);return N.sort((s,l)=>s.objectApiName<l.objectApiName?-1:s.objectApiName>l.objectApiName?1:0),k.info(`[forge-discover] whole org: ${P.length} object(s), ${G.length} relation(s), ${N.length} left out, ${F} record(s), in ${Date.now()-c}ms`),{nodes:P,edges:G,totalRecords:F,estimatedSizeMB:F*V,estimatedDurationSeconds:F*ge,truncated:!1,leftOut:N}}export{fe as a,ot as b,zt as c,ne as d,st as e,it as f,at as g,lt as h,ut as i,Ue as j,yt as k,he as l,Xe as m,se as n,Ve as o,Mt as p,ze as q};
@@ -0,0 +1,11 @@
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{g as ae,i as V}from"./chunk-V4RKM4QZ.mjs";import{m as oe,o as ie}from"./chunk-ETT5GP4P.mjs";import{B as q,H as ee,I as te,J as ne,L as re,d as M,k as B,s as W,t as E,u as Z,v as z,w as Q,z as j}from"./chunk-E2YJVSX6.mjs";import{$a as J,ab as U,bb as D}from"./chunk-DPYTG6DM.mjs";import{b as N,e as K,m as F,v as L}from"./chunk-WZQEK4WT.mjs";import{createCipheriv as Se,createDecipheriv as Ce,createHash as m,hkdfSync as Te,randomBytes as C,timingSafeEqual as Pe}from"node:crypto";import{createReadStream as He}from"node:fs";import{lstat as se,open as _,rename as _e,rm as $e,statfs as Ne}from"node:fs/promises";import{basename as de,dirname as le,join as ue}from"node:path";import{Readable as pe}from"node:stream";import{pipeline as ye}from"node:stream/promises";import{createGunzip as Ke,createGzip as Fe}from"node:zlib";var bt=".sfcheckpoint",De=1024*1024,Me=new Set([1]),ze=new Set([1,2]),$=32,O=16,je=4096,Ve=1024,Xe=64*1024*1024,me=2**32,ge="sandforge-checkpoint/1 block key",we="sandforge-checkpoint/1 key check",X="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",Ye=Math.ceil($*8/5),g="Nothing was imported.";function Bt(){return C($)}function At(n){if(n.length!==$)throw new RangeError("Not a key of a checkpoint file");let e="",t=0,r=0;for(let o of n)for(t=(t<<8|o)&65535,r+=8;r>=5;)e+=X[t>>>r-5&31],r-=5;return r>0&&(e+=X[t<<5-r&31]),(e.match(/.{1,4}/g)??[]).join("-")}function Et(n){let e=n.replace(/[\s-]/g,"").toUpperCase();if(e.length!==Ye||!/^[A-Z2-7]+$/.test(e))return;let t=Buffer.alloc($),r=0,o=0,i=0;for(let a of e)r=(r<<5|X.indexOf(a))&65535,o+=5,o>=8&&(t[i++]=r>>>o-8&255,o-=8);if((r&(1<<o)-1)===0)return t}function T(n,e,t,r){return Buffer.from(Te("sha256",n,e,t,r))}function ke(n,e){let t=Buffer.alloc(12);return n.copy(t,0),t.writeUInt32BE(e,8),t}function be(n,e,t){let r=Buffer.alloc(37);return n.copy(r,0),r.writeUInt32BE(e,32),r[36]=t?1:0,r}function Ge(n,e,t,r){let o=Se("aes-256-gcm",n.blockKey,ke(n.prefix,e),{authTagLength:O});return o.setAAD(be(n.headerHash,e,t)),Buffer.concat([o.update(r),o.final(),o.getAuthTag()])}function Le(n,e,t,r){let o=Ce("aes-256-gcm",n.blockKey,ke(n.prefix,e),{authTagLength:O});o.setAAD(be(n.headerHash,e,t)),o.setAuthTag(r.subarray(r.length-O));try{let i=o.update(r.subarray(0,r.length-O));return Buffer.concat([i,o.final()])}catch{return}}var P=class extends Error{constructor(t){super(t.message);this.refusal=t;this.name="ImportRefused"}refusal};function f(n){return new P({code:"IMPORT_DAMAGED",message:`This checkpoint file ${n}: it was changed or damaged after it was exported. ${g}`})}var I=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointExportError"}code};function Je(n){return{...H(n,Be),org:H(n.org,Ae)}}var Be=["lastRewind","takenOn","expiresAt","bytes","importedFrom"],Ae=["alias"];function H(n,e){return Object.fromEntries(Object.entries(n).filter(([t])=>!e.includes(t)))}async function*Ee(n,e){if(e===0)return;let t=0;for await(let r of He(n,{start:0,end:e-1})){let o=r;t+=o.length,yield o}if(t!==e)throw new I("EXPORT_CHANGED",`${de(n)} of the checkpoint shrank while it was exported: export it again.`)}async function xe(n,e){let t=m("sha256");for await(let r of Ee(n,e))t.update(r);return t.digest("hex")}async function xt(n){let{folder:e,checkpoint:t,out:r,key:o}=n,i=n.chunkBytes??De;if(await se(r).catch(()=>{}))throw new I("EXPORT_EXISTS",`${r} is there already: name another file, or move that one away first.`);let a=Buffer.from(`${JSON.stringify(Je(t))}
8
+ `,"utf8"),s=[{path:E,bytes:a.length,sha256:m("sha256").update(a).digest("hex"),content:a}];for(let u of await z(e))u.path!==E&&s.push({...u,sha256:await xe(u.file,u.bytes)});let h=s.some(u=>u.path===W);h&&await V(e);let c=C(32),d=C(8),{dataStorageMaxMB:l,staging:p}=t.org,v={format:"sandforge-checkpoint",formatVersion:h?2:1,checkpointFormat:1,sandforgeVersion:n.sandforgeVersion,organizationId:B(t.org.organizationId),orgTier:t.org.tier,...l!==void 0?{dataStorageMaxMB:l}:{},...p===!0?{staging:p}:{},checkpointId:t.checkpointId,takenAt:t.takenAt,records:Ie(t),objects:t.objects.length,files:s.length,bytes:s.reduce((u,b)=>u+b.bytes,0),cipher:"aes-256-gcm",kdf:"hkdf-sha256",salt:c.toString("hex"),noncePrefix:d.toString("hex"),keyCheck:T(o,c,we,16).toString("hex"),chunkBytes:i},R=Buffer.from(`${JSON.stringify(D.parse(v))}
9
+ `),w={blockKey:T(o,c,ge,32),prefix:d,headerHash:m("sha256").update(R).digest()},S=ue(le(r),`.${de(r)}.${process.pid}-${C(4).toString("hex")}.tmp`),y=m("sha256"),k=0,A=await _(S,"wx",M);try{try{let u=async b=>{y.update(b),k+=b.length,await Oe(A,b)};await u(R),await ye(pe.from(Ue(s)),Fe({level:6}),async b=>{await We(b,i,w,u)}),await A.sync()}finally{await A.close()}if(await se(r).catch(()=>{}))throw new I("EXPORT_EXISTS",`${r} appeared while the checkpoint was exported: name another file.`);await _e(S,r)}catch(u){throw await $e(S,{force:!0}),u}return{header:v,bytes:k,sha256:y.digest("hex")}}async function Oe(n,e){for(let t=0;t<e.length;){let{bytesWritten:r}=await n.write(e,t,e.length-t);t+=r}}function Ie(n){return n.objects.reduce((e,t)=>e+t.records,0)}async function*Ue(n){for(let e of n){let{path:t,bytes:r,sha256:o}=e;if(yield Buffer.from(`${JSON.stringify({path:t,bytes:r,sha256:o})}
10
+ `,"utf8"),e.content!==void 0){yield e.content;continue}let i=m("sha256");for await(let a of Ee(e.file??"",r))i.update(a),yield a;if(i.digest("hex")!==o)throw new I("EXPORT_CHANGED",`${t} of the checkpoint changed while it was exported: export it again.`)}yield Buffer.from(`${JSON.stringify({end:!0,files:n.length})}
11
+ `,"utf8")}async function We(n,e,t,r){let o=0,i,a=[],s=0,h=async c=>{if(i!==void 0){if(o>=me)throw new RangeError("The checkpoint is too large for one file");await r(Ge(t,o,c,i)),o++,i=void 0}};for await(let c of n)for(a.push(c),s+=c.length;s>=e;){let d=Buffer.concat(a);await h(!1),i=d.subarray(0,e),a=[d.subarray(e)],s=d.length-e}s>0&&(await h(!1),i=Buffer.concat(a)),await h(!0)}async function Y(n,e,t){let r=Buffer.alloc(t),o=0;for(;o<t;){let{bytesRead:i}=await n.read(r,o,t-o,e+o);if(i===0)break;o+=i}return o===t?r:r.subarray(0,o)}function x(n){return{refusal:{code:"IMPORT_NOT_ARCHIVE",message:`This is not a checkpoint file SandForge exported: ${n}. ${g}`}}}async function ve(n){let e;try{e=await _(n,"r")}catch(t){let r=t.code;return x(r==="ENOENT"?"there is no such file":"it cannot be read")}try{let t=await e.stat();if(!t.isFile())return x("it is not a file");let r=await Y(e,0,Math.min(t.size,je)),o=r.indexOf(10);if(o<0)return x("it does not start with a checkpoint file\u2019s header");let i=r.subarray(0,o+1),a;try{a=JSON.parse(i.toString("utf8"))}catch{return x("it does not start with a checkpoint file\u2019s header")}let s=U.safeParse(a);if(!s.success)return x("it does not start with a checkpoint file\u2019s header");let{formatVersion:h,checkpointFormat:c,sandforgeVersion:d}=s.data;if(!ze.has(h)||!Me.has(c))return{refusal:{code:"IMPORT_VERSION",message:`This file was made by SandForge ${d}, with checkpoint format ${c} in file format ${h}, which this SandForge does not read: update SandForge, then import it. ${g}`}};let l=D.safeParse(a);return l.success?{read:{header:l.data,headerBytes:i.length,headerHash:m("sha256").update(i).digest(),size:t.size}}:x("its header does not read")}finally{await e.close()}}async function Ze(n){try{let e=await Ne(n);return Number(e.bavail)*Number(e.bsize)}catch{return}}async function Qe(n){try{return await qe(n)}catch(e){if(e instanceof P)return{imported:!1,refusal:e.refusal};if(e instanceof ee&&e.code==="damaged")return{imported:!1,refusal:{code:"IMPORT_DAMAGED",message:`${e.message} ${g}`}};throw e}}async function qe(n){let{store:e,file:t,key:r}=n,o=n.now??new Date,i=await ve(t);if("refusal"in i)return{imported:!1,refusal:i.refusal};if(!i.read.headerHash.equals(n.read.headerHash))throw f("changed since its header was read");let a=i.read,{header:s}=a,h=Buffer.from(s.salt,"hex");if(!Pe(T(r,h,we,16),Buffer.from(s.keyCheck,"hex")))return{imported:!1,refusal:{code:"IMPORT_KEY",message:`This key is not the one the file was exported with. ${g}`}};let c={blockKey:T(r,h,ge,32),prefix:Buffer.from(s.noncePrefix,"hex"),headerHash:a.headerHash},d=await e.read(s.checkpointId);if(d!==void 0)return he(d,t,a,c);let l=await(n.freeBytes??Ze)(e.root),p=s.bytes+oe(s.records,2)+s.objects*8;if(l!==void 0&&l<p)return{imported:!1,refusal:{code:"IMPORT_DISK",message:`The checkpoint takes about ${ce(p)} on this machine, and its disk has ${ce(l)} free: make room, then import it. ${g}`}};let v=await e.importInto(s.organizationId,s.checkpointId,async w=>{let S=await Re(t,a,c,w.dir),y=ot(S,a,{...n.alias!==void 0?{alias:n.alias}:{},keepDays:n.keepDays,takenOn:n.takenOn,now:o});await it(w,y,s),await j(w.indexDir);for(let k of y.objects){let A=await ie(w,y.snapshotId,k.objectApiName);if(A.rows!==k.records)throw f(`holds ${A.rows} records of ${k.objectApiName} where its checkpoint counts ${k.records}`)}return await ne(w,y.objects),y});if(v.outcome==="imported")return{imported:!0,outcome:"imported",checkpoint:v.checkpoint};let R=await e.read(s.checkpointId);if(R===void 0)throw f("could not be kept");return he(R,t,a,c)}function ce(n){return`${(n/(1024*1024)).toFixed(1)} MB`}async function he(n,e,t,r){let o=c=>({imported:!1,refusal:{code:"IMPORT_KEPT_OTHER",message:`A checkpoint ${t.header.checkpointId} is kept on this machine already, ${c}: delete it first to import this file. ${g}`}});if(n.folder.organizationId!==B(t.header.organizationId))return o("of another org");if(n.checkpoint===void 0)return o("damaged");let i=o("and differs from this one"),a=await Re(e,t,r),s=new Map(a.hashes.filter(([c])=>c!==E).map(([c,d])=>[c,d])),h=(await z(n.folder)).filter(c=>c.path!==E);if(h.length!==s.size)return i;for(let c of h)if(s.get(c.path)!==await xe(c.file,c.bytes))return i;return{imported:!0,outcome:"alreadyKept",checkpoint:n.checkpoint}}var et=F({path:N().min(1).max(300),bytes:K().int().nonnegative(),sha256:N().regex(/^[0-9a-f]{64}$/)}),tt=F({end:L(!0),files:K().int().positive()});async function Re(n,e,t,r){let o=await _(n,"r"),i=m("sha256");try{let a=new G(e.header,r);try{await ye(pe.from(nt(o,e,t,i)),Ke(),async h=>{for await(let c of h)await a.take(c)})}catch(h){throw String(h.code??"").startsWith("Z_")?f("does not inflate"):h}finally{await a.close()}return{...a.ended(),sha256:i.digest("hex")}}finally{await o.close()}}async function*nt(n,e,t,r){r.update(await Y(n,0,e.headerBytes));let o=e.header.chunkBytes+O,i=e.size-e.headerBytes;if(i<=0)throw f("holds nothing after its header");let a=Math.ceil(i/o),s=i-(a-1)*o;if(s<=O)throw f("ends inside a block");if(a>me)throw f("holds more blocks than a file can");for(let h=0;h<a;h++){let c=h===a-1,d=c?s:o,l=await Y(n,e.headerBytes+h*o,d);if(l.length<d)throw f("is cut short");r.update(l);let p=Le(t,h,c,l);if(p===void 0)throw f(`holds a block, the ${rt(h+1)} of ${a}, that does not decrypt`);yield p}}function rt(n){let e=n%100,t=e>=11&&e<=13?"th":["th","st","nd","rd"][n%10]??"th";return`${n}${t}`}var G=class{constructor(e,t){this.header=e;this.into=t}header;into;line=[];lineBytes=0;current;seen=new Set;hashes=[];portable;bytes=0;end=!1;async take(e){let t=0;for(;t<e.length;){if(this.end)throw f("holds bytes after its last entry");let r=this.current;if(r!==void 0){let s=e.subarray(t,t+Math.min(r.left,e.length-t));t+=s.length,r.left-=s.length,r.hash.update(s),r.handle!==void 0&&await Oe(r.handle,s),r.held?.push(Buffer.from(s)),r.left===0&&await this.endEntry();continue}let o=e.indexOf(10,t),i=o<0?e.length:o;if(this.lineBytes+=i-t,this.lineBytes>Ve)throw f("holds a line too long for an entry");if(this.line.push(e.subarray(t,i)),t=i,o<0)continue;t++;let a=Buffer.concat(this.line).toString("utf8");this.line=[],this.lineBytes=0,await this.startEntry(a)}}async startEntry(e){let t;try{t=JSON.parse(e)}catch{throw f("holds an entry that does not read")}let r=tt.safeParse(t);if(r.success){if(r.data.files!==this.hashes.length||r.data.files!==this.header.files)throw f("counts other files than it holds");this.end=!0;return}let o=et.safeParse(t);if(!o.success)throw f("holds an entry that does not read");let{path:i,bytes:a,sha256:s}=o.data;if(!Z(i))throw f(`names a file no checkpoint holds, ${JSON.stringify(i)}`);if(this.seen.has(i))throw f(`holds ${i} twice`);if(this.seen.add(i),this.bytes+=a,this.bytes>this.header.bytes||this.seen.size>this.header.files)throw f("holds more than its header says");let h=i===E;if(h&&a>Xe)throw f("holds a checkpoint.json larger than any checkpoint\u2019s");let c;if(!h&&this.into!==void 0){let d=Q(this.into,i);await j(le(d)),c=await _(d,"wx",M)}this.current={path:i,left:a,sha256:s,hash:m("sha256"),...c!==void 0?{handle:c}:{},...h?{held:[]}:{}},a===0&&await this.endEntry()}async endEntry(){let e=this.current;if(e!==void 0){if(this.current=void 0,e.handle!==void 0)try{await e.handle.sync()}finally{await e.handle.close()}if(e.hash.digest("hex")!==e.sha256)throw f(`holds ${e.path} with other bytes than its sha256 says`);e.held!==void 0&&(this.portable=Buffer.concat(e.held)),this.hashes.push([e.path,e.sha256])}}async close(){await this.current?.handle?.close().catch(()=>{})}ended(){if(!this.end||this.current!==void 0)throw f("is cut short");if(this.bytes!==this.header.bytes)throw f("holds other bytes than its header says");if(this.portable===void 0)throw f("holds no checkpoint.json");return{portable:this.portable,hashes:this.hashes}}};function ot(n,e,t){let r;try{r=JSON.parse(n.portable.toString("utf8"))}catch{throw f("holds a checkpoint.json that does not read")}if(!fe(r)||!fe(r.org))throw f("holds a checkpoint.json that does not read");let o=J.safeParse({...H(r,Be),org:{...H(r.org,Ae),...t.alias!==void 0?{alias:t.alias}:{}},takenOn:t.takenOn,expiresAt:q(t.now,t.keepDays),bytes:0,importedFrom:{at:t.now.toISOString(),sandforgeVersion:e.header.sandforgeVersion,sha256:n.sha256}});if(!o.success)throw f("holds a checkpoint.json that does not parse");let i=o.data,{header:a}=e;if(i.checkpointId!==a.checkpointId||B(i.org.organizationId)!==B(a.organizationId)||i.takenAt!==a.takenAt||i.status!=="ready"||Ie(i)!==a.records||i.objects.length!==a.objects)throw f("holds another checkpoint than its header says");return i}function fe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}async function it(n,e,t){let r=await V(n);if(r===void 0){if(t.formatVersion===2)throw f("says it carries a replay annex, and holds none");return}if(t.formatVersion!==2)throw f("carries a replay annex, which its file format does not");if(B(r.organizationId)!==B(e.org.organizationId))throw f("holds the replay annex of another org");let o=e.replayAnnex,i=ae(r);if(o!==void 0&&(o.recordTypes!==i.recordTypes||o.users!==i.users||o.queues!==i.queues||o.standardPricebook!==i.standardPricebook))throw f("holds another replay annex than its checkpoint counts")}var at=".received";function st(n){return ue(n,at)}async function Ot(n){let e=await ve(n.file);if("refusal"in e)return{imported:!1,refusal:e.refusal};let t=st(n.storeRoot),r=re({root:t,...n.locksDir!==void 0?{locksDir:n.locksDir}:{}});if("refusal"in r)throw new Error(`The checkpoints of files received cannot be kept in ${t}: ${te(r.refusal,t,"Another store")} ${g}`);let o=await Qe({store:r.store,file:n.file,read:e.read,key:n.key,keepDays:n.keepDays,takenOn:n.takenOn,...n.now!==void 0?{now:n.now}:{},...n.freeBytes!==void 0?{freeBytes:n.freeBytes}:{}});return o.imported?{...o,store:r.store}:o}export{bt as a,De as b,Bt as c,At as d,Et as e,I as f,Je as g,xt as h,ve as i,Qe as j,st as k,Ot as l};
@@ -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 W}from"./chunk-CA5NAXSU.mjs";import{b as I,e as z,l as F,u as U}from"./chunk-7EANH5PY.mjs";function p(n){return`${n.op}\0${n.objectApiName}`}var j=class{entries=new Map;keys=new Map;of(t){let e=this.entries.get(p(t));return!e||e.spent?200:e.size}wasRefused(t){return this.entries.has(p(t))}wasCut(t){let e=this.entries.get(p(t));return e!==void 0&&e.size<200}firstRefusal(t,e,r){if(this.entries.has(p(t)))return;let o=this.entry(t,e);o.limit=r?.limit,o.automation=r?.automation,o.event=r?.event}refusedAt(t,e,r){this.firstRefusal(t,e,r);let o=this.entry(t,e);return o.size=Math.min(o.size,Math.max(1,Math.ceil(e/2))),this.of(t)}probes(t){return this.entries.get(p(t))?.probes??0}probed(t){let e=this.entries.get(p(t));e&&e.probes++}keepWhole(t){let e=this.entries.get(p(t));e&&(e.wholeAlone=!0)}isKeptWhole(t){return this.entries.get(p(t))?.wholeAlone===!0}spend(t){let e=this.entries.get(p(t));e&&(e.spent=!0)}isSpent(t){return this.entries.get(p(t))?.spent===!0}countExtraCalls(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.extraCalls+=e)}countSmallCallRows(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.rows+=e)}countNoted(t,e,r=1){let o=this.entries.get(p(t));!o||r<=0||(e===T?o.alone+=r:e===L?o.notSplit+=r:o.keptWhole+=r)}report(t){let e=this.entries.get(p(t));if(e)return{objectApiName:t.objectApiName,op:t.op,from:e.from,to:e.size,rows:e.rows,extraCalls:e.extraCalls,...e.limit!==void 0?{limit:e.limit}:{},...e.automation!==void 0?{automation:e.automation}:{},...e.event!==void 0?{event:e.event}:{},alone:e.alone,notSplit:e.notSplit,keptWhole:e.keptWhole,wholeAlone:e.wholeAlone,spent:e.spent}}reports(t){let e=[];for(let r of this.keys.values()){if(t!==void 0&&r.op!==t)continue;let o=this.report(r);o&&e.push(o)}return e}entry(t,e){let r=p(t),o=this.entries.get(r);return o||(o={size:200,from:e,spent:!1,wholeAlone:!1,probes:0,rows:0,extraCalls:0,alone:0,notSplit:0,keptWhole:0},this.entries.set(r,o),this.keys.set(r,{objectApiName:t.objectApiName,op:t.op})),o}};function E(n){return Math.max(0,Math.floor(Number.isFinite(n)?n:0))}var J=class{grantedCalls;perObject;takenInAll=0;byObject=new Map;constructor(t=2e3,e=500){this.grantedCalls=E(t),this.perObject=E(e)}get granted(){return this.grantedCalls}limitTo(t){this.grantedCalls=Math.min(this.grantedCalls,E(t))}left(t){let e=this.byObject.get(t.objectApiName)??0;return Math.max(0,Math.min(this.grantedCalls-this.takenInAll,this.perObject-e))}take(t,e){let r=Math.max(0,Math.min(Math.floor(e),this.left(t)));return r>0&&(this.takenInAll+=r,this.byObject.set(t.objectApiName,(this.byObject.get(t.objectApiName)??0)+r)),r}get spent(){return this.takenInAll}taken(t){return this.byObject.get(t.objectApiName)??0}};function se(n=2e3){return{sizes:new j,allowance:new J(n)}}function D(n,t){let e=Math.floor((n-t)/2);return Number.isFinite(e)?Math.min(2e3,Math.max(0,e)):0}function oe(n){return n.remaining===void 0?{}:{splitAllowance:D(n.remaining,n.estimate)}}function N(n,t,e,r){if(r<=0||n.isSpent(e))return 0;let o=t.take(e,r);return n.countExtraCalls(e,o),o<r&&n.spend(e),o}var T="alone",L="notSplit",v="keptWhole",Q="Sent on its own, the record still made the target's automation hit a Salesforce limit: the automation does too much for this record alone \u2014 fix it, or have it honour the bypass Forge's automation mute sets.",V="Not sent in smaller calls: records of the same object sent on their own were refused for a Salesforce limit too, so a smaller call would not take it \u2014 fix the target's automation, or have it honour the bypass Forge's automation mute sets.";function B(n,t){return n>0?`the ${t} had spent the ${n} smaller calls it allows itself`:`what the org has left today allowed the ${t} none`}function q(n,t="run"){return`Not sent in smaller calls: ${B(n,t)}.`}function ie(n,t,e="run"){return n===T?Q:n===v?V:q(t,e)}function M(n){return`${n} ${n===1?"call":"calls"} more`}function X(n){return`${n} ${n===1?"record":"records"}`}function Y(n){return n.automation===void 0?"The target's automation":n.event===void 0?n.automation:`${n.automation} (${n.event})`}function ae(n){let t=`${Y(n)} hit ${n.limit??"a Salesforce limit"} on a call of ${n.from}`;return n.wholeAlone?`${t}, and ${X(n.alone)} sent on ${n.alone===1?"its":"their"} own were refused too: not sent in smaller calls, ${M(n.extraCalls)}.`:n.to<200&&n.rows>0?`${t}: sent ${n.to} at a time, ${M(n.extraCalls)}.`:n.extraCalls>0?`${t}: ${M(n.extraCalls)}.`:`${t}.`}function le(n,t,e="run"){return`${n} not sent in smaller calls: ${B(t,e)}.`}function ue(n,t){let e=n.perObject-n.taken(t),r=n.granted-n.spent;return e<r?n.perObject:n.granted}function ee(n,t,e=200){return n<=t?!1:Math.ceil(n/e)===Math.ceil((n-t)/e)}var te=new Set;async function ce(n,t){let{key:e,sizes:r,allowance:o}=t,c=Math.min(t.maxSize??200,200),h=[],m,f=0,S=()=>[...h.flatMap(s=>s.items),...m?.items??[],...n.slice(f)],K=()=>{let s=Math.min(c,r.of(e)),l=s<c,g=t.pricedAs==="job"||ee(n.length-f,s,c);l&&g&&(t.paid&&t.paid.calls>0?t.paid.calls--:N(r,o,e,1)===0&&(s=c,l=!1));let i=n.slice(f,f+s);return f+=i.length,{items:i,reduced:l}},A=async s=>{let l=m;if(m=void 0,!l||l.items.length===0)return;r.countNoted(e,s,l.items.length);let g=new Map(l.items.map((i,d)=>[d,s]));try{await t.settle(l.items,l.answers,te,g,!0)}catch(i){throw t.onThrow?.(S(),i),i}},k=async()=>{let s=m;if(!s)return;if(s.items.length===0){m=void 0;return}let l=r.refusedAt(e,s.from,s.cause),g=N(r,o,e,Math.ceil(s.items.length/l)),i=Math.min(s.items.length,g*l),d=[];for(let b=0;b<i;b+=l)d.push({items:s.items.slice(b,Math.min(i,b+l)),reduced:!0});h.unshift(...d),m={...s,items:s.items.slice(i),answers:s.answers.slice(i)},await A(L)},_=async()=>{let s=m;if(!s||s.items.length===0){m=void 0;return}if(N(r,o,e,1)===0){await A(L);return}r.probed(e),h.unshift({items:[s.items[0]],reduced:!0,probe:!0}),m={...s,items:s.items.slice(1),answers:s.answers.slice(1)}},P=!0,w=t.refusedIn;if(w&&n.length>0){if(f=n.length,P=!1,!r.wasRefused(e)){r.firstRefusal(e,w.from,w.cause);let s=r.report(e);s&&t.onFirstRefusal?.(s)}m={items:[...n],answers:[...w.answers],from:w.from,...w.cause?{cause:w.cause}:{}},r.isSpent(e)?await A(L):r.isKeptWhole(e)?await A(v):!r.wasCut(e)&&r.probes(e)<2?await _():await k()}for(;;){let s;if(P){if(n.length===0)return{};s=K()}else{if(s=h.shift()??(f<n.length?K():void 0),!s)return{};try{if(await t.beforeEachSend?.()==="stop")return{stopped:{part:s.items,rest:S(),sent:!1}}}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}}P=!1;let l;try{l=await t.send(s.items)}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}if(l==="stop")return{stopped:{part:s.items,rest:S(),sent:!0}};let{answers:g}=l,i=s.items,d=[],b;for(let u=0;u<i.length;u++){let a=t.limited(g[u],i[u]);a&&(d.push(u),b??=a)}let R=new Set,C=new Map,x;if(s.probe)d.length>0?(C.set(0,T),x=r.probes(e)<2&&(m?.items.length??0)>0?_:async()=>{r.probes(e)>=2&&r.keepWhole(e),await A(v)}):x=k;else if(d.length>0){if(!r.wasRefused(e)){r.firstRefusal(e,i.length,b);let a=r.report(e);a&&t.onFirstRefusal?.(a)}let u=!r.wasCut(e)&&!r.isKeptWhole(e)&&r.probes(e)<2;if(i.length===1)C.set(0,T),u&&!r.isSpent(e)&&(r.probed(e),r.probes(e)>=2&&r.keepWhole(e));else if(r.isSpent(e))for(let a of d)C.set(a,L);else if(r.isKeptWhole(e))for(let a of d)C.set(a,v);else if(u){for(let a of d)R.add(a);m={items:d.map(a=>i[a]),answers:d.map(a=>g[a]),from:i.length,...b?{cause:b}:{}},x=_}else{let a=r.refusedAt(e,i.length,b),Z=N(r,o,e,Math.ceil(d.length/a)),O=d.slice(0,Z*a);for(let y of O)R.add(y);for(let y of d.slice(O.length))C.set(y,L);let $=[];for(let y=0;y<O.length;y+=a)$.push({items:O.slice(y,y+a).map(H=>i[H]),reduced:!0});h.unshift(...$)}}for(let u of C.values())r.countNoted(e,u);s.reduced&&r.countSmallCallRows(e,i.length-R.size);try{await t.settle(i,g,R,C)}catch(u){throw t.onThrow?.(S(),u),u}await x?.()}}var ne=60*6e4,re=F({state:U(["Open","UploadComplete","InProgress","JobComplete","Failed","Aborted"]),numberRecordsProcessed:z().int().nonnegative().optional(),errorMessage:I().nullish(),systemModstamp:I().optional(),createdDate:I().optional()});function G(n,t){let e=re.safeParse(t);if(e.success)return e.data;let r=typeof t=="object"&&t!==null&&"state"in t?String(JSON.stringify(t.state)):"none";throw new Error(`The org's answer about Bulk API job ${n||"(no id)"} is not an ingest job's state (state: ${r})`)}async function fe(n,t,e={}){let r=e.now??(()=>Date.now());try{let o=n.bulk2.job("ingest",{id:t}),c=G(t,await o.check());if(c.state==="Open"){let h=Date.parse(c.createdDate??""),m=e.openGraceMs??ne,f=m-(r()-h);if(Number.isFinite(h)&&f>0)return{state:"running",info:c,openUntil:new Date(h+m).toISOString(),graceLeftMs:f};if(!await o.abort().then(()=>!1,()=>!0)&&m>0)return{state:"never-closed"};if(c=G(t,await o.check()),c.state==="Open"||c.state==="Aborted"&&c.numberRecordsProcessed===0)return{state:"never-closed"}}if(c.state==="UploadComplete"||c.state==="InProgress")return{state:"running",info:c};if(e.successfulOnly)return{state:"ended",info:c,results:{successfulResults:[...await o.getSuccessfulResults()]}};if(o.getAllResults===void 0)throw new Error(`Bulk API job ${t}: this connection reads no failed or unprocessed rows`);return{state:"ended",info:c,results:await o.getAllResults()}}catch(o){return{state:"unread",reason:W(o)}}}export{se as a,D as b,oe as c,Q as d,V as e,ie as f,ae as g,le as h,ue as i,ce as j,G as k,fe as l};
7
+ import{b as W}from"./chunk-CA5NAXSU.mjs";import{b as I,e as z,l as F,u as U}from"./chunk-WZQEK4WT.mjs";function p(n){return`${n.op}\0${n.objectApiName}`}var j=class{entries=new Map;keys=new Map;of(t){let e=this.entries.get(p(t));return!e||e.spent?200:e.size}wasRefused(t){return this.entries.has(p(t))}wasCut(t){let e=this.entries.get(p(t));return e!==void 0&&e.size<200}firstRefusal(t,e,r){if(this.entries.has(p(t)))return;let o=this.entry(t,e);o.limit=r?.limit,o.automation=r?.automation,o.event=r?.event}refusedAt(t,e,r){this.firstRefusal(t,e,r);let o=this.entry(t,e);return o.size=Math.min(o.size,Math.max(1,Math.ceil(e/2))),this.of(t)}probes(t){return this.entries.get(p(t))?.probes??0}probed(t){let e=this.entries.get(p(t));e&&e.probes++}keepWhole(t){let e=this.entries.get(p(t));e&&(e.wholeAlone=!0)}isKeptWhole(t){return this.entries.get(p(t))?.wholeAlone===!0}spend(t){let e=this.entries.get(p(t));e&&(e.spent=!0)}isSpent(t){return this.entries.get(p(t))?.spent===!0}countExtraCalls(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.extraCalls+=e)}countSmallCallRows(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.rows+=e)}countNoted(t,e,r=1){let o=this.entries.get(p(t));!o||r<=0||(e===T?o.alone+=r:e===L?o.notSplit+=r:o.keptWhole+=r)}report(t){let e=this.entries.get(p(t));if(e)return{objectApiName:t.objectApiName,op:t.op,from:e.from,to:e.size,rows:e.rows,extraCalls:e.extraCalls,...e.limit!==void 0?{limit:e.limit}:{},...e.automation!==void 0?{automation:e.automation}:{},...e.event!==void 0?{event:e.event}:{},alone:e.alone,notSplit:e.notSplit,keptWhole:e.keptWhole,wholeAlone:e.wholeAlone,spent:e.spent}}reports(t){let e=[];for(let r of this.keys.values()){if(t!==void 0&&r.op!==t)continue;let o=this.report(r);o&&e.push(o)}return e}entry(t,e){let r=p(t),o=this.entries.get(r);return o||(o={size:200,from:e,spent:!1,wholeAlone:!1,probes:0,rows:0,extraCalls:0,alone:0,notSplit:0,keptWhole:0},this.entries.set(r,o),this.keys.set(r,{objectApiName:t.objectApiName,op:t.op})),o}};function E(n){return Math.max(0,Math.floor(Number.isFinite(n)?n:0))}var J=class{grantedCalls;perObject;takenInAll=0;byObject=new Map;constructor(t=2e3,e=500){this.grantedCalls=E(t),this.perObject=E(e)}get granted(){return this.grantedCalls}limitTo(t){this.grantedCalls=Math.min(this.grantedCalls,E(t))}left(t){let e=this.byObject.get(t.objectApiName)??0;return Math.max(0,Math.min(this.grantedCalls-this.takenInAll,this.perObject-e))}take(t,e){let r=Math.max(0,Math.min(Math.floor(e),this.left(t)));return r>0&&(this.takenInAll+=r,this.byObject.set(t.objectApiName,(this.byObject.get(t.objectApiName)??0)+r)),r}get spent(){return this.takenInAll}taken(t){return this.byObject.get(t.objectApiName)??0}};function se(n=2e3){return{sizes:new j,allowance:new J(n)}}function D(n,t){let e=Math.floor((n-t)/2);return Number.isFinite(e)?Math.min(2e3,Math.max(0,e)):0}function oe(n){return n.remaining===void 0?{}:{splitAllowance:D(n.remaining,n.estimate)}}function N(n,t,e,r){if(r<=0||n.isSpent(e))return 0;let o=t.take(e,r);return n.countExtraCalls(e,o),o<r&&n.spend(e),o}var T="alone",L="notSplit",v="keptWhole",Q="Sent on its own, the record still made the target's automation hit a Salesforce limit: the automation does too much for this record alone \u2014 fix it, or have it honour the bypass Forge's automation mute sets.",V="Not sent in smaller calls: records of the same object sent on their own were refused for a Salesforce limit too, so a smaller call would not take it \u2014 fix the target's automation, or have it honour the bypass Forge's automation mute sets.";function B(n,t){return n>0?`the ${t} had spent the ${n} smaller calls it allows itself`:`what the org has left today allowed the ${t} none`}function q(n,t="run"){return`Not sent in smaller calls: ${B(n,t)}.`}function ie(n,t,e="run"){return n===T?Q:n===v?V:q(t,e)}function M(n){return`${n} ${n===1?"call":"calls"} more`}function X(n){return`${n} ${n===1?"record":"records"}`}function Y(n){return n.automation===void 0?"The target's automation":n.event===void 0?n.automation:`${n.automation} (${n.event})`}function ae(n){let t=`${Y(n)} hit ${n.limit??"a Salesforce limit"} on a call of ${n.from}`;return n.wholeAlone?`${t}, and ${X(n.alone)} sent on ${n.alone===1?"its":"their"} own were refused too: not sent in smaller calls, ${M(n.extraCalls)}.`:n.to<200&&n.rows>0?`${t}: sent ${n.to} at a time, ${M(n.extraCalls)}.`:n.extraCalls>0?`${t}: ${M(n.extraCalls)}.`:`${t}.`}function le(n,t,e="run"){return`${n} not sent in smaller calls: ${B(t,e)}.`}function ue(n,t){let e=n.perObject-n.taken(t),r=n.granted-n.spent;return e<r?n.perObject:n.granted}function ee(n,t,e=200){return n<=t?!1:Math.ceil(n/e)===Math.ceil((n-t)/e)}var te=new Set;async function ce(n,t){let{key:e,sizes:r,allowance:o}=t,c=Math.min(t.maxSize??200,200),h=[],m,f=0,S=()=>[...h.flatMap(s=>s.items),...m?.items??[],...n.slice(f)],K=()=>{let s=Math.min(c,r.of(e)),l=s<c,g=t.pricedAs==="job"||ee(n.length-f,s,c);l&&g&&(t.paid&&t.paid.calls>0?t.paid.calls--:N(r,o,e,1)===0&&(s=c,l=!1));let i=n.slice(f,f+s);return f+=i.length,{items:i,reduced:l}},A=async s=>{let l=m;if(m=void 0,!l||l.items.length===0)return;r.countNoted(e,s,l.items.length);let g=new Map(l.items.map((i,d)=>[d,s]));try{await t.settle(l.items,l.answers,te,g,!0)}catch(i){throw t.onThrow?.(S(),i),i}},k=async()=>{let s=m;if(!s)return;if(s.items.length===0){m=void 0;return}let l=r.refusedAt(e,s.from,s.cause),g=N(r,o,e,Math.ceil(s.items.length/l)),i=Math.min(s.items.length,g*l),d=[];for(let b=0;b<i;b+=l)d.push({items:s.items.slice(b,Math.min(i,b+l)),reduced:!0});h.unshift(...d),m={...s,items:s.items.slice(i),answers:s.answers.slice(i)},await A(L)},_=async()=>{let s=m;if(!s||s.items.length===0){m=void 0;return}if(N(r,o,e,1)===0){await A(L);return}r.probed(e),h.unshift({items:[s.items[0]],reduced:!0,probe:!0}),m={...s,items:s.items.slice(1),answers:s.answers.slice(1)}},P=!0,w=t.refusedIn;if(w&&n.length>0){if(f=n.length,P=!1,!r.wasRefused(e)){r.firstRefusal(e,w.from,w.cause);let s=r.report(e);s&&t.onFirstRefusal?.(s)}m={items:[...n],answers:[...w.answers],from:w.from,...w.cause?{cause:w.cause}:{}},r.isSpent(e)?await A(L):r.isKeptWhole(e)?await A(v):!r.wasCut(e)&&r.probes(e)<2?await _():await k()}for(;;){let s;if(P){if(n.length===0)return{};s=K()}else{if(s=h.shift()??(f<n.length?K():void 0),!s)return{};try{if(await t.beforeEachSend?.()==="stop")return{stopped:{part:s.items,rest:S(),sent:!1}}}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}}P=!1;let l;try{l=await t.send(s.items)}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}if(l==="stop")return{stopped:{part:s.items,rest:S(),sent:!0}};let{answers:g}=l,i=s.items,d=[],b;for(let u=0;u<i.length;u++){let a=t.limited(g[u],i[u]);a&&(d.push(u),b??=a)}let R=new Set,C=new Map,x;if(s.probe)d.length>0?(C.set(0,T),x=r.probes(e)<2&&(m?.items.length??0)>0?_:async()=>{r.probes(e)>=2&&r.keepWhole(e),await A(v)}):x=k;else if(d.length>0){if(!r.wasRefused(e)){r.firstRefusal(e,i.length,b);let a=r.report(e);a&&t.onFirstRefusal?.(a)}let u=!r.wasCut(e)&&!r.isKeptWhole(e)&&r.probes(e)<2;if(i.length===1)C.set(0,T),u&&!r.isSpent(e)&&(r.probed(e),r.probes(e)>=2&&r.keepWhole(e));else if(r.isSpent(e))for(let a of d)C.set(a,L);else if(r.isKeptWhole(e))for(let a of d)C.set(a,v);else if(u){for(let a of d)R.add(a);m={items:d.map(a=>i[a]),answers:d.map(a=>g[a]),from:i.length,...b?{cause:b}:{}},x=_}else{let a=r.refusedAt(e,i.length,b),Z=N(r,o,e,Math.ceil(d.length/a)),O=d.slice(0,Z*a);for(let y of O)R.add(y);for(let y of d.slice(O.length))C.set(y,L);let $=[];for(let y=0;y<O.length;y+=a)$.push({items:O.slice(y,y+a).map(H=>i[H]),reduced:!0});h.unshift(...$)}}for(let u of C.values())r.countNoted(e,u);s.reduced&&r.countSmallCallRows(e,i.length-R.size);try{await t.settle(i,g,R,C)}catch(u){throw t.onThrow?.(S(),u),u}await x?.()}}var ne=60*6e4,re=F({state:U(["Open","UploadComplete","InProgress","JobComplete","Failed","Aborted"]),numberRecordsProcessed:z().int().nonnegative().optional(),errorMessage:I().nullish(),systemModstamp:I().optional(),createdDate:I().optional()});function G(n,t){let e=re.safeParse(t);if(e.success)return e.data;let r=typeof t=="object"&&t!==null&&"state"in t?String(JSON.stringify(t.state)):"none";throw new Error(`The org's answer about Bulk API job ${n||"(no id)"} is not an ingest job's state (state: ${r})`)}async function fe(n,t,e={}){let r=e.now??(()=>Date.now());try{let o=n.bulk2.job("ingest",{id:t}),c=G(t,await o.check());if(c.state==="Open"){let h=Date.parse(c.createdDate??""),m=e.openGraceMs??ne,f=m-(r()-h);if(Number.isFinite(h)&&f>0)return{state:"running",info:c,openUntil:new Date(h+m).toISOString(),graceLeftMs:f};if(!await o.abort().then(()=>!1,()=>!0)&&m>0)return{state:"never-closed"};if(c=G(t,await o.check()),c.state==="Open"||c.state==="Aborted"&&c.numberRecordsProcessed===0)return{state:"never-closed"}}if(c.state==="UploadComplete"||c.state==="InProgress")return{state:"running",info:c};if(e.successfulOnly)return{state:"ended",info:c,results:{successfulResults:[...await o.getSuccessfulResults()]}};if(o.getAllResults===void 0)throw new Error(`Bulk API job ${t}: this connection reads no failed or unprocessed rows`);return{state:"ended",info:c,results:await o.getAllResults()}}catch(o){return{state:"unread",reason:W(o)}}}export{se as a,D as b,oe as c,Q as d,V as e,ie as f,ae as g,le as h,ue as i,ce as j,G as k,fe as l};
@@ -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 O,f as dt,h as C}from"./chunk-TZE3Y7IQ.mjs";import{pc as at}from"./chunk-DPYTG6DM.mjs";var It="AccountContactRelation",D="EmailMessage",z="Task",tt="TaskRelation",B="EventRelation",j=200,en={ProductSellingModel:["SellingModelType","PricingTerm","PricingTermUnit"]},rn={objectApiName:"FeedItem",field:"Type",value:"CreateRecordEvent",parent:"ParentId"},X={FeedItem:[{field:"Type",value:"TrackedChange",noun:"tracked change"}],[tt]:[{field:"IsWhat",value:!0,noun:"what relation",from:"the task's WhatId"}],[B]:[{field:"IsWhat",value:!0,noun:"what relation",from:"the event's WhatId"}],EmailMessageRelation:[{noun:"email relation",from:"the email's addresses"}]};function Et(t,n){return X[t]?.find(e=>e.field===void 0||e.value!==void 0&&String(n[e.field])===String(e.value))}var ut=class{constructor(n=Et){this.rowsOf=n}rowsOf;reasons=new Map;byObject=new Map;leaveOut(n,e,r,o=[]){let i=this.reasons.get(e);if(i)return i;let s=this.reasonFor(n,r,o);if(!s)return;this.reasons.set(e,s);let d=this.byObject.get(n)??new Map,u=`${s.rows.field}=${s.rows.value}|${s.through??""}`,l=d.get(u)??{why:s,ids:new Set};return l.ids.add(e),d.set(u,l),this.byObject.set(n,d),s}keep(n,e,r=[]){return e.filter(o=>!this.leaveOut(n,String(o.Id),o,r))}has(n){return this.reasons.has(n)}counts(n){return(n===void 0?[...this.byObject]:[[n,this.byObject.get(n)]]).flatMap(([r,o])=>[...o?.values()??[]].map(({why:i,ids:s})=>({objectApiName:r,why:i,count:s.size})))}reasonFor(n,e,r){let o=this.rowsOf(n,e);if(o)return{rows:o};for(let i of r){let s=e[i],d=typeof s=="string"?this.reasons.get(s):void 0;if(d)return{rows:d.rows,through:i}}}};function on(t,n){if(n.through)return`${t} left out: ${n.through} names a ${n.rows.noun}, which the platform writes itself`;let e=n.rows.from?`, from ${n.rows.from}`:"";return`${t} ${n.rows.noun}${t===1?"":"s"} left out: the platform writes them itself${e}`}function sn(t,n){let e=`${t} record${t===1?"":"s"}`;return n.through?`${n.through} \u2192 ${n.rows.noun} (${e})`:n.rows.field===void 0?`every ${n.rows.noun} (${e})`:`${n.rows.field}=${String(n.rows.value)} (${e})`}function an(t){return t.through?`Not written: ${t.through} may not be left empty, and the ${t.rows.noun} it names is one the platform writes itself, which no copy sends.`:t.rows.from?`Not written: the platform writes each ${t.rows.noun} itself, from ${t.rows.from}.`:`Not written: the platform writes each ${t.rows.noun} itself, and refuses one a copy sends.`}function ct({field:t,value:n},e){if(t===void 0)return e==="="?"Id != null":"Id = null";let r=typeof n=="boolean"?String(n):`'${O(n??"")}'`;return`${C(t)} ${e} ${r}`}function dn(t,n,e){let r=s=>s.map(d=>ct(d,"=")).join(" OR "),o=(X[t]??[]).map(s=>ct(s,"!=")),i=n.flatMap(s=>s.referenceTo.flatMap(d=>{let u=X[d];if(d===t||!e.has(d)||!u||u.length===0)return[];let l=e.get(d),I=l?`(${dt(l)}) AND (${r(u)})`:`(${r(u)})`;return[`${C(s.name)} NOT IN (SELECT Id FROM ${C(d)} WHERE ${I})`]}));return[...o,...i]}var $t={[tt]:new Set(["Contact","Lead"]),[B]:new Set(["Contact","Lead","User","Calendar"])};function un(t,n,e){let r=$t[t];if(!r)return n;let o=n.IsWhat;return o!==""&&o!==null&&o!==void 0||e===void 0||r.has(e)?n:{...n,IsWhat:!0}}var Ct="500";function Pt(t){return t.startsWith(Ct)?"Case":void 0}function ht(t,n=Pt){let e=t.ParentId;if(typeof e=="string"&&e!=="")return!0;let r=t.RelatedToId;return typeof r=="string"&&r!==""&&n(r)==="Case"}function cn(t,n){return t===D&&!ht(n)?["ActivityId"]:[]}function fn(t){return!t.has(D)||!t.has(z)?[]:[{sourceObject:D,targetObject:z,relationshipName:`${D}Before${z}`,type:"lookup",required:!0}]}function ln(t,n){let e=t.ActivityId;return typeof e=="string"&&e!==""&&ht(t,n)}var S=200;async function gn(t,n){let e=new Map;for(let r=0;r<n.length;r+=S){let o=n.slice(r,r+S).map(s=>`'${O(s)}'`).join(", "),i=await t(`SELECT Id, ActivityId FROM ${D} WHERE Id IN (${o})`);for(let s of i){let d=s.ActivityId;typeof s.Id=="string"&&typeof d=="string"&&d!==""&&e.set(s.Id,d)}}return e}var L="Account",H="Contact",Q="PersonContactId",mt="IsPersonAccount";function kt(t){let n=t[mt];return n===!0||n==="true"||n===1}function pn(t,n){return kt(t)?n?"personAsBusiness":"person":"business"}function yn(t,n){return t==="person"?n==="person":n!=="person"}function Rn(t,n){return!t.has(L)||!t.has(H)?[]:n.get(L)?.some(r=>r.name===Q)===!0||n.get(H)?.some(r=>r.name===mt)===!0?[{sourceObject:L,targetObject:H,relationshipName:`${L}Before${H}`,type:"lookup",required:!0}]:[]}function Mt(t){let n=t.map(e=>`'${O(e)}'`).join(", ");return`SELECT Id, ${Q} FROM ${L} WHERE Id IN (${n})`}var At=new RegExp(`^SELECT Id, ${Q} FROM ${L} WHERE Id IN \\((.*)\\)$`);function wn(t){let n=At.exec(t);if(n)return[...n[1].matchAll(/'([^']*)'/g)].map(([,e])=>e)}async function In(t,n){let e=new Map;for(let r=0;r<n.length;r+=S){let o=await t(Mt(n.slice(r,r+S)));for(let i of o){let s=i[Q];typeof i.Id=="string"&&typeof s=="string"&&s!==""&&e.set(i.Id,s)}}return e}var v="OpportunityTeamMember",M="OpportunitySplit",Nt="Opportunity",Z="OpportunitySplitType",$="SplitTypeId",nt={[v]:"UserId",[M]:"SplitOwnerId"};function hn(t){return nt[t]!==void 0}function mn(t){return t==="Task"?"their email":t==="Contact"?"their person account":t===It?"their contact":t===Ot?"their opportunity, for its contact":"their opportunity, for its owner"}var Ot="OpportunityContactRole",Y="ContactId",ft=t=>t.IsPrimary===!0||t.IsPrimary==="true";function Lt(t,n){let e=new Map;return t.forEach((r,o)=>{let i=w(r,"OpportunityId"),s=w(r,Y);if(i===void 0||s===void 0)return;let d=n(i);if(d===void 0||y(d)!==y(s))return;let u=y(i),l=e.get(u);(l===void 0||!ft(t[l])&&ft(r))&&e.set(u,o)}),[...e.values()].sort((r,o)=>r-o)}var lt=["CreatedDate","CreatedById","Opportunity.CreatedDate","Opportunity.CreatedById"];function xt(t,n=[]){let e=["Id","OpportunityId",Y],r=[...e,...lt];return`SELECT ${[...e,...lt,...n.filter(i=>!r.includes(i)).map(C)].join(", ")} FROM ${Ot} WHERE OpportunityId IN ${et(t)} ORDER BY CreatedDate, Id`}var bt=/^SELECT Id, OpportunityId, ContactId, CreatedDate, CreatedById, Opportunity\.CreatedDate, Opportunity\.CreatedById((?:, \w+)*) FROM OpportunityContactRole WHERE OpportunityId IN (\(.*\)) ORDER BY CreatedDate, Id$/;function On(t){let n=bt.exec(t);if(!n)return;let[,e,r]=n;return{fields:e.split(", ").filter(o=>o!==""),opportunities:rt(r)}}async function _t(t,n,e=[]){let r=[];for(let o=0;o<n.length;o+=S)r.push(...await t(xt(n.slice(o,o+S),e)));return r}var Ft=1,gt=t=>typeof t=="string"&&t!==""?Math.floor(Date.parse(t)/1e3):Number.NaN;function Wt(t){let n=t.Opportunity;if(typeof n!="object"||n===null)return!1;let e=n,r=w(t,"CreatedById"),o=w(e,"CreatedById"),i=gt(t.CreatedDate),s=gt(e.CreatedDate);return r!==void 0&&o!==void 0&&y(r)===y(o)&&!Number.isNaN(i)&&!Number.isNaN(s)&&i-s>=0&&i-s<=Ft}function Dt(t,n){let e=new Map;for(let i of n){let s=w(i,"Id"),d=w(i,"OpportunityId"),u=w(i,Y);if(!s||!d||!u||!Wt(i))continue;let l=`${y(d)}:${y(u)}`;e.set(l,[...e.get(l)??[],i])}let r=new Map,o=[];for(let[i,{opportunity:s,contact:d}]of t){let u=e.get(`${y(s)}:${y(d)}`)??[];u.length>1?o.push(i):u.length===1&&r.set(i,u[0])}return{found:r,alike:o}}function Tn(t,n="read"){return`${t} contact role(s) not linked to the one the platform wrote with their opportunity, so written as ${n}: the target holds more than one role of their contact under it made with it, within a second, by the same user, and nothing tells which the platform wrote. The opportunity holds the role of its contact more than once.`}var vt="the user the run writes as";function Sn(t,n){let e={CreatedDate:n,CreatedById:vt};return{...t,...e,Opportunity:{...e}}}async function En(t,n,e,r=[]){let o=Lt(n,e);if(o.length===0)return{found:new Map,alike:[]};let i=new Map(o.map(d=>[d,{opportunity:String(n[d].OpportunityId),contact:String(n[d][Y])}])),s=await _t(t,[...new Set([...i.values()].map(({opportunity:d})=>d))],r);return Dt(i,s)}function $n(t){return!t.has(v)||!t.has(M)?[]:[{sourceObject:v,targetObject:M,relationshipName:`${v}Before${M}`,type:"lookup",required:!0}]}var Ut={[v]:{TeamMemberRole:"Opportunity Owner",OpportunityAccessLevel:"All"},[M]:{}},pt=t=>!/__c$/i.test(t),qt=new Set(["SplitPercentage","SplitAmount","CurrencyIsoCode"]),U=`SELECT Id, OwnerId FROM ${Nt} WHERE Id IN `,Kt=`SELECT Id, DeveloperName, IsTotalValidated FROM ${Z} WHERE IsActive = true`,et=t=>`(${t.map(n=>`'${O(n)}'`).join(", ")})`,rt=t=>[...t.matchAll(/'([^']*)'/g)].map(([,n])=>n);function Cn(t){return`${U}${et(t)}`}function Pn(t){if(!t.startsWith(U))return;let n=t.slice(U.length);return/^\(.*\)$/.test(n)?rt(n):void 0}function Tt(t,n){let e=nt[t];return`SELECT ${["Id","OpportunityId",...t===M?[e,$]:[e],...n].join(", ")} FROM ${t} WHERE OpportunityId IN `}function kn(t,n,e){return`${Tt(t,n)}${et(e)}`}var Ht=/^SELECT Id, OpportunityId, (?:UserId|SplitOwnerId, SplitTypeId)((?:, \w+)*) FROM (OpportunityTeamMember|OpportunitySplit) WHERE OpportunityId IN (\(.*\))$/;function Mn(t){let n=Ht.exec(t);if(!n)return;let[,e,r,o]=n;return{objectApiName:r,fields:e.split(", ").filter(i=>i!==""),opportunities:rt(o)}}var y=t=>t.slice(0,15);async function W(t,n,e){let r=[];for(let o=0;o<e.length;o+=S){let i=e.slice(o,o+S).map(s=>`'${O(s)}'`).join(", ");r.push(...await t(`${n}(${i})`))}return r}function J(t,n){let e=new Map;for(let r of t){let o=r[n];typeof r.Id=="string"&&typeof o=="string"&&o!==""&&e.set(y(r.Id),o)}return e}var w=(t,n)=>{let e=t[n];return typeof e=="string"&&e!==""?e:void 0};async function An(t,n,e){let r={lookups:new Map,linked:new Map,held:new Map,defaulted:new Set},o=nt[t];if(o===void 0)return r;let i=t===M,s=n.filter(a=>{let f=w(a,"OpportunityId");return f!==void 0&&e.targetIdOf(f)!==void 0});if(s.length===0)return r;let d=[...new Set(s.map(a=>String(a.OpportunityId)))],u=J(await W(e.source,U,d),"OwnerId"),l=a=>e.targetIdOf(String(a.OpportunityId)),I=[...new Set(s.map(l))],{simulated:T}=e,x=T?void 0:J(await W(e.target,U,I),"OwnerId"),b=a=>{let f=u.get(y(String(a.OpportunityId)));return f===void 0?{}:{source:f,target:T?T.ownerOf(f):x?.get(y(l(a)))}},_=a=>{let f=w(a,o),R=b(a).source;return f!==void 0&&R!==void 0&&y(f)===y(R)},A=[...new Set(s.flatMap(a=>{let f=w(a,o);return f===void 0||_(a)||e.mappedUser(f)!==void 0?[]:[f]}))],q=A.length>0?new Set((await W(e.target,"SELECT Id FROM User WHERE IsActive = true AND Id IN ",A)).flatMap(a=>typeof a.Id=="string"?[y(a.Id)]:[])):new Set,K=i?J(await W(e.source,`SELECT Id, DeveloperName FROM ${Z} WHERE Id IN `,[...new Set(s.flatMap(a=>w(a,$)??[]))]),"DeveloperName"):new Map,F=new Map;if(i)for(let a of await e.target(Kt))typeof a.Id=="string"&&typeof a.DeveloperName=="string"&&F.set(a.DeveloperName,{id:a.Id,total:a.IsTotalValidated===!0||a.IsTotalValidated==="true"});let c=(e.written??[]).filter(a=>a!=="Id"&&a!=="OpportunityId"&&a!==o&&a!==$&&!qt.has(a)),g=(a,f)=>{let R=a[f];return!(R==null||R===""||R===!1)},p=(a,f,R=c)=>R.filter(P=>g(a,P)&&String(a[P])!==String(f[P]??"")),m=new Map,h=(a,f,R)=>[a,f,R??""].map(y).join("|");if(!T)for(let a of await W(e.target,Tt(t,c),I)){let f=w(a,"OpportunityId"),R=w(a,o);typeof a.Id!="string"||f===void 0||R===void 0||m.set(h(f,R,i?w(a,$):void 0),a)}for(let a of s){let f=w(a,o);if(f===void 0)continue;let R=_(a),P=b(a).target,N=R?P:e.mappedUser(f)??(q.has(y(f))?f:void 0),ot=!R&&N===void 0&&e.defaultUser!==void 0;if(ot&&(N=e.defaultUser),N===void 0){r.held.set(a,{field:o,parentObject:"User",why:R?`${o} names the owner of its opportunity, whose owner in the target could not be read.`:`${o} names a user the target has no counterpart of: a team member and a split go in for the opportunity's owner, which is the owner of its copy in the target, for a user an owner mapping gives, or for a user of the same id the target holds active.`});continue}let G={[o]:N},it=!1;if(i){let E=w(a,$);if(E!==void 0){let k=K.get(y(E)),V=k===void 0?void 0:F.get(k);if(V===void 0){r.held.set(a,{field:$,parentObject:Z,why:`${$} names ${k===void 0?"a split type":`the split type ${k}`}, which the target holds no active one of by that name: sent without it, the split would go in as one of the Revenue type.`});continue}G[$]=V.id,it=V.total}}let St=l(a),st=P!==void 0&&y(N)===y(P);if(T){if(st&&(!i||it)){let E=c.filter(k=>!pt(k)&&g(a,k));r.linked.set(a,{id:T.idFor(),owners:!0,notKept:p(a,Ut[t]??{},c.filter(pt)),...E.length>0?{unread:E}:{}});continue}}else{let E=m.get(h(St,N,G[$]));if(E!==void 0){r.linked.set(a,{id:String(E.Id),owners:st,notKept:p(a,E)});continue}}r.lookups.set(a,G),ot&&r.defaulted.add(a)}return r}var jt={[tt]:"TaskId",[B]:"EventId"};async function Nn(t,n,e){let r=new Map,o=jt[n];if(o===void 0)return r;let i=[...new Set(e.map(d=>d[o]).filter(d=>typeof d=="string"&&d!==""))];if(i.length===0)return r;let s=new Map;for(let d=0;d<i.length;d+=S){let u=i.slice(d,d+S).map(I=>`'${O(I)}'`).join(", "),l=await t(`SELECT Id, ${o}, RelationId FROM ${n} WHERE ${o} IN (${u})`);for(let I of l)typeof I.Id=="string"&&s.set(`${String(I[o])}|${String(I.RelationId)}`,I.Id)}return e.forEach((d,u)=>{let l=s.get(`${String(d[o])}|${String(d.RelationId)}`);l&&r.set(u,l)}),r}var Bt={[B]:["IsInvitee"]},yt={IsInvitee:["Status","Response","RespondedDate"]},Rt="the run was cancelled before it was updated";async function Ln(t,n,e,r,o=()=>!1){return Qt(await Yt(t,n,e,r,o))}function Qt(t){if(!(t===void 0||t.size===0))return[...t].map(([n,e])=>`${e} linked without ${n}`).join(", ")}function xn(t,n){if(n.size===0)return t;let e=new Map(t??[]);for(let[r,o]of n)e.set(r,(e.get(r)??0)+o);return e}async function Yt(t,n,e,r,o=()=>!1){let i=Bt[t]??[],s=new Set(i.flatMap(c=>[c,...yt[c]??[]]).filter(c=>!e(c))),d=new Map,u=(c,g)=>{let p=`${c}: ${g}`;d.set(p,(d.get(p)??0)+1)},l=[];for(let[c,g]of n){let p={},m={};for(let h of i.filter(a=>String(c[a])==="true")){if(s.has(h)){u(h,"the target does not let it be updated");continue}p[h]=!0;for(let a of yt[h]??[]){let f=c[a];f==null||f===""||(s.has(a)?u(a,"the target does not let it be updated"):m[a]=f)}}Object.keys(p).length>0&&l.push({Id:g,flagsGiven:p,answer:m})}let I=!1,T=async c=>{let g=new Map;if(c.length===0)return g;if(o()){for(let h of c)g.set(h.Id,Rt);return g}if(I)return g;let p=await r(c);I=p.length<c.length;let m=o();return c.forEach((h,a)=>{let f=p[a];f?.success||g.set(h.Id,f===void 0&&m?Rt:`the target refused the update, ${f?.errors[0]??"without saying why"}`)}),g},x=(c,g)=>{for(let p of c){let m=g.get(p.Id);if(m!==void 0)for(let h of Object.keys(p).filter(a=>a!=="Id"))u(h,m)}},b=l.map(({Id:c,flagsGiven:g,answer:p})=>({Id:c,...g,...p})),_=await T(b),A=I||o()?[]:l.filter(({Id:c,answer:g})=>_.has(c)&&Object.keys(g).length>0);x(b.filter(c=>!A.some(({Id:g})=>g===c.Id)),_);let q=A.map(({Id:c,flagsGiven:g})=>({Id:c,...g})),K=await T(q);x(q,K);let F=A.filter(({Id:c})=>!K.has(c));for(let c of new Set(F.flatMap(({answer:g})=>Object.keys(g)))){let g=F.filter(({answer:p})=>c in p).map(({Id:p,answer:m})=>({Id:p,[c]:m[c]}));x(g,await T(g))}return d}var bn={Order:"OrderStatus",Contract:"ContractStatus"},_n=new Set(["Contract"]);function Gt(t){return t==null||t===""?"null":typeof t=="number"||typeof t=="boolean"?String(t):`'${O(String(t))}'`}async function Fn(t,n){let e=new Map,r=[...new Set(n.map(i=>i.ContactId).filter(i=>typeof i=="string"&&i!==""))];if(r.length===0)return e;let o=new Map;for(let i=0;i<r.length;i+=j){let s=r.slice(i,i+j).map(u=>`'${O(u)}'`).join(", "),d=await t(`SELECT Id, AccountId, ContactId FROM ${It} WHERE IsDirect = true AND ContactId IN (${s})`);for(let u of d)typeof u.Id=="string"&&o.set(`${String(u.AccountId)}|${String(u.ContactId)}`,u.Id)}return n.forEach((i,s)=>{let d=o.get(`${String(i.AccountId)}|${String(i.ContactId)}`);d&&e.set(s,d)}),e}async function Wn(t,n){let e=new Set;for(let r=0;r<n.length;r+=j){let o=n.slice(r,r+j).map(s=>`'${O(s)}'`).join(", "),i=await t(`SELECT Id FROM PricebookEntry WHERE Id IN (${o}) AND Pricebook2.IsStandard = true`);for(let s of i)typeof s.Id=="string"&&e.add(s.Id)}return e}var wt=200;async function Dn(t,n){let e=new Map,r=[...new Set(n.map(i=>i.Product2Id).filter(i=>typeof i=="string"&&i!==""))];if(r.length===0)return e;let o=new Map;for(let i=0;i<r.length;i+=wt){let s=r.slice(i,i+wt).map(u=>`'${O(u)}'`).join(", "),d=await t(`SELECT Id, Product2Id, ProductSellingModelId FROM ${at} WHERE Product2Id IN (${s})`);for(let u of d)typeof u.Id=="string"&&o.set(`${String(u.Product2Id)}|${String(u.ProductSellingModelId)}`,u.Id)}return n.forEach((i,s)=>{let d=o.get(`${String(i.Product2Id)}|${String(i.ProductSellingModelId)}`);d&&e.set(s,d)}),e}async function vn(t,n,e,r){let o=new Map;for(let i of r){let s=JSON.stringify(e.map(l=>i[l]??null));if(o.has(s))continue;let d=e.map(l=>`${C(l)} = ${Gt(i[l])}`).join(" AND "),u=await t(`SELECT Id FROM ${C(n)} WHERE ${d} LIMIT 2`);o.set(s,u.length===1&&typeof u[0].Id=="string"?u[0].Id:void 0)}return r.map(i=>o.get(JSON.stringify(e.map(s=>i[s]??null))))}async function Un(t,n){let e;try{e=await t(`SELECT ApiName, StatusCode FROM ${C(n)}`)}catch{return}return{categoryOf:new Map(e.map(r=>[String(r.ApiName),String(r.StatusCode)])),draft:e.filter(r=>r.StatusCode==="Draft").map(r=>String(r.ApiName)).sort()[0]}}function qn(t,n){if(typeof t!="string"||t===""||!n.draft)return;let e=n.categoryOf.get(t);if(!(e===void 0||e==="Draft"))return n.draft}export{It as a,D as b,z as c,en as d,rn as e,ut as f,on as g,sn as h,an as i,dn as j,un as k,ht as l,cn as m,fn as n,ln as o,gn as p,L as q,H as r,Q as s,kt as t,pn as u,yn as v,Rn as w,Mt as x,wn as y,In as z,v as A,M as B,nt as C,hn as D,mn as E,Ot as F,Y as G,ft as H,Lt as I,xt as J,On as K,_t as L,Dt as M,Tn as N,Sn as O,En as P,$n as Q,Ut as R,Kt as S,Cn as T,Pn as U,kn as V,Mn as W,An as X,jt as Y,Nn as Z,Bt as _,Ln as $,Qt as aa,xn as ba,Yt as ca,bn as da,_n as ea,Fn as fa,Wn as ga,Dn as ha,vn as ia,Un as ja,qn as ka};
@@ -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{Ib as o,Lc as d}from"./chunk-DPYTG6DM.mjs";var u=new Set(["picklist","multipicklist"]);function c(a){return(a.picklistValues??[]).filter(s=>s.active!==!1&&typeof s.value=="string"&&s.value!=="").map(s=>s.value)}function m(a){let s=new Map,r=i=>{let t=s.get(i);return t||(t=a(i),s.set(i,t)),t};return{async createable(i){let{fields:t}=await r(i);return new Set(t.filter(e=>e.createable===!0).map(e=>e.name))},async visible(i){let{fields:t}=await r(i);return new Set(t.map(e=>e.name))},async computed(i){let{fields:t}=await r(i);return new Set(t.filter(e=>e.calculated===!0||e.autoNumber===!0).map(e=>e.name))},async picklistValues(i){let{fields:t}=await r(i),e=new Map;for(let n of t){if(!u.has(n.type??""))continue;let l=c(n);l.length>0&&e.set(n.name,l)}return e},async keyPrefix(i){let{keyPrefix:t}=await r(i);return typeof t=="string"&&t.length===3?t:void 0},async lengths(i){let{fields:t}=await r(i);return new Map(t.flatMap(e=>typeof e.length=="number"&&e.length>0?[[e.name,e.length]]:[]))},async unset(i){let{fields:t}=await r(i),e=n=>n.type==="reference"||(n.referenceTo??[]).length>0;return{empty:new Set(t.filter(n=>e(n)&&n.nillable===!0&&n.defaultedOnCreate!==!0).map(n=>n.name)),filled:new Set(t.filter(n=>n.nillable===!1||n.defaultedOnCreate===!0).map(n=>n.name))}},async required(i){let{fields:t}=await r(i);return t.filter(e=>e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0&&(e.referenceTo??[]).length===0).map(e=>({fieldApiName:e.name,type:e.type??"string",picklistValues:c(e),referenceTo:[],length:e.length??0,integerDigits:o({...e,type:e.type??"string"}),objectApiName:i,required:!0}))}}}function p(a,s){return async r=>(await a.required(r)).filter(i=>!d(r,i.fieldApiName,s.includes(r)?"person":"business"))}export{m as a,p as b};
@@ -0,0 +1,11 @@
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{b as l,e as u,i as U,k as w,l as f,r as W,s as F,u as Z,v as L}from"./chunk-WZQEK4WT.mjs";import*as B from"node:fs";import*as v from"node:path";function ee(n){let e=v.resolve(n);for(;;){if(B.existsSync(v.join(e,".git"))||B.existsSync(v.join(e,"pnpm-workspace.yaml")))return e;let t=v.dirname(e);if(t===e)throw new Error(`No repository root found above ${n}`);e=t}}function G(n){let e=v.resolve(n);return process.platform==="win32"?e.toLowerCase():e}function k(n){if(!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new Error(`Not an org id a file of the sas can be named after: "${n}"`);return n}var J=class extends Error{constructor(t,r){super(`Refusing output path inside the repository: ${t} (repo root: ${r}). Frozen-dataset exports, retained-ID lists and working manifests must live in a sas directory OUTSIDE the repo \u2014 versioning them would create a real\u2194anonymized correspondence table.`);this.resolvedPath=t;this.repoRoot=r;this.name="InsideRepoPathError"}resolvedPath;repoRoot},M=class{repoRoot;constructor(e){this.repoRoot=e?v.resolve(e):ee(process.cwd())}isInsideRepo(e){let t=G(this.repoRoot),r=G(e);if(r===t)return!0;let s=v.relative(t,r);return s!==""&&!s.startsWith("..")&&!v.isAbsolute(s)}assertOutsideRepo(e){if(this.isInsideRepo(e))throw new J(v.resolve(e),this.repoRoot);return v.resolve(e)}};import*as m from"node:fs/promises";import*as R from"node:path";var be=4*1024*1024,Re=64*1024*1024;var q=1e4,A=l().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),S=l().min(1).max(40),Se=f({forgeId:l().min(1).max(200),targetOrgId:l().min(1).max(128),timestamp:S,duration:u().nonnegative(),status:Z(["success","partial","failure"]),cancelled:L(!0).optional(),writtenBetween:f({first:S,last:S}).optional(),retryOf:l().min(1).max(200).optional(),objects:w(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:w(A)})),linked:u().int().nonnegative(),mayHaveBeenWritten:u().int().nonnegative().optional(),undo:f({removedAt:S,deleted:u().int().nonnegative(),alreadyGone:u().int().nonnegative(),kept:u().int().nonnegative(),refused:u().int().nonnegative(),notReached:u().int().nonnegative().optional(),notVisible:u().int().nonnegative().optional()}).optional(),removalStamps:F(A,S).optional(),removalSpans:w(f({first:S,last:S,userId:A})).optional(),removalLeft:w(A).optional(),sweep:f({sweptAt:S,deleted:u().int().nonnegative(),keptChanged:u().int().nonnegative(),refused:u().int().nonnegative()}).optional(),inJournal:f({journalId:l().min(1).max(200),part:u().int().nonnegative(),left:w(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:u().int().nonnegative()}))}).optional()}),je=f({version:L(1),plans:w(U())}),Oe=f({version:L(1),runs:w(f({forgeId:l().min(1).max(300),ids:w(A),late:w(A).optional()}))});var _="referenceid-mapping.json",ne=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,ae=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,x=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,D=new Set;function ie(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var se=f({at:l().min(1).max(40),object:l().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:w(W([l().min(1).max(400),l().regex(x)])).max(1e4)}),oe=f({journal:f({startedAt:l().min(1).max(40),pid:u().int().positive(),runUserId:l().regex(x).optional()})});function de(n){let e,t={},r=new Map,s;for(let a of n.split(`
8
+ `)){if(a.trim()==="")continue;let o;try{o=JSON.parse(a)}catch{continue}if(!e){let c=oe.safeParse(o);c.success&&(e=c.data.journal);continue}let i=se.safeParse(o);if(!i.success)continue;let d=r.get(i.data.object)??[];for(let[c,h]of i.data.created)Object.prototype.hasOwnProperty.call(t,c)||d.push(c),t[c]=h;r.set(i.data.object,d),s=i.data.at}if(!(!e||s===void 0||Object.keys(t).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:s,mapping:t,created:[...r].filter(([,a])=>a.length>0).map(([a,o])=>({objectApiName:a,referenceIds:o})),load:{startedAt:e.startedAt,endedAt:s},...e.runUserId?{runUserId:e.runUserId}:{}}}}function ce(n){return`referenceid-mapping.${k(n)}.json`}async function N(n){let e;try{e=await m.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}return JSON.parse(e)}async function Fe(n,e){let t=e.assertOutsideRepo(n),r;try{r=await m.readdir(t)}catch(a){if(a.code==="ENOENT")return[];throw a}let s=new Set(r.flatMap(a=>ne.exec(a)?.[1]??ae.exec(a)?.[1]??[]));if(r.includes(_)){let o=(await N(e.assertOutsideRepo(R.join(t,_))))?.orgId;typeof o=="string"&&le(o)&&s.add(o)}return[...s].sort()}function le(n){try{return k(n),!0}catch{return!1}}var ge=w(f({objectApiName:l(),referenceIds:w(l())})),pe=f({startedAt:l(),endedAt:l()}),ue=f({first:l(),last:l()}),fe=f({removedAt:l(),deleted:u(),alreadyGone:u(),kept:u(),refused:u(),notReached:u().optional()}),me=F(l(),l()),he=w(f({first:l(),last:l(),userId:l()})),K=F(l(),l()),$=l().regex(x);function z(n,e){let t=n.safeParse(e);return t.success?t.data:void 0}function b(n){if(typeof n!="object"||n===null)return;let e=n,t=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(y=>typeof y[1]=="string")):{},r=z(ge,e.created),s=z(pe,e.load),a=z(ue,e.writtenBetween),o=z(fe,e.removal),i=z(me,e.removalStamps),d=z(he,e.removalSpans),c=z(K,e.personContacts),h=z(K,e.withTheirRecord),g=z($,e.runUserId),p=z(w($),e.madeEarlier),P=z(w($),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:t,...r?{created:r}:{},...s?{load:s}:{},...a?{writtenBetween:a}:{},...o?{removal:o}:{},...i?{removalStamps:i}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...h?{withTheirRecord:h}:{},...g?{runUserId:g}:{},...p?{madeEarlier:p}:{},...P?{lateEarlier:P}:{}}}function j(n){return Array.isArray(n.earlier)?n.earlier.flatMap(e=>b(e)??[]):[]}function O(n){return n.load?.endedAt??n.updatedAt}function ye(n,e){return n.slice(0,15)===e.slice(0,15)}function I(n){return n.slice(0,15)}function V(n,e){let t={};for(let[r,s]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(e,s)?Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=s):delete e[r];return t}function H(n,e){if(e.size===0)return n;let t=Object.fromEntries(Object.entries(n.mapping).filter(([,d])=>!e.has(I(d)))),r=V(n.personContacts,t),s=V(n.withTheirRecord,t),a=n.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(h=>Object.prototype.hasOwnProperty.call(t,h))})).filter(d=>d.referenceIds.length>0),o=Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([d])=>!e.has(I(d)))),i={...n,mapping:t};return delete i.removalStamps,delete i.personContacts,delete i.withTheirRecord,{...i,...a?{created:a}:{},...Object.keys(o).length>0?{removalStamps:o}:{},...Object.keys(r).length>0?{personContacts:r}:{},...Object.keys(s).length>0?{withTheirRecord:s}:{}}}function Y(n){return n.created?n.created.some(e=>e.referenceIds.length>0):Object.keys(n.mapping).length>0}var X=class{constructor(e,t){this.sasDir=e;this.guard=t?.guard??new M,this.orgId=t?.orgId??"";let r=t?.organizationId;this.askOrganizationId=typeof r=="function"?r:async()=>r,this.now=t?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(R.join(this.sasDir,this.orgId===""?_:ce(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(R.join(this.sasDir,_))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${k(this.orgId)}`}journalPath(e){let t=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(R.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(t))}.ndjson`))}retiring=new Map;journal(e){let t=this.journalPath(e),r=!1,s=!1,a=!1,o,i=Promise.resolve(),d;D.add(t);let c=g=>{i=i.then(async()=>{if(!(d!==void 0||s))try{if(!r){r=!0,await m.mkdir(R.dirname(t),{recursive:!0});let p={journal:{startedAt:e.toISOString(),pid:process.pid,...o?{runUserId:o}:{}}};await m.appendFile(t,`${JSON.stringify(p)}
9
+ `,"utf8")}await m.appendFile(t,`${JSON.stringify(g)}
10
+ `,"utf8")}catch(p){d=p instanceof Error?p.message:String(p)}})},h=async()=>{await i,s=!0,await m.rm(t,{force:!0})};return this.retiring.set(t,h),{writtenAs:g=>{x.test(g)&&(o=g)},created:(g,p)=>{let P=p.filter(([y,E])=>y!==""&&x.test(E));if(P.length!==0){a=!0;for(let y=0;y<P.length;y+=1e4)c({at:this.now().toISOString(),object:g,created:P.slice(y,y+1e4)})}},flush:async()=>(await i,d),close:async()=>{await i,this.retiring.delete(t),(s||!a)&&await m.rm(t,{force:!0}),s=!0,D.delete(t)}}}async stoppedLoads(e){let t;try{t=await m.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(o){if(o.code==="ENOENT")return[];throw o}let r=`${this.journalStem}.load-`,s=new Set(e.flatMap(o=>o.load?[o.load.startedAt]:[])),a=[];for(let o of t){if(!o.startsWith(r)||!/^\d{1,16}\.ndjson$/.test(o.slice(r.length)))continue;let i=this.guard.assertOutsideRepo(R.join(this.sasDir,o));if(D.has(i))continue;let d;try{d=await m.readFile(i,"utf8")}catch{continue}let c=de(d);!c||s.has(c.startedAt)||c.pid!==process.pid&&ie(c.pid)||a.push({file:i,load:c.load})}return a}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let t=b(e);return[...t?[t]:[],...j(e)].map(r=>({mapping:new Map(Object.entries(r.mapping)),...r.created?{created:r.created}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},endedAt:O(r),...r.removalStamps?{removalStamps:r.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let t=typeof e.orgId=="string"?e.orgId:"",r=b(e);return[...r?[this.recordedOf(r,t)]:[],...j(e).map(s=>({...this.recordedOf(s,t),earlier:!0}))]}recordedOf(e,t){return{orgId:t,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:O(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let t=e.organizationId;if(t===void 0)return!1;let r=await this.currentOrganizationId();return r!==void 0&&!ye(t,r)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await N(this.filePath);if(e!==void 0)return e;let t=this.singleFilePath;if(t===void 0)return;let r=await N(t);return r?.orgId===this.orgId?r:void 0}async readWithJournals(){let e=await this.readFile(),t=e?[b(e),...j(e)]:[],r=await this.stoppedLoads(t.filter(i=>i!==void 0));if(r.length===0)return{payload:e,journals:[]};let s=[...t.filter(i=>i!==void 0),...r.map(({load:i})=>i)].sort((i,d)=>Date.parse(O(d))-Date.parse(O(i))),[a,...o]=s;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...a,...o.length>0?{earlier:o}:{}},journals:r.map(({file:i})=>i)}}async dropJournals(e){for(let t of e)await m.rm(t,{force:!0}).catch(()=>{})}async write(e){let t=this.filePath;await m.mkdir(R.dirname(t),{recursive:!0}),await m.writeFile(t,`${JSON.stringify(e,null,2)}
11
+ `,"utf8");let r=this.singleFilePath;if(r!==void 0)try{(await N(r))?.orgId===this.orgId&&await m.rm(r)}catch{}}async keptLoads(e,t,r=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let s=new Set(t.map(I)),a=new Set(r),o=b(e);return[...o?[o]:[],...j(e)].map(i=>H(i,s)).filter(i=>Y(i)||a.has(O(i)))}async persist(e,t){let{payload:r,journals:s}=await this.readWithJournals(),a=t?.earlier?await this.keptLoads(r,t.earlier.settled,t.earlier.stillToSweep):[],o=await this.currentOrganizationId(),i=this.now().toISOString(),d=g=>Object.fromEntries(Object.entries(g??{}).filter(([p,P])=>e.has(p)&&e.has(P))),c=d(t?.personContacts),h=d(t?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...o!==void 0?{organizationId:o}:{},updatedAt:i,mapping:Object.fromEntries([...e.entries()].sort(([g],[p])=>g.localeCompare(p))),...t?{created:t.created.map(({objectApiName:g,referenceIds:p})=>({objectApiName:g,referenceIds:p.filter(P=>e.has(P))})).filter(g=>g.referenceIds.length>0),load:{startedAt:t.startedAt.toISOString(),endedAt:i},...t.writtenBetween?{writtenBetween:{...t.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(h).length>0?{withTheirRecord:h}:{},...t.runUserId?{runUserId:t.runUserId}:{}}:{},...a.length>0?{earlier:a}:{}}),t?.earlier&&await this.dropJournals(s),t){let g=this.journalPath(t.startedAt),p=this.retiring.get(g);p?await p():await m.rm(g,{force:!0}).catch(()=>{})}}async recordRemoval(e,t){let{payload:r,journals:s}=await this.readWithJournals(),a=b(r);if(r===void 0||a===void 0)return!1;let o=[a,...j(r)],i=o.findIndex(g=>O(g)===e);if(i<0)return!1;let d=new Set(t.gone.map(I)),[c,...h]=o.map((g,p)=>H(p===i?ve(g,t):g,d));return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...c,updatedAt:this.now().toISOString(),...h.length>0?{earlier:h}:{}}),await this.dropJournals(s),!0}async recordMade(e,t,r=[],s=[]){let{payload:a,journals:o}=await this.readWithJournals(),i=b(a);if(a===void 0||i===void 0)return!1;let d=[i,...j(a)],c=d.findIndex(y=>O(y)===e);if(c<0)return!1;let h=[...s],g=y=>{let E=Q(y.madeEarlier,t,h),C=Q(y.lateEarlier,r,h),T={...y};return delete T.madeEarlier,delete T.lateEarlier,{...T,...E.length>0?{madeEarlier:E}:{},...C.length>0?{lateEarlier:C}:{}}},[p,...P]=d.map((y,E)=>E===c?g(y):y);return await this.write({version:1,orgId:typeof a.orgId=="string"?a.orgId:"",...a.organizationId!==void 0?{organizationId:a.organizationId}:{},...p,...P.length>0?{earlier:P}:{}}),await this.dropJournals(o),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:t,journals:r}=await this.readWithJournals(),s=b(t);if(t===void 0||s===void 0)return!1;let a=new Set(e),o=j(t),i=o.filter(d=>Y(d)||!a.has(O(d)));return i.length===o.length?!1:(await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...s,...i.length>0?{earlier:i}:{}}),await this.dropJournals(r),!0)}async recordStamps(e){let{payload:t,journals:r}=await this.readWithJournals(),s=b(t);if(t===void 0||s===void 0)return!1;let a=[s,...j(t)],o=a.map(c=>we(c,e));if(o.every((c,h)=>c===a[h]))return!1;let[i,...d]=o;return await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...i,...d.length>0?{earlier:d}:{}}),await this.dropJournals(r),!0}};function Q(n,e,t=[]){let r=new Map,s=new Set(t.map(I)),a=[];for(let o of[...n??[],...e]){let i=I(o),d=i.slice(0,3),c=r.get(d)??0;!x.test(o)||s.has(i)||c>=q||(s.add(i),r.set(d,c+1),a.push(o))}return a}function we(n,e){let t=new Set(Object.values(n.mapping).map(I)),r=Object.entries(e).filter(([a])=>t.has(I(a)));if(r.length===0)return n;let s=new Set(r.map(([a])=>I(a)));return{...n,removalStamps:{...Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([a])=>!s.has(I(a)))),...Object.fromEntries(r)}}}function ve(n,e){let t={...n.removalStamps,...e.stamps},r=[...n.removalSpans??[],...e.span?[e.span]:[]],s=e.mark??n.removal;return{...n,...s?{removal:s}:{},...Object.keys(t).length>0?{removalStamps:t}:{},...r.length>0?{removalSpans:r}:{}}}export{ee as a,k as b,J as c,M as d,ce as e,Fe as f,X as g};