sandforge 1.79.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 (256) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-BN7A4GRQ.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-PBI4BYWW.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/chunk-2OIRJEYE.mjs +7 -0
  5. package/lib/{chunk-FOVVHGEP.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-5CD257T7.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-4NAHW2D3.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-4SNDMJP2.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-SIOZXPFG.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-GNC27UEU.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/chunk-5WGA5CZB.mjs +7 -0
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/chunk-67CC7RAE.mjs +7 -0
  26. package/lib/{chunk-5O6JOMHS.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-7UQD6V6F.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-H2PJNIYJ.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-AUTM6H6Z.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-HV2MXMGI.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-OTWRDD6L.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-XBG5SP6Q.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-BILZ3SSR.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/chunk-DHGPDSXS.mjs +7 -0
  48. package/lib/{chunk-ZXH4MBWP.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-NM4MDLK4.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/chunk-DQR5NDMI.mjs +7 -0
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/chunk-E2OBAWSH.mjs +7 -0
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/chunk-EAFLDSQ2.mjs +7 -0
  56. package/lib/{chunk-HCIDVIOW.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-2BVTCNWA.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-3SRXFZSD.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-3DCUADVK.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-HTJ5OGP5.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-HJKM3E56.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/chunk-FTA5LOVX.mjs +7 -0
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-QRV2OSIS.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-5MMXFWPD.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-P7GSGFJO.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-342FN7AO.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-LQ4DRFUH.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/chunk-HVC5CYIB.mjs +7 -0
  73. package/lib/{chunk-EQF2IJS2.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-TQX3PURV.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-K22PA4XL.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-P2PJYWGQ.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-JVL444U5.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-IAZB4WIL.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-TEOLMRDO.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-PNCONNFJ.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/chunk-L5FGY6YA.mjs +7 -0
  90. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  91. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  92. package/lib/{chunk-ZOVSMN5C.mjs → chunk-LO527YLT.mjs} +1 -1
  93. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  94. package/lib/{chunk-QQZZMKU3.mjs → chunk-MHW6DV6T.mjs} +1 -1
  95. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  96. package/lib/{chunk-6EBMEGZB.mjs → chunk-MKNAZPOT.mjs} +1 -1
  97. package/lib/{chunk-NTDN2JQZ.mjs → chunk-MNITSYI2.mjs} +8 -8
  98. package/lib/chunk-MO3N5XVV.mjs +341 -0
  99. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  100. package/lib/chunk-MWLFFVQV.mjs +8 -0
  101. package/lib/chunk-N6HHNR6J.mjs +7 -0
  102. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  103. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  104. package/lib/chunk-NWPQF5XR.mjs +7 -0
  105. package/lib/{chunk-PUOX4NBJ.mjs → chunk-NWVVCZUK.mjs} +1 -1
  106. package/lib/{chunk-DLDX6RRC.mjs → chunk-O6ADMP36.mjs} +1 -1
  107. package/lib/chunk-O7DAFE6M.mjs +14 -0
  108. package/lib/chunk-OEHVAJAB.mjs +7 -0
  109. package/lib/chunk-OETEC3P7.mjs +7 -0
  110. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  111. package/lib/chunk-OIIL4NVI.mjs +7 -0
  112. package/lib/chunk-OMZJ37JI.mjs +15 -0
  113. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-ONMBSACW.mjs} +1 -1
  114. package/lib/chunk-OQQHNYR7.mjs +272 -0
  115. package/lib/{chunk-AAVJ5XVX.mjs → chunk-OU5W7SCB.mjs} +1 -1
  116. package/lib/{chunk-RSYICMZG.mjs → chunk-OVOLG3AL.mjs} +1 -1
  117. package/lib/{chunk-F74IHMGL.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  118. package/lib/{chunk-W7KFAY55.mjs → chunk-OZNLOV4U.mjs} +1 -1
  119. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  120. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  121. package/lib/{chunk-RACDTRZA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  122. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  123. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  124. package/lib/{chunk-PZTSVQSF.mjs → chunk-QXLZINZB.mjs} +1 -1
  125. package/lib/chunk-R2BJWO5N.mjs +20 -0
  126. package/lib/chunk-R6TF26V4.mjs +10 -0
  127. package/lib/{chunk-P42X3B4D.mjs → chunk-RKALOKAU.mjs} +1 -1
  128. package/lib/chunk-SQGP46QS.mjs +7 -0
  129. package/lib/chunk-SU65Z2BA.mjs +7 -0
  130. package/lib/chunk-SW2NUKQL.mjs +9 -0
  131. package/lib/chunk-T26C576X.mjs +9 -0
  132. package/lib/{chunk-3OHPD72J.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  133. package/lib/chunk-T5VAULLQ.mjs +7 -0
  134. package/lib/chunk-TEIBWMJM.mjs +7 -0
  135. package/lib/chunk-TKQQVB2D.mjs +9 -0
  136. package/lib/{chunk-RAAANPPG.mjs → chunk-TPHXRHOA.mjs} +1 -1
  137. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  138. package/lib/{chunk-IEYG5ATY.mjs → chunk-TQM2XJ27.mjs} +1 -1
  139. package/lib/{chunk-X65MT4W3.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  140. package/lib/chunk-UIUPPEFB.mjs +7 -0
  141. package/lib/{chunk-QPF6C5MX.mjs → chunk-UT27HXE7.mjs} +1 -1
  142. package/lib/{chunk-J7HVXMSW.mjs → chunk-UUSLTW5V.mjs} +1 -1
  143. package/lib/chunk-V2QO6KOE.mjs +19 -0
  144. package/lib/chunk-V473C7LY.mjs +7 -0
  145. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  146. package/lib/chunk-VSU74RQ3.mjs +9 -0
  147. package/lib/chunk-VV3B6IC3.mjs +7 -0
  148. package/lib/chunk-W2AAGIZF.mjs +7 -0
  149. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  150. package/lib/chunk-WD47PGUS.mjs +10 -0
  151. package/lib/{chunk-3CA767QB.mjs → chunk-WEZLXE34.mjs} +1 -1
  152. package/lib/{chunk-WFEB5X4U.mjs → chunk-WI4HYWV6.mjs} +1 -1
  153. package/lib/{chunk-AR7BE5O2.mjs → chunk-WM5JI4JI.mjs} +1 -1
  154. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  155. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  156. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  157. package/lib/{chunk-SFURUNJM.mjs → chunk-XC2QKQT5.mjs} +1 -1
  158. package/lib/chunk-XC54KKKC.mjs +7 -0
  159. package/lib/chunk-XEB6HZ34.mjs +7 -0
  160. package/lib/chunk-XGKSSCW7.mjs +7 -0
  161. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  162. package/lib/{chunk-RFEO2KAN.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  163. package/lib/{chunk-TBZMC2VV.mjs → chunk-YCSFP6ER.mjs} +4 -4
  164. package/lib/{chunk-YBU4Z4QV.mjs → chunk-YHIOS2PU.mjs} +1 -1
  165. package/lib/chunk-YIGFYZQY.mjs +7 -0
  166. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  167. package/lib/{chunk-57VHUYNG.mjs → chunk-YOGMP72T.mjs} +4 -4
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-55HEMHEG.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  170. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  171. package/lib/{chunk-VHI54FBK.mjs → chunk-ZWZXQTAK.mjs} +53 -53
  172. package/lib/sandforge-autopilot.mjs +29 -24
  173. package/lib/sandforge-backup.mjs +67 -32
  174. package/lib/sandforge-checkpoint.mjs +1 -347
  175. package/lib/sandforge-cleanup.mjs +14 -10
  176. package/lib/sandforge-clone.mjs +1 -1
  177. package/lib/sandforge-compare.mjs +9 -8
  178. package/lib/sandforge-dataops.mjs +1 -1
  179. package/lib/sandforge-empty.mjs +15 -15
  180. package/lib/sandforge-env.mjs +101 -101
  181. package/lib/sandforge-frozen.mjs +1 -257
  182. package/lib/sandforge-mcp.mjs +33 -14
  183. package/lib/sandforge-monitor.mjs +7 -7
  184. package/lib/sandforge-pipeline.mjs +88 -0
  185. package/lib/sandforge-seed.mjs +1 -1
  186. package/lib/sandforge-sync.mjs +1 -1
  187. package/lib/sandforge.mjs +6 -6
  188. package/package.json +2 -1
  189. package/lib/chunk-2S5OMIIA.mjs +0 -7
  190. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  191. package/lib/chunk-3F5YMM2F.mjs +0 -7
  192. package/lib/chunk-3RYLICRX.mjs +0 -7
  193. package/lib/chunk-42RER7V4.mjs +0 -14
  194. package/lib/chunk-4GL773D5.mjs +0 -7
  195. package/lib/chunk-4HFRHFGQ.mjs +0 -7
  196. package/lib/chunk-4U6NXJNL.mjs +0 -7
  197. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  198. package/lib/chunk-5AJRHRXA.mjs +0 -20
  199. package/lib/chunk-5HMAPZBV.mjs +0 -7
  200. package/lib/chunk-5P4PHJRL.mjs +0 -9
  201. package/lib/chunk-5QKTYCWE.mjs +0 -11
  202. package/lib/chunk-6LAXTAVN.mjs +0 -7
  203. package/lib/chunk-6MUEPV7M.mjs +0 -9
  204. package/lib/chunk-6QSM2WIH.mjs +0 -10
  205. package/lib/chunk-75ADZS6B.mjs +0 -7
  206. package/lib/chunk-ALJVEUUS.mjs +0 -7
  207. package/lib/chunk-ALUFROGA.mjs +0 -7
  208. package/lib/chunk-B45CNPUX.mjs +0 -47
  209. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  210. package/lib/chunk-CGWXQX75.mjs +0 -7
  211. package/lib/chunk-D3QRXG63.mjs +0 -787
  212. package/lib/chunk-EEVVGGM6.mjs +0 -7
  213. package/lib/chunk-ENLBYECD.mjs +0 -7
  214. package/lib/chunk-EQOQASDQ.mjs +0 -7
  215. package/lib/chunk-FQBRBBY4.mjs +0 -7
  216. package/lib/chunk-GAM726CK.mjs +0 -7
  217. package/lib/chunk-HJC7AIBK.mjs +0 -7
  218. package/lib/chunk-HUMEKZT5.mjs +0 -8
  219. package/lib/chunk-I3JKJTLO.mjs +0 -110
  220. package/lib/chunk-I7O6C2B5.mjs +0 -8
  221. package/lib/chunk-KLX67VPL.mjs +0 -7
  222. package/lib/chunk-L776PUMV.mjs +0 -7
  223. package/lib/chunk-LRFAIUN7.mjs +0 -7
  224. package/lib/chunk-LV6G4XTK.mjs +0 -7
  225. package/lib/chunk-MYTIL2JD.mjs +0 -10
  226. package/lib/chunk-NEVXIGR6.mjs +0 -10
  227. package/lib/chunk-NGSMZZDA.mjs +0 -7
  228. package/lib/chunk-NHWE66K5.mjs +0 -7
  229. package/lib/chunk-OQOZAPCI.mjs +0 -7
  230. package/lib/chunk-PA3MKJVH.mjs +0 -7
  231. package/lib/chunk-QROPNEGY.mjs +0 -14
  232. package/lib/chunk-QWT2C74M.mjs +0 -7
  233. package/lib/chunk-RH3N2H7P.mjs +0 -7
  234. package/lib/chunk-SRQDABQ2.mjs +0 -15
  235. package/lib/chunk-SVS6UMDU.mjs +0 -323
  236. package/lib/chunk-TNXUU6W7.mjs +0 -14
  237. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  238. package/lib/chunk-VXHDBYMI.mjs +0 -7
  239. package/lib/chunk-WJY54JO7.mjs +0 -13
  240. package/lib/chunk-WRU5FJFC.mjs +0 -7
  241. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  242. package/lib/chunk-XEFDB2R4.mjs +0 -7
  243. package/lib/chunk-XETCPL7E.mjs +0 -7
  244. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  245. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  246. package/lib/chunk-YMJVMFPY.mjs +0 -7
  247. package/lib/chunk-YPSRZRIT.mjs +0 -7
  248. package/lib/chunk-YS4G22C2.mjs +0 -7
  249. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  250. package/lib/chunk-Z7X534S4.mjs +0 -10
  251. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  252. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  253. package/lib/chunk-ZPYJPGDK.mjs +0 -7
  254. package/lib/chunk-ZQOZ4EFW.mjs +0 -7
  255. package/lib/chunk-ZUTYVST5.mjs +0 -7
  256. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as c,b as f,c as p}from"./chunk-DBFJB2B6.mjs";import{createHmac as m,randomBytes as d}from"node:crypto";function k(o){let e=o.truncateLength;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function A(o,e){let n=o.maskKeepLast;if(typeof n!="number"||!Number.isFinite(n)||n<=0)return 0;let t=Math.floor(n);return e>t?t:0}var g=/^[^\s@]+@[^\s@]+$/,h="example.invalid";function R(o){let e=o.lastIndexOf("@");return`${e===-1?o:o.slice(0,e)}@${h}`}var u=class extends Error{constructor(e){super(`Hash rule for ${e} has no hashSalt. The values being hashed are low-entropy PII (emails, phone numbers, names), so an unkeyed digest is recovered by enumeration in seconds. Set config.hashSalt to a secret value.`),this.name="MissingHashSaltError"}},y=class{personaRegistry;fallbackKey;constructor(e,n){this.fallbackKey=n??d(32).toString("hex"),this.personaRegistry=e??new p(this.fallbackKey)}saltedRegistries=new Map;registryFor(e){let n=e.config.hashSalt;if(!n)return this.personaRegistry;let t=this.saltedRegistries.get(n);return t||(t=new p(n),this.saltedRegistries.set(n,t)),t}namesGiven(){return this.personaRegistry.namesGiven()}continueFrom(e){return this.personaRegistry.continueFrom(e)}anonymize(e,n){return e.map(t=>{let a={...t},r=String(t.Id??t.id??"");for(let s of n)s.fieldApiName in a&&(a[s.fieldApiName]=this.applyRule(a[s.fieldApiName],s,r));return a})}applyRule(e,n,t=""){let r={mask:(s,i)=>this.applyMask(s,i),hash:(s,i)=>this.applyHash(s,i),fake:(s,i)=>this.applyFake(s,i,t),nullify:()=>null,shuffle:(s,i)=>this.applyShuffle(s,i),truncate:(s,i)=>this.applyTruncate(s,i),constant:(s,i)=>i.config.constantValue??"",preserve_format:s=>this.applyPreserveFormat(s)}[n.method];return r?r(e,n):e}preview(e,n,t){let a=e.slice(0,Math.max(0,t));return this.anonymize(a,n)}validateRules(e){let n=[];for(let t of e)t.fieldApiName||n.push("Rule must specify a fieldApiName"),t.objectApiName||n.push("Rule must specify an objectApiName"),t.method==="mask"&&!t.config.maskChar&&n.push(`Mask rule for ${t.fieldApiName} must specify a maskChar`),t.method==="hash"&&t.config.hashAlgorithm!=="sha256"&&t.config.hashAlgorithm!=="md5"&&n.push(`Hash rule for ${t.fieldApiName} must specify hashAlgorithm as sha256 or md5`),t.method==="hash"&&!t.config.hashSalt&&n.push(`Hash rule for ${t.fieldApiName} must specify a hashSalt \u2014 an unkeyed digest of low-entropy PII is trivially reversible`),t.method==="constant"&&t.config.constantValue===void 0&&n.push(`Constant rule for ${t.fieldApiName} must specify a constantValue`);return n}applyMask(e,n){let t=String(e??""),a=n.config.maskChar??"*",r=n.config.maskStart??0,s=n.config.maskEnd??t.length-A(n.config,t.length),i=t.split("");for(let l=r;l<Math.min(s,i.length);l++)i[l]=a;return i.join("")}applyHash(e,n){let t=n.config.hashSalt;if(!t)throw new u(n.fieldApiName);let a=n.config.hashAlgorithm??"sha256",r=String(e??""),s=m(a,t).update(r).digest("hex").slice(0,32);return g.test(r)?`${a}-${s}@${h}`:`${a}:${s}`}applyFake(e,n,t){let a=t!==""?t:this.keyedDigest(String(e??""),n),r=this.registryFor(n).getPersona(a),s=c[n.fieldApiName];if(s==="email")return R(r.email);if(s)return r[s];let i=this.keyedDigest(`${n.fieldApiName}:${a}`,n).slice(0,8);return g.test(String(e??""))?`fake-${i}@${h}`:`fake_${i}`}applyShuffle(e,n){return f(String(e??""),n.config.hashSalt??this.fallbackKey)}applyTruncate(e,n){let t=k(n.config);if(t===0)return"";let a=String(e??"");return n.config.truncateKeep==="first"?a.slice(0,t):a.slice(-t)}keyedDigest(e,n){return m("sha256",n.config.hashSalt??this.fallbackKey).update(e).digest("hex")}applyPreserveFormat(e){return String(e??"").replace(/[a-zA-Z]/g,"x").replace(/[0-9]/g,"0")}};export{u as a,y as b};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{p as ne,q as De}from"./chunk-ENLBYECD.mjs";import{D as Fe,V as Ne,xa as Ie}from"./chunk-ZLZRU6MO.mjs";import{a as _e,b as Me}from"./chunk-HF6LAK3G.mjs";import{j as xe,k as ve,l as Ce,m as $e,n as je}from"./chunk-PNCONNFJ.mjs";import{D as $,Z as Te,b as C,ca as Pe,p as W,q as G,s as re}from"./chunk-CGWXQX75.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{Hc as be,Jc as ye,Lc as ee,Mc as we,Oc as x,Pc as Re,Qc as te,Sc as L,Xc as Ae,Yc as Ee,_c as Se,bc as Z,bd as v,hd as Be,jd as Oe,kd as ke,l as pe,r as he}from"./chunk-B45CNPUX.mjs";import{b as Q,e as w,f as D,k as fe,l as b}from"./chunk-7EANH5PY.mjs";import{createHash as vt}from"node:crypto";var Le="lineage:runs",Tt="lineage";function We(e){let t=e.objects.filter(i=>i.records>0);if(t.length===0)return null;let r="source",n="target",o=[{id:r,type:"source",label:e.source.label,origin:e.source.origin,...e.source.orgId?{orgId:e.source.orgId}:{}}],s=[];for(let i of t){let u=`object:${i.objectApiName}`;o.push({id:u,type:"object",label:i.objectApiName,objectApiName:i.objectApiName,recordCount:i.records}),s.push({sourceId:r,targetId:u}),s.push({sourceId:u,targetId:n,recordCount:i.records})}return o.push({id:n,type:"destination",label:e.target.label,orgId:e.target.orgId,origin:"org"}),{nodes:o,edges:s,operationId:e.operationId,generatedAt:e.generatedAt,module:e.module,action:e.action}}var U=class{constructor(t,r=100){this.configStore=t;this.limit=r}configStore;limit;save(t){let r=this.read().filter(n=>n.operationId!==t.operationId);r.push(t),this.configStore.set(Le,r.slice(-this.limit),Tt)}get(t){let r=this.read();return t===void 0?r[r.length-1]??null:r.find(n=>n.operationId===t)??null}runs(){return this.read().reverse().map(t=>({operationId:t.operationId,generatedAt:t.generatedAt,...t.module?{module:t.module}:{},...t.action?{action:t.action}:{},...Pt(t)}))}read(){let t=this.configStore.get(Le);return Array.isArray(t)?t.filter(xt):[]}};function Pt(e){let t=e.nodes.find(r=>r.type==="destination");return t?{targetLabel:t.label}:{}}function xt(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.operationId=="string"&&typeof t.generatedAt=="string"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}var Ct=100,Ge="audit:trail",$t="audit",oe=class{constructor(t,r=he){this.configStore=t;this.limit=r}configStore;limit;append(t){let r=this.read();r.push(t),this.configStore.set(Ge,r.slice(-this.limit),$t)}list(t={}){let r=this.read().reverse(),n=r.filter(i=>(t.module===void 0||i.module===t.module)&&(t.orgId===void 0||i.orgId===t.orgId)),o=t.offset??0,s=t.limit??Ct;return{entries:n.slice(o,o+s),total:n.length,offset:o,facets:jt(r)}}read(){let t=this.configStore.get(Ge);return Array.isArray(t)?t.filter(Ft):[]}};function jt(e){let t=new Set,r=new Map;for(let n of e)t.add(n.module),n.orgId!==void 0&&!r.has(n.orgId)&&r.set(n.orgId,n.orgAlias);return{modules:[...t].sort(),orgs:[...r].map(([n,o])=>o?{orgId:n,orgAlias:o}:{orgId:n})}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.action=="string"&&typeof t.module=="string"&&typeof t.timestamp=="string"}var Ln="ABORTED_BEFORE_START";function _t(e){let t=e?.trim().toLowerCase();if(t)return`sha256:${vt("sha256").update(t).digest("hex").slice(0,12)}`}function Wn(e,t,r=new Date){try{let n=e.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1;if(!n&&t.outcome==="stopped"&&t.code===void 0)return;let o=r.toISOString(),s=e.orgManager.getOrg(t.orgId),i=s?Z(s):void 0,u=_t(s?.username),a=t.source?.origin==="org"?t.source.orgId:void 0,d=a!==void 0?e.orgManager.getOrg(a):void 0,l=d?Z(d):void 0,c=t.objects??[];if(new oe(e.configStore).append({id:crypto.randomUUID(),action:t.action,module:t.module,orgId:t.orgId,...i?{orgAlias:i}:{},...a!==void 0?{sourceOrgId:a}:{},...l?{sourceOrgAlias:l}:{},operationId:t.operationId,outcome:t.outcome,...n&&t.guard?{guard:t.guard}:{},objects:[...c],...t.leftBy?{leftBy:t.leftBy}:{},...u?{userId:u}:{},...t.context?{context:t.context}:{},...t.verdict?{verdict:t.verdict}:{},...t.muted?{muted:t.muted}:{},...t.checkpointId?{checkpointId:t.checkpointId}:{},...t.beforeRun?{beforeRun:{...t.beforeRun}}:{},...t.fit?{fit:{...t.fit}}:{},details:{...t.details,...t.code?{code:t.code}:{}},timestamp:o}),!t.source)return;let g=We({operationId:t.operationId,module:t.module,action:t.action,source:t.source.origin==="org"?{origin:"org",orgId:t.source.orgId,label:l??t.source.orgId}:{origin:t.source.origin,label:t.source.label??""},target:{label:i??t.orgId,orgId:t.orgId},objects:Mt(c,t.carried),generatedAt:o});g&&new U(e.configStore).save(g)}catch(n){e.log(`[WARN] audit trail: run ${t.operationId} was not recorded \u2014 ${R(n)}`)}}function Mt(e,t){return t?Object.entries(t).map(([r,n])=>({objectApiName:r,records:n})):e.map(r=>({objectApiName:r.objectApiName,records:r.created+r.updated+(r.upserted??0)}))}function Ue(e){return{objectApiName:e,created:0,updated:0,deleted:0,failed:0}}var Nt="__pass2__";function qe(e){let t=e.errors??[],r=t.some(s=>s.skipped===!0),n=t.some(s=>s.objectApiName===Nt&&s.failedCount>0);return e.failedCount===0&&e.failedReads.length===0&&!r&&!n?"success":e.successCount+e.updatedCount+e.linkedCount+(e.wouldInsertCount??0)>0?"partial":"failure"}function Un(e,t,r){return{forgeId:`forge-${Date.now()}`,status:r.status,graph:t,duration:Date.now()-r.startedAt,timestamp:new Date().toISOString(),idRemapCount:e.remapCount,idRemapTable:e.remapTable,idRemapExisting:e.existingSourceIds,...e.withTheirRecordSourceIds?{idRemapWithTheirRecord:e.withTheirRecordSourceIds}:{},...e.withTheirRecordCount!==void 0&&e.withTheirRecordCount>0?{withTheirRecordCount:e.withTheirRecordCount}:{},...e.linkedToCreatedCount!==void 0&&e.linkedToCreatedCount>0?{linkedToCreatedCount:e.linkedToCreatedCount}:{},createdCount:e.successCount,...e.updatedCount>0?{updatedCount:e.updatedCount}:{},linkedExistingCount:e.linkedCount,existingRecords:e.existingRecords,idRemapByObject:e.remapByObject,idRemapCreated:e.createdByObject,readByObject:e.readByObject,failedReads:e.failedReads,errors:e.errors,truncatedObjects:e.truncatedObjects,...e.cappedObjects?{cappedObjects:e.cappedObjects}:{},...e.files?{files:e.files}:{},...e.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:e.fileContentFieldsLeftOut}:{},...e.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:e.encryptedFieldsLeftOut}:{},...e.picklistValuesChanged?{picklistValuesChanged:e.picklistValuesChanged}:{},...e.currenciesReplaced?{currenciesReplaced:e.currenciesReplaced}:{},...e.recordTypesGiven?{recordTypesGiven:e.recordTypesGiven}:{},...e.writtenWithoutFields?{writtenWithoutFields:e.writtenWithoutFields}:{},...e.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:e.lookupsLeftEmptyByFilter}:{},...e.contactPoints?{contactPoints:e.contactPoints}:{},...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.apiCalls!==void 0?{apiCalls:e.apiCalls}:{},...e.dryRun?{dryRun:!0,wouldInsertCount:e.wouldInsertCount}:{},...e.gaps?{gaps:e.gaps}:{},...e.decisionsApplied?{decisionsApplied:e.decisionsApplied}:{},...e.mayHaveBeenWritten?{mayHaveBeenWritten:e.mayHaveBeenWritten}:{},...e.remapInJournal?{remapInJournal:!0}:{},...e.sample?{sample:e.sample}:{}}}var ze="RUN_CANCELLED";function Vn(e){return{idRemapByObject:e.remapByObject,errors:e.errors,notSentByObject:e.notSentByObject,writtenWithoutFields:e.writtenWithoutFields,mayHaveBeenWritten:e.mayHaveBeenWritten}}function Kn(e){let t=new Map,r=n=>{let o=t.get(n)??Ue(n);return t.set(n,o),o};for(let n of e.idRemapByObject??[]){let o=r(n.objectApiName);o.created+=n.created,o.updated+=n.updated??0}for(let n of e.errors??[]){if(n.objectApiName.startsWith("__")||n.referenceData===!0||n.stage==="scope"&&n.failedCount===0&&n.skipped!==!0)continue;let o=r(n.objectApiName);o.failed+=n.failedCount,n.skipped===!0&&(o.skipped=n.failedCount>0?"counted":"uncounted")}for(let n of e.notSentByObject??[]){let o=r(n.objectApiName);o.notSent=(o.notSent??0)+n.notSent}for(let n of e.writtenWithoutFields??[]){let o=r(n.objectApiName);o.writtenWithoutFields=(o.writtenWithoutFields??0)+n.rows}for(let{objectApiName:n,sourceIds:o}of e.mayHaveBeenWritten??[]){let s=r(n);s.mayHaveBeenWritten=(s.mayHaveBeenWritten??0)+o.length}return[...t.values()]}function Xn(e,t){return t.some(n=>n.created+n.updated>0)?"cancelled":(e?qe(e):"success")==="success"?"stopped":"cancelled"}function Yn(e){return e?{details:{contactPoints:e.neutralized?"neutralized":"kept",contactPointFields:e.fields.length,contactPointValues:e.values}}:{}}function Jn(e){return Object.fromEntries((e.idRemapByObject??[]).map(t=>[t.objectApiName,t.created+t.linked+(t.updated??0)]))}var j=class extends Error{operation;timeoutMs;constructor(t,r){super(`Operation "${t}" timed out after ${r}ms`),this.name="TimeoutError",this.operation=t,this.timeoutMs=r}},q=class{defaultTimeoutMs;constructor(t=3e4){this.defaultTimeoutMs=t}async withTimeout(t,r,n){let o=n??this.defaultTimeoutMs,s=new AbortController;return new Promise((i,u)=>{let a=setTimeout(()=>{s.abort(),u(new j(t,o))},o);r(s.signal).then(d=>{clearTimeout(a),i(d)},d=>{clearTimeout(a),u(d)})})}getDefaultTimeout(){return this.defaultTimeoutMs}};var lo=2e3,co=1e4,Dt=Be;function mo(e,t,r=Dt){let n=t!==void 0&&t>0?Math.floor(t):void 0;return n!==void 0&&n<=r?[]:e.nodes.filter(o=>o.included&&o.recordCountUnknown!==!0).map(o=>({objectApiName:o.objectApiName,rows:n===void 0?o.recordCount:Math.min(o.recordCount,n)})).filter(o=>o.rows>r).sort((o,s)=>s.rows-o.rows)}var tt=.8,N=1024,H=2*N,rt=4*N,Lt=8*N,Wt=1*N,Gt=4*N,Ut=255,qt=/__kav$/i,zt=new Map([C,W,G,"Campaign","CampaignMember"].map(e=>[e.toLowerCase(),e]));function V(e){return zt.get(e.toLowerCase())??e}function He(e,t=0){let r=0;for(let n of Object.values(e))typeof n=="string"&&n.length>t&&(r+=Buffer.byteLength(n,"utf8"));return r}function ie(e,t){let r=V(e);return r===C?He(t):r===W?re(t)?rt:H:r===G&&re(t)?0:r==="Campaign"?Lt:r==="CampaignMember"?Wt:qt.test(e)?Gt+He(t,Ut):H}function Ht(e,t){let r=Math.min(t.personAccounts??0,t.rows),n=t.rows-r,o=V(e);return o===W?n*H+r*rt:o===G?n*H:n*ie(e,{})}function Vt(e){let t=e.map(({objectApiName:m,rows:f,counted:p,mayAdd:h=0,mayBeByThePlatform:O})=>{let E={rows:h,storageBytes:h*ie(m,{}),...h>0?{mayAdd:h}:{},...O&&O.rows>0?{mayBeByThePlatform:O}:{}};return p?{objectApiName:m,...E,rows:p.rows+E.rows,storageBytes:Ht(m,p)+E.storageBytes}:{objectApiName:m,...E,rows:f.length+E.rows,storageBytes:f.reduce((J,kt)=>J+ie(m,kt),0)+E.storageBytes}}).filter(({rows:m})=>m>0).sort((m,f)=>f.rows-m.rows||m.objectApiName.localeCompare(f.objectApiName)),r=e.reduce((m,f)=>m+(f.leftOut?.writtenBefore??0),0),n=e.filter(m=>(m.leftOut?.heldBack??0)>0).map(({objectApiName:m,leftOut:f})=>({objectApiName:m,rows:f?.heldBack??0})),o=e.filter(m=>(m.leftOut?.byThePlatform??0)>0).map(({objectApiName:m,leftOut:f})=>({objectApiName:m,rows:f?.byThePlatform??0})),s=e.flatMap(({objectApiName:m,leftOut:f})=>f?.linkedByValue&&f.linkedByValue.rows>0?[{objectApiName:m,...f.linkedByValue}]:[]),i=m=>e.filter(f=>(f.leftOut?.[m]??0)>0).map(({objectApiName:f,leftOut:p})=>({objectApiName:f,rows:p?.[m]??0})),u=i("recordTypeNotInTarget"),a=i("withoutParent"),d=i("noParentInSource"),l=i("outsideFilter"),c=i("linkedToTarget"),g=i("currencyReplaced");return{objects:t,totalRows:t.reduce((m,f)=>m+f.rows,0),storageBytes:t.reduce((m,f)=>m+f.storageBytes,0),...r>0||n.length>0||u.length>0||o.length>0||s.length>0||a.length>0||d.length>0||l.length>0||c.length>0||g.length>0?{leftOut:{writtenBefore:r,heldBack:n,...u.length>0?{recordTypeNotInTarget:u}:{},...o.length>0?{byThePlatform:o}:{},...s.length>0?{linkedByValue:s}:{},...a.length>0?{withoutParent:a}:{},...d.length>0?{noParentInSource:d}:{},...l.length>0?{outsideFilter:l}:{},...c.length>0?{linkedToTarget:c}:{},...g.length>0?{currencyReplaced:g}:{}}}:{}}}function go(e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null])}var Kt=16,Ve=class{kept=new Map;note(t,r,n=Date.now()){this.kept.delete(t),this.kept.set(t,{at:n,total:r.totalRows,objects:r.objects.map(({objectApiName:o,rows:s})=>({objectApiName:o,rows:s}))});for(let o of this.kept.keys()){if(this.kept.size<=Kt)break;this.kept.delete(o)}}of(t){return this.kept.get(t)}},Xt=500;function Yt(e,t){return e>2*t||e-t>Xt}function fo(e,t,r=Date.now()){return{minutesBefore:Math.max(1,Math.ceil((r-e.at)/6e4)),total:e.total,objects:e.objects.map(({objectApiName:n,rows:o})=>({objectApiName:n,rows:o})),...Yt(t,e.total)?{farAbove:!0}:{}}}function po(e){let t=e.objects.reduce((r,n)=>r+(n.mayAdd??0),0);return t>0?{pricesForLines:t}:{}}function ho(e){let t=e.objects.find(r=>r.mayBeByThePlatform)?.mayBeByThePlatform;return!t||t.rows<=0?{}:{rolesMayBeByThePlatform:{rows:t.rows,...t.before===!0?{before:!0}:{}}}}var z=b({Max:w(),Remaining:w()}).loose(),Jt=b({DataStorageMB:z,DailyApiRequests:z.optional(),DailyBulkApiBatches:z.optional(),FileStorageMB:z.optional()}).loose(),Qt=b({DailyApiRequests:b({Max:w(),Remaining:w()}).loose()}).loose(),Zt="the org does not tell this user its daily API requests";function nt(e,t,r){if(e!==null&&typeof e=="object"&&!(t in e))throw new Error(r)}async function er(e){let t=await e.request({method:"GET",url:"/limits"});nt(t,"DataStorageMB",pe);let r=Jt.parse(t);return{maxMB:r.DataStorageMB.Max,remainingMB:r.DataStorageMB.Remaining,...r.DailyApiRequests?{dailyApiRequests:{max:r.DailyApiRequests.Max,remaining:r.DailyApiRequests.Remaining}}:{},...r.DailyBulkApiBatches?{dailyBulkApiBatches:{max:r.DailyBulkApiBatches.Max,remaining:r.DailyBulkApiBatches.Remaining}}:{},...r.FileStorageMB?{fileStorage:{maxMB:r.FileStorageMB.Max,remainingMB:r.FileStorageMB.Remaining}}:{}}}async function Ke(e){let t=await e.request({method:"GET",url:"/limits"});nt(t,"DailyApiRequests",Zt);let r=Qt.parse(t);return{max:r.DailyApiRequests.Max,remaining:r.DailyApiRequests.Remaining}}var ae=200,ot=2e3,tr=.1;function rr(e){return e.reduce((t,{rows:r,bulk:n,readRows:o,perCall:s})=>{let i=Math.min(ae,Math.max(1,s??ae)),u=r<=0?0:n?je(r):Math.ceil(r/i),a=o&&o>0?Math.ceil(o/ot):0;return t+u+a},0)}var le=["checkpoint","mute","readBack","deliverability","fit"],nr={checkpoint:"for the checkpoint taken first",mute:"to assign and take back the permission sets that mute the target's automation",readBack:"to read back the record types the target gave",deliverability:"to read whether the target delivers its emails",fit:"to fit the run to the storage"};function or(e){return le.reduce((t,r)=>t+Math.max(0,e[r]??0),e.run)}function sr(e){return le.some(t=>(e[t]??0)>0)?{...e}:void 0}function se(e,t){let r=typeof e=="number"?void 0:sr(e),n=typeof e=="number"?e:or(e),o=r?{parts:r}:{};if(!t)return{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyApiRequests",...o};if("unread"in t)return{verdict:"unread",estimate:n,unread:t.unread,...o};let{max:s,remaining:i}=t;return{verdict:n>i?"exceeds":i-n<tr*s?"near":"fits",estimate:n,max:s,remaining:i,...o}}function ir(e){if(!e)return"";let t=le.filter(r=>(e[r]??0)>0).map((r,n)=>`${e[r]}${n===0?" of them":""} ${nr[r]}`);return t.length>0?` (${t.join(", ")})`:""}var F="API_BUDGET_EXCEEDED";function ar(e,t){if(e.verdict==="exceeds")return`The run takes about ${e.estimate} API requests${ir(e.parts)}, and ${t} has ${e.remaining} of its ${e.max} daily requests left: it would stop part way through, its records refused with REQUEST_LIMIT_EXCEEDED. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records. Nothing was written.`}function ur(e){return e.verdict==="near"?{apiRequests:{estimate:e.estimate,remaining:e.remaining,max:e.max,...e.parts?{parts:{...e.parts}}:{}}}:{}}var K="CHECKPOINT_REFUSED";function dr(e){return e?{checkpoint:e.estimate.apiRequests}:{}}function lr(e){let t=e?.refusal;if(t!==void 0)return{code:K,message:ne(t),refusal:t}}var cr="The run was stopped while it took the checkpoint first: nothing of it was kept, and nothing was written.";async function bo(e){let t;try{t=await e()}catch(r){return{stop:{code:K,message:De(r)}}}return t.taken?{checkpoint:t.checkpoint}:"stopped"in t?{stop:{code:ze,message:cr}}:{stop:{code:K,message:ne(t.refusal),refusal:t.refusal}}}var Xe=1e4,mr=1e4,gr=.01;function fr(e,t,r){return t<2e3||_e.has(e)||(r??Me).has(e)}function X(e,t,r){if(t<=0)return{jobs:[],rest:0};if(fr(e,t,r.restOnly))return{jobs:[],rest:t};let n=[];for(let o=t;o>0;o-=Xe){let s=Math.min(o,Xe);if(s<2e3)return{jobs:n,rest:s};n.push(s)}return{jobs:n,rest:0}}function pr(e){return ve({stateReads:$e(e,xe,"save")})}function hr(e,t,r){let{jobs:n,rest:o}=X(e,t,r);return n.reduce((s,i)=>s+pr(i),0)+Math.ceil(o/ae)}var br=4,yr=3;function wr(e){let t=new Set(e.updatedAfterInsert??[]),r=new Map((e.plan.leftOut?.linkedByValue??[]).map(({objectApiName:a,rows:d})=>[a,d])),n=[...e.plan.objects.map(({objectApiName:a,rows:d})=>({objectApiName:a,rows:d+(r.get(a)??0)})),...[...r].filter(([a])=>!e.plan.objects.some(d=>d.objectApiName===a)).map(([a,d])=>({objectApiName:a,rows:d}))],o=e.plan.objects.filter(({objectApiName:a})=>t.has(a)).map(({objectApiName:a,rows:d})=>({objectApiName:a,rows:d})),{bulk:s}=e,i=e.files!==void 0&&e.files>0?e.files:0,u=s?br*n.filter(({rows:a})=>a>0).length:0;return{run:(s?[...n,...o].reduce((a,{objectApiName:d,rows:l})=>a+hr(d,l,s),0):rr([...n,...o]))+i+u+Math.max(0,e.sentBefore??0),...dr(e.checkpoint),...e.mute!==void 0&&e.mute>0?{mute:e.mute}:{},...e.readBack!==void 0&&e.readBack>0?{readBack:e.readBack}:{},...e.deliverability!==void 0&&e.deliverability>0?{deliverability:e.deliverability}:{}}}var Rr=200;function Ar(e){let t={...e.measures.restOnly?{restOnly:e.measures.restOnly}:{}},r=new Set(e.updatedAfterInsert??[]),n=e.plan.objects.map(({objectApiName:u,rows:a})=>({objectApiName:u,rows:a,writes:X(u,a,t),updates:r.has(u)?X(u,a,t):void 0})),o=n.flatMap(({writes:u,updates:a})=>a?[u,a]:[u]),s=e.measures.files,i=s&&"count"in s&&s.count>0?s.count:0;return{objects:n.map(({objectApiName:u,rows:a,writes:d})=>({objectApiName:u,rows:a,jobs:d.jobs.length})),sourceRequests:(e.measures.sourceReads??n.reduce((u,{rows:a})=>u+Math.ceil(Math.max(0,a)/ot),0)+i+Math.ceil(i/Rr))+yr*n.filter(({rows:u})=>u>0).length+(e.sourceSentBefore===void 0?Math.max(0,e.measures.heldReads??0):Math.max(0,e.sourceSentBefore)),bulkBatches:o.reduce((u,{jobs:a})=>u+a.reduce((d,l)=>d+Math.ceil(l/mr),0),0),durationSeconds:o.reduce((u,{jobs:a,rest:d})=>u+a.reduce((l,c)=>l+Ce(c,"save"),0)+d*gr,0),restObjects:n.filter(({rows:u,writes:a})=>u>0&&a.jobs.length===0).map(({objectApiName:u})=>u)}}var Er="the limits the org answered list no DailyBulkApiBatches";function Sr(e,t){if(e.verdict==="exceeds")return`The run writes through Bulk API jobs that take about ${e.estimate} of the daily Bulk API batches, and ${t} has ${e.remaining} of its ${e.max} left: its jobs would be refused part way through. Run it once the org has batches to spare \u2014 the limit is counted over the last 24 hours, and Bulk API 1.0 shares it \u2014 or leave objects out. Nothing was written.`}function Br(e,t){if(e.verdict==="exceeds")return`The run reads the source records in about ${e.estimate} API requests, and ${t} has ${e.remaining} of its ${e.max} daily requests left: the reads would stop part way through, and the org's own integrations with them. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or leave objects out. Nothing was written.`}function Or(e,t){if(e.verdict==="exceeds")return`The files to copy take about ${P(e.estimateMB)} MB of file storage, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB: leave out the objects whose files take it, turn the copy of files off on Review, or free file storage in ${t}. Nothing was written.`}function kr(e,t){return`A clone of the whole org reads a few objects whole, and ${e.map(({objectApiName:n,rows:o})=>`${n} (${o} rows)`).join(", ")} ${e.length===1?"holds":"hold"} more than the ${t} rows of one object the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting or leave the object out on Review. Nothing was written.`}var Tr=200;function Pr(e){if(!e||e.length===0)return;let t=Math.min(...e.map(n=>n.bound)),r=e.map(({objectApiName:n,rows:o})=>({objectApiName:n,rows:o}));return{code:"READ_BOUND_EXCEEDED",message:kr(r,t),readBound:{bound:t,objects:r.slice(0,Tr)}}}var st="FILES_UNREAD",it="FILE_STORAGE_UNREAD";function xr(e,t,r){if(!e)return{};if("unmeasured"in e)return{files:{unmeasured:!0},stop:{code:st,message:`The source would neither sum nor list its files, so what they take of the file storage ${r} has left is not known: turn the copy of files off on Review, or run it again once the source answers. Nothing was written.`}};if(e.count<=0)return{};let n=at({storageBytes:e.bytes},"unread"in t?t:t.fileStorage??{unread:"the limits the org answered list no FileStorageMB"});if(n.verdict==="unread")return{files:{count:e.count,check:n},stop:{code:it,message:`The file storage ${r} has left could not be read (${n.unread}), so the ${e.count} files to copy could not be checked against it: turn the copy of files off on Review, or run it again once the org answers. Nothing was written.`}};let o=Or(n,r);return{files:{count:e.count,check:n},...o!==void 0&&n.verdict==="exceeds"?{stop:{code:"STORAGE_EXCEEDED",message:o,storage:{estimateMB:Number(P(n.estimateMB)),remainingMB:n.remainingMB,kind:"files"}}}:{}}}function vr(e){let t=e.wholeOrg,r=t?.measures.files,n=se(wr({...e,...t?{bulk:t.measures.restOnly?{restOnly:t.measures.restOnly}:{},...r&&"count"in r?{files:r.count}:{}}:{}}),e.budget),o=ar(n,e.target),s=[],i=lr(e.checkpoint);i&&s.push(i),o!==void 0&&s.push({code:F,message:o,...t&&n.verdict==="exceeds"?{api:{kind:"requests",org:"target",estimate:n.estimate,remaining:n.remaining}}:{}});let u;if(t){let c=Ar({...e,measures:t.measures,...t.sourceSentBefore!==void 0?{sourceSentBefore:t.sourceSentBefore}:{}}),g=c.bulkBatches>0?se(c.bulkBatches,t.bulkBatches??{unread:Er}):void 0,m=g&&Sr(g,e.target);m!==void 0&&g?.verdict==="exceeds"&&s.push({code:F,message:m,api:{kind:"bulkBatches",org:"target",estimate:g.estimate,remaining:g.remaining}});let f=se(c.sourceRequests,t.sourceBudget),p=Br(f,t.source);p!==void 0&&f.verdict==="exceeds"&&s.push({code:F,message:p,api:{kind:"requests",org:"source",estimate:f.estimate,remaining:f.remaining}}),u={source:f,...g?{bulkBatches:g}:{},cost:c}}let[a,...d]=s,l=d.filter(c=>c.code===F);return{api:n,...a?{stop:a}:{},...t&&l.length>0?{alsoRefused:l}:{},...u?{wholeOrg:u}:{},asks:e.checkpoint!==void 0||t!==void 0,confirmation:{...ur(n),...e.checkpoint?{checkpoint:e.checkpoint}:{}}}}function at(e,t,r=0){let n=Math.max(0,r),o=e.storageBytes+n,s=o/1048576,i=n>0?{automationMB:n/1048576}:{};if("unread"in t)return{verdict:"unread",estimateMB:s,unread:t.unread,...i};let{maxMB:u,remainingMB:a}=t;return{verdict:o>a*1048576?"exceeds":o>tt*a*1048576?"near":"fits",estimateMB:s,maxMB:u,remainingMB:a,...i}}function Cr(e,t){if(!t||t.length===0)return 0;let r=new Map;for(let{objectApiName:n,bytes:o}of t)r.set(n,(r.get(n)??0)+Math.max(0,o));return e.objects.reduce((n,{objectApiName:o,rows:s})=>n+s*(r.get(o)??0),0)}function ut(e){return`about ${P(e.estimateMB)} MB of data storage`+(e.automationMB!==void 0&&e.automationMB>0?`, about ${P(e.automationMB)} MB of it for what the target's automation creates under them`:"")}function $r(e,t){let r=Vt(e),n=t.emailTextBytes,o=e.some(i=>V(i.objectApiName)===C&&i.counted);if(n===void 0||!Number.isFinite(n)||!o)return r;let s=r.objects.map(i=>V(i.objectApiName)===C?{...i,storageBytes:i.storageBytes+Math.max(0,n)}:i);return{...r,objects:s,storageBytes:s.reduce((i,u)=>i+u.storageBytes,0)}}function jr(e,t,r){return e.flatMap(({objectApiName:n,included:o,piiFields:s,anonymizeFields:i})=>{if(!o||!t.has(n))return[];let u=new Set(r?i:[]),a=s.filter(d=>!u.has(d));return a.length>0?[{objectApiName:n,fields:a}]:[]})}function Fr(e){let t=e.leftOut??[],r=new Set(t.map(({objectApiName:s})=>s)),n=[...t,...e.nodes.filter(s=>s.leftOutByUser===!0&&!r.has(s.objectApiName)).map(({objectApiName:s})=>({objectApiName:s,reason:"excludedByUser"}))],o=new Map;for(let{reason:s}of n)o.set(s,(o.get(s)??0)+1);return{objects:n,counts:[...o].map(([s,i])=>({reason:s,count:i})).sort((s,i)=>i.count-s.count||s.reason.localeCompare(i.reason))}}var _r=2;async function yo(e){let t=h=>({unread:R(h)}),r=$r(e.objects,e.measures),n=await er(e.target.limits).catch(t),o="unread"in n?await Ke(e.target.limits).catch(t):n.dailyApiRequests,s=await Ke(e.source.limits).catch(t),i=at(r,n,Cr(r,e.automation)),u=pn(i,e.target.org),a=e.sample?Wr({sample:e.sample,storage:n,target:e.target.org}):void 0,d=xr(e.measures.files,n,e.target.org),l=e.sentBefore?.(),c=vr({plan:r,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...e.readBack!==void 0?{readBack:e.readBack}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{},...e.mute!==void 0?{mute:e.mute}:{},deliverability:e.deliverability??_r,...l?{sentBefore:l.target}:{},budget:o,target:e.target.org,wholeOrg:{measures:e.measures,bulkBatches:"unread"in n?n:n.dailyBulkApiBatches,sourceBudget:s,source:e.source.org,...l?.source!==void 0?{sourceSentBefore:l.source}:{}}}),g=[Pr(e.measures.readWholeOver),a,a===void 0&&u!==void 0&&i.verdict==="exceeds"?{code:"STORAGE_EXCEEDED",message:`${u} Nothing was written.`,storage:{estimateMB:Number(P(i.estimateMB)),remainingMB:i.remainingMB}}:void 0,d.stop,c.stop,...c.alsoRefused??[]].filter(h=>h!==void 0),m=e.measures.restOnly?{restOnly:e.measures.restOnly}:{},f=new Set(r.objects.map(({objectApiName:h})=>h)),{wholeOrg:p}=c;return{wouldInsert:r.objects.map(({objectApiName:h,rows:O})=>{let{jobs:E,rest:J}=X(h,O,m);return{objectApiName:h,rows:O,jobs:E.length,byRest:J}}),totalRows:r.totalRows,targetRequests:c.api,sourceRequests:p.source,...p.bulkBatches?{bulkBatches:p.bulkBatches}:{},storage:i,...d.files?{files:d.files}:{},durationSeconds:p.cost.durationSeconds,leftOut:{...Fr(e.graph),...r.leftOut?{rows:r.leftOut}:{}},personalAsIs:jr(e.graph.nodes,f,e.anonymizePII),wouldBeRefused:g,...e.sample?{sample:e.sample}:{}}}var Mr="SAMPLE_STORAGE_UNREAD",dt="SAMPLE_CANNOT_FIT",Nr="SAMPLE_TOO_LARGE",lt="SAMPLE_PLAN_MISMATCH",ue="SAMPLE_PLAN_GONE";function Ir(e){let{storage:t,bounds:r,target:n}=e;if("unread"in t&&!(r.withinMB!==void 0||r.maxTotal!==void 0))return{code:Mr,message:`The data storage ${n} has left could not be read (${t.unread}), and a sample is fitted to it: there is nothing to hold it to. Give the most it may take (--fit-within <MB>) or the most records (--max-total <n>), or run it again once the org answers. Nothing was written.`}}function Dr(e,t){if(e.remainingMB===void 0||e.share===void 0)return;let r=Math.max(0,t.remainingMB-(e.roundingMB??0));return Math.floor(e.share*r*1048576)}function Lr(e){let{sample:t,storage:r,target:n}=e,o=Dr(t.budget,r);if(o===void 0||t.storageBytes<=o)return;let s=Et(t.storageBytes/1048576,o/1048576),i=P(t.budget.bytes/1048576);return{code:"STORAGE_EXCEEDED",message:`The sample was fitted to ${i} MB of the data storage ${n} had left (${t.budget.remainingMB} MB), and ${n} now says ${r.remainingMB} MB left, which holds ${s.bound} MB of a sample: the sample takes about ${s.over} MB. Simulate again \u2014 run the dry run again \u2014 to draw a sample that fits: a run never cuts its sample short. Nothing was written.`,storage:{estimateMB:Number(s.over),remainingMB:r.remainingMB},sample:{fittedMB:Number(i),holdsMB:Number(s.bound)}}}function Wr(e){let{sample:t,storage:r,target:n}=e;return"unread"in r?Ir({storage:r,bounds:t.budget,target:n}):Lr({sample:t,storage:r,target:n})}var Gr=new Set(["gone","changed","otherOrg","otherSetup","otherSha"]),Ur={changed:"is no longer as its dry run wrote it: its ids changed since",otherOrg:"was drawn of another org than the source",otherSetup:"was drawn for another setup of the run \u2014 other flags, filters, objects or options of the sample",otherSha:"is not the plan its dry run printed"};function qr(e,t){return t==="resume"?{code:ue,message:`The plan of the sample this run resumes ${e==="gone"?"is no longer on this machine":"is no longer as it was written"}: the records it was to write cannot be taken up after where it stopped (--resume). Remove what it wrote (--remove), or run the clone again without --resume to draw a new sample. Nothing was written.`,sample:{plan:e}}:e==="gone"?{code:ue,message:'No plan of a sample is at the path given to --fit-plan: give the folder its dry run printed ("sample plan: \u2026"), within a day of it, or leave --fit-plan out to draw a new sample. Nothing was written.',sample:{plan:e}}:{code:lt,message:`The plan given to --fit-plan ${Ur[e]}: run the dry run again with the flags of this run, and replay the plan it prints. Nothing was written.`,sample:{plan:e}}}var zr=new Set([Nr,dt,ue,lt]),Hr=20;function wo(e,t){if(e instanceof Error){if(e.name==="SampleRefusedError"){let{code:r,heaviest:n,sample:o}=e;if(typeof r!="string"||!zr.has(r))return;let s=Array.isArray(n)?n.flatMap(a=>{let d=a?.objectApiName;return typeof d=="string"?[d]:[]}):[],i=ke({code:r,sample:o})?.sample??{},u={...i,...r===dt&&i.heaviest===void 0&&s.length>0?{heaviest:s.slice(0,Hr)}:{}};return B.of({code:r,message:e.message,...Object.keys(u).length>0?{sample:u}:{}})}if(e.name==="SamplePlanError"&&t!=="draw"){let{refusal:r}=e;return typeof r!="string"||!Gr.has(r)?void 0:B.of(qr(r,t))}}}var Vr=b({SingleEmail:b({Max:w(),Remaining:w()}).loose().optional(),DailyWorkflowEmails:b({Max:w(),Remaining:w()}).loose().optional()}).loose();async function Ro(e){let t=Vr.parse(await e.request({method:"GET",url:"/limits"})),r={};for(let n of["SingleEmail","DailyWorkflowEmails"]){let o=t[n];o&&(r[n]={max:o.Max,remaining:o.Remaining})}return r}var Kr=15;function ct(e){let t=e.SingleEmail;return t!==void 0&&t.max<=Kr}function Xr(e){return ct(e)&&e.DailyWorkflowEmails!==void 0}function Yr(e,t,r=!1){let n=e.map(u=>({...u,sentBy:[...u.sentBy]})),o=(u,a)=>{let d=n.find(l=>l.objectApiName===u.objectApiName&&l.limit===a);if(!d){let l={...u,limit:a,sentBy:[...u.sentBy]};return n.push(l),l}d.perRecord+=u.perRecord;for(let l of u.sentBy)d.sentBy.includes(l)||d.sentBy.push(l);return d},s=e.filter(u=>u.limit==="SingleEmail"),i=e.filter(u=>u.limit==="DailyWorkflowEmails");if(r)for(let u of s)o(u,"DailyWorkflowEmails");if(t)for(let u of i)o(u,"SingleEmail").alertsAmong=!0;return n}function mt(e){let t=new Map(e.objects.map(r=>[r.objectApiName,{rows:r.rows,byThePlatform:0}]));for(let{objectApiName:r,rows:n}of e.leftOut?.byThePlatform??[]){let o=t.get(r)??{rows:0,byThePlatform:0};t.set(r,{rows:o.rows+n,byThePlatform:o.byThePlatform+n})}return t}function ce(e){return new Set([...mt(e)].flatMap(([t,{rows:r}])=>r>0?[t]:[]))}function Jr(e,t,r){let n=mt(e),o=new Map;for(let i of t){let{rows:u,byThePlatform:a}=n.get(i.objectApiName)??{rows:0,byThePlatform:0};if(u===0)continue;let d=o.get(i.limit)??{limit:i.limit,objects:[],emails:0,verdict:"fits"};d.objects.push({objectApiName:i.objectApiName,rows:u,perRecord:i.perRecord,sentBy:i.sentBy,...a>0?{byThePlatform:a}:{}}),d.emails+=u*i.perRecord,o.set(i.limit,d)}let s=Y(r)?r.unread:void 0;return[...o.values()].map(i=>{if(s!==void 0||Y(r))return{...i,verdict:"unread",unread:s};let u=r[i.limit];return u?{...i,verdict:i.emails>u.remaining?"exceeds":"fits",remaining:u.remaining,max:u.max}:{...i,verdict:"unread",unread:`the org's limits list no ${i.limit}`}})}function Y(e){return typeof e.unread=="string"}function Qr(e,t,r){let n=!Y(r)&&ct(r),o=!Y(r)&&Xr(r),s=Jr(e,Yr(t,n,o),r);if(!n)return s;let i=ce(e);return t.some(a=>a.limit==="DailyWorkflowEmails"&&i.has(a.objectApiName))?s.map(a=>a.limit==="SingleEmail"?{...a,alertsCounted:!0}:a):s}async function Ao(e){if(e.plan.totalRows===0||e.objects.length===0)return{checks:[]};let t;try{t=await e.readAutomation(e.objects)}catch(i){return{checks:[],unread:`the target's automation: ${R(i)}`}}let r=en(t,Zr(e.plan)),n=r!==void 0?{unread:r}:{},o=we(t);if(o.length===0)return{checks:[],...n};let s=await e.readLimits().catch(i=>({unread:R(i)}));return{checks:Qr(e.plan,o,s),...n}}function Zr(e){let t=ce(e);return(r,n)=>n==="insert"&&t.has(r)}function en(e,t,r="the target's"){let n=[gt(e.unread,r),nn(e,t)].filter(o=>o!==void 0).join("; ");return n!==""?n:void 0}var tn={flows:"flows",processes:"processes",workflowRules:"workflow rules"};function gt(e,t){let r=e.flatMap(({part:n,reason:o})=>{let s=tn[n];return s!==void 0?[`${t} ${s}: ${o}`]:[]});return r.length>0?r.join("; "):void 0}var k=10;function rn(e){if(e.condition!=="unreadable")return;let t=e.apiName.indexOf("__");return t>0?e.apiName.slice(0,t):void 0}function nn(e,t){let r=e.objects.flatMap(o=>{let i=[...new Set(be(o).filter(a=>t(o.objectApiName,a.write)).flatMap(a=>a.fired).flatMap(({flow:a,keptQuiet:d})=>a!==void 0&&d!==!0&&a.condition!=="read"&&a.timing!=="beforeSave"?[a]:[]))].map(a=>{let d=rn(a);return d!==void 0?`${a.label} (package ${d}, whose flows the org lets no one read)`:a.label});if(i.length===0)return[];let u=i.length>k?` and ${i.length-k} more`:"";return[{count:i.length,words:`${i.slice(0,k).join(", ")}${u} on ${o.objectApiName}`}]});return r.length===0?void 0:`the definition${r.reduce((o,{count:s})=>o+s,0)===1?"":"s"} of ${r.map(({words:o})=>o).join("; ")}`}function Eo(e){return{limit:e.limit,emails:e.emails,remaining:e.remaining??0,max:e.max??0,objects:e.objects.map(({objectApiName:t,perRecord:r})=>({objectApiName:t,perRecord:r})),...e.alertsCounted?{alertsCounted:!0}:{}}}function So(e){return{limit:e.limit,emails:e.emails,unread:e.unread??""}}var on={SingleEmail:{one:"single email",more:"single emails"},DailyWorkflowEmails:{one:"workflow email",more:"workflow emails"}};function ft(e,t){let r=on[t];return`${e} ${e===1?r.one:r.more}`}function sn(e,t){return e.alertsCounted?`, its email alerts among them: ${t} counts them against its single emails, as a Developer Edition does`:""}function Bo(e,t){let r=e.filter(o=>o.verdict==="exceeds");if(r.length===0)return;let n=r.map(o=>`about ${ft(o.emails,o.limit)}`+(o.alertsCounted?" (its email alerts among them, as a Developer Edition counts them)":"")+`, ${o.remaining??0} of ${o.max??0} left today`).join("; ");return`The target's automation would make ${t} send ${n}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. Assign the user a bypass that keeps what sends quiet, or write fewer records.`}function Oo(e,t){return e.map(r=>{let n=r.objects.map(s=>`${s.perRecord} per ${s.objectApiName}, by ${s.sentBy.join(", ")}`+(s.byThePlatform?`; ${s.byThePlatform} ${s.objectApiName} written by the platform with ${$(s.objectApiName)}, whose flows run all the same`:"")).join("; "),o=` emails: these records make ${t} send about ${ft(r.emails,r.limit)} (${n})`+sn(r,t);return r.verdict==="unread"?`${o}; what it has left today could not be read (${r.unread??""})`:r.verdict==="fits"?`${o}; it has ${r.remaining??"?"} of ${r.max??"?"} left today`:`${o}, more than the ${r.remaining??"?"} of ${r.max??"?"} it has left today: past them the action fails, and a record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER). A bypass that keeps the flow quiet, or a smaller run, avoids it`})}var pt="EMAILS_NOT_ACCEPTED";function ht(e,t={}){let r=[gt(e,"the target's"),...t.applyAssignmentRules===!0?e.filter(({part:n})=>n==="assignmentRules").map(({reason:n})=>`the target's assignment rules: ${n}`):[]].filter(n=>n!==void 0);return r.length>0?r.join("; "):void 0}function ko(e){return"requests"in e&&typeof e.requests=="number"?Math.max(0,e.requests):Ne}function To(e){let t=e?.read?.requests??0;return t>0?{deliverability:t}:{}}var bt={clone:{run:"this clone",allTheSame:"to clone all the same"},sync:{run:"this sync",allTheSame:"to sync all the same"},seed:{run:"this seed",allTheSame:"to seed all the same"},autopilot:{run:"this Autopilot run",allTheSame:"to run it all the same"},rewind:{run:"this rewind",allTheSame:"to rewind all the same"},undo:{run:"this undo",allTheSame:"to undo all the same"},masking:{run:"this masking",allTheSame:"to mask all the same"},restore:{run:"this restore",allTheSame:"to restore all the same"},cleanup:{run:"this cleanup",allTheSame:"to delete all the same"},empty:{run:"this emptying",allTheSame:"to empty all the same"},load:{run:"this load",allTheSame:"to load all the same"}},an={flow:"flow",process:"process",workflowRule:"workflow rule",assignmentRule:"assignment rule"},un={email:"",notRead:" (its definition was not read)",assignment:" (applied: it can mail the owner it assigns)"};function yt(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function _(e){let t=new Map;for(let r of e){let n=t.get(r.objectApiName)??[];n.push(`${an[r.kind]} "${r.name}"${un[r.why]}`),t.set(r.objectApiName,n)}return[...t].map(([r,n])=>{let o=n.length>k?[...n.slice(0,k),`${n.length-k} more`]:n;return`${yt(o)} on ${r}`}).join("; ")}var Ye="read with one line of anonymous Apex that sends nothing";function wt(e){return"level"in e&&e.level==="withheld"}function dn(e){return"unread"in e?`deliverability: not read (${e.unread}) \u2014 the run is refused without --accept-emails, as on All email`:e.level==="all"?`deliverability: All email \u2014 the emails of what still runs go out (${Ye})`:`deliverability: System email only or No access \u2014 none of the emails its flows, processes, workflow rules and Apex send goes out, and the org still counts them against its daily email limits (${Ye})`}function ln(e,t){let{run:r,allTheSame:n}=bt[e.run],{target:o}=e,s=_(e.senders),i=e.sendersUnread,u=s!==""?`what still runs as ${r} writes its records sends some: ${s}`+(i!==void 0?`; what could not be read may send more (${i})`:""):`what runs as ${r} writes its records could not all be read (${i??""}), so it may send some`,a=[];"unread"in t?a.push(`Whether ${o} delivers the emails its automation sends could not be read (${t.unread}), and ${u}.`,`Nothing was written. Add --accept-emails ${n}, or check Setup > Deliverability: on System email only or No access, none of them goes out.`):a.push(`${o} delivers every email its automation sends (Setup > Deliverability: All email), and ${u}.`,e.keepsAddresses===!0?`They go to the addresses the records and the alerts name: those of the records ${r} writes, as they hold them, the records' owners, the records already in ${o}, and an address an alert names.`:`They go to the addresses the records and the alerts name: those ${r} writes are under .invalid, but not the records' owners, the records already in ${o}, nor an address an alert names.`,`Nothing was written. Add --accept-emails ${n}, set the org's deliverability to System email only, or turn off what sends them.`);let d=e.muteQuiets??[];if(d.length>0){let l=new Set(d.map(g=>`${g.objectApiName}\0${g.kind}\0${g.name}`)),c=e.senders.filter(g=>!l.has(`${g.objectApiName}\0${g.kind}\0${g.name}`));a.push(`--mute-automation keeps quiet ${_(d)}, which ${d.length===1?"tests":"test"} a bypass a permission set of ${o} holds`+(c.length>0?`; it cannot quiet ${_(c)}.`:"."))}return a.join(" ")}function Rt(e){if(e.senders.length===0&&e.sendersUnread===void 0)return{verdict:"nothingSends",confirmation:{}};let t=e.reading??{unread:"the run did not read it"},r={reading:t,senders:[...e.senders],...e.sendersUnread!==void 0?{sendersUnread:e.sendersUnread}:{}},n=dn(t);return wt(t)?{verdict:"withheld",deliverability:r,confirmation:{},line:n,audit:"withheld"}:{verdict:"asks",deliverability:r,confirmation:{deliverability:e.keepsAddresses===!0?{...r,keepsAddresses:!0}:r},...e.accepted?{}:{stop:{code:pt,message:ln(e,t)}},line:n,audit:"unread"in t?"unread":"all"}}function Po(e,t){let r=ce(t);return e.filter(n=>!r.has(n.objectApiName))}function xo(e){if(e.length===0)return;let t=[...new Set(e.map(r=>r.objectApiName))];return` emails: ${_(e)} send nothing: the run writes no ${yt(t)} record. A real run is refused all the same, and names them: it asks before it reads which records it writes`}function At(e){let t=a=>`${a.objectApiName}\0${a.kind}\0${a.name}`,r=new Set(e.planned.map(t)),n=e.held.filter(a=>!r.has(t(a)));if(n.length===0||e.accepted)return;let o=e.reading;if(o!==void 0&&wt(o))return;let{run:s,allTheSame:i}=bt[e.run],u=o===void 0?`whether ${e.target} delivers them was not read, as nothing that sends one was to run`:"unread"in o?`whether ${e.target} delivers them could not be read (${o.unread})`:`${e.target} delivers every one of them (All email)`;return{code:pt,relit:n,message:`The mute's lease does not hold every permission set it was to assign, and what they were to keep quiet still runs for ${s}: ${_(n)} may send emails, and ${u}. The run's question did not ask about them. Nothing was written. Add --accept-emails ${i}, or run it again once the lease can assign them.`}}function vo(e){return e.verdict==="unread"?{estimateMB:e.estimateMB,unread:e.unread}:{estimateMB:e.estimateMB,maxMB:e.maxMB,remainingMB:e.remainingMB,near:e.verdict==="near"}}function P(e){return de(e,e<10?2:1)}function de(e,t){if(e<=0)return"0";let r=10**t;return(Math.ceil(e*r-1e-9)/r).toString()}function Et(e,t){let r={over:e<10?2:1,bound:t<10?2:1};for(;;){let n={over:de(e,r.over),bound:de(t,r.bound)},o=Math.max(r.over,r.bound);if(Number(n.over)>Number(n.bound)||o>=6)return n;r={over:o+1,bound:o+1}}}function St(e){return e.map(({objectApiName:t,kind:r,name:n})=>({objectApiName:t,kind:r,name:n}))}function cn(e){return St(ee(e,"insert"))}function mn(e,t){let r=new Set(t);return St(ee(e,"update",n=>r.has(n)))}var Bt=["lookups","statuses","invitees","retry","upsert"];function Co(e,t={}){let r=Ie(e,t.leftOut),n=new Set(r),o=new Map,s=(l,c)=>{if(!n.has(l))return;let g=o.get(l)??new Set;g.add(c),o.set(l,g)},i=e.edges.filter(l=>Fe(l)&&n.has(l.sourceObject)&&n.has(l.targetObject)),u=new Map;for(let{sourceObject:l,targetObject:c}of i)l!==c&&u.set(l,[...u.get(l)??[],c]);let a=(l,c)=>{let g=new Set([l]),m=[l];for(let f=m.shift();f!==void 0;f=m.shift())for(let p of u.get(f)??[]){if(p===c)return!0;g.has(p)||(g.add(p),m.push(p))}return!1},d=i.filter(l=>l.required!==!0&&l.insertOnly!==!0);for(let{sourceObject:l,targetObject:c}of d)(l===c||a(c,l))&&s(c,"lookups");for(let l of Object.keys(Pe))s(l,"statuses");for(let l of Object.keys(Te))s(l,"invitees");if(t.retry===!0)for(let{sourceObject:l,targetObject:c}of d)l!==c&&s(c,"retry");if(t.upsert===!0)for(let l of r)s(l,"upsert");return r.flatMap(l=>{let c=o.get(l);return c?[{objectApiName:l,steps:Bt.filter(g=>c.has(g))}]:[]})}function gn(e){let t=new Set(e.flatMap(r=>r.steps));return Bt.filter(r=>t.has(r))}function $o(e,t=[]){let r=new Set(t);return Re(e,(n,o)=>o==="insert"||o==="update"&&r.has(n))}function jo(e,t,r){let n=new Set(ye(e).map(i=>i.toLowerCase())),o=t.filter(i=>!n.has(i.toLowerCase())),s=Ae(e,o);return o.map(i=>{let u=s.find(d=>d.permission.toLowerCase()===i.toLowerCase()),a=u?.permissionSet?.name;return{permission:i,...a?{permissionSet:a}:{},others:u?.others.map(d=>d.name)??[],...u&&!a?{noneHolds:!0}:{},...a&&r?.alias&&r.username?{command:Ee(a,r.alias,r.username)}:{}}})}function fn(e){return e==="flows"||e==="triggers"||e==="processes"||e==="workflowRules"||e==="automation"}function I(e){return e.unread.flatMap(({part:t,reason:r})=>fn(t)?[{part:t,reason:r}]:[])}var Fo="OWNER_MAP_INACTIVE",_o="OWNER_MAP_UNKNOWN",B=class e extends Error{code;storage;ceiling;reason;api;readBound;sample;constructor(t,r,n,o,s,i){super(r),this.name="ForgeRunGateError",this.code=t,n&&(this.storage=n),o!==void 0&&(this.ceiling=o),s!==void 0&&(this.reason=s),i?.api&&(this.api=i.api),i?.readBound&&(this.readBound=i.readBound),i?.sample&&(this.sample=i.sample)}static of(t){return new e(t.code,t.message,t.storage,void 0,t.refusal?.code,{...t.api?{api:t.api}:{},...t.readBound?{readBound:t.readBound}:{},...t.sample?{sample:t.sample}:{}})}get stop(){if(Oe(this.code))return{code:this.code,...this.storage?{storage:this.storage}:{},...this.ceiling!==void 0?{ceiling:this.ceiling}:{},...this.reason!==void 0&&this.code===K?{reason:this.reason}:{},...this.api&&this.code===F?{api:this.api}:{},...this.readBound&&this.code==="READ_BOUND_EXCEEDED"?{readBound:this.readBound}:{},...this.sample?{sample:this.sample}:{}}}};function Mo(e){return e instanceof B||e instanceof Error&&e.name==="ForgeRunGateError"&&typeof e.code=="string"}var Je="FILE_STORAGE_EXCEEDED";function No(e){if(!(e instanceof Error)||e.name!=="ForgeFilesRefusedError")return;let{code:t,storage:r}=e;if(t===st||t===it)return new B(t,e.message);let n=r?.neededBytes,o=r?.remainingBytes;if(t!==Je||typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o))return;let s=o/1048576;return new B(Je,e.message,{estimateMB:Number(Et(n/1048576,s).over),remainingMB:s,kind:"files"})}function pn(e,t){if(e.verdict==="exceeds")return`The records to write take ${ut(e)}, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB: leave objects out, lower the records per object, or free data storage in ${t}.`}var Qe=10;function Io(e,t,r){let n=[`write gate: ${e.totalRows} record(s) to write to ${r}, ${ut(t)}`];for(let s of e.objects.slice(0,Qe))n.push(` ${s.objectApiName.padEnd(42)}${String(s.rows).padStart(8)}`);let o=e.objects.slice(Qe);if(o.length>0){let s=o.reduce((i,u)=>i+u.rows,0);n.push(` and ${o.length} more object(s), ${s} record(s)`)}for(let{objectApiName:s,mayAdd:i}of e.objects)i!==void 0&&n.push(` counted in: up to ${i} ${s} record(s) the run may read as it writes them, a price in the currency of the record its lines belong to, the source's own beside the one read`);for(let{objectApiName:s,mayBeByThePlatform:i}of e.objects)i!==void 0&&n.push(` counted in: up to ${i.rows} ${s} record(s) the platform `+(i.before===!0?`may have written with ${$(s)}, in the run this one takes up`:`may write itself with ${$(s)}`)+", which the run then links to and does not send");return n.push(...hn(e.leftOut)),t.verdict==="unread"?(n.push(` the data storage ${r} has left could not be read (${t.unread}): whether the records fit is not known`),n):(n.push(` data storage of ${r}: ${t.remainingMB} MB left of ${t.maxMB} MB`),t.verdict==="near"&&n.push(` that is more than ${Math.round(tt*100)} % of what ${r} has left: Salesforce counts storage a while after a load, so less may be left than it says`),n)}function hn(e){if(!e)return[];let t=[];e.writtenBefore>0&&t.push(` not counted: ${e.writtenBefore} record(s) the run it retries or resumes wrote, which it links to and does not write again`);for(let{objectApiName:r,rows:n}of e.heldBack)t.push(` not counted: ${r}, ${n} record(s), held back for a record type closed to the user the run writes as`);for(let{objectApiName:r,rows:n}of e.recordTypeNotInTarget??[])t.push(` not counted: ${r}, ${n} record(s), held back for a record type the target has none of, which it would refuse`);for(let{objectApiName:r,rows:n}of e.withoutParent??[])t.push(` not counted: ${r}, ${n} record(s) held back with a record they cannot be written without, held back itself`);for(let{objectApiName:r,rows:n}of e.noParentInSource??[])t.push(` not counted: ${r}, ${n} record(s) left aside: a lookup they may not leave empty names a record the source does not hold, which no copy can write`);for(let{objectApiName:r,rows:n}of e.outsideFilter??[])t.push(` not counted: ${r}, ${n} record(s) left aside: a lookup they may not leave empty names a record outside its object's filter, which the run does not copy`);for(let{objectApiName:r,rows:n}of e.byThePlatform??[])t.push(` not counted: ${r}, ${n} record(s) written by the platform with ${$(r)}, which the run links to and does not send`);for(let{objectApiName:r,rows:n,fields:o}of e.linkedByValue??[])t.push(` not counted: ${r}, ${n} record(s) the target holds under the same ${o.join(", ")}, which the run links to and does not create`);for(let{objectApiName:r,rows:n}of e.linkedToTarget??[])t.push(` not counted: ${r}, ${n} record(s), the standard price book: linked to the target's own, never written`);for(let{objectApiName:r,rows:n}of e.currencyReplaced??[])t.push(` not counted: ${r}, ${n} record(s) in a currency the target lacks, replaced by the source's own price in the currency written, for the same product and price book`);return t}var bn={flow:e=>`flow "${e}" runs before a record is deleted, and can refuse the delete`,trigger:e=>`Apex trigger ${e} runs on a delete, and can refuse it`,packageTrigger:e=>`Apex trigger ${e}, installed by a managed package, runs on a delete and can refuse it; no one in the org can change it`,lock:()=>"once activated, a record locks the records under it, which a removal then takes only with it, or once it is back in Draft"},yn=["flows","triggers"];function Do(e,t,r=[],n="--remove"){let o=yn.filter(i=>r.some(u=>u.part===i)),s=o.length===0?[]:[` ${o.map(i=>A[i]).join(" and ")} could not be read: whether one refuses the removal is not known`];if(e.length===0&&o.length===0)return[`reversibility: nothing found in ${t} that refuses a removal of this run's records (no flow before a delete, no Apex trigger on one, no record that locks past Draft)`];if(e.length===0){let i=[...o.includes("flows")?[]:["no flow before a delete"],...o.includes("triggers")?[]:["no Apex trigger on a delete"],"no record that locks past Draft"];return[`reversibility: nothing found in ${t} that refuses a removal of this run's records in what could be read (${i.join(", ")})`,...s]}return[`reversibility: a removal of this run's records (${n}) may be refused in ${t}:`,...e.map(({objectApiName:i,kind:u,name:a})=>` ${i}: ${bn[u](a??"")}`),...s]}var A={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function S({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}var wn={lookups:"a lookup filled in once its record exists",statuses:"an order or a contract given back its status after it went in as a draft",invitees:"an event's invitee given its answer",retry:"a lookup the run it retries left empty filled in",upsert:"a record the target holds written over by --upsert"};function T(e){return e.map(t=>`${t.objectApiName}: ${S(t)}`).join("; ")}function me(e,t,r){return e.flatMap(n=>{if(n.command){let o=n.others.length>0?`; ${n.others.join(", ")} hold${n.others.length===1?"s":""} it too`:"";return[`${n.permissionSet} is the smallest permission set of ${t} that holds ${n.permission}${o}. Assigned to the user ${r} writes as, it keeps quiet what ${n.permission} excludes: ${n.command}`]}return n.noneHolds?[`No permission set of ${t} holds ${n.permission}: an admin creates one that includes it, and assigns it to the user ${r} writes as.`]:[]})}function ge(e,t,r){let n=[...new Set(e.flatMap(o=>o.permissionSet??[]))];return!r||n.length===0?[]:[`With --mute-automation, the ${t} assigns ${n.join(", ")} to the user it writes as for the ${t} alone, under a lease, and what ${n.length===1?"it keeps":"they keep"} quiet does not fire.`]}function Lo(e,t,r={}){let n=r.updated??[],o=cn(e),s=mn(e,n.map(d=>d.objectApiName)),i=I(e);if(o.length===0&&s.length===0&&i.length===0)return;let u=[];if(o.length>0&&u.push(`${t} runs automation on the records this clone inserts: ${T(o)}.`),s.length>0){let d=gn(n.filter(l=>s.some(c=>c.objectApiName===l.objectApiName))).map(l=>wn[l]);u.push(`${t} runs automation as this clone updates records it inserted (${d.join("; ")}): ${T(s)}.`)}let a=n.length>0?"inserts and updates":"inserts";for(let{part:d,reason:l}of i)u.push(`${A[d][0].toUpperCase()}${A[d].slice(1)} of ${t} could not be read (${l}), so what fires as the clone ${a} is not known.`);return u.push(...me(r.assign??[],t,"the clone")),u.push(...ge(r.assign??[],"clone",r.mayMute===!0)),u.push(`Nothing was written. Add --accept-automation to clone all the same, or turn that automation off in ${t} first.`),u.join(" ")}function Wo(e,t,r={}){let n=te(e,r.drafted??[]),o=I(e);if(n.length===0&&o.length===0)return;let s=[],i=n.filter(a=>a.write==="update"),u=n.filter(a=>a.write==="delete");if(u.length>0){let a=u.map(d=>`${d.objectApiName}: ${S(d)} (${M[d.when]})`);s.push(`${t} runs automation on the records this removal deletes: ${a.join("; ")}.`)}i.length>0&&s.push(`${t} runs automation as this removal sets activated records back to Draft, the only way the platform deletes them: ${T(i)}.`);for(let{part:a,reason:d}of o)s.push(`${A[a][0].toUpperCase()}${A[a].slice(1)} of ${t} could not be read (${d}), so what fires as the removal deletes is not known.`);return s.push(...me(r.assign??[],t,"the removal")),s.push(...ge(r.assign??[],"removal",r.mayMute===!0)),s.push(`Nothing was deleted. Add --accept-automation to remove all the same, or turn that automation off in ${t} first.`),s.join(" ")}var M={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"};function Go(e,t,r,n){let o=[`removal automation: what ${t} runs as the removal takes the records back`];for(let i of te(e,n))o.push(i.write==="delete"?` ${i.objectApiName}: ${M[i.when]}: ${S(i)}`:` ${i.objectApiName}: set back to Draft before its delete: ${S(i)}`);let s=I(e);o.length===1&&s.length===0&&o.push(` nothing fires on the ${r} object(s) it deletes records of`);for(let{part:i,reason:u}of s)o.push(` ${A[i]} could not be read: ${u}`);return o}var Rn={bringBack:"brought back from the recycle bin",recreate:"made again with a new Id",giveBack:"given back its values from before the run",setToDraft:"set back to Draft before its delete"};function Uo(e,t,r,n="removal",o){let s=I(e),i=(u,a)=>{let d=[An[a](t)];for(let l of L(e,u))d.push(l.step==="delete"?` ${l.objectApiName}: ${M[l.when]}: ${S(l)}`:` ${l.objectApiName}: ${Rn[l.step]}: ${S(l)}`);if(d.length===1&&s.length===0){let l=new Set(Object.values(u).flat()).size,c=a==="reloadSweep"?"deletes":"writes";d.push(` nothing fires on the ${l} object(s) it ${c} records of`)}return d};return[...i(r,n),...o?i(o,"reloadSweep"):[],...s.map(({part:u,reason:a})=>` ${A[u]} could not be read: ${a}`)]}var An={removal:e=>`removal automation: what ${e} runs as the removal takes the run back`,reload:e=>`reload automation: what ${e} runs as the reload purges what earlier loads created`,reloadSweep:e=>`reload automation: what ${e} runs as the reload's sweep deletes what the target's automation made for the loads it replaces`};function qo(e,t,r){let n=L(e,r.steps),o=r.sweep?L(e,r.sweep):[],s=I(e);if(n.length===0&&o.length===0&&s.length===0)return;let i=d=>n.filter(l=>l.step===d),u=Ze[r.subject??"removal"],a=[];if(i("bringBack").length>0&&a.push(`${t} runs automation as ${u.this} brings back from the recycle bin what the run deleted: ${T(i("bringBack"))}.`),i("giveBack").length>0&&a.push(`${t} runs automation as ${u.this} gives the records the run wrote over their values from before it: ${T(i("giveBack"))}.`),i("setToDraft").length>0&&a.push(`${t} runs automation as ${u.this} sets activated records back to Draft, the only way the platform deletes them: ${T(i("setToDraft"))}.`),i("delete").length>0){let d=i("delete").map(l=>`${l.objectApiName}: ${S(l)} (${M[l.when]})`);a.push(`${t} runs automation on the records ${u.this} deletes: ${d.join("; ")}.`)}if(o.length>0){let d=o.map(l=>`${l.objectApiName}: ${S(l)} (${M[l.when]})`);a.push(`${t} runs automation on the records ${Ze.reloadSweep.this} deletes: ${d.join("; ")}.`)}for(let{part:d,reason:l}of s)a.push(`${A[d][0].toUpperCase()}${A[d].slice(1)} of ${t} could not be read (${l}), so what fires as ${u.the} writes is not known.`);return a.push(...me(r.assign??[],t,u.who)),a.push(...ge(r.assign??[],u.run,r.mayMute===!0)),a.push(`Nothing was written or deleted. Add --accept-automation to ${u.verb} all the same, or turn that automation off in ${t} first.`),a.join(" ")}var Ze={removal:{this:"this removal",the:"the removal",who:"the removal",run:"removal",verb:"remove"},reload:{this:"this reload's purge",the:"the reload's purge",who:"the reload",run:"reload",verb:"reload"},reloadSweep:{this:"this reload's sweep",the:"the reload's sweep",who:"the reload",run:"reload",verb:"reload"}};var En="Messaging.reserveSingleEmailCapacity(1);",Sn="System.NoAccessException: The organization is not permitted to send email",Bn=`/tooling/executeAnonymous?anonymousBody=${encodeURIComponent(En)}`,On=`/query?q=${encodeURIComponent("SELECT PermissionsEmailSingle FROM UserPermissionAccess")}`,kn=3e4,Tn=b({compiled:D(),success:D(),compileProblem:Q().nullish(),exceptionMessage:Q().nullish()}).loose(),Pn=b({records:fe(b({PermissionsEmailSingle:D().optional()}).loose())}).loose(),Yo={reading:{unread:"SandForge runs no Apex in a production org"},requests:0};function xn(e){return e%1e3===0?`${e/1e3} s`:`${e} ms`}function Ot(e,t){return e instanceof j?`the org did not answer within ${xn(t)}`:`the org refused it: ${R(e)}`}function vn(e){let t=Tn.safeParse(e);if(!t.success)return{unread:"its answer is not one anonymous Apex gives"};let{compiled:r,success:n,compileProblem:o,exceptionMessage:s}=t.data;if(!r)return{unread:`it did not compile${o?`: ${o}`:""}`};if(n)return{level:"all"};let i=s?.trim();return i===Sn?{refused:!0}:{unread:i?`the org answered: ${i}`:"it failed, and the org did not say why"}}async function Jo(e,t={}){let r=t.timeoutMs??kn,n=l=>new q(r).withTimeout("forge:deliverability",()=>e.request({method:"GET",url:l})),o;try{o=await n(Bn)}catch(l){return{reading:{unread:Ot(l,r)},requests:1}}let s=vn(o);if(!("refused"in s))return{reading:s,requests:1};let i="so the org's refusal does not say how it is set",u;try{u=await n(On)}catch(l){return{reading:{unread:`whether the user the run writes as may send email could not be read (${Ot(l,r)}), ${i}`},requests:2}}let a=Pn.safeParse(u),d=a.success?a.data.records[0]?.PermissionsEmailSingle:void 0;return d===!0?{reading:{level:"withheld"},requests:2}:{reading:{unread:d===!1?`the user the run writes as may not send email (Send Email), ${i}`:`the org did not say whether the user the run writes as may send email, ${i}`},requests:2}}async function Cn(e){let t=x(e.running,{applyAssignmentRules:e.applyAssignmentRules,writes:e.writes}),r=ht(e.running.automation.unread??[],{applyAssignmentRules:e.applyAssignmentRules===!0}),n=r!==void 0?{sendersUnread:r}:{};if(t.length===0&&r===void 0)return{senders:t};let o;try{o=await e.read()}catch(s){o={reading:{unread:R(s)},requests:1}}return{senders:t,...n,read:o}}function $n(e,t={}){let r=s=>`${s.objectApiName}\0${s.kind}\0${s.name}`,n=x(v(e,void 0,t.writes),t),o=new Set(x(v(e,Se(e,t.writes),t.writes),t).map(r));return n.filter(s=>!o.has(r(s)))}function jn(e,t){let r=new Set([...t.assigned,...t.held]);return{assign:e.assign.filter(n=>r.has(n.permissionSet))}}var Fn=["flows","processes","workflowRules"];async function Qo(e){let{plan:t,writes:r,applyAssignmentRules:n,read:o,target:s,run:i}=e,u=typeof o.unread=="string"?void 0:o,a=n===!0?{applyAssignmentRules:n}:{},d=await Cn({running:u?v(u,t,r):{automation:{objects:[],unread:Fn.map(g=>({part:g,reason:String(o.unread)}))},firing:[]},...a,writes:r,read:e.readDeliverability}),l=e.mayMute===!0&&t===void 0&&u!==void 0&&d.senders.length>0?$n(u,{...a,writes:r}):[],c=d.read?.reading;return{ofRun:d,gate:Rt({senders:d.senders,...d.sendersUnread!==void 0?{sendersUnread:d.sendersUnread}:{},...c!==void 0?{reading:c}:{},accepted:e.accepted,target:s,run:i,muteQuiets:l,keepsAddresses:e.keepsAddresses===!0}),afterLease:(g,m)=>{if(!(t===void 0||u===void 0))return At({planned:d.senders,held:x(v(u,jn(t,g),r),{...a,writes:r}),...c!==void 0?{reading:c}:{},accepted:m,target:s,run:i})}}}export{U as a,oe as b,Ln as c,_t as d,Wn as e,Ue as f,qe as g,Un as h,ze as i,Vn as j,Kn as k,Xn as l,Yn as m,Jn as n,j as o,q as p,kn as q,Yo as r,Jo as s,Cn as t,$n as u,jn as v,Qo as w,lo as x,co as y,Dt as z,mo as A,tt as B,ie as C,Ht as D,Vt as E,go as F,Ve as G,fo as H,po as I,ho as J,er as K,Ke as L,tr as M,rr as N,se as O,F as P,ar as Q,ur as R,K as S,dr as T,lr as U,cr as V,bo as W,Pr as X,xr as Y,vr as Z,at as _,Cr as $,ut as aa,$r as ba,jr as ca,Fr as da,yo as ea,lt as fa,ue as ga,Ir as ha,Wr as ia,wo as ja,Ro as ka,ct as la,Xr as ma,Yr as na,Jr as oa,Qr as pa,Ao as qa,Zr as ra,en as sa,Eo as ta,So as ua,ft as va,Bo as wa,Oo as xa,pt as ya,ht as za,ko as Aa,To as Ba,dn as Ca,Rt as Da,Po as Ea,xo as Fa,At as Ga,vo as Ha,P as Ia,Et as Ja,cn as Ka,mn as La,Co as Ma,gn as Na,$o as Oa,jo as Pa,I as Qa,Fo as Ra,_o as Sa,B as Ta,Mo as Ua,No as Va,pn as Wa,Io as Xa,Do as Ya,me as Za,Lo as _a,Wo as $a,Go as ab,Uo as bb,qo as cb};
@@ -1,13 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{E as k,d as I,l as H,m as W,n as K}from"./chunk-NEVXIGR6.mjs";import{C as at}from"./chunk-HJC7AIBK.mjs";import{a as J}from"./chunk-SIOZXPFG.mjs";import{b as N,l as j}from"./chunk-7EANH5PY.mjs";import{createReadStream as $t}from"node:fs";import{appendFile as Ut,stat as jt,writeFile as Jt}from"node:fs/promises";import{StringDecoder as Ht}from"node:string_decoder";import{promisify as dt}from"node:util";import{createGunzip as Wt,gunzip as Kt,gzip as Gt}from"node:zlib";var Yt=dt(Gt),Zt=dt(Kt),Xt=64*1024,Vt=".gz",Qt=6,A=10,ft=4,ut=Buffer.from("SF","latin1"),Y=8,F=6+Y,Z=A+F,X=Z+2+8;function B(s){return`${s}${Vt}`}async function qt(s){let t=await Yt(s,{level:Qt});if(t[3]!==0)throw new Error("zlib wrote a gzip header with flags set");let e=Buffer.from(t.subarray(0,A));e[3]=ft;let n=Buffer.alloc(F);return n.writeUInt16LE(F-2,0),ut.copy(n,2),n.writeUInt16LE(Y,4),n.writeUInt32LE(t.length+F,6),n.writeUInt32LE(s.length,10),Buffer.concat([e,n,t.subarray(A)])}function ht(s){if(s.length<Z||s[0]!==31||s[1]!==139||s[2]!==8||s[3]!==ft||s.readUInt16LE(A)!==F-2||!s.subarray(A+2,A+4).equals(ut)||s.readUInt16LE(A+4)!==Y)return;let t=s.readUInt32LE(A+6),e=s.readUInt32LE(A+10);return t>=X&&e>0?{total:t,raw:e}:void 0}function te(s,t=Xt){let e=[],n=0,r=0;for(;r<s.length;){let i=s.indexOf(10,r),o=i<0?s.length:i+1;o-n>t&&r>n&&(e.push(s.subarray(n,r)),n=r),r=o,r-n>=t&&(e.push(s.subarray(n,r)),n=r)}return r>n&&e.push(s.subarray(n,r)),e}async function ct(s){let t=te(Buffer.from(s,"utf8"));return Buffer.concat(await Promise.all(t.map(e=>qt(e))))}function T(s){return s.endsWith(".ndjson")}function _e(s){let t=new Map,e=(n,r)=>{let i=r(t.get(n)??Promise.resolve());return t.set(n,i),i.then(()=>{t.get(n)===i&&t.delete(n)},()=>{}),i};return{...s,writeFile:(n,r)=>{if(!T(n))return s.writeFile(n,r);let i=B(n);return e(i,o=>o.catch(()=>{}).then(async()=>{let a=r===""?Buffer.alloc(0):await ct(r);await Jt(i,a,{mode:I})}))},appendFile:(n,r)=>{if(!T(n))return s.appendFile(n,r);let i=B(n);return e(i,o=>o.then(async()=>{r!==""&&await Ut(i,await ct(r),{mode:I})}))},exists:n=>s.exists(T(n)?B(n):n),rm:n=>s.rm(T(n)?B(n):n),readLines:n=>T(n)?ee(B(n)):s.readLines(n)}}async function*ee(s){if((await jt(s)).size===0)return;let t=$t(s),e=Wt(),n=o=>{e.destroy(o)};t.on("error",n),t.pipe(e);let r=new Ht("utf8"),i="";try{for await(let o of e){let a=(i+r.write(o)).split(`
8
- `);i=a.pop()??"",yield*a}i+=r.end(),i!==""&&(yield i)}finally{t.off("error",n),t.destroy(),e.destroy()}}async function G(s,t,e){let n=Buffer.alloc(e),r=0;for(;r<e;){let{bytesRead:i}=await s.read(n,r,e-r,t+r);if(i===0)break;r+=i}return r===e?n:n.subarray(0,r)}async function lt(s,t,e,n){let r;try{r=await Zt(s,{maxOutputLength:t.raw})}catch{throw n(`holds a block that does not inflate at byte ${e}`)}if(r.length!==t.raw)throw n(`holds a block at byte ${e} that inflates to other than its header says`);return r}async function pt(s,t,e,n){let r=await G(s,t,e);if(r.length<e)throw n(`is cut short at byte ${t+r.length}`);let i=ht(r);if(i===void 0)throw n(`holds no block where its index says, at byte ${t}`);if(i.total!==e)throw n(`holds another block than its index says at byte ${t}`);return lt(r,i,t,n)}async function*gt(s,t,e){for(let n=0;n<t;){let r=ht(await G(s,n,Math.min(Z,t-n)));if(r===void 0)throw e(`holds no block at byte ${n}`);if(r.total>t-n)throw e(`is cut short: its block at byte ${n} ends past the file's end`);let i=await G(s,n,r.total);yield{at:n,total:r.total,lines:await lt(i,r,n,e)},n+=r.total}}function*mt(s){let t=0;for(;t<s.length;){let e=s.indexOf(10,t),n=e<0?s.length:e;yield{at:t,length:n-t},t=n+1}}import{randomBytes as Se}from"node:crypto";import{open as C,readFile as it,rename as xe,rm as ke,stat as Ae}from"node:fs/promises";import{dirname as Ft,join as Be}from"node:path";import{closeSync as ne,fstatSync as re,openSync as ie,readSync as se,writeSync as oe}from"node:fs";function Ue(s){let t=ie(s,"a+"),e=re(t).size;return{size:()=>e,append:n=>{let r=Buffer.from(n,"utf8"),i=0;for(;i<r.length;)i+=oe(t,r,i);e+=r.length},read:(n,r)=>{let i=Buffer.alloc(r),o=0;for(;o<r;){let a=se(t,i,o,r-o,n+o);if(a===0)break;o+=a}return i.subarray(0,o)},close:()=>ne(t)}}function yt(s,t){return t===void 0?s:`${s}/${t}`}var wt=/^[A-Za-z][A-Za-z0-9]*$/,bt=/^[0-9a-f]{64}$/,x=1,O=2,z=3,S=4,ae={created:x,existing:O,updated:z},St={[x]:"created",[O]:"existing",[z]:"updated"},xt={[x]:"c",[O]:"e",[z]:"u",[S]:"i"},V={c:x,e:O,u:z,i:S},ce="x",de="a",fe="j",Ot="d",Q="n",P="t",kt="found",ue="found-owed";function je(s,t,e,n){return JSON.stringify([Ot,s,t,e,n])}function Je(s){if(!s.startsWith(`["${Ot}"`))return;let t;try{t=JSON.parse(s)}catch{return}if(!Array.isArray(t))return;let[,,,e,n]=t;if(!(typeof e!="string"||!Number.isFinite(Date.parse(e)))&&!(typeof n!="string"||!Number.isFinite(Date.parse(n))))return{orgAt:e,at:n}}function he(s,t=!1){return JSON.stringify([t?"w":"o",s.objectApiName,s.newId,s.sourceId??"",s.fieldName,s.sourceRefId,s.insertOnly?1:0])}var le=1024*1024,pe=1024*1024,ge=2e4,me=2e4,ye=.6,we=3;function g(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return t>>>0}function y(s){let t=2538058380;for(let e=0;e<s.length;e++)t=Math.imul(t^s.charCodeAt(e),1540483477),t^=t>>>15;return t>>>0}var v=class{constructor(t){this.keyAt=t}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(t,e,n,r){let i=this.capacity-1,o=n&i;for(;;){let a=this.at[o];if(a===0)return~o;if(this.h1[o]===e&&this.h2[o]===n&&(r===a-1||this.keyAt(a-1,this.len[o])===t))return o;o=o+1&i}}offsetOf(t){return this.at[t]-1}lengthOf(t){return this.len[t]}codeOf(t){return this.code[t]}put(t,e,n,r,i,o){let a=t;t<0&&(this.used+1>this.capacity*ye?(this.grow(),a=this.freeSlotFor(n)):a=~t,this.used++,this.h1[a]=e,this.h2[a]=n),this.at[a]=r+1,this.len[a]=i,this.code[a]=o}freeSlotFor(t){let e=this.capacity-1,n=t&e;for(;this.at[n]!==0;)n=n+1&e;return n}grow(){let{h1:t,h2:e,at:n,len:r,code:i}=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 o=0;o<n.length;o++){if(n[o]===0)continue;let a=this.freeSlotFor(e[o]);this.h1[a]=t[o],this.h2[a]=e[o],this.at[a]=n[o],this.len[a]=r[o],this.code[a]=i[o]}}};function At(s){return s?s[0]==="p"&&s.length>=3?tt(String(s[1]),String(s[2])):s[0]==="g"&&s.length>=3?et(String(s[2])):s[0]===P&&s.length>=2?q(String(s[1])):"":""}function q(s){return`t\0${s}`}function tt(s,t){return`p\0${s}\0${t}`}function et(s){return`g\0${s}`}function*be(s){let t=s.size(),e=0,n=Buffer.alloc(0),r=0;for(;e<t;){let i=s.read(e,Math.min(pe,t-e));if(i.length===0)break;e+=i.length;let o=n.length>0?Buffer.concat([n,i]):i,a=0;for(;;){let d=o.indexOf(10,a);if(d<0)break;d>a&&(yield{offset:r+a,length:d-a,text:o.toString("utf8",a,d)}),a=d+1}n=o.subarray(a),r+=a}}var Bt=class s{constructor(t){this.file=t;this.index=new v((e,n)=>this.idOfLine(e,n)),this.marks=new v((e,n)=>At(w(this.lineAt(e,n)))),this.createdTargets=new v((e,n)=>{let r=w(this.lineAt(e,n));return r?M(String(r[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;static open(t){let e=new s(t);return e.readWhatIsThere(),e}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(t){this.flush(),this.mappedBeforePart=this.mappedCount,this.withTheirRecordMarked=0,this.partStart=this.file.size(),this.write({part:{n:this.parts,startedAt:t.toISOString()}}),this.parts++,this.flush()}nameSamplePlan(t){if(!bt.test(t.sha256))throw new Error("Not the SHA-256 of a plan.");this.write({sample:{dir:t.dir,sha256:t.sha256}}),this.plan={dir:t.dir,sha256:t.sha256},this.flush()}get samplePlan(){return this.plan?{...this.plan}:void 0}setMapping(t,e,n,r){let i=ae[t],o=g(e),a=y(e),d=this.cache.get(e),u=this.index.find(e,o,a,d?.at),h=u>=0&&this.index.codeOf(u)!==S;h&&this.uncount(e,u,d);let c=JSON.stringify([xt[i],e,n,r??""]),f=this.write(c);if(this.index.put(u,o,a,f,Buffer.byteLength(c),i),i===x&&this.indexCreated(n,f,Buffer.byteLength(c)),h||this.mappedCount++,r){let l=this.countsOf(r);i===x?l.created++:i===O?l.linked++:l.updated++}this.remember(e,{at:f,code:i,targetId:n,objectApiName:r??""})}uncount(t,e,n){let r=this.index.offsetOf(e);if(r<this.partStart)return;let i=this.index.codeOf(e),o=n?.at===r?n:this.recordAt(t,e),a=o?.objectApiName?this.counts.get(o.objectApiName):void 0;a&&(i===x?a.created--:i===O?a.linked--:a.updated--)}countsOf(t){let e=this.counts.get(t);return e||(e={created:0,linked:0,updated:0},this.counts.set(t,e)),e}mapping(t){let e=this.lookUp(t);if(!(!e||e.code===S))return{kind:St[e.code],sourceId:t,targetId:e.targetId,...e.objectApiName?{objectApiName:e.objectApiName}:{},earlier:e.at<this.partStart}}createdTarget(t){let e=M(t);if(this.createdUnattributedKeys.has(e))return!0;if(this.createdTargets.size===0)return!1;let n=this.createdTargets.find(e,g(e),y(e));if(n<0)return!1;let r=this.createdTargets.offsetOf(n),i=w(this.lineAt(r,this.createdTargets.lengthOf(n)));if(!i)return!1;let o=String(i[1]),a=this.index.find(o,g(o),y(o));return a>=0&&this.index.offsetOf(a)===r&&this.index.codeOf(a)===x}indexCreated(t,e,n){let r=M(t);if(!r)return;let i=g(r),o=y(r);this.createdTargets.put(this.createdTargets.find(r,i,o),i,o,e,n,x)}targetOf(t){let e=this.lookUp(t);return e&&e.code!==S?e.targetId:void 0}get mappedSize(){return this.mappedCount}countsByObject(){let t=[];for(let[e,{created:n,linked:r,updated:i}]of this.counts)n+r+i!==0&&t.push(i>0?{objectApiName:e,created:n,linked:r,updated:i}:{objectApiName:e,created:n,linked:r});return t}linkedToCreatedCount(){let t=0;for(let c of this.counts.values())t+=c.linked;if(t===0)return 0;let e=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart,n=(c,f)=>{let l=w(this.lineAt(c,f));return l?String(l[2]).slice(0,15):""},r=(c,f)=>{if(c.offset<e)return;let l=V[String(f[0])];if(l===void 0||l===S||!f[3])return;let p=String(f[1]),m=this.index.find(p,g(p),y(p),c.offset);return m>=0&&this.index.offsetOf(m)===c.offset?l:void 0},i=(c,f,l)=>{let p=g(f),m=y(f);c.put(c.find(f,p,m),p,m,l.offset,l.length,0)},o=(c,f)=>c.size>0&&c.find(f,g(f),y(f))>=0,a=new v(n);for(let c of this.lines()){if(!c.text.startsWith('["'))continue;let f=w(c.text);!f||r(c,f)!==O||this.markedWithTheirRecord(String(f[1]))||i(a,String(f[2]).slice(0,15),c)}if(a.size===0)return 0;let d=new v(n),u=new Set;for(let c of this.lines()){if(!c.text.startsWith('["')||c.offset<e)continue;let f=w(c.text);if(!f)continue;if(f[0]===Q&&Array.isArray(f[2])){for(let p of f[2]){let m=String(p).slice(0,15);o(a,m)&&u.add(m)}continue}if(r(c,f)!==x)continue;let l=String(f[2]).slice(0,15);o(a,l)&&i(d,l,c)}if(d.size===0&&u.size===0)return 0;let h=0;for(let c of this.lines()){if(!c.text.startsWith('["'))continue;let f=w(c.text);if(!f||r(c,f)!==O||this.markedWithTheirRecord(String(f[1])))continue;let l=String(f[2]).slice(0,15);(o(d,l)||u.has(l))&&h++}return h}earlierRecordsOf(t,e=!1){return(e?this.earlierPastCheckpoint:this.earlierByObject).get(t)??0}*mappings(){for(let t of this.lines()){if(!t.text.startsWith('["'))continue;let e=w(t.text);if(!e)continue;let n=V[String(e[0])];if(n===void 0||n===S)continue;let r=String(e[1]),i=this.index.find(r,g(r),y(r),t.offset);if(i<0||this.index.offsetOf(i)!==t.offset)continue;let o=String(e[3]??"");yield{kind:St[n],sourceId:r,targetId:String(e[2]),...o?{objectApiName:o}:{},earlier:t.offset<this.partStart}}}noteRead(t){this.readsHeld.push(t),this.readsHeld.length>=me&&this.settleReads()}settleReads(){let t=this.readsHeld;this.readsHeld=[];for(let e of t){let n=g(e),r=y(e),i=this.index.find(e,n,r,this.cache.get(e)?.at);if(i>=0)continue;let o=JSON.stringify([xt[S],e]),a=this.write(o);this.index.put(i,n,r,a,Buffer.byteLength(o),S)}}wasRead(t){return this.readsHeld.includes(t)?!0:this.index.find(t,g(t),y(t),this.cache.get(t)?.at)>=0}checkpoint(t,e,n){if(n!==void 0&&!wt.test(n))throw new Error(`Not the name of a pass: ${JSON.stringify(n.slice(0,40))}`);this.settleReads(),this.write({at:{object:t,...n!==void 0?{pass:n}:{},...e}}),this.checkpointsByObject.set(yt(t,n),{...e}),this.flush()}checkpoints(){return new Map(this.checkpointsByObject)}owe(t,e=!1){this.owedCount++,this.write(he(t,e))}get owed(){return this.owedCount}*owedPages(t){let e=[];for(let n of this.lines()){if(!n.text.startsWith('["o"')&&!n.text.startsWith('["w"'))continue;let r=w(n.text);if(!r||r.length<7)continue;let[i,o,a,d,u,h,c]=r;e.push({update:{objectApiName:String(o),newId:String(a),sourceId:d?String(d):void 0,fieldName:String(u),sourceRefId:String(h),...c===1?{insertOnly:!0}:{}},toRowWrittenBefore:i==="w"}),e.length>=t&&(yield e,e=[])}e.length>0&&(yield e)}patched(t,e){this.mark(JSON.stringify(["p",t,e]),tt(t,e))}wasPatched(t,e){return this.hasMark(tt(t,e))}mark(t,e){let n=g(e),r=y(e),i=this.marks.find(e,n,r),o=this.write(t);this.marks.put(i,n,r,o,Buffer.byteLength(t),0)}hasMark(t){return this.marks.size>0&&this.marks.find(t,g(t),y(t))>=0}owedLeftByEarlierParts(){let t=new Set;for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["p"'))continue;let r=w(n.text);r&&r.length>=3&&t.add(`${String(r[1])}\0${String(r[2])}`)}let e=[];for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["o"'))continue;let r=w(n.text);if(!r||r.length<7)continue;let[,i,o,a,d,u,h]=r;t.has(`${String(o)}\0${String(d)}`)||e.push({objectApiName:String(i),newId:String(o),sourceId:a?String(a):void 0,fieldName:String(d),sourceRefId:String(u),...h===1?{insertOnly:!0}:{}})}return e}oweStatus(t,e,n){this.write(JSON.stringify(["s",t,e,n])),this.tallyStatus({objectApiName:t,id:e,status:n})}tallyStatus(t){let e=this.statuses.get(t.objectApiName);e||(e={count:0,samples:[]},this.statuses.set(t.objectApiName,e)),e.count++,e.samples.length<we&&e.samples.push(t)}gaveStatus(t,e){this.statusGiven(e)||(this.mark(JSON.stringify(["g",t,e]),et(e)),this.given.set(t,(this.given.get(t)??0)+1))}statusGiven(t){return this.hasMark(et(t))}statusesOwed(){let t=new Map;for(let[e,n]of this.statuses){let r=n.count-(this.given.get(e)??0);r<=0||t.set(e,{count:r,samples:n.samples.filter(({id:i})=>!this.statusGiven(i))})}return t}*statusLines(){for(let t of this.lines()){if(!t.text.startsWith('["s"'))continue;let e=w(t.text);!e||e.length<4||(yield{objectApiName:String(e[1]),id:String(e[2]),status:String(e[3])})}}withTheirRecord(t){let e=q(t),n=g(e),r=y(e),i=this.marks.find(e,n,r),o=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;if(i>=0&&this.marks.offsetOf(i)>=o)return;let a=JSON.stringify([P,t]),d=this.write(a);this.marks.put(i,n,r,d,Buffer.byteLength(a),0),this.withTheirRecordMarked++}get withTheirRecordCount(){return this.withTheirRecordMarked}markedWithTheirRecord(t){if(this.withTheirRecordMarked===0)return!1;let e=q(t),n=this.marks.find(e,g(e),y(e)),r=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;return n>=0&&this.marks.offsetOf(n)>=r}*withTheirRecordIds(){if(this.withTheirRecordMarked!==0)for(let t of this.lines()){if(t.offset<this.partStart||!t.text.startsWith(`["${P}"`))continue;let e=w(t.text);e&&e.length>=2&&(yield String(e[1]))}}sent(t,e,n,r=new Date,i){this.callsSent++;let o=`${Math.max(0,this.parts-1)}.${this.callsSent}`;return this.write(JSON.stringify([ce,o,t,r.toISOString(),e,n.map(({sourceId:a,fingerprint:d,externalKey:u,jobKey:h})=>i!==void 0&&u!==void 0?[a,d,u]:h!==void 0?[a,d,"",h]:[a,d]),n.flatMap(({owes:a},d)=>(a??[]).map(({field:u,sourceRefId:h,insertOnly:c})=>[d,u,h,c?1:0])),...i!==void 0?[i]:[]])),this.flush(),o}answered(t){this.write(JSON.stringify([de,t]))}jobOpened(t,e){this.write(JSON.stringify([fe,t,e])),this.flush()}createdUnattributed(t,e){if(e.length!==0){this.write(JSON.stringify([Q,t,[...e]]));for(let n of e)this.createdUnattributedKeys.add(M(n))}}wasFoundAfterStop(t){return this.foundAfterStop.has(t)}owesUntold(t){return this.foundOwingUntold.has(t)}flush(){if(this.pending.length===0)return;let t=this.pending.join("");this.pending=[],this.pendingBytes=0,this.file.append(t)}close(){this.settleReads(),this.flush(),this.file.close()}write(t){let e=typeof t=="string"?t:JSON.stringify(t),n=this.file.size()+this.pendingBytes,r=`${e}
9
- `;return this.pending.push(r),this.pendingBytes+=Buffer.byteLength(r),this.pendingBytes>=le?this.flush():this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()})),n}lineAt(t,e){return t+e>this.file.size()&&this.flush(),this.file.read(t,e).toString("utf8")}idOfLine(t,e){let n=w(this.lineAt(t,e));return n?String(n[1]):""}lookUp(t){let e=this.cache.get(t);if(e)return this.cache.delete(t),this.cache.set(t,e),e;let n=this.index.find(t,g(t),y(t));if(n<0)return;let r=this.recordAt(t,n);return r&&this.remember(t,r),r}recordAt(t,e){let n=this.index.offsetOf(e),r=w(this.lineAt(n,this.index.lengthOf(e)));if(!(!r||String(r[1])!==t))return{at:n,code:this.index.codeOf(e),targetId:String(r[2]??""),objectApiName:String(r[3]??"")}}remember(t,e){if(this.cache.delete(t),this.cache.set(t,e),this.cache.size>ge){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}}*lines(){this.flush(),yield*be(this.file)}readWhatIsThere(){for(let t of this.lines()){if(t.text.startsWith('["')){let n=w(t.text);n&&this.readRegistration(t,n);continue}let e;try{e=JSON.parse(t.text)}catch{continue}if(!(typeof e!="object"||e===null)){if("part"in e)this.parts++;else if("sample"in e){let n=e.sample;if(typeof n!="object"||n===null)continue;let{dir:r,sha256:i}=n;if(typeof r!="string"||r===""||typeof i!="string"||!bt.test(i))continue;this.plan={dir:r,sha256:i}}else if("at"in e){let n=e.at;if(typeof n!="object"||n===null)continue;let{object:r,pass:i,lastId:o,read:a,done:d}=n;if(typeof r!="string"||typeof o!="string"||typeof a!="number"||i!==void 0&&(typeof i!="string"||!wt.test(i)))continue;this.checkpointsByObject.set(yt(r,i),{lastId:o,read:a,...d===!0?{done:d}:{}}),i===void 0&&this.earlierPastCheckpoint.delete(r)}}}}readRegistration(t,e){let n=String(e[0]);if(n==="o"||n==="w"){this.owedCount++;return}if(n==="s"){e.length>=4&&this.tallyStatus({objectApiName:String(e[1]),id:String(e[2]),status:String(e[3])});return}if(n==="p"||n==="g"||n===P){let c=At(e);if(!c)return;let f=g(c),l=y(c),p=this.marks.find(c,f,l);if(n==="g"&&p<0){let m=String(e[1]);this.given.set(m,(this.given.get(m)??0)+1)}this.marks.put(p,f,l,t.offset,t.length,0);return}if(n===Q){if(Array.isArray(e[2]))for(let c of e[2])this.createdUnattributedKeys.add(M(String(c)));return}let r=V[n];if(r===void 0)return;let i=String(e[1]);r===x&&(e[4]===kt||e[4]===ue)&&(this.foundAfterStop.add(i),e[4]===kt&&this.foundOwingUntold.add(i));let o=g(i),a=y(i),d=this.index.find(i,o,a),u=d>=0&&this.index.codeOf(d)!==S;if(r===S&&d>=0||(this.index.put(d,o,a,t.offset,t.length,r),r===S))return;r===x&&this.indexCreated(String(e[2]??""),t.offset,t.length),u||this.mappedCount++;let h=String(e[3]??"");h&&(this.earlierByObject.set(h,(this.earlierByObject.get(h)??0)+1),this.earlierPastCheckpoint.set(h,(this.earlierPastCheckpoint.get(h)??0)+1))}};function M(s){return s.slice(0,15)}function w(s){try{let t=JSON.parse(s);return Array.isArray(t)?t:void 0}catch{return}}var Et=2e3,b=15,nt=b,E=nt+8,st={format:1,head:Buffer.from("SFCKIDX1","latin1"),lengthAt:E+8,rowBytes:E+8+4},Mt={format:2,head:Buffer.from("SFCKIDX2","latin1"),memberBytesAt:E+8,lineAt:E+12,lengthAt:E+16,rowBytes:E+20},Lt={1:st,2:Mt},L=st.head.length,Rt=1<<20,Oe=500,R=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ee=/^[A-Za-z0-9]{15}$/,ot=/^[A-Za-z][A-Za-z0-9_]*$/;function tn(s,t){return L+s*Lt[t].rowBytes}function It(s){return s.replace(/[^A-Za-z0-9_-]/g,"_")}function Ct(s,t,e){if(!ot.test(e)||e.length>80)throw new k("invalid","Not a Salesforce API name");return Be(s.dir,"backups",`${It(t)}__${It(e)}.ndjson`)}var D=class{constructor(t,e){this.layout=t;this.rowBytes=t.rowBytes,this.bytes=e??Buffer.alloc(this.rowBytes*1024),this.size=e?e.length/this.rowBytes:0}layout;bytes;rowBytes;size;push(t,e,n){let r=this.size*this.rowBytes;if(r+this.rowBytes>this.bytes.length){let d=Buffer.alloc(Math.max(this.bytes.length*2,this.rowBytes*1024));this.bytes.copy(d,0,0,r),this.bytes=d}let{memberBytesAt:i,lineAt:o,lengthAt:a}=this.layout;return this.bytes.write(t,r,b,"latin1"),this.bytes.writeDoubleLE(e,r+nt),this.bytes.writeDoubleLE(n.offset,r+E),i!==void 0&&this.bytes.writeUInt32LE(n.memberBytes??0,r+i),o!==void 0&&this.bytes.writeUInt32LE(n.line??0,r+o),this.bytes.writeUInt32LE(n.length,r+a),this.size++}keyAt(t){let e=t*this.rowBytes;return this.bytes.toString("latin1",e,e+b)}holds(t,e){let n=t*this.rowBytes;for(let r=0;r<b;r++)if(this.bytes[n+r]!==e.charCodeAt(r))return!1;return!0}stampAt(t){return this.bytes.readDoubleLE(t*this.rowBytes+nt)}offsetAt(t){return this.bytes.readDoubleLE(t*this.rowBytes+E)}memberBytesAt(t){let e=this.layout.memberBytesAt;return e===void 0?0:this.bytes.readUInt32LE(t*this.rowBytes+e)}lineAt(t){let e=this.layout.lineAt;return e===void 0?0:this.bytes.readUInt32LE(t*this.rowBytes+e)}lengthAt(t){return this.bytes.readUInt32LE(t*this.rowBytes+this.layout.lengthAt)}before(t,e){return this.offsetAt(t)-this.offsetAt(e)||this.lineAt(t)-this.lineAt(e)}wellFormed(t){let e=this.stampAt(t),n=this.offsetAt(t);return Ee.test(this.keyAt(t))&&Number.isFinite(e)&&Number.isSafeInteger(n)&&n>=0&&this.lengthAt(t)>0&&(this.layout.format===1||this.memberBytesAt(t)>=X)}written(){return this.bytes.subarray(0,this.size*this.rowBytes)}},$=class{constructor(t,e){this.rows=t;let n=1024;for(;n<e*2;)n*=2;this.slots=new Uint32Array(n)}rows;slots;used=0;find(t){let e=this.slots.length-1;for(let n=g(t)&e;;n=n+1&e){let r=this.slots[n];if(r===0)return-1;if(this.rows.holds(r-1,t))return r-1}}add(t){let e=this.rows.keyAt(t),n=this.find(e);return n>=0?n:((this.used+1)*2>this.slots.length&&this.grow(),this.place(t,e),this.used++,-1)}place(t,e){let n=this.slots.length-1,r=g(e)&n;for(;this.slots[r]!==0;)r=r+1&n;this.slots[r]=t+1}grow(){let t=this.slots;this.slots=new Uint32Array(t.length*2);for(let e of t)e!==0&&this.place(e-1,this.rows.keyAt(e-1))}};async function U(s,t){try{return await C(s,"r")}catch(e){throw e.code!=="ENOENT"?e:new k("damaged",`The checkpoint\u2019s snapshot of ${t} is not on this machine.`)}}async function*Pt(s,t){let e=await U(s,t);try{let n=Buffer.alloc(Rt),r=Buffer.alloc(0),i=0,o=0,a=0;for(;;){let{bytesRead:d}=await e.read(n,0,Rt,o);if(d===0)break;o+=d;let u=r.length>0?Buffer.concat([r,n.subarray(0,d)]):n.subarray(0,d),h=0;for(let c=u.indexOf(10);c>=0;c=u.indexOf(10,h))a++,c>h&&(yield{number:a,offset:i+h,length:c-h,text:u.toString("utf8",h,c)}),h=c+1;r=Buffer.from(u.subarray(h)),i+=h}r.length>0&&(yield{number:a+1,offset:i,length:r.length,text:r.toString("utf8")})}finally{await e.close()}}async function*Re(s,t,e){let n=await U(s,t);try{let r=0;for await(let i of gt(n,(await n.stat()).size,e))for(let o of mt(i.lines))r++,o.length!==0&&(yield{number:r,offset:i.at,memberBytes:i.total,line:o.at,length:o.length,text:i.lines.toString("utf8",o.at,o.at+o.length)})}finally{await n.close()}}async function Ie(s){try{return await Ae(s),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zt(s){let t=at(s);return t===null?Number.NaN:Date.parse(t)}function _(s){let t;try{t=JSON.parse(s)}catch{return}return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}async function ve(s,t){let e=`${s}.${process.pid}-${Se(4).toString("hex")}.tmp`,n=await C(e,"wx",I);try{try{await n.writeFile(t),await n.sync()}finally{await n.close()}await xe(e,s)}catch(r){throw await ke(e,{force:!0}),r}}async function en(s,t,e){let n=Ct(s,t,e),r=B(n),i=await Ie(r)?2:1,o=H(s,e),a=new D(Lt[i]),d=new $(a,0),u=(f,l)=>new k("damaged",`The snapshot of ${e} holds ${l} at line ${f} of its file: it cannot be indexed.`),h=i===2?Re(r,e,f=>new k("damaged",`The snapshot of ${e} ${f}: it cannot be indexed.`)):Pt(n,e);for await(let f of h){let l=_(f.text);if(!l)throw u(f.number,"no record");let p=l.Id;if(typeof p!="string"||!R.test(p))throw u(f.number,"a record without its Id");let m=zt(l.SystemModstamp);if(!Number.isFinite(m))throw u(f.number,`record ${p} without its SystemModstamp`);let Dt=a.push(p.slice(0,b),m,f);if(d.add(Dt)>=0)throw u(f.number,`record ${p} a second time`)}let c=Buffer.concat([a.layout.head,a.written()]);return await ve(o,c),{rows:a.size,bytes:c.length}}var Ne=j({objectApiName:N().regex(ot).max(80),from:N().regex(R),to:N().regex(R)});async function _t(s){let t;try{t=await C(s,"r"),await t.sync()}catch{}finally{await t?.close().catch(()=>{})}}var rt=class s{constructor(t,e){this.current=t;this.original=e}current;original;static none=new s(new Map,new Map);static of(t){let e=new Map;for(let{from:r,to:i}of t)e.set(r.slice(0,b),i);let n=new Map;for(let[r,i]of e)n.set(i.slice(0,b),r);return new s(e,n)}static async read(t){let e;try{e=await it(W(t),"utf8")}catch(i){if(i.code==="ENOENT")return s.none;throw i}let n=e.split(`
10
- `).slice(0,-1),r=[];for(let[i,o]of n.entries()){if(o==="")continue;let a;try{a=JSON.parse(o)}catch{a=void 0}let d=Ne.safeParse(a);if(!d.success)throw new k("damaged",`The checkpoint\u2019s list of the records a rewind made again is damaged at line ${i+1}.`);r.push(d.data)}return s.of(r)}static async add(t,e){if(e.length===0)return;let n=W(t),r=e.map(({objectApiName:a,from:d,to:u})=>`${JSON.stringify({objectApiName:a,from:d,to:u})}
11
- `).join(""),i=await C(n,"a",I),o=!1;try{o=(await i.stat()).size===0,await i.appendFile(r,"utf8"),await i.sync()}finally{await i.close()}o&&await _t(Ft(n))}get empty(){return this.current.size===0}currentOf(t){return this.current.get(t)}originalOf(t){return this.original.get(t)}retired(t){return typeof t=="string"&&R.test(t)&&this.current.has(t.slice(0,b))}remapped(t){return typeof t!="string"||!R.test(t)?t:this.current.get(t.slice(0,b))??t}rowAsNow(t){if(this.empty)return t;let e={...t};for(let[n,r]of Object.entries(t)){if(n==="attributes")continue;let i=this.remapped(r);i!==r&&(e[n]=i)}return e}},Te=j({objectApiName:N().regex(ot).max(80),id:N().regex(R)}),vt=class s{constructor(t){this.held=t}held;static none=new s(new Set);static async read(t){let e;try{e=await it(K(t),"utf8")}catch(r){if(r.code==="ENOENT")return s.none;throw r}let n=new Set;for(let r of e.split(`
12
- `)){if(r==="")continue;let i;try{i=JSON.parse(r)}catch{continue}let o=Te.safeParse(i);o.success&&n.add(o.data.id.slice(0,b))}return new s(n)}static async add(t,e,n){if(n.length===0)return;let r=K(t),i=n.map(d=>`${JSON.stringify({objectApiName:e,id:d})}
13
- `).join(""),o=await C(r,"a",I),a=!1;try{a=(await o.stat()).size===0,await o.appendFile(i,"utf8"),await o.sync()}finally{await o.close()}a&&await _t(Ft(r))}has(t){return this.held.has(t.slice(0,b))}keys(){return this.held.values()}},Nt=class s{constructor(t,e,n,r,i,o,a){this.objectApiName=t;this.snapshotId=e;this.snapshotFile=n;this.rows=r;this.byKey=i;this.recreated=o;this.extent=a}objectApiName;snapshotId;snapshotFile;rows;byKey;recreated;extent;static async read(t,e,n,r){let i=H(t,n),o=p=>new k("damaged",`The checkpoint\u2019s index of ${n} ${p}.`),a;try{a=await it(i)}catch(p){throw p.code==="ENOENT"?o("is not on this machine"):p}let d=[st,Mt].find(({head:p})=>a.length>=L&&a.subarray(0,L).equals(p));if(d===void 0||(a.length-L)%d.rowBytes!==0)throw o("is not an index of its snapshot");let u=Ct(t,e,n),h=d.format===2?B(u):u,c=new D(d,a.subarray(L)),f=new $(c,c.size),l=0;for(let p=0;p<c.size;p++){if(!c.wellFormed(p))throw o(`is damaged at row ${p+1}`);if(f.add(p)>=0)throw o(`holds record ${c.keyAt(p)} twice`);d.format===2&&(l=Math.max(l,c.offsetAt(p)+c.memberBytesAt(p)))}return new s(n,e,h,c,f,r??await rt.read(t),l)}get format(){return this.rows.layout.format}get size(){return this.rows.size}rowOf(t){if(typeof t!="string"||!R.test(t))return-1;let e=t.slice(0,b),n=this.recreated.originalOf(e);return n!==void 0?this.byKey.find(n):this.recreated.retired(t)?-1:this.byKey.find(e)}retired(t){return this.recreated.retired(t)&&this.byKey.find(String(t).slice(0,b))>=0}snapshotIdOf(t){let e=this.rowOf(t);if(e<0)return t;let n=this.rows.keyAt(e);return J(n)??n}has(t){return this.rowOf(t)>=0}stampOf(t){let e=this.rowOf(t);return e<0?void 0:this.rows.stampAt(e)}idAt(t){let e=this.rows.keyAt(t);return this.recreated.currentOf(e)??J(e)??e}chunk(t){if(t.length>Et)throw new RangeError(`A chunk of the snapshot reads ${Et} records at most; ${t.length} were asked.`);let e=new Set;for(let r of t){let i=this.rowOf(r);i>=0&&e.add(i)}let n=[...e].sort((r,i)=>this.rows.before(r,i));return{batches:async(r,i,o)=>{if(r!==this.snapshotId||i!==this.objectApiName)return null;let a=o>=1?Math.floor(o):1;return{[Symbol.asyncIterator]:()=>this.rowsAt(n,a)}}}}async*records(){if(this.size===0)return;if(this.format===2){let e=function*(n){for(let r=0;r<n;r++)yield r};for await(let n of this.compressedRowsAt(e(this.size),Oe))yield*n;return}let t=0;for await(let e of Pt(this.snapshotFile,this.objectApiName)){let n=_(e.text);if(t>=this.size)throw this.moreThanIndexed();if(!n||!this.isRowOf(t,n))throw this.notWhereIndexed(t);yield this.recreated.rowAsNow(n),t++}if(t<this.size)throw this.notWhereIndexed(t)}notWhereIndexed(t){return new k("damaged",`The checkpoint\u2019s snapshot of ${this.objectApiName} does not hold record ${this.idAt(t)} where its index says: the file changed since the checkpoint was taken.`)}moreThanIndexed(){return new k("damaged",`The checkpoint\u2019s snapshot of ${this.objectApiName} holds more records than its index: the file changed since the checkpoint was taken.`)}async*rowsAt(t,e){if(t.length===0)return;if(this.format===2){yield*this.compressedRowsAt(t,e);return}let n=await U(this.snapshotFile,this.objectApiName);try{let r=Buffer.alloc(0),i=[];for(let o of t){let a=this.rows.lengthAt(o),d=this.rows.offsetAt(o);r.length<a&&(r=Buffer.alloc(Math.max(a,r.length*2)));let u=0;for(;u<a;){let{bytesRead:c}=await n.read(r,u,a-u,d+u);if(c===0)break;u+=c}let h=u===a?_(r.toString("utf8",0,a)):void 0;if(!h||!this.isRowOf(o,h))throw this.notWhereIndexed(o);i.push(this.recreated.rowAsNow(h)),i.length===e&&(yield i,i=[])}i.length>0&&(yield i)}finally{await n.close()}}async*compressedRowsAt(t,e){let n=i=>new k("damaged",`The checkpoint\u2019s snapshot of ${this.objectApiName} ${i}: the file changed since the checkpoint was taken.`),r=await U(this.snapshotFile,this.objectApiName);try{let i=(await r.stat()).size;if(i!==this.extent)throw n(`takes ${i} bytes where its index says ${this.extent}`);let o=-1,a=0,d=Buffer.alloc(0),u=[];for(let h of t){let c=this.rows.offsetAt(h);(c!==o||this.rows.memberBytesAt(h)!==a)&&(a=this.rows.memberBytesAt(h),d=await pt(r,c,a,n),o=c);let f=this.rows.lineAt(h),l=f+this.rows.lengthAt(h),m=l<=d.length&&(f===0||d[f-1]===10)&&(l===d.length||d[l]===10)?_(d.toString("utf8",f,l)):void 0;if(!m||!this.isRowOf(h,m))throw this.notWhereIndexed(h);u.push(this.recreated.rowAsNow(m)),u.length===e&&(yield u,u=[])}u.length>0&&(yield u)}finally{await r.close()}}isRowOf(t,e){let n=e.Id;return typeof n=="string"&&R.test(n)&&this.rows.holds(t,n.slice(0,b))&&zt(e.SystemModstamp)===this.rows.stampAt(t)}},Tt=class{constructor(t){this.index=t;this.marked=new Uint8Array(Math.ceil(t.size/8))}index;marked;found=0;mark(t){let e=this.index.rowOf(t);if(e<0)return!1;let n=1<<(e&7),r=e>>>3;return(this.marked[r]&n)===0&&(this.marked[r]|=n,this.found++),!0}get count(){return this.index.size-this.found}*ids(){for(let t=0;t<this.index.size;t++)(this.marked[t>>>3]&1<<(t&7))===0&&(yield this.index.idAt(t))}};export{_e as a,Ue as b,yt as c,ce as d,de as e,fe as f,Ot as g,Q as h,P as i,kt as j,ue as k,je as l,Je as m,he as n,g as o,y as p,v as q,be as r,Bt as s,Et as t,tn as u,Ct as v,en as w,rt as x,vt as y,Nt as z,Tt as A};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Fe}from"./chunk-GMY5427L.mjs";import{h as we,i as Oe,j as be,k as Se,n as ke,o as Te}from"./chunk-XETCPL7E.mjs";import{c as Re}from"./chunk-K2FBZIXY.mjs";import{f as he,i as me}from"./chunk-3F5YMM2F.mjs";import{a as z,k as ie,n as ae,p as de,s as ce,t as ue,u as le}from"./chunk-ZUTYVST5.mjs";import{b as ye,e as ge}from"./chunk-55HEMHEG.mjs";import{b as fe,c as q,m as pe}from"./chunk-WIO4XO4F.mjs";import{d as K}from"./chunk-GCOB7K5N.mjs";import{F as se,p as te,r as ne,s as re,t as oe}from"./chunk-CGWXQX75.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{Rb as X,fc as B}from"./chunk-B45CNPUX.mjs";var H=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function R(t){return t.slice(0,15)}var Ce=class{constructor(e=new Map){this.earlier=e}earlier;written=new Map;refused=new Map;deleted=new Set;ownersRefused=new Set;contactsSentWith=new Map;noteSentWithContact(e,n){this.contactsSentWith.set(R(e),n)}contactSentWith(e){return this.contactsSentWith.get(R(e))}roleLinkedFor(e){this.contactsSentWith.delete(R(e))}get sentWithAContact(){return this.contactsSentWith.size>0}noteOwnerRefused(e){this.ownersRefused.add(R(e))}isOwnerRefused(e){return this.ownersRefused.has(R(e))}noteDeleted(e){for(let n of e)this.deleted.add(R(n))}standing(e){return e!==void 0&&this.deleted.has(R(e))?void 0:e}noteMatched(e,n){this.noteWritten(e,n)}noteWritten(e,n){this.written.set(R(e),n),this.refused.delete(R(e))}noteRefused(e,n){this.written.has(R(e))||this.refused.set(R(e),n)}targetOf(e){return this.standing(this.written.get(R(e)))??this.standing(this.earlier.get(R(e)))}refusedObjectOf(e){if(this.standing(this.earlier.get(R(e)))===void 0)return this.refused.get(R(e))}};function Ae(t,e,n){if(e.length===0||!n.some(o=>!o.master))return;let r={};for(let o of e)r[o]=(r[o]??0)+1;let s=be(Oe(n));return{objectApiName:t,rows:e.length,why:r,...s?{predicted:s}:{}}}function Ie(t,e){return q(t,e?.target??[])}function Y(t){switch(t.operation){case"insert":return null;case"upsert":return t.externalIdField??"Id";case"update":case"delete":return"Id"}}function Me(t,e,n,r,s){let o=ge(t,e);for(let i of n)(!(i.fieldApiName in o)||i.overwriteExisting)&&(o[i.fieldApiName]=i.value);if(!r)return o;let a={};for(let i of Object.keys(o))i!=="attributes"&&(r.has(i)||i===s)&&(a[i]=o[i]);return a}function Le(t,e){return`${t} ${e} record${t===1?"":"s"}`}function ze(t,e,n){let r=a=>e.find(i=>R(i.recordTypeId)===R(a)),s=t;if(!r(t)&&n){let a=n.mappings.find(i=>R(i.sourceId)===R(t));if(!a){let i=n.source.find(c=>R(c.id)===R(t)),p=i?(n.target??[]).filter(c=>c.sobjectType===i.sobjectType&&c.developerName===i.developerName):[];return{unmapped:i?K(i):"",namesakes:p.map(K)}}s=a.targetId}let o=q(e.filter(a=>R(a.recordTypeId)===R(s)),n?.target??[])[0];return o&&!o.available&&!o.master?{unavailable:o}:o?{sent:s,info:o}:{sent:s}}function Ue(t,e,n){if(t?.personAccounts===!1)return!0;if(!n)return!1;let r=e??ke(t?.recordTypes);return r!==void 0&&!n.has(R(r))}function We(t,e,n){return{group:`parent:${e}:${n}`,reason:`PARENT_REFUSED: the ${n} record its ${e} names was refused in this run.`,say:r=>`PARENT_REFUSED: ${Le(r,t)} held back, not sent: the ${n} record their ${e} names was refused in this run, and written without it they would stand without their ${n}.`}}function ve(t){let{config:e,records:n,target:r,run:s}=t,o=e.objectApiName,a=Y(e),i=r?.recordTypes??[],p=r?.references??new Set,c={payloads:[],sentAt:[],settled:[],held:[],deferred:[],deferredAcross:[],notes:[],currencies:[],withoutRecordType:new Map},g=new Map,h=new Map,F=(d,l,y,k)=>{c.held.push({index:d,reason:y}),g.delete(d);let L=h.get(l);L?L.count++:h.set(l,{count:1,say:k})},O=e.operation==="insert"||e.operation==="upsert",T=O&&i.some(d=>!d.master),b=new Map;s&&O&&s.sources.forEach((d,l)=>{let y=d?.Id;typeof y=="string"&&H.test(y)&&b.set(R(y),l)});let v=new Set([...s&&O?s.later??[]:[]].map(d=>d.toLowerCase())),m=new Set(v.size===0?[]:(r?.fields??[]).flatMap(d=>d.isReference&&(d.referenceTo??[]).some(l=>v.has(l.toLowerCase()))&&!(d.nillable===!1&&d.defaultedOnCreate!==!0)?[d.name]:[]));n.forEach((d,l)=>{let y=Me(d,e.fieldMappings,e.addOnFields,r?.creatable??null,a);if(e.operation==="delete"){g.set(l,{payload:y,settled:new Set});return}let k=new Set;if(s)for(let f of Object.keys(y)){let W=y[f];if(f==="RecordTypeId"||!p.has(f)||typeof W!="string"||!H.test(W))continue;if(b.has(R(W))){delete y[f],c.deferred.push({index:l,field:f,parent:W});continue}let _=s.links.targetOf(W);if(_){y[f]=_,k.add(f);continue}let M=s.links.refusedObjectOf(W);if(M===void 0){m.has(f)&&(delete y[f],c.deferredAcross.push({index:l,field:f,parent:W}));continue}let G=We(o,f,M);F(l,G.group,G.reason,G.say);return}let L=y.RecordTypeId,E,j=Re(L);if(j)delete y.RecordTypeId;else if(typeof L=="string"&&H.test(L)){let f=ze(L,i,s?.recordTypes);if("unmapped"in f){let W=f.unmapped,_=f.namesakes.length>0?` The target org's ${f.namesakes.join(" and ")} carries its DeveloperName under another namespace, and a record type is mapped to one of the same namespace only.`:"";F(l,`unmapped:${W}`,"RECORD_TYPE_UNMAPPED: its record type has no counterpart in the target org.",M=>`RECORD_TYPE_UNMAPPED: ${Le(M,o)} held back, not sent: `+(W?`their record type ${W} has no active ${o} record type of that API name in the target org.${_} Create or activate record type ${W} on ${o} in the target org.`:"their record type is inactive in the source org, and has no counterpart in the target org."));return}if("unavailable"in f){let W=f.unavailable;F(l,`unavailable:${W.recordTypeId}`,`RECORD_TYPE_UNAVAILABLE: record type ${W.developerName} is closed to the running user in the target org.`,_=>`${pe({objectApiName:o,recordTypeId:W.recordTypeId,developerName:W.developerName,name:W.name,inactive:!W.active,recordCount:_})} Held back, not sent.`);return}y.RecordTypeId=f.sent,E=f.sent,f.info&&k.add("RecordTypeId")}let $=s?.sources[l]??d;if(re($)){let f=oe($,Ue(r,E,s?.recordTypes?.personTypes));for(let W of Object.keys(y))B(o,W,f)&&delete y[W]}else for(let f of Object.keys(y))B(o,f,"business")&&delete y[f];T&&!("RecordTypeId"in y)&&c.withoutRecordType.set(l,j?"masterInSource":"notRead"),g.set(l,{payload:y,settled:k})});let A=!0;for(;A;){A=!1;for(let{index:d,field:l,parent:y}of c.deferred){let k=b.get(R(y));if(!g.has(d)||k===void 0||g.has(k)||s?.links.targetOf(y)!==void 0)continue;let L=We(o,l,o);F(d,L.group,L.reason,L.say),A=!0}}c.deferred=c.deferred.filter(({index:d})=>g.has(d)),c.deferredAcross=c.deferredAcross.filter(({index:d})=>g.has(d));for(let d of[...c.withoutRecordType.keys()])g.has(d)||c.withoutRecordType.delete(d);c.held.sort((d,l)=>d.index-l.index);let S=e.operation==="delete"?void 0:s?.currencies,w=r?.creatable.has(z)===!0,u=!w&&(s?.currencyChangesById?.size??0)>0&&r?.fields?.some(d=>d.name===z)===!0,C=S&&(w||u)?ae(r?.fields??[]):void 0,P=[...r?.references??[]],I=new le;for(let[d,{payload:l,settled:y}]of[...g].sort(([k],[L])=>k-L)){for(let k of X(o,l))delete l[k];if(S&&C){let k=s?.sources[d]??n[d],L=k?.[z],E=w?de(l,{read:L,currencyFields:C,ratesOn:ie(o,k)},S):ue(l,{read:L,parent:k?ce(o,k,P,$=>s?.currencyChangesById?.get($)):void 0,currencyFields:C},S);I.add(o,E);let j=k?.Id;E&&typeof j=="string"&&s?.currencyChangesById?.set(j,E)}c.payloads.push(l),c.sentAt.push(d),c.settled.push(y)}return c.notes=[...h.values()].map(({count:d,say:l})=>l(d)),c.currencies=I.list(),c}function V(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}function Ge(t){let e=V(t.length),n=V(t.precision),r=V(t.digits);return{name:t.name,queryable:t.queryable!==!1,createable:t.createable===!0,isReference:t.type==="reference",...t.type!==void 0?{type:t.type}:{},...e!==void 0?{length:e}:{},...t.nillable!==void 0?{nillable:t.nillable}:{},...t.defaultedOnCreate!==void 0?{defaultedOnCreate:t.defaultedOnCreate}:{},...t.calculated===!0?{calculated:!0}:{},...n!==void 0?{precision:n}:{},...n!==void 0&&typeof t.scale=="number"&&t.scale>=0?{scale:t.scale}:{},...r!==void 0?{digits:r}:{},...t.unique===!0?{unique:!0}:{},...t.referenceTo?{referenceTo:[...t.referenceTo]}:{}}}function pt(t){let e=t.fields.filter(r=>r.createable===!0),n=t.fields.some(r=>typeof r.idLookup=="boolean");return{creatable:new Set(e.map(r=>r.name)),references:new Set(e.filter(r=>r.type==="reference").map(r=>r.name)),...typeof t.createable=="boolean"?{objectCreateable:t.createable}:{},...typeof t.updateable=="boolean"?{objectUpdateable:t.updateable}:{},recordTypes:fe(t.recordTypeInfos),...t.name===te?{personAccounts:t.fields.some(r=>r.name===ne)}:{},fields:t.fields.map(Ge),...n?{upsertKeys:new Set(t.fields.filter(r=>r.externalId===!0||r.idLookup===!0).map(r=>r.name.toLowerCase()))}:{}}}function Z(t,e,n){switch(e){case"notInTarget":return`Object is not in the target org, or the user the run writes as cannot see it: ${t}. None of its records were sent.`;case"notCreateable":return`Object is not createable on target org: the user the run writes as may not create ${t} records there. None of its records were sent.`;case"notUpdateable":return`Object is not updateable on target org: the user the run writes as may not edit ${t} records there. None of its records were sent.`;case"unread":return`The target org did not describe ${t}${n?` (${n})`:""}, so what it takes could not be told and none of its records were sent.`;case"notAKey":return`The upsert of ${t} matches on ${n??"a field"}, which the target org does not match an upsert on: it takes an External ID field, the Id, or a field its describe marks idLookup. None of its records were sent.`}}function yt(t,e){let n=t.externalIdField?.trim().toLowerCase();if(t.operation!=="upsert"||!n)return t;let r=e.fields?.find(s=>s.name.toLowerCase()===n)?.name;return r===void 0?t:{...t,externalIdField:r}}function gt(t,e){if(t.operation==="delete"||t.query===void 0)return t;let n=Fe(t.query);if(!("list"in n))return t;let r=new Set([...n.list,t.externalIdField??"",...t.fieldMappings.filter(o=>ye.has(o.type)).map(o=>o.sourceField)].map(o=>o.toLowerCase())),s=[...e.creatable].filter(o=>!r.has(o.toLowerCase()));return s.length===0?t:{...t,excludedFields:[...new Set([...t.excludedFields??[],...s])]}}async function Ee(t,e,n,r){let s;try{s=await t(e)}catch(c){if(n==="delete")return{notAsked:!0};let g=Te(c)?"notInTarget":"unread";return{refused:{why:g,message:Z(e,g,ee(c))}}}let o=n==="insert"||n==="upsert",a=n==="update"||n==="upsert",i=o&&s.objectCreateable===!1?"notCreateable":a&&s.objectUpdateable===!1?"notUpdateable":void 0;if(i)return{refused:{why:i,message:Z(e,i)},target:s};let p=r?.trim()||"Id";return n==="upsert"&&s.upsertKeys&&!s.upsertKeys.has(p.toLowerCase())?{refused:{why:"notAKey",message:Z(e,"notAKey",p),key:p},target:s}:{target:s}}function wt(t){return t.keepContactPoints===!0?void 0:new we}function Rt(t,e){if(!t)return e?{neutralized:!1,fields:[],values:0}:void 0;let n=t.report();return n.values>0?n:void 0}function Pe(t,e,n,r,s){let o=s?n.filter(i=>i.name!==s):n,a=t.forObject(e,o);if(a)for(let i of r)a(i)}var x=class extends Error{constructor(n,r=[],s=[],o=[],a){super(r.length===0?`The write of ${n} was cancelled before any of its records was written.`:`The write of ${n} was cancelled after ${r.length} of its records were sent.`);this.objectApiName=n;this.written=r;this.notes=s;this.lookupsLeftOut=o;this.writtenWithoutFields=a;this.name="WriteCancelledError"}objectApiName;written;notes;lookupsLeftOut;writtenWithoutFields};var xe=class{deps;constructor(e){this.deps=e}async sync(e,n,r){let{outcomes:s,notes:o,currencies:a,lookupsLeftOut:i,writtenWithoutFields:p}=await this.write(e,n,r);return Ze(Je(e.objectApiName,e.operation,s,o,i,p),a)}updateRecords(e,n,r){return this.executeOperation(e,"update",n,r)}async write(e,n,r){let s=null;if(this.deps.describeTargetFields){let u=await Ee(this.deps.describeTargetFields,e.objectApiName,e.operation,e.externalIdField);if("refused"in u){let C=n.map(()=>({success:!1,errors:[u.refused.message]}));return r&&De(e,C,r),{outcomes:C,notes:[],currencies:[],lookupsLeftOut:[]}}"target"in u&&u.target.creatable.size>0&&(s=u.target)}let o=ve({config:e,records:n,target:s,run:r}),a=r?r.contactPoints:this.deps.contactPoints;a&&s?.fields&&Pe(a,e.objectApiName,s.fields,o.payloads,e.externalIdField);let i=qe(o.payloads,o.settled,r),p=new Map(o.held.map(({index:u,reason:C})=>[u,C])),c=u=>{let C=[],P=0;for(let I=0;I<n.length;I++){let d=p.get(I);if(d!==void 0){C.push({success:!1,errors:[d],heldBack:!0});continue}if(P>=u.length)break;C.push(u[P++])}return C},g,h=o.sentAt.filter(u=>u<(r?.standardFirst??0)).length,F=u=>this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField);try{g=o.payloads.length===0&&n.length>0?[]:h>0&&h<o.payloads.length?await Ye(e.objectApiName,F,o.payloads.slice(0,h),o.payloads.slice(h)):await F(o.payloads)}catch(u){if(!(u instanceof x))throw u;let C=Ne(i,u.written),P=c(u.written);throw je(e,o.withoutRecordType,P,s,r),new x(e.objectApiName,P,[...o.notes,...u.notes],[...C?[C]:[],...u.lookupsLeftOut,...Q(U([...o.deferred,...o.deferredAcross],P))],u.writtenWithoutFields)}let O=await this.retryRefused(e,o.payloads,g,s?.references??null,o.settled);if(r)for(let u of O.ownersRefused)r.links.noteOwnerRefused(u);let T=c(O.outcomes);je(e,o.withoutRecordType,T,s,r);let b=Ne(i,O.outcomes),v=[...o.notes,...O.notes],m=[...b?[b]:[],...O.lookupsLeftOut],{writtenWithoutFields:A}=O,S=U(o.deferredAcross,T),w=0;if(O.cancelled)throw new x(e.objectApiName,T,v,[...m,...Q([...U(o.deferred,T),...S])],A);if(r){De(e,T,r),Ve(e,o.payloads,O.outcomes,r.links);let u=await this.setLookups(e,U(o.deferred,T),r.links,!1);if(m.push(...u.leftOut),w=u.unset,u.cancelled)throw new x(e.objectApiName,T,v,[...m,...Q(S)],A)}return{outcomes:T,notes:v,currencies:o.currencies,lookupsLeftOut:m,...A?{writtenWithoutFields:A}:{},...S.length>0?{lookupsToSet:S}:{},...w>0?{lookupsUnset:w}:{}}}async setLookups(e,n,r,s){let o=e.objectApiName,a=new Map,i=new Map,p=new D;for(let{id:b,field:v,parent:m}of n){let A=r.targetOf(m),S=A!==void 0?a:s&&r.refusedObjectOf(m)===void 0?i:void 0;if(!S){p.add(b,v);continue}let w=S.get(b)??{Id:b};w[v]=A??m,S.set(b,w)}let c=new D,g=new D,h=new D,F=new D,O=!1;for(let b of[[...a.values()],[...i.values()]]){if(b.length===0)continue;if(O){for(let m of b)F.addRow(m);continue}let v;try{v=await this.executeOperation(o,"update",b,e.batchSize)}catch(m){if(!(m instanceof x)){let A=m instanceof Error?m.message:String(m);for(let S of b)h.addRow(S,A);continue}v=m.written,O=!0}b.forEach((m,A)=>{let S=v[A];S===void 0?F.addRow(m):S.success?c.addRow(m):S.errors.some(w=>J(w))?g.addRow(m):h.addRow(m,S.errors[0])})}let T=[p,g,h,F];return{...c.records>0?{set:{records:c.records,fields:c.fields()}}:{},leftOut:[p.leftOut("parentRefused"),g.leftOut("notInTarget"),h.leftOut("notSet"),F.leftOut("notReached")].flatMap(b=>b?[b]:[]),unset:new Set(T.flatMap(b=>[...b.recordIds])).size,cancelled:O}}async retryRefused(e,n,r,s,o){let a=Y(e)??void 0,i=[...r],p=[...n],c=n.map(()=>new Set),g=n.map(()=>[]),h=n.map(()=>[]),F=[],O,T=new Set;for(let S=0;S<2&&!O;S++){let w=[],u=[],C=[];if(i.forEach((I,d)=>{if(I.success)return;let l=p[d],y=o[d]??new Set;if(I.errors.some(E=>J(E))){let E=n[d]?.[N];if(typeof E=="string"&&!y.has(N)&&(I.errorDetails??[]).some(f=>J(f.statusCode)&&f.fields.includes(N))&&T.add(E),c[d].has("lookup")||!s||s.size===0)return;let j={},$=!1;for(let f of Object.keys(l)){if(s.has(f)&&!y.has(f)&&l[f]!==null&&l[f]!==void 0){$=!0;continue}j[f]=l[f]}if(!$)return;w.push(d),u.push(j),C.push(null);return}if(c[d].has("fields"))return;let k=he(I.errorDetails,l,a);if(!k||k.some(({field:E})=>y.has(E)))return;let L=new Set(k.map(({field:E})=>E));w.push(d),u.push(Object.fromEntries(Object.entries(l).filter(([E])=>!L.has(E)))),C.push(k)}),w.length===0)break;let P;try{P=await this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField)}catch(I){if(!(I instanceof x)){F.push(...He(w,p,u,C,I));break}P=I.written,O=I}P.forEach((I,d)=>{let l=w[d],y=C[d];c[l].add(y===null?"lookup":"fields"),y===null?g[l].push(...Object.keys(p[l]).filter(k=>!(k in u[d]))):h[l].push(...y),p[l]=u[d],i[l]=I})}let b=new Set,v=0,m,A=new Set(T);return i.forEach((S,w)=>{if(!(!S.success||c[w].size===0)){if(g[w].length>0){v++;for(let C of g[w])b.add(C);let u=n[w]?.[N];typeof u=="string"&&g[w].length===1&&g[w][0]===N&&A.add(u)}h[w].length>0&&(m=me(m,{rows:1,fields:h[w].map(u=>({...u,rows:1}))}))}}),{outcomes:i,notes:[...F,...O?.notes??[]],...m?{writtenWithoutFields:m}:{},cancelled:O!==void 0,ownersRefused:[...A],lookupsLeftOut:[...v>0?[{records:v,fields:[...b].sort(),reason:"notInTarget"}]:[],...O?.lookupsLeftOut??[]]}}async executeOperation(e,n,r,s,o){if(this.deps.crudFlsGuard){let a=r.length>0?Object.keys(r[0]):[],i=await this.deps.crudFlsGuard.checkCrudAndFls(e,n,a);if(!i.allowed)throw new Error(`CRUD/FLS check failed for ${n} on ${e}: ${i.reason}`)}switch(n){case"insert":return this.deps.insert(e,r,s);case"update":return this.deps.update(e,r,s);case"upsert":return this.deps.upsert(e,o??"Id",r,s);case"delete":{let a=r.map(i=>i.Id).filter(i=>typeof i=="string");return this.deps.delete(e,a,s)}}}},Be=["INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY","INVALID_CROSS_REFERENCE_KEY"],Ke=/cross[- ]reference id|r[ée]f[ée]rence crois[ée]e/i;function J(t){return Be.some(e=>t.includes(e))||Ke.test(t)}var N="OwnerId";function qe(t,e,n){let r=new Set;return n&&t.forEach((s,o)=>{let a=s[N];typeof a!="string"||e[o]?.has(N)||n.links.isOwnerRefused(a)&&(delete s[N],r.add(o))}),r}function Ne(t,e){let n=0;for(let r of t)e[r]?.success&&n++;if(n!==0)return{records:n,fields:[N],reason:"ownerRefusedEarlier"}}function He(t,e,n,r,s){let o=s instanceof Error?s.message:String(s),a=new Set,i=new Set,p=0;return r.forEach((c,g)=>{if(c===null){p++;let h=n[g];for(let F of Object.keys(e[t[g]]))F in h||a.add(F)}else for(let{field:h}of c)i.add(h)}),[...p>0?[`${p} record(s) the target refused for a lookup it does not have could not be written again without ${[...a].sort().join(", ")}: ${o}`]:[],...i.size>0?[`${t.length-p} record(s) the target refused on fields it named could not be written again without ${[...i].sort().join(", ")}: ${o}`]:[]]}var D=class{ids=new Set;named=new Set;said;add(e,n){this.ids.add(e),this.named.add(n)}addRow(e,n){let r=String(e.Id);for(let s of Object.keys(e))s!=="Id"&&this.add(r,s);n!==void 0&&n!==""&&(this.said??=n)}get records(){return this.ids.size}get recordIds(){return this.ids}fields(){return[...this.named].sort()}leftOut(e){if(this.ids.size!==0)return{records:this.ids.size,fields:this.fields(),reason:e,...this.said!==void 0?{refusal:this.said}:{}}}};function U(t,e){return t.flatMap(({index:n,field:r,parent:s})=>{let o=e[n];return o?.success&&typeof o.id=="string"&&o.id!==""?[{id:o.id,field:r,parent:s}]:[]})}function It(t){return new Set(t.map(({id:e})=>e)).size}function Q(t){let e=new D;for(let{id:r,field:s}of t)e.add(r,s);let n=e.leftOut("notReached");return n?[n]:[]}function _e(t,e){if(!(e.success||t!=="insert"&&t!=="upsert"))return e.existingId!==void 0&&e.existingId!==""?e.existingId:void 0}async function Ye(t,e,n,r){let s=await e(n);try{return[...s,...await e(r)]}catch(o){throw o instanceof x?new x(t,[...s,...o.written],o.notes,o.lookupsLeftOut,o.writtenWithoutFields):o}}function je(t,e,n,r,s){if(!s?.createdWithoutRecordType||e.size===0)return;let o=[],a=[];for(let[c,g]of e){let h=n[c];!h?.success||typeof h.id!="string"||h.id===""||t.operation!=="insert"&&h.created!==!0||(o.push(g),a.length<Se&&a.push(h.id))}let i=Ie(s.recordTypesUnderTheLease??r?.recordTypes??[],s.recordTypes),p=Ae(t.objectApiName,o,i);p&&s.createdWithoutRecordType.set(t.objectApiName,{given:p,types:i,ids:a})}function Ve(t,e,n,r){t.objectApiName==="Opportunity"&&(t.operation!=="insert"&&t.operation!=="upsert"||e.forEach((s,o)=>{let a=n[o],i=s[se];!a?.success||typeof a.id!="string"||a.id===""||t.operation!=="insert"&&a.created!==!0||typeof i=="string"&&i!==""&&r.noteSentWithContact(a.id,i)}))}function De(t,e,n){if(t.operation==="delete")return;let r=t.operation==="insert"||t.operation==="upsert";e.forEach((s,o)=>{let a=n.sources[o]?.Id;if(typeof a!="string"||a==="")return;let i=_e(t.operation,s);s.success&&typeof s.id=="string"&&s.id!==""?n.links.noteWritten(a,s.id):i!==void 0?n.links.noteWritten(a,i):!s.success&&r&&n.links.noteRefused(a,t.objectApiName)})}function Ze(t,e){return e.length>0?{...t,currenciesReplaced:[...e]}:t}var $e=1e3;function Je(t,e,n,r=[],s=[],o){let a=0,i=0,p=0,c,g=[],h=0,F={created:0,updated:0};for(let T of n)T.success?(a++,T.created===!0?F.created++:T.created===!1&&F.updated++):_e(e,T)!==void 0?(p++,c??=T.errors[0]):(i++,!T.heldBack&&h++<$e&&g.push(...T.errors));let O=Math.max(0,h-$e);return{objectApiName:t,operation:e,processed:n.length,success:a,failed:i,skipped:p,conflictCount:0,errors:[...g,...r],...p>0?{linkedToExisting:{records:p,...c?{refusal:c}:{}}}:{},...s.length>0?{lookupsLeftOut:[...s]}:{},...o?{writtenWithoutFields:o}:{},...O>0?{refusalsDropped:O}:{},...e==="upsert"?{upsertSplit:F}:{}}}export{Ce as a,Ae as b,Ie as c,ve as d,pt as e,yt as f,gt as g,Ee as h,wt as i,Rt as j,Pe as k,x as l,xe as m,It as n,Q as o,_e as p,Ze as q,$e as r,Je as s};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-FQBRBBY4.mjs";import"./chunk-F74IHMGL.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-Y5CGXLUB.mjs";import"./chunk-3F5YMM2F.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{h as ACTIVE_DUPLICATE_RULES_SOQL,a as FORMULAS_BOUND,c as FORMULAS_IN_COMPOSITES_BOUND,b as FORMULA_REQUESTS_BOUND,o as TargetGapReader,i as bypassesOf,j as callsEstimateOf,f as fieldLabelsSoql,p as gapAnsweredBy,d as gapFieldOf,r as gapLines,q as gapsWithAnswers,l as readActiveValidationRules,m as readValidationRuleBypasses,k as toolingQueriesOver,n as toolingValidationRules,g as validationFormulaSoql,e as validationRulesSoql};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{c as De,d as Cn,f as ve}from"./chunk-H45UXY6G.mjs";import{l as B}from"./chunk-WRU5FJFC.mjs";import{b as On,d as En}from"./chunk-GNC27UEU.mjs";import{a as In,c as Pn}from"./chunk-YBU4Z4QV.mjs";import{Bc as It}from"./chunk-YMJVMFPY.mjs";import{a as z,c as xe}from"./chunk-BOGNK4LV.mjs";import{$a as pn,Q as an,R as dn,W as cn,X as un,Z as ln,ab as fn,g as on,hb as gn,ib as mn,jb as hn,kb as yn,lb as wn,nb as Sn,ob as bn,qb as Rn,ub as kn,vb as An}from"./chunk-36U7IQ6Y.mjs";import{i as Pt,p as Lt}from"./chunk-Z7X534S4.mjs";import{$ as Bt,G as Ot,N as Et,Z as $t,m as Me,r as Ct}from"./chunk-6QSM2WIH.mjs";import{a as Te}from"./chunk-QSRAEUGZ.mjs";import{a as Nt}from"./chunk-Y5CGXLUB.mjs";import{f as Dt,h as vt,i as V,k as jt}from"./chunk-3F5YMM2F.mjs";import{l as At}from"./chunk-SAR5622P.mjs";import{s as Tt,w as xt}from"./chunk-6MUEPV7M.mjs";import{A as Ee,B as pt,C as Ie,w as ut,z as lt}from"./chunk-HJC7AIBK.mjs";import{b as Pe,c as Y,d as $}from"./chunk-OTWRDD6L.mjs";import{c as dt,d as ct}from"./chunk-55HEMHEG.mjs";import{Aa as Qt,Ba as en,D as Wt,E as Gt,Ga as tn,Ha as nn,Ia as rn,K as Ut,L as zt,N as _,O as ae,P as qt,Q as de,R as Kt,S as Ht,T as ce,U as ue,W as Jt,Wa as sn,_ as X,qa as Yt,ta as Vt,ua as Xt,v as Ft,w as Mt,wa as Zt}from"./chunk-VXHDBYMI.mjs";import{q as _t}from"./chunk-ENLBYECD.mjs";import{a as at}from"./chunk-EADHKH3A.mjs";import{a as wt,d as St,e as bt,f as Rt,g as kt}from"./chunk-PNCONNFJ.mjs";import{E as ot}from"./chunk-CGWXQX75.mjs";import{f as it,h as J}from"./chunk-TZE3Y7IQ.mjs";import{c as ft,d as gt,f as mt,h as ht,j as yt,k as Fe}from"./chunk-SIOZXPFG.mjs";import{b as M}from"./chunk-CA5NAXSU.mjs";import{Fb as se,Jb as ie,Oc as st,Tb as nt,Va as et,Wa as ne,Yb as rt,bd as Oe,dc as oe,f as Ze,gb as tt,h as Ce,i as Qe,j as U,vb as re}from"./chunk-B45CNPUX.mjs";import{b as H,k as Re,l as ke,u as Ve,v as Xe,z as Ae}from"./chunk-7EANH5PY.mjs";var le=class{classify(e){let t=ne(e.statusCode),r=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:r}}classifyBatch(e){let t=e.map(a=>this.classify(a)),r={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},s={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";r[d]=(r[d]??0)+1,s[a.originalError.statusCode]=(s[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:r,byErrorCode:s,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return ne(e).retryable}hasBlockingError(e){return e.some(t=>ne(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys(et).length}getSuggestedAction(e,t){return t.suggestUpsert?"Consider using upsert with external ID":t.suggestTruncate?"Truncate field values to fit within limits":t.blockAll?"Operation blocked: resolve storage/limit issue first":t.strategy==="reauth_then_retry"?"Re-authenticate and retry":t.strategy==="reduce_batch"?"Reduce batch size and retry":t.retryable?`Retry after ${t.delay??0}ms`:`Fix ${e} error and retry manually`}};function ar(n,e){return new Promise(t=>{if(e?.aborted){t();return}let r=()=>{clearTimeout(s),e?.removeEventListener("abort",r),t()},s=setTimeout(r,n);e?.addEventListener("abort",r,{once:!0})})}var pe=class{constructor(e={}){this.options=e;this.strategy=new Nt({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new le}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),r,s=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:s}}catch(o){r=o instanceof Error?o:new Error(String(o));let a=dr(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:r,attempts:i+1,totalDelay:s};if(i<t.maxRetries){let u={success:!1,error:r,attempts:i+1,totalDelay:s,cancelled:!0};if(this.options.signal?.aborted)return u;let c=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,c),s+=c,await ar(c,this.options.signal),this.options.signal?.aborted)return{...u,totalDelay:s}}}return{success:!1,error:r,attempts:t.maxRetries+1,totalDelay:s}}async executeBatch(e,t){let r=[...e],s=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;r.length>0&&o<=a;){let d=await t(r);s.push(...d.successes);let u=[];for(let c of d.failures)this.classifier.classify(c.error).classification.retryable&&o<a?u.push(c.record):i.push(c);if(r=u,r.length>0){let c=this.options.retryConfig?.initialDelay??1e3,l=this.options.retryConfig?.maxDelay??3e4,p=c*Math.pow(2,o);await new Promise(f=>setTimeout(f,Math.min(p,l))),o++}}return{successes:s,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function dr(n){if(typeof n!="object"||n===null)return{statusCode:"UNKNOWN_ERROR",message:String(n)};let e=n,t=[e.errorCode,e.statusCode,e.name].find(s=>typeof s=="string"&&s.length>0&&s!=="Error"),r=e.fields??e.data?.fields;return{statusCode:t??"UNKNOWN_ERROR",errorCode:typeof e.errorCode=="string"?e.errorCode:void 0,message:typeof e.message=="string"?e.message:String(n),fields:Array.isArray(r)?r.filter(s=>typeof s=="string"):void 0}}var cr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ur(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function lr(n,e,t,r=()=>Date.now()){let s=await At(n,e,{now:r,successfulOnly:!0});return s.state==="running"?{state:"running"}:s.state!=="ended"?s:{state:"ended",created:(s.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!cr.test(a)?[]:t&&ur(o.sf__Created)!==!0?[]:[a]}),...typeof s.info.systemModstamp=="string"?{at:s.info.systemModstamp}:{}}}async function Js(n,e,t,r,s=()=>new Date){let i,o=()=>(i??=(async()=>{if(!r)return 0;try{let d=s().getTime(),u=Date.parse(await r());return Number.isFinite(u)?u-(d+s().getTime())/2:0}catch{return 0}})(),i),a=[];for(let d of e.jobs??[]){if(d.job===void 0)continue;let u={job:d.job,objectApiName:d.objectApiName},c=await lr(t,d.job,d.upsert===!0,()=>s().getTime());if(c.state==="running"||c.state==="unread"){a.push({...u,read:c,answered:!1});continue}let l=s().toISOString();c.state==="ended"&&c.at!==void 0&&Number.isFinite(Date.parse(c.at))?l=new Date(Date.parse(c.at)-await o()).toISOString():e.lastWrittenAt!==void 0&&(l=e.lastWrittenAt);let p=c.state==="ended"?c.created:[],f=await n.answerInFlight(e.runId,d.objectApiName,p,l,d.job);a.push({...u,read:c,answered:f})}return a}function Ys(n,e){return e.map(({job:t,read:r})=>{let s=`${n}, job ${t}`;switch(r.state){case"ended":return`[INFO] ${s}: the job no line of the run answered ended in the org; ${r.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${s}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${s}: the job is still running in the org; read again later`;default:return`[WARN] ${s}: the job could not be read back: ${r.reason}`}})}var K=5e3,$e=200,fe=H().refine(n=>Y(n),"not a record id"),pr=ke({sourceOrgId:H().min(1).max(200),targetOrgId:H().min(1).max(200),objectApiName:H().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:Ve(["document","attachment"]),sourceId:fe,targetId:fe,sourceVersionId:fe.optional(),sourceModifiedAt:Ae.datetime().optional(),linked:Re(fe).max($e),copiedAt:Ae.datetime()}),fr=ke({version:Xe(1),entries:Re(pr).max(K)});function Mn(n){if(n==null)return{kind:"none"};let e=fr.safeParse(n);if(e.success)return{kind:"stored",map:e.data};let t=e.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"map"}: ${t.message}`}}function ai(n,e,t){return n?n.check({orgId:e,orgTier:rt(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var W=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Z=class extends Error{};function gr(){return{copied:0,versions:0,bytes:0,links:0,unchanged:0,tooLarge:0,pastRunCap:0,external:0,recordNotWritten:0,failed:0}}function N(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function ge(n,e){let t=n;for(let r of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[r]}return Ie(t)}function q(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function mr(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function Q(n,e,t){return`${n}|${e}|${t}`}function hr(n,e){let t=e.load(n.id);if(t===null)throw new W("Files are copied by a saved configuration only: it keeps which file it copied where, so that running it again copies none of them twice. Save the configuration, then run it. Nothing was read or written.");if(t.kind==="unreadable")throw new W(`The record of the files this configuration copied could not be read (${t.issue}), so a run could copy them a second time. Turn the files off, or save the configuration again under a new name. Nothing was read or written.`);let r=new Map;if(t.kind==="stored")for(let s of t.map.entries)r.set(Q(s.sourceOrgId,s.targetOrgId,s.sourceId),s);return r}var je="ContentDocument.LatestPublishedVersion.SystemModstamp";async function yr(n,e,t,r){let s=nt(t.objectApiName),i=t.where?.trim()?` WHERE (${it(t.where)})`:"",o=`SELECT Id FROM ${s}${i}`,a=Ee(r),d=new Set,u,c=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${je} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${je} > ${a})`);for(let p of c){let f=N(p,"LinkedEntityId");f&&Y(f)&&d.add(f),u=q(q(u,ge(p,"SystemModstamp")),ge(p,je))}let l=await n.copy.queryRecords(e.sourceOrgId,`SELECT ParentId, LastModifiedDate FROM Attachment WHERE ParentId IN (${o}) AND LastModifiedDate > ${a}`);for(let p of l){let f=N(p,"ParentId");f&&Y(f)&&d.add(f),u=q(u,ge(p,"LastModifiedDate"))}return{ids:[...d],...u!==void 0?{newest:u}:{}}}async function wr(n,e,t){let r=new Map;for(let s of $(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${s})`);for(let o of i){let a=N(o,"Id"),d=Ie(o.LastModifiedDate);a&&d&&r.set(a,d)}}return r}function Sr(n,e,t){return e===void 0||n.targetId===n.sourceId?!1:n.sourceModifiedAt!==void 0?n.sourceModifiedAt!==e:t!==void 0&&Date.parse(e)>Date.parse(t)}async function br(n,e,t,r,s,i){let o=[...s.values()].filter(c=>c.kind==="document"&&c.objectApiName===t&&c.sourceOrgId===e.sourceOrgId&&c.targetOrgId===e.targetOrgId&&!i.has(c.sourceId)).map(c=>c.sourceId),a=Ee(r),d=[],u;for(let c of $(o)){let l=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SystemModstamp FROM ContentVersion WHERE ContentDocumentId IN (${c}) AND IsLatest = true AND SystemModstamp > ${a}`);for(let p of l){u=q(u,ge(p,"SystemModstamp"));let f=N(p,"ContentDocumentId"),g=N(p,"Id");if(!f||!g||(N(p,"ContentLocation")??"S")!=="S")continue;let h=N(p,"Title")??f;d.push({objectApiName:"ContentDocument",sourceId:f,body:{objectApiName:"ContentVersion",id:g},name:h,bytes:mr(p,"ContentSize"),hosts:[],fields:{Title:h,PathOnClient:N(p,"PathOnClient")??h}})}}return{files:d,...u!==void 0?{newest:u}:{}}}async function Rr(n,e,t,r){let s=new Map,i=new Date().toISOString(),o=(c,l,p)=>({sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:t,kind:c,sourceId:l,targetId:l,linked:[],copiedAt:i,...p}),a=r.filter(c=>c.objectApiName==="ContentDocument").map(c=>c.sourceId);for(let c of $(a)){let l=await n.copy.queryRecords(e.targetOrgId,`SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN (${c})`);for(let p of l){let f=N(p,"Id");if(!f)continue;let g=N(p,"LatestPublishedVersionId");s.set(f,o("document",f,g?{sourceVersionId:g}:{}))}}let d=[...s.keys()];for(let c of $(d)){let l=await n.copy.queryRecords(e.targetOrgId,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${c})`);for(let p of l){let f=N(p,"ContentDocumentId"),g=N(p,"LinkedEntityId"),h=f?s.get(f):void 0;h&&g&&Y(g)&&h.linked.length<$e&&h.linked.push(g)}}let u=r.filter(c=>c.objectApiName==="Attachment").map(c=>c.sourceId);for(let c of $(u)){let l=await n.copy.queryRecords(e.targetOrgId,`SELECT Id FROM Attachment WHERE Id IN (${c})`);for(let p of l){let f=N(p,"Id");f&&s.set(f,o("attachment",f,{}))}}return s}async function di(n){let{config:e,option:t,objects:r,deps:s}=n,i=hr(e,s.store),o;try{o=await cn(s.copy,e.targetOrgId)}catch(f){throw new W(`The file storage the target has left could not be read (${M(f)}), so the files could not be measured against it. Nothing was written.`)}let a=t.maxFileSizeMB*1048576,d=t.maxRunMB*1048576,u=0,c=0,l=new Set,p={objects:new Map,storage:{remainingBytes:o,plannedBytes:0}};for(let{objectConfig:f,changedSince:g,filesSeen:h}of r){if(f.operation==="delete")continue;let w=f.objectApiName,A=await s.sourceIds(f,g),R=[],y=g===void 0?void 0:h!==void 0&&Date.parse(h)>Date.parse(g)?lt(h):g,S=g===void 0?void 0:h,m=new Map;if(y!==void 0)try{let C=new Set(A),E=await yr(s,e,f,y);S=q(S,E.newest);let F=E.ids.filter(x=>!C.has(x));if(F.length>0){let x=n.tie?await n.tie(f,F):{held:new Map};m=x.held;let G=F.filter(or=>!m.has(or)).length;G>0&&R.push(`${G} record(s) whose files changed since the last run, and nothing else of them, could not be tied to their copy in the target`+(x.refused?` (${x.refused})`:"")+": their new files are copied when the record changes, or on a full read.")}}catch(C){throw new W(`${w}: the files its records gained since the last run could not be looked up (${M(C)}). Run it again, or turn the files off. Nothing was written.`)}let b=[...A,...m.keys()],T=await an({scope:new Map([[w,b]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:s.copy.queryRecords});if(dn(T)){let C=new Set(T.errors.flatMap(E=>E.samples.flatMap(F=>F.messages)));throw new W(`${w}: the files of its records could not all be looked up in the source (${[...C].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let I=gr();for(let C of T.leftOut)C.reason==="too-large"?I.tooLarge++:C.reason==="external"&&I.external++;I.tooLarge>0&&R.push(`${I.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let P=T.files,v=[],j=new Map;try{if(y!==void 0){let F=new Set(P.map(G=>G.sourceId)),x=await br(s,e,w,y,i,F);S=q(S,x.newest);for(let G of x.files)G.bytes>a?I.tooLarge++:P=[...P,G]}let C=P.filter(F=>!i.has(Q(e.sourceOrgId,e.targetOrgId,F.sourceId)));if(C.length>0)for(let[F,x]of await Rr(s,e,w,C))i.set(Q(e.sourceOrgId,e.targetOrgId,F),x),v.push(x);let E=P.filter(F=>F.objectApiName==="Attachment");E.length>0&&(j=await wr(s,e,E.map(F=>F.sourceId)))}catch(C){throw new W(`${w}: the files an earlier run copied could not be looked up (${M(C)}), so a run could copy them twice. Nothing was written.`)}let D=[],L=new Map,k=0,O=0;for(let C of P){if(l.has(C.sourceId)){I.unchanged++,D.push(C);continue}let E=i.get(Q(e.sourceOrgId,e.targetOrgId,C.sourceId)),F=E?.kind==="attachment"&&Sr(E,j.get(C.sourceId),g);if(F&&!s.deleteFromTarget){O++;continue}if(E&&!F&&(E.kind==="attachment"||E.sourceVersionId===C.body.id)){I.unchanged++,E.kind==="document"&&D.push({...C,into:{documentId:E.targetId,linked:E.linked,unchanged:!0}});continue}if(!E&&c>=K-i.size){k++,I.pastRunCap++;continue}if(u+C.bytes>d){I.pastRunCap++;continue}u+=C.bytes,I.bytes+=C.bytes,l.add(C.sourceId),E&&F?(I.replaced=(I.replaced??0)+1,L.set(C.sourceId,E.targetId),D.push(C)):E?(I.versions++,D.push({...C,into:{documentId:E.targetId,linked:E.linked}})):(c++,I.copied++,D.push(C))}I.pastRunCap>k&&R.push(`${I.pastRunCap-k} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),O>0&&R.push(`${O} legacy attachment(s) the source changed since they were copied were left as copied: replacing one deletes its earlier copy, and this run may not delete in the target.`),k>0&&R.push(`${k} file(s) were not copied: this configuration keeps the record of ${K} copied files at most, which it holds already.`),p.objects.set(w,{scope:new Set(b),files:D,outcome:I,notes:R,shared:v,held:m,replacing:L,attachmentsChangedAt:j,...S!==void 0?{filesSeen:S}:{}})}return p.storage={remainingBytes:o,plannedBytes:u,...u>o?{shortfall:`The files to copy take ${oe(u)} and the target has ${oe(Math.max(0,o))} of file storage left. Lower the largest file or the most a run copies, or leave the files out.`}:{}},p}function kr(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function ci(n){let{config:e,option:t,objectApiName:r,planned:s,written:i,deps:o,signal:a}=n,d={...s.outcome,copied:0,versions:0,bytes:0,...s.outcome.replaced!==void 0?{replaced:0}:{}},u=[...s.notes],c=[...i.keys()].filter(m=>!s.scope.has(m)).length;c>0&&u.push(`${c} record(s) written were not in the source when the files were looked up: their files are copied by the next run.`);try{for(let m of s.shared)o.store.record(e.id,m)}catch(m){u.push(`The files the target already held could not be recorded (${M(m)}): the next run looks them up again.`)}if(s.files.length===0)return{outcome:d,notes:u,unplanned:c,cancelled:!1};let l=o.store.load(e.id),p=new Map((l?.kind==="stored"?l.map.entries:[]).filter(m=>m.sourceOrgId===e.sourceOrgId&&m.targetOrgId===e.targetOrgId).map(m=>[m.sourceId,m])),f=s.files.map(m=>{let b=m.into?void 0:p.get(m.sourceId);return b&&b.kind==="document"?{...m,into:{documentId:b.targetId,linked:b.linked,unchanged:!0}}:m}),g=un({files:f.filter(m=>!m.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),h=[],w,A=!1,R=[],y={ids:[],note:void 0},S=(m,b)=>{let T=Q(e.sourceOrgId,e.targetOrgId,m.sourceId),I=[...new Set([...m.into?.linked??[],...b.linked])].slice(0,$e),P=m.objectApiName==="ContentDocument",v=s.replacing.get(m.sourceId),j=s.attachmentsChangedAt.get(m.sourceId);b.asVersion?(d.versions++,d.bytes+=m.bytes):v!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=m.bytes):m.into?.unchanged||(d.copied++,d.bytes+=m.bytes),!b.asVersion&&!m.into&&n.onCreated?.(P?"ContentDocument":"Attachment",b.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:r,kind:P?"document":"attachment",sourceId:m.sourceId,targetId:b.targetId,...P?{sourceVersionId:m.body.id}:{},...!P&&j!==void 0?{sourceModifiedAt:j}:{},linked:I,copiedAt:new Date().toISOString()}),v!==void 0&&v!==b.targetId&&R.push(v)}catch(D){w=`${M(D)} (${T})`}};try{await ln({files:f,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:m=>i.has(m)||s.held.has(m),get:m=>i.get(m)??s.held.get(m),add:()=>{}},deps:o.copy,report:g,errors:h,waitIfPaused:async()=>{if(w!==void 0)throw new Z;if(await n.waitIfPaused?.(),a?.aborted)throw new Z},onProgress:m=>{m.status==="running"&&o.onProgress?.(m.progress,`${r}: ${m.message}`)},onCopied:S})}catch(m){if(!(m instanceof Z))throw m;A=w===void 0}finally{R.length>0&&(y=await Ar(o,R))}return d.links=g.links,d.failed=g.objects.reduce((m,b)=>m+b.failed,0)+y.ids.length,d.recordNotWritten=g.leftOut.filter(m=>m.reason==="record-not-created").length,u.push(...kr(h)),y.note!==void 0&&u.push(y.note),d.recordNotWritten>0&&u.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),w!==void 0&&(d.failed++,u.push(`A copied file could not be recorded, so no more files were copied: ${w}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:u,unplanned:c,cancelled:A}}var Fn=200;async function Ar(n,e){let t=[],r=new Set;for(let s=0;s<e.length;s+=Fn){let i=e.slice(s,s+Fn);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let u=o[d];u?.success||(t.push(a),r.add(u?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),r.add(M(o))}}return t.length===0?{ids:[],note:void 0}:{ids:t,note:`${t.length} earlier copy(ies) of an attachment replaced could not be deleted from the target (${[...r].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function ui(n){let e=t=>{let r=n[t];if(!r)throw new Error(`No connection for the org ${t}.`);return r};return{queryRecords:async(t,r)=>(await at(e(t).pages,r)).records,readFileBody:(t,r,s)=>gn(e(t).transport,r,s),insertFile:(t,r,s)=>mn(e(t).transport,r,s),insertRecords:async(t,r,s)=>yt(await e(t).create(r,s),r).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>hn(e(t).transport)}}function li(n){let e=0,t=0,r=0;for(let s of n)e+=s.copied+s.versions+(s.replaced??0),t+=s.bytes,r+=s.tooLarge+s.pastRunCap;return`${e} file(s), ${oe(t)} copied, ${r} skipped past the caps`}var Be="sync:config:",Tn="syncConfigs",ee="sync:delta:",Le="syncDelta",me="sync:files:",xn="syncFiles",Dn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Be}${e.id}`,e,Tn)}load(e){return this.configStore.get(`${Be}${e}`)}isSaved(e){return this.load(e)!==void 0}deltaStore(){return{load:e=>this.isSaved(e)?this.loadDelta(e):null,record:(e,t)=>this.recordWatermark(e,t)}}fileStore(){return{load:e=>this.isSaved(e)?this.loadFiles(e):null,record:(e,t)=>this.recordFile(e,t)}}list(){let e=this.configStore.getByCategory(Tn);return Object.values(e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${ee}${e}`),this.configStore.delete(`${me}${e}`),this.configStore.delete(`${Be}${e}`)}loadDelta(e){return ut(this.configStore.get(`${ee}${e}`))}recordWatermark(e,t){let r=this.loadDelta(e),o={version:1,entries:[...(r.kind==="stored"?r.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...r.kind==="stored"&&r.state.resetAt?{resetAt:r.state.resetAt}:{}};this.configStore.set(`${ee}${e}`,o,Le)}loadFiles(e){return Mn(this.configStore.get(`${me}${e}`))}recordFile(e,t){let r=this.loadFiles(e);if(r.kind==="unreadable")throw new Error(`the record of copied files does not read: ${r.issue}`);let i=(r.kind==="stored"?r.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=K)throw new Error(`the record of copied files holds ${K} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${me}${e}`,o,xn)}forgetFiles(e,t,r){let s=this.loadFiles(e);if(s.kind!=="stored"||r.length===0)return[];let i=new Set(r.map(d=>d.slice(0,15))),o=[],a=s.map.entries.filter(d=>{let u=d.sourceOrgId===t.sourceOrgId&&d.targetOrgId===t.targetOrgId&&i.has(d.targetId.slice(0,15));return u&&o.push(d),!u});if(o.length>0){let d={version:1,entries:a};this.configStore.set(`${me}${e}`,d,xn)}return o}markRemoved(e,t,r,s){let i=this.loadDelta(e);if(i.kind!=="stored"||r.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!r.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:s}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${ee}${e}`,d,Le)}return o}clearDelta(e){let t=this.loadDelta(e),r=t.kind==="stored"?t.state.entries.length:0,s={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${ee}${e}`,s,Le),r}};async function Cr(n,e,t){let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=J(i);for(let d of $(o)){if(t?.aborted)return;let u=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${a} WHERE Id IN (${d})`);for(let c of u.records){let l=Date.parse(String(c.CreatedDate??""));Number.isFinite(l)&&(r=Math.min(r,l),s=Math.max(s,l))}}}if(!(!Number.isFinite(r)||!Number.isFinite(s)))return{first:new Date(r).toISOString(),last:new Date(s).toISOString()}}async function Ri(n,e){let t=s=>({note:`What the duplicate rules of the target reported of the run could not be read (${M(s)}): the empty DuplicateRecordSet records it left, if any, stay.`}),r=new Set;try{for(let{ids:s}of e)for(let i of $(s)){let{records:o}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE RecordId IN (${i})`);for(let a of o){let d=a.DuplicateRecordSetId;typeof d=="string"&&r.add(d)}}}catch(s){return{take:async()=>t(s)}}return{take:async()=>{if(r.size===0)return{};let s=new Set;try{for(let a of $([...r])){let{records:d}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${a})`);for(let u of d)s.add(String(u.DuplicateRecordSetId))}}catch(a){return t(a)}let i=[...r].filter(a=>!s.has(a));if(i.length===0)return{};let o={objectApiName:"DuplicateRecordSet",planned:i.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let a=0;a<i.length;a+=Pe){let d=i.slice(a,a+Pe);for(let u of await Ct(n,o.objectApiName,d))u.kind==="deleted"?o.deleted+=1:u.kind==="gone"?o.alreadyGone+=1:(o.refused+=1,o.reasons.includes(u.reason)||o.reasons.push(u.reason))}return{object:o}}}}async function Or(n,e){if(!n||!e)return n;let t=Date.parse(e.at),r=Date.parse(e.lastAt??""),s=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(r))return n;let o=await vn(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(s,t+o):s,d=Number.isFinite(r)?Math.max(i,r+o):i;return a===s&&d===i?n:{first:a===s?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function vn(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),r=Date.parse(await n.serverTime());return Number.isFinite(r)?r-(t+e().getTime())/2:void 0}catch{return}}async function Er(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),r=await vn(n);if(r===void 0)return;let s=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+r).toISOString(),last:new Date(s+r).toISOString()}}var Ir=50,Pr=3,jn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Fr(n,e,t,r){let s=Date.parse(t.first)-yn,i=Date.parse(t.last)+wn;if(!Number.isFinite(s)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:u}of e){if(a>=Pr||o.size>1||r?.aborted)break;let c=u.slice(0,Ir);if(c.length===0)continue;let l;try{let[f]=$(c,c.length);l=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${J(d)} WHERE Id IN (${f})`)).records}catch{continue}let p=!1;for(let f of l){let{LastModifiedById:g,LastModifiedDate:h}=f??{},w=typeof h=="string"?Date.parse(h):Number.NaN;typeof g!="string"||!jn.test(g)||!(w>=s&&w<=i)||(o.has(g.slice(0,15))||o.set(g.slice(0,15),g),p=!0)}p&&a++}return o.size===1?[...o.values()][0]:void 0}async function ki(n,e,t,r,s,i,o){let a=e.some(({ids:f})=>f.length>0),d=a?await Or(await Cr(n,e,r),s):await Er(s),u=o.runUserId!==void 0&&jn.test(o.runUserId)?o.runUserId:void 0,c=n.query?.bind(n),l=!u&&!a&&d&&c?await Fr({query:c},i,d,r):void 0,p=i.filter(({ids:f})=>f.length>0);return{writtenBetween:d,created:e,remap:new Set([...e,...i].flatMap(({ids:f})=>f.map(g=>g.slice(0,15)))),automation:Sn(t),...u?{runUserId:u}:{},...l?{user:l}:{},ties:{...o.ties,...p.length>0?{writtenOver:p}:{}},...r?{signal:r}:{}}}var he={status:"cancelled",objects:[],unread:[],handWork:[]};function Ti(n,e,t){return{...Et(n,e),counts:bn(Bt($t(n),t))}}async function xi(n,e){let t=Date.parse(n.writtenBetween?.first??""),r=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(r))return n;let{created:s}=n,i=new Set(s.flatMap(({ids:u})=>u.map(c=>c.slice(0,15)))),o=await Ot(e,{has:u=>i.has(u),start:t,end:r,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},s.filter(u=>u.objectApiName==="Quote").flatMap(({ids:u})=>u),new Set(s.map(u=>u.objectApiName))),a=new Set(o.flatMap(u=>u.copies.map(c=>c.id.slice(0,15))));if(a.size===0)return n;let{remap:d}=n;return{...n,remap:{has:u=>d.has(u)||a.has(u)}}}async function Di(n){let e,t,r;try{let o=await n.input();"refused"in o?r={...he,status:"refused",refusal:o.refused}:t=Rn(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:u}=await It(n.guard,{...n.guardOf,objectName:An(a).join(", "),recordCount:kn(a)});if(e=u,u==="refused")return`Operation blocked by Production Guard: ${d.blockedReason??d.impactSummary}`;if(u==="declined")return"Operation cancelled by user (confirmation declined)."}})}catch(o){r={...he,status:"failure",refusal:M(o)}}let s=async o=>{if(!t||r)return!1;try{return await o(t)}catch(a){return r={...t.result(),status:"failure",refusal:M(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await s(async o=>(await o.ask(),!1))},get takes(){return r?[]:t?.takes??[]},first:o=>s(a=>a.first(o)),afterRemoval:o=>s(a=>a.afterRemoval(o)),result:()=>r??t?.result()??he,settle:()=>(i??=(async()=>{let o=r??t?.result()??he;return n.onGuardDecision(o,e),t&&(t.made.size>0||t.late.size>0||t.gone.size>0)&&await n.keepMade?.(t.made,t.late,t.gone).catch(()=>{}),o})(),i)}}function vi(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var Nn=6e4;function xr(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&Dr(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function Dr(n,e){let t=Date.parse(n?.first??""),r=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(r)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=r+9e5+Nn&&Math.max(e.from,e.to)>=t-2e3-Nn}var vr=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function ji(n,e){return n.filter(t=>vr.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let r=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:r,to:r}})}function jr(n){let e=Date.parse(n.firstWrittenAt??n.startedAt),t=Date.parse(n.lastWriteAt??n.lastWrittenAt??n.end?.at??n.startedAt);return{ids:[...n.created,...n.overwritten??[]].flatMap(({ids:r})=>r),from:e,to:Number.isFinite(t)?t:e}}function Nr(n,e,t){return n.filter(r=>r.targetOrgId===e&&r.runId!==t).map(jr)}async function Ni(n,e,t,r){let s=await r(n.targetOrgId,e).catch(()=>[]),i=$r(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:xr(e,[...Nr(t,n.targetOrgId,n.runId),...s]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function $i(n,e,t,r=[]){let s=[...r],i=Te(n.madeEarlier,e,s),o=Te(n.lateEarlier,t,s),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function $r(n){let e;for(let t of n??[]){let r=Date.parse(t.first);Number.isFinite(r)&&(!e||r<e.at)&&(e={at:r,first:t.first})}return e?.first}var _e=class extends Error{constructor(t,r,s){super(t);this.result=r;this.cause=s;this.name="SyncRunFailure"}result;cause},$n=class extends _e{constructor(t,r,s){super(t,r);this.code=s;this.name="SyncRunRefused"}code};var Br=2e3,Lr=5e3,ye=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??Br,this.pollIntervalMs=e.pollIntervalMs??Lr,this.signal=e.signal}async executeChunked(e,t,r,s,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:r,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,u={id:d,operation:r,object:t,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString(),totalRecords:i};e.bulkManager.registerJob(u);try{await a.open();let c=bt(a);c!==void 0&&e.onOpened?.(c);let l=[];for await(let b of s){if(this.signal?.aborted)break;for(let T of b)l.push(T);e.onProgress?.(l.length,i)}let p,f=0;if(this.signal?.aborted||(p=wt(r,l,o),await a.uploadData(p.text),f=l.length),this.signal?.aborted||p===void 0)return await kt(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(f);await a.close();let g=await a.check();for(;g.state==="InProgress"||g.state==="UploadComplete";)e.bulkManager.updateJobState(d,g.state),e.onProgress?.(g.numberRecordsProcessed??0,i),await new Promise(b=>setTimeout(b,this.pollIntervalMs)),g=await a.check();let h=await a.getAllResults(),w=St(h,p,Rt(g)),A=w.outcomes,R=[],y=[],S=w.unattributedSuccessIds.length;for(let b of A)b.success?(S++,b.id!==void 0&&R.push(b.id)):y.push(b.error??"Unknown error");R.push(...w.unattributedSuccessIds),y.push(...w.unattributedFailures);let m=g.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,m),e.bulkManager.updateJobCounts(d,g.numberRecordsProcessed??i,y.length),{totalRecords:f,successCount:S,failureCount:y.length,successIds:R,errors:y,aborted:!1,outcomes:A,...w.unattributedSuccessIds.length>0?{unmatchedIds:w.unattributedSuccessIds}:{}}}catch(c){throw e.bulkManager.updateJobState(d,"Failed"),c}}async*createChunkGenerator(e,t){let r=t??this.chunkSize;for(let s=0;s<e.length;s+=r)yield e.slice(s,s+r)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var _r=1e4,Wr=U.REST_API_BATCH_SIZE;function Gr(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function We(n){return typeof n.created=="boolean"?{created:n.created}:{}}function _n(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function Bn(n){let e=n===void 0?void 0:gt(n);return e?_n([e]):{}}function Ur(n,e){return n!=="insert"&&n!=="upsert"?[]:e.flatMap(t=>t.success&&typeof t.id=="string"&&t.id!==""&&(n==="insert"||t.created===!0)?[t.id]:[])}function zr(n,e){return!n||!e?n??e:{before:async(t,r,s,i)=>await n.before?.(t,r,s,i)??await e.before?.(t,r,s,i),sending:(t,r,s)=>{n.sending(t,r,s),e.sending(t,r,s)},opened:(t,r,s,i)=>{n.opened?.(t,r,s,i),e.opened?.(t,r,s,i)},answered:(t,r,s,i)=>{n.answered(t,r,s,i),e.answered(t,r,s,i)}}}function Yi(n,e){let t=r=>r==="insert"||r==="upsert";return{...e?{before:(r,s,i,o)=>e.before(r,s,i,o)}:{},sending:(r,s,i)=>{t(s)?n.sending?.(r,i,s==="upsert"?{upsert:!0}:void 0):n.writing?.(r,i)},opened:(r,s,i,o)=>{t(s)&&n.sending?.(r,i,{job:o,...s==="upsert"?{upsert:!0}:{}})},answered:(r,s,i)=>{t(s)?n.answered?.(r,Ur(s,i)):i.length>0&&n.writing?.(r,i.length),e?.answered(r,s,i)}}}var Ln=class{constructor(e){this.deps=e;this.retryOp=new pe({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,r,s)=>{e.log(`[RETRY] sync attempt=${t} code=${r.originalError.statusCode} delay=${s}ms`)}})}deps;retryOp;async insert(e,t,r,s){let i=zr(this.deps.calls,s),o=u=>this.deps.connection.sobject(e).create(u,{headers:re()}),a="Insert failed after retries",d=await this.tryStreaming("insert",e,t,void 0,i)??await this.tryBulk("insert",e,t,void 0,i);return d?this.duplicatesAgain("insert",e,t,d,o,a,i):this.executeRestBatches("insert",e,t,r,o,a,i)}async upsert(e,t,r,s){let i=d=>this.deps.connection.sobject(e).upsert(d,t,{headers:re()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,r,t)??await this.tryBulk("upsert",e,r,t);return a?this.duplicatesAgain("upsert",e,r,a,i,o,this.deps.calls,t):this.executeRestBatches("upsert",e,r,s,i,o,this.deps.calls,t)}async update(e,t,r){let s=a=>this.deps.connection.sobject(e).update(a,{headers:re()}),i="Update failed after retries",o=await this.tryStreaming("update",e,t)??await this.tryBulk("update",e,t);return o?this.duplicatesAgain("update",e,t,o,s,i):this.executeRestBatches("update",e,t,r,s,i)}async delete(e,t,r){let s=t.map(o=>({Id:o})),i=await this.tryBulk("delete",e,s);return i||this.executeRestBatches("delete",e,t,r,o=>this.deps.connection.sobject(e).destroy(o),"Delete failed after retries")}async tryStreaming(e,t,r,s,i=this.deps.calls){if(r.length<=_r)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new B(t);let o=await this.refusedBefore(i,t,e,r,s);if(o)return o;let a=new ye({signal:this.deps.signal});i?.sending(t,e,r.length);let d={connection:Me(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(l,p)=>{this.deps.onProgress(l,p,`Streaming ${e} ${t}`)},onOpened:l=>i?.opened?.(t,e,r.length,l)},u=await a.executeChunked(d,t,e,a.createChunkGenerator(r),r.length,s);if(u.aborted)throw i?.answered(t,e,[]),new B(t);this.logUnmatched(`Streaming ${e} ${t}`,u.unmatchedIds);let c=(u.outcomes??[]).map(l=>this.withExistingRecord(t,{id:l.id,success:l.success,errors:l.success?[]:[l.error??"Streaming error"],...We(l),...l.success?{}:Bn(l.error)}));return i?.answered(t,e,c),c}async tryBulk(e,t,r,s,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(r.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new B(t);let o={connection:Me(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(c,l)=>{this.deps.onProgress(c,l,`Bulk ${e} ${t}`)},signal:this.deps.signal,onOpened:c=>i?.opened?.(t,e,r.length,c)},a=await this.refusedBefore(i,t,e,r,s);if(a)return a;i?.sending(t,e,r.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,r,s);if(d.aborted)throw i?.answered(t,e,[]),new B(t);this.logUnmatched(`Bulk ${e} ${t}`,d.unmatchedIds);let u=d.outcomes.map(c=>this.withExistingRecord(t,{id:c.id,success:c.success,errors:c.success?[]:[c.error??"Bulk error"],...We(c),...c.success?{}:Bn(c.error)}));return i?.answered(t,e,u),u}async refusedBefore(e,t,r,s,i){if(r==="delete"||!e?.before)return;let o=await e.before(t,r,s,i);if(o!==void 0)return this.deps.log(`[WARN] ${r} ${t}: ${s.length} row(s) not sent: ${o}`),s.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,r,s,i,o,a=this.deps.calls,d){let u=s.flatMap((f,g)=>g<r.length&&Gr(f)?[g]:[]);if(u.length===0||this.deps.signal?.aborted)return s;let c;try{c=await this.executeRestBatches(e,t,u.map(f=>r[f]),Wr,i,o,a,d,u)}catch(f){if(!(f instanceof B))throw f;c=f.written}let l=[...s];c.forEach((f,g)=>{l[u[g]]=f});let p=c.filter(f=>f.success).length;return this.deps.log(`[INFO] ${e} ${t}: ${u.length} row(s) a duplicate rule refused in the Bulk API job, which cannot carry the header that lets a rule's matches be saved, went again through REST with it: ${p} saved`+(c.length<u.length?`, ${u.length-c.length} not sent (cancelled)`:"")),l}logUnmatched(e,t){t&&t.length>0&&this.deps.log(`[WARN] ${e}: the job wrote ${t.length} record(s) no row was matched to: ${t.join(", ")}`)}withExistingRecord(e,t){if(t.success)return t;let r=Fe(t,this.deps.keyPrefixOf?.(e));return r.kind==="linked"?{...t,existingId:r.id}:t}async executeRestBatches(e,t,r,s,i,o,a=this.deps.calls,d,u){let c=[];for(let l=0;l<r.length;l+=s){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new B(t,c);let p=r.slice(l,l+s);if(e!=="delete"){let h=await this.refusedBefore(a,t,e,p,d);if(h){c.push(...h);continue}if(this.deps.signal?.aborted)throw new B(t,c)}a?.sending(t,e,p.length);let f=await this.retryOp.execute(()=>i(p));if(f.cancelled)throw a?.answered(t,e,[],u&&[]),new B(t,c);let g=[];if(f.success&&f.result)for(let h of Array.isArray(f.result)?f.result:[f.result])g.push(this.restOutcome(t,h));else g.push(...p.map(()=>({success:!1,errors:[f.error?.message??o]})));c.push(...g),a?.answered(t,e,g,u?.slice(l,l+p.length))}return c}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...We(t)};let r=t.errors??[],s=r.map(mt),i={id:t.id,success:!1,errors:[s[0]??"Unknown error"],..._n(r.map(ft))},o=Fe({success:!1,errors:s,duplicateMatchIds:r.flatMap(a=>ht(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};var qr=2;async function Wn(n,e,t,r,s=()=>!1){let i=t.rows;if(!i||i.length!==e.length||t.stopped)return{result:t,unsent:[]};let o=[...i],a=[...e],d=e.map(()=>[]),u=[],c=!1;for(let p=0;p<qr&&!s();p++){let f=[],g=[],h=[];if(o.forEach((R,y)=>{if(R.id)return;let S=Dt(R.errorDetails,a[y],void 0);!S||S.some(({field:m})=>r.has(m))||(f.push(y),g.push(vt(a[y],S)),h.push(S))}),f.length===0)break;let w;try{w=await n(g)}catch(R){let y=[...new Set(h.flat().map(({field:S})=>S))].sort();u.push(`${f.length} record(s) refused on ${y.join(", ")} could not be written again without ${y.length===1?"it":"them"}: ${M(R)}`);break}if(Kr(w,g.length).forEach((R,y)=>{let S=f[y];o[S]=R,a[S]=g[y],d[S].push(...h[y])}),w.stopped){c=!0;break}}let l;return o.forEach((p,f)=>{!p.id||d[f].length===0||(l=V(l,{rows:1,fields:d[f].map(g=>({...g,rows:1}))}))}),{result:{successIds:o.flatMap(p=>p.id?[p.id]:[]),errors:o.flatMap(p=>p.id?[]:[p.error??"Unknown insert error"]),rows:o,...c?{stopped:!0}:{}},...l?{written:l}:{},unsent:u}}function Kr(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(s=>({id:s})),...n.errors.map(s=>({error:s}))];return(e===1?t:t.map(s=>({...s,unmatched:!0}))).slice(0,e)}var Hr=1e4,Jr=5e5,ze=200;function Se(n){let e=Math.floor(Jr/Math.max(1,n.fieldRules.length));return Math.max(ze,Math.min(Hr,e))}var Gn=class{deps;constructor(e){this.deps=e}async execute(e,t,r){let s=r??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return Hn(e.id,s,o.errors.map(c=>c.message),this.deps.now());let a=await En(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return Hn(e.id,s,a,this.deps.now());let d=e.objects.reduce((c,l)=>c+l.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,s,i):this.executeSequential(e,t,s,i)}preview(e){return this.deps.planBuilder.build(e)}shouldActivateGrappe(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}reportProgress(e,t,r,s=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,s);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:r,percentage:Math.round(i/Math.max(r,1)*100)})}async executeSequential(e,t,r,s){let i=Un(e,this.platformRolesOf(t),this.deps.onRowIds),o=this.deps.referenceLinker.resolveInsertOrder(e.objects,i.relations),a=e.objects.reduce((d,u)=>d+u.recordCount,0);for(let d of o){if(this.deps.signal?.aborted)return this.stoppedResult(e,r,i,s);let u=await this.readyToWrite(d,i,a);if(!u)continue;let c={},l={successIds:[],errors:[]},p={result:l,unsent:[]},f=zn(u),g=0,h=0,w=!1,A=Se(u.config);for await(let R of this.slicesOf(u,i,A,c)){if(this.deps.signal?.aborted){w=!0;break}g>0&&this.reportProgress(d.objectApiName,i.objectResults,a,l.successIds.length+l.errors.length);let y=await this.insert(t,d,R,u,i);if(g++,qn(f,u.config.rows,h,R.length,y.result),h+=R.length,os(p,y),y.result.stopped){w=!0;break}}if(g>0&&we(i,d,Ue(l,u),[...u.notes,...Ge(p)],c,f),w)return this.stoppedResult(e,r,i,s)}return this.ended(e,r,i,s)}async ended(e,t,r,s){let i,o=!1;try{i=await this.deps.knowledge?.({ids:Zr(r),results:r.objectResults})}catch(c){o=!0,i={skipped:`The articles were neither published nor linked: ${M(c)}`}}let a=Kn(e.id,t,r.objectResults,s,this.deps.now());if(!i)return a;let d=o||[i.publish,i.links].some(c=>(c?.notDone.length??0)>0),u=this.deps.signal?.aborted===!0;return{...a,knowledge:i,...(d||u)&&a.status==="success"?{status:"partial"}:{},...u?{cancelled:!0}:{}}}async readyToWrite(e,t,r){let s=Ce(e.objectApiName,t.relations),i=Qe(e,t.relations).filter(w=>t.wroteNothing.has(w));if(i.length>0)return te(t,e.objectApiName,`Skipped: ${i.join(", ")} wrote no records, so there is nothing for ${e.objectApiName} to point at.`);let o=await this.closedObject(e.objectApiName);if(o)return te(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,r);let a=Xn(e,s),{config:d,dropped:u}=await Jn(a,this.deps.describeCreateableFields),c=await this.whyDropped(e.objectApiName,u),l=w=>w.fieldRules.length===0&&qe(w.rows).length===0;if(l(d)&&!l(a))return te(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${c.join("; ")}).`);let{config:p,filled:f}=await Yn(await this.withTheOrgsPicklistValues(d),s,this.deps.describeRequiredFields),g=await this.matchStandardPricebook(p,t);if(g)return te(t,e.objectApiName,g);let h;if(s){let w=await this.placeChildren(p,s,t);if("skipped"in w)return te(t,e.objectApiName,w.skipped);if(w.parentIds.length===0&&w.unwritten){let{lines:A,keys:R}=w.unwritten;return we(t,e,{successIds:[],errors:A},[],{},R),null}h=w}return{relation:s,config:h?{...p,recordCount:h.parentIds.length,...h.rows?{rows:h.rows}:{}}:p,placed:h,...p.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...c.map(w=>`Written without ${w}.`),...f.length>0?[`Written with ${f.join(", ")}, which this org requires and the template names no rule for.`]:[],...h?.notes??[]]}}async placeChildren(e,t,r){let{childObject:s,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(s,i))return{skipped:`Skipped: this org does not let a seed write ${s}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return Xr(e.rows??[],t,r.keys.get(o));let a=r.existingIds,d;if(t.parents.kind==="generated")d=a.get(o)??[];else if(t.parents.kind==="records")d=[...t.parents.ids];else{let p=this.deps.readExistingParentIds;if(!p)return{skipped:`Skipped: this run cannot read the ${o} records already in the org, so ${s} has nothing to point at.`};try{d=await p(o,t.parents.where,t.parents.limit)}catch(f){return{skipped:`Skipped: reading the ${o} records already in the org failed (${M(f)}), so ${s} has nothing to point at.`}}}if(d.length===0){let p=t.parents.kind==="existing"?t.parents.where?.trim():"";return{skipped:`Skipped: ${t.parents.kind==="generated"?`${o} wrote no records`:`no ${o} record in the org matches ${p?`"${p}"`:"the relation"}`}, so there is nothing for ${s} to point at.`}}let u=Ze(t.distribution,d.length,this.deps.random),c=u.reduce((p,f)=>p+f,0),l=[];for(let[p,f]of u.entries())for(let g=0;g<f&&l.length<e.recordCount;g++)l.push(d[p]);return l.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${s}.`}:{parentIds:l,notes:c>l.length?[`Stopped at ${l.length} ${s} records, the most the template asks for: the relation spreads ${c} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,r,s){let i=e.config.recordCount,o=Math.max(1,Math.floor(r)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),u=ns(e.config,e.relation)?rs(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,c=>{s.aiFallback=is(s.aiFallback,c)},a,e.lengths);ss(u,e.relation,e.placed,a),yield u,a+=d}while(a<i)}async insert(e,t,r,s,i){let o=p=>this.deps.insert(e,t.objectApiName,p,t.batchSize),a=t.objectApiName===ot?await i.platformRoles.link(r):new Map,d=a.size>0?r.filter((p,f)=>!a.has(f)):r,u=d.length===0&&r.length>0?{successIds:[],errors:[],rows:[]}:await o(d),c=await Wn(o,d,u,Yr(s),()=>this.deps.signal?.aborted===!0);t.objectApiName===In&&i.platformRoles.opportunitiesWritten(d,c.result);let l=a.size>0?Qr(c,r.length,a):c;return u.notes&&u.notes.length>0?{...l,notes:u.notes}:l}platformRolesOf(e){return new Pn({orgId:e,readTarget:this.deps.readTarget,update:this.deps.update,stopped:()=>this.deps.signal?.aborted===!0})}async closedObject(e){if(!this.deps.objectAccess)return;let t;try{t=await this.deps.objectAccess(e)}catch{return}if(t.access==="createable")return;let r=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${r}.`:`Skipped: the user this seed runs as may not create ${e} records${r}.`}async withTheOrgsPicklistValues(e){if(!this.deps.describePicklistValues||!e.fieldRules.some(i=>i.ruleType==="picklist_random"))return e;let t;try{t=await this.deps.describePicklistValues(e.objectApiName)}catch{return e}let r=!1,s=e.fieldRules.map(i=>{let o=t.get(i.fieldApiName),a=i.config.picklistValues;if(i.ruleType!=="picklist_random"||!o?.length||!a)return i;let d=a.filter(u=>o.includes(u));return d.length===a.length?i:(r=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return r?{...e,fieldRules:s}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>ie(o,t.written))||t.existingIds.has(se))return;let r=this.deps.readExistingParentIds,s=`${e.objectApiName} points at the org's standard price book`;if(!r)return`Skipped: ${s}, and this run cannot read it.`;let i;try{i=await r(se,"IsStandard = true",1)}catch(o){return`Skipped: ${s}, and reading it failed (${M(o)}).`}if(i.length===0)return`Skipped: ${s}, and the org shows none to this user.`;t.existingIds.set(se,i)}async orgTakesField(e,t){if(!this.deps.describeCreateableFields)return!0;try{return(await this.deps.describeCreateableFields(e)).has(t)}catch{return!0}}async whyDropped(e,t){if(t.length===0)return[];let r=new Set;try{this.deps.describeVisibleFields&&(r=await this.deps.describeVisibleFields(e))}catch{}let s=t.filter(a=>r.has(a)),i=t.filter(a=>!r.has(a)),o=(a,d,u)=>a.length===1?d:u;return[...i.length>0?[`${i.join(", ")}: this org does not have ${o(i,"that field","those fields")}, or field-level security hides ${o(i,"it","them")} from the user SandForge connects as`]:[],...s.length>0?[`${s.join(", ")}: ${o(s,"it exists","they exist")}, but the user SandForge connects as may not set ${o(s,"it","them")}`]:[]]}async fieldLengths(e){if(!this.deps.describeFieldLengths)return new Map;try{return await this.deps.describeFieldLengths(e)}catch{return new Map}}async executeWithGrappe(e,t,r,s){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((h,w)=>h+w.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:o.length,totalRecords:a}});let d=Un(e,this.platformRolesOf(t),this.deps.onRowIds),u=this.deps.referenceLinker.resolveInsertOrder(e.objects,d.relations),c=[],l=0,p=this.deps.grappeConfig?.grappeSize??2e3,f=()=>{let h=d.objectResults.reduce((A,R)=>A+R.recordsCreated,0),w=d.objectResults.reduce((A,R)=>A+R.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:h,totalFailed:w}})},g=()=>(f(),this.stoppedResult(e,r,d,s));for(let h of u){if(this.deps.signal?.aborted)return g();let w=Math.ceil(h.recordCount/p),A=await this.readyToWrite(h,d,a);if(!A){l=this.settleUnusedPartitions(o,l,w,0);continue}let R={},y=Math.max(1,Math.ceil(A.config.recordCount/p)),S=0,m=0,b=[],T=[],I={result:{successIds:[],errors:[]},unsent:[]},P,v=zn(A),j=0,D=-1;for await(let L of this.slicesOf(A,d,p,R)){if(D++,this.deps.signal?.aborted){P=D;break}D>0&&this.reportProgress(h.objectApiName,d.objectResults,a,S+m);let k=Date.now(),O=o[l]?.id??this.deps.generateId(),C=await this.insert(t,h,L,A,d),E=C.result;qn(v,A.config.rows,j,L.length,E),j+=L.length,C.written&&(I.written=V(I.written,C.written)),I.unsent.push(...C.unsent);for(let x of C.notes??[])(I.notes??[]).includes(x)||(I.notes=[...I.notes??[],x]);S+=E.successIds.length,m+=E.errors.length,b.push(...E.errors),T.push(...E.successIds),c.push({grappeId:O,status:E.errors.length===0?"success":E.successIds.length>0?"partial":"failure",processedRecords:L.length,successCount:E.successIds.length,failureCount:E.errors.length,errors:E.errors,duration:Date.now()-k}),l++;let F=Math.round(l/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:O,percentage:F,processedRecords:S+m}}),E.stopped){P=D+1;break}}if(P!==void 0)return P>0&&we(d,h,Ue({successIds:T,errors:b},A),[...A.notes,...Ge(I)],R,v),g();l=this.settleUnusedPartitions(o,l,w-y,S+m),we(d,h,Ue({successIds:T,errors:b},A),[...A.notes,...Ge(I)],R,v)}return f(),this.ended(e,r,d,s)}stoppedResult(e,t,r,s){let i=Kn(e.id,t,r.objectResults,s,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,r,s){let i=t;for(let o=r;o>0;o--){let a=e[i]?.id??this.deps.generateId();i++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:a,percentage:Math.round(i/Math.max(e.length,1)*100),processedRecords:s}})}return i}};function Un(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(r=>r.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function Yr(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function Ge(n){return[...n.notes??[],...n.written?[jt(n.written)]:[],...n.unsent]}function te(n,e,t,r=!1){let s=as(e,t);return n.objectResults.push(r?{...s,optional:!0}:s),n.wroteNothing.add(e),null}function we(n,e,t,r,s,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,Vr(i)));let o=n.platformRoles.resultOf(e.objectApiName),a=[...t.successIds,...o.linkedIds];n.existingIds.set(e.objectApiName,a),e.recordCount>0&&a.length===0&&n.wroteNothing.add(e.objectApiName),n.objectResults.push({objectApiName:e.objectApiName,recordsCreated:t.successIds.length,recordsFailed:t.errors.length,createdIds:t.successIds,errors:[...t.errors,...r,...o.notes],...s,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function Vr(n){let e={};for(let[t,r]of n)"id"in r&&(e[t]=r.id);return e}function Xr(n,e,t){let{childObject:r,parentObject:s}=e;if(!t)return{skipped:`Skipped: ${r} is placed by key, and ${s} wrote no rows to place it under.`};let i=[],o=[],a=[],d=new Map;for(let u of n){let c=u.parentKey,l=c===void 0?void 0:t.get(c);if(l&&"id"in l){i.push(l.id),o.push(u);continue}let p=c===void 0?`it names no ${s} row`:`its ${s} ${c} ${l?l.why:`is no ${s} row this run wrote`}`;a.push(`${r} ${u.key} not written: ${p}.`),d.set(u.key,{why:`was not written, as ${p}`})}return{parentIds:i,notes:[],rows:o,unwritten:{lines:a,keys:d}}}function Zr(n){let e=new Map;for(let[t,r]of n.keys){let s=new Map;for(let[i,o]of r)"id"in o&&s.set(i,o.id);e.set(t,s)}return e}function zn(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function qn(n,e,t,r,s){if(!n||!e)return;let i=s.rows&&(s.rows.length===r||s.stopped)?s.rows:void 0;for(let o=0;o<r;o++){let a=e[t+o];if(!a)continue;let d=i?.[o];i?d?d.id&&d.unmatched?n.set(a.key,{why:"has no id this run can tell: the org did not say which of the ids it answered is its"}):d.id?n.set(a.key,{id:d.id}):n.set(a.key,{why:`was refused (${d.error??"Unknown insert error"})`}):n.set(a.key,{why:"was not sent: the run was stopped before it"}):n.set(a.key,{why:"has no id this run can tell: the insert did not answer record by record"})}}function Ue(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function Qr(n,e,t){let r=n.result.rows;if(!r)return n;let s=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){s.push({id:String(a.Id)});continue}let d=r[i++];if(!d)break;s.push(d)}return{...n,result:{...n.result,rows:s}}}function qe(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function es(n){return!n||n.length===0?[]:qe(n).filter(e=>n.every(t=>e in t.values))}function ts(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([r])=>!e.has(r)))}))}async function Jn(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let r=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),s=qe(n.rows).filter(a=>!t.has(a));if(r.length===n.fieldRules.length&&s.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!r.includes(a)).map(a=>a.fieldApiName),...s])],o=n.rows&&ts(n.rows,new Set(s));return{config:{...n,fieldRules:r,...o?{rows:o}:{}},dropped:i}}async function Yn(n,e,t){if(!t)return{config:n,filled:[]};let r;try{r=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let s=new Set([...n.fieldRules.map(o=>o.fieldApiName),...es(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of r){if(s.has(o.fieldApiName))continue;let a=tt(o);a.ruleType==="static"&&a.config.staticValue===void 0||i.push({fieldApiName:o.fieldApiName,fieldType:o.type,...a})}return i.length===0?{config:n,filled:[]}:{config:{...n,fieldRules:[...n.fieldRules,...i]},filled:i.map(o=>o.fieldApiName)}}async function Vn(n,e,t){let r=Ce(n.objectApiName,e),{config:s}=await Jn(Xn(n,r),t.describeCreateableFields),{config:i}=await Yn(s,r,t.describeRequiredFields);return Se(i)}function Xn(n,e){if(!e)return n;let t=n.fieldRules.filter(r=>r.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function ns(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function rs(n){return Array.from({length:n},()=>({}))}function ss(n,e,t,r=0){if(!(!e||!t))for(let[s,i]of n.entries())i[e.lookupField]=t.parentIds[r+s]}function is(n,e){return n?{fields:[...new Set([...n.fields,...e.fields])],reason:n.reason==="no-answer"&&e.reason==="no-answer"?"no-answer":"short-answer"}:e}function os(n,e){for(let t of e.result.successIds)n.result.successIds.push(t);for(let t of e.result.errors)n.result.errors.push(t);e.written&&(n.written=V(n.written,e.written)),n.unsent.push(...e.unsent);for(let t of e.notes??[])(n.notes??[]).includes(t)||(n.notes=[...n.notes??[],t])}function as(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function Kn(n,e,t,r,s){let i=t.reduce((d,u)=>d+u.recordsCreated,0),o=t.reduce((d,u)=>d+u.recordsFailed,0),a=t.some(d=>!d.optional&&d.recordsCreated===0&&d.recordsFailed===0&&d.errors.length>0);return{templateId:n,operationId:e,status:ds(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-r,timestamp:s}}function ds(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function Hn(n,e,t,r){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:r}}var cs=200,us=1,ls=1,Ke=2,ps=2,Zn=3,fs=1,gs=200,ms="Campaign";function Qn(n,e){if(!n)return;let t=e.toLowerCase();for(let[r,s]of n)if(r.toLowerCase()===t)return s}function hs(n,e){let t=Math.max(1,Math.floor(e)),r=[],s=0;do{let i=Math.max(0,Math.min(t,n-s));r.push(i),s+=i}while(s<n);return r}function ys(n,e={}){let t=e.bulkThreshold??cs,r=!1;return n.objects.flatMap(i=>{let o=Qn(e.duplicateRules,i.objectApiName),a=o===!1&&!pn.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??Se(i);return hs(i.recordCount,d).map(u=>{let c=_([{rows:u,perCall:i.batchSize}]);if(u<=t||(r=!0,o===!0))return c;let l=_([{rows:u,bulk:!0}]);return a?l:Math.max(l,c)})}).reduce((i,o)=>i+o,0)+(r?us:0)+_(bs(n))}function ws(n,e={}){return ys(n,e)+Ss(n,e)}function Ss(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),r=n.objects.some(i=>i.fieldRules.some(o=>ie(o,t))),s=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+_([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/On):i,0);return ls+n.objects.length+Ke+(t.has(ms)?Ke+1:0)+s+(r?fs:0)+(e.typedFirst?ps:0)+Zn+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function mo(n,e,t){let r=new Map;if(t!==void 0)return r;for(let s of n.objects)s.recordCount<=ze||r.set(s.objectApiName,await Vn(s,n.relations,e));return r}function ho(n,e){return n?.enabled&&e.objects.reduce((r,s)=>r+s.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function be(n,e){return n.reduce((t,{objectApiName:r,rows:s,perCall:i,deletes:o})=>{if(s<=e.threshold)return t+_([{rows:s,perCall:i??e.perCall}]);let a=o===!0||Qn(e.duplicateRules,r)===!1?0:s;return t+_([{rows:s,bulk:!0},{rows:a}])},0)}function He(n=0,e=0){return Zn+Ke+Math.max(0,n)+Math.max(0,e)}function yo(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,r=Math.min(t("Opportunity"),t("OpportunityContactRole")),s=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return be(n,e)+(r>0?Math.ceil(r/gs)+be([{objectApiName:"OpportunityContactRole",rows:r}],e):0)+_(s)+He(n.length,e.automationRead)}function bs(n){let e=r=>n.objects.find(s=>s.objectApiName===r)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function Rs(n,e){return n.objects.reduce((t,r)=>t+Wt(r.objectApiName,{rows:r.recordCount,personAccounts:e.includes(r.objectApiName)?r.recordCount:0}),0)}var So="SEED_STORAGE_EXCEEDED";async function bo(n,e,t,r,s,i={},o={}){let a={storageBytes:Rs(e,t)},d;try{d=await Ut(n)}catch(h){d={unread:M(h)}}let u=X(a,d),c="unread"in d?await zt(n).catch(h=>({unread:M(h)})):d.dailyApiRequests,l=ae({run:ws(e,o),...ce(s),...i},c),p=ue(s);if(p)return{check:u,api:l,refusal:p.message,refusedFor:"checkpoint",checkpointRefusal:p.refusal};let f=sn(u,r);if(f)return{check:u,api:l,refusal:`${f} Nothing was written.`,refusedFor:"storage"};let g=de(l,r);return g?{check:u,api:l,refusal:g,refusedFor:"apiRequests"}:{check:u,api:l}}function Ro(n,e){let{check:t,api:r}=n,s=r.parts??{},i={checkpoint:s.checkpoint??0,mute:s.mute??0,readBack:s.readBack??0,deliverability:s.deliverability??0,fit:s.fit??0};return on({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB},...e!==void 0?{withinMB:e}:{},api:r.verdict==="unread"?{unread:r.unread}:{max:r.max,remaining:r.remaining},otherRequests:i})}function ks(n){return n==="insert"||n==="upsert"}function nr(n){return n==="update"||n==="upsert"}function As(n){return Gt(n.objects.filter(e=>ks(e.operation)).map(({objectApiName:e,rows:t,personAccounts:r})=>({objectApiName:e,rows:[],counted:{rows:t,...r!==void 0?{personAccounts:r}:{}}})))}var rr=U.REST_API_BATCH_SIZE;function Cs(n,e){return be(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:r,rows:s,batchSize:i})=>({objectApiName:t,rows:s,...i!==void 0?{perCall:i}:{},...r==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??rr,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var Os="Opportunity",Es="OpportunityContactRole",Is=200,Ps={update:{characters:De,wide:!0},upsert:{characters:Cn(),wide:!0}},Fs=2,er=Array.from({length:Fs},()=>1),Ms=1;function Ts(n){let e=Math.min(Math.max(0,n),5e4);return Ms+Math.max(1,Math.ceil(e/Lt))}function Ye(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(r,s)=>Math.min(t,n-s*t))}function xs(n,e){if(n.rows<=(e.bulkThreshold??rr))return Ye(n.rows,n.batchSize??U.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([r])=>r.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:Ye(n.rows,U.REST_API_BATCH_SIZE)]}function Ds(n,e){let t=0,r=!1;for(let d of e.targetHeld?.values()??[])t+=Ts(d);for(let d of n.objects)d.rows<=0||d.operation==="delete"||(t+=er.length,!(d.operation!=="update"&&d.operation!=="upsert")&&(r=!0,t+=ve([...xs(d,e),...er],d.overwriteKey??Ps[d.operation])));let s=d=>n.objects.find(u=>u.objectApiName===d&&(u.operation==="insert"||u.operation==="upsert")),i=s(Os),o=s(Es),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=Ye(a,o.batchSize??U.REST_API_BATCH_SIZE);r=!0,t+=Math.ceil(a/Is)+d.length+ve(d,{characters:De,wide:o.overwriteKey?.wide??!0})}return r&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function sr(n){let e=new Map;for(let{objectApiName:t,operation:r}of n.objects){let s=e.get(t)??new Set;(r==="insert"||r==="upsert")&&s.add("insert"),(r==="update"||r==="upsert")&&s.add("update"),r==="delete"&&s.add("delete"),e.set(t,s)}return(t,r)=>e.get(t)?.has(r)===!0}function ir(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(r=>t.has(r)),objects:n.objects.filter(r=>t.has(r.objectApiName))}}function vs(n){let e;return t=>{if(e&&t.every(s=>e?.objects.includes(s)))return e.answer.then(s=>ir(s,t));let r=n(t);return e??={objects:[...t],answer:r},r}}function $o(n,e){if(n.direction==="bidirectional")return async t=>{let r=n.objects.find(i=>i.objectApiName===t),s=pt(r?.where,void 0);return e(`SELECT COUNT() FROM ${J(t)}${s?` WHERE ${s}`:""}`)}}async function js(n,e){let t=new Set((n.heldBack??[]).filter(({rows:s})=>s>0).map(({objectApiName:s})=>s)),r=new Map;for(let{objectApiName:s,operation:i,rows:o}of n.objects){if(!nr(i)||r.has(s)||o<=0&&!t.has(s))continue;let a=await e(s).catch(()=>5e4);r.set(s,Number.isFinite(a)&&a>=0?a:5e4)}return r}async function tr(n,e){let t=As(n),r=n.objects.filter(k=>k.rows>0).map(({objectApiName:k,rows:O})=>({objectApiName:k,rows:O})).sort((k,O)=>O.rows-k.rows||k.objectApiName.localeCompare(O.objectApiName)),s=r.reduce((k,O)=>k+O.rows,0),i=n.objects.filter(k=>nr(k.operation)).reduce((k,O)=>k+O.rows,0),o=X(t,{maxMB:0,remainingMB:0}),a=[],d,u=s>0?vs(e.readAutomation):e.readAutomation,c,l,p,f=sr(n),g;if(s>0){let k=n.objects.filter(O=>O.rows>0).map(O=>O.objectApiName);if(g=await u(k).catch(O=>({unread:O instanceof Error?O.message:String(O)})),e.checkpointFirst){let O="objects"in g?Oe(g,void 0,f):{firing:[]};try{c=await e.checkpointFirst.scope(k,O)}catch(C){l=_t(C)}}}let h={unread:"not read"};if(s>0){let k=await e.readStorage().catch(O=>({unread:O instanceof Error?O.message:String(O)}));h="unread"in k?await e.readApiBudget().catch(O=>({unread:O instanceof Error?O.message:String(O)})):k.dailyApiRequests,t.totalRows>0&&(o=X(t,k))}if(t.totalRows>0){let k=await Yt({plan:t,objects:t.objects.map(O=>O.objectApiName),readAutomation:u,readLimits:e.readLimits});a=k.checks,d=k.unread}g!==void 0&&(p=await Mt({...e.emails,read:g,writes:f,readDeliverability:e.readDeliverability,run:"sync"}));let w=s>0&&e.countTarget?await js(n,e.countTarget):void 0,A=en(p?.ofRun),R=e.sentBefore?.(),y=s===0?0:R!==void 0?Math.max(0,R-(A.deliverability??0)):He(0,g!==void 0?Qt(g):0)+(w?.size??0),S=g!==void 0?fn(g):void 0,m=s===0?0:Ds(n,{bulkThreshold:e.bulkThreshold,duplicateRules:S,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...w?{targetHeld:w}:{}}),b=ae({run:Cs(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:S})+y+m,...ce(c),...xt(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...A},h),T=e.confirmAboveRecords,I=T>0&&s>T?T:void 0,P=(n.unwritable??[]).map(({objectApiName:k,rows:O,why:C,key:E})=>({...E!==void 0?{key:E}:{},objectApiName:k,rows:O,why:C})),v=(n.heldBack??[]).map(({objectApiName:k,rows:O,parent:C,field:E,parents:F})=>({objectApiName:k,rows:O,parent:C,field:E,...F!==void 0?{parents:F.map(x=>({...x}))}:{}})),j=p?.gate,D=s===0?P.length>0?"refused":"writes":o.verdict==="exceeds"||b.verdict==="exceeds"||l!==void 0||c?.refusal!==void 0?"refused":I!==void 0||P.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(k=>k.verdict!=="fits")||d!==void 0||c!==void 0||j?.verdict==="asks"?"asks":"writes";return{check:{objects:r,total:s,alreadyCopied:n.alreadyCopied,...(n.alreadyLinked??0)>0?{alreadyLinked:n.alreadyLinked}:{},...i>0?{overwrites:i}:{},...(n.rolesByThePlatform??0)>0?{rolesByThePlatform:n.rolesByThePlatform}:{},...(n.rolesLinked??0)>0?{rolesLinked:n.rolesLinked}:{},...I!==void 0?{aboveRecords:I}:{},storage:o.verdict==="unread"?{verdict:"unread",estimateMB:o.estimateMB,unread:o.unread}:t.totalRows===0?{verdict:"fits",estimateMB:0}:{verdict:o.verdict,estimateMB:o.estimateMB,maxMB:o.maxMB,remainingMB:o.remainingMB},emails:a.map(k=>({limit:k.limit,emails:k.emails,verdict:k.verdict,...k.remaining!==void 0?{remaining:k.remaining}:{},...k.max!==void 0?{max:k.max}:{},...k.alertsCounted?{alertsCounted:!0}:{},objects:k.objects.map(({objectApiName:O,perRecord:C})=>({objectApiName:O,perRecord:C})),...k.unread!==void 0?{unread:k.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...j?.deliverability?{deliverability:j.deliverability}:{},...P.length>0?{unwritable:P}:{},...v.length>0?{heldBack:v}:{},...s>0?{apiRequests:b.verdict==="unread"?{verdict:"unread",estimate:b.estimate,unread:b.unread}:{verdict:b.verdict,estimate:b.estimate,remaining:b.remaining,max:b.max}}:{},verdict:D,...l!==void 0?{checkpointUnread:l}:{}},plan:t,storage:o,emails:a,api:b,...c!==void 0?{checkpoint:c}:{},...l!==void 0?{checkpointFailed:l}:{},...p!==void 0?{runEmails:p}:{},emailsAccepted:e.emails.accepted}}function Ns(n,e){let{check:t,storage:r,emails:s,plan:i,api:o}=n,a=[],d=t.unwritable??[];if(d.length>0&&(e.policy!=="ask"||t.total===0)&&a.push({code:"SYNC_TARGET_UNWRITABLE",message:Ls(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:Ht,message:n.checkpointFailed});else{let c=ue(n.checkpoint);c&&a.push(c)}i.totalRows>0&&r.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${rn(r.estimateMB)} MB of data storage, and ${e.org} has ${r.remainingMB} MB left of ${r.maxMB} MB: leave objects out, narrow their filters, or free data storage in ${e.org}. Nothing was written.`});let u=de(o,e.org);if(u&&a.push({code:qt,message:u}),e.policy!=="ask"){let c=Zt(s,e.org);c&&a.push({code:"SYNC_EMAILS_EXCEEDED",message:`${c} Nothing was written.`});let l=n.runEmails?.gate,p=l?.stop;p&&a.push({code:p.code,message:xe(p.message,"sync",e.emailsLiftedBy),...z(l,!1)})}return a}async function $s(n,e){let{check:t,storage:r,emails:s,api:i}=n,[o]=Ns(n,e);if(o)return{go:!1,...o};if(t.total===0)return{go:!0,asked:!1};let a=n.runEmails?.gate;if(e.policy!=="ask")return{go:!0,asked:!1,...z(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...z(a,!1)};let u=Pt(e.orgTier),c=s.filter(g=>g.verdict==="exceeds").map(Vt),l=s.filter(g=>g.verdict==="unread").map(Xt),p=e.confirm?await e.confirm({stage:"write",module:"sync",org:e.org,orgTier:e.orgTier,objects:t.objects,total:t.total,...t.aboveRecords!==void 0?{aboveRecords:t.aboveRecords}:{},...u!==void 0&&t.total>u?{largeVolume:u}:{},storage:nn(r),counted:!0,...t.overwrites!==void 0?{overwrites:t.overwrites}:{},...c.length>0?{emails:c}:{},...l.length>0?{emailsUnread:l}:{},...t.emailsUnread!==void 0?{emailsUncounted:t.emailsUnread}:{},...t.alreadyCopied>0?{alreadyCopied:t.alreadyCopied}:{},...(t.alreadyLinked??0)>0?{alreadyLinked:t.alreadyLinked}:{},...(t.rolesLinked??0)>0?{rolesLinked:t.rolesLinked}:{},...d.length>0?{unwritable:d}:{},...t.heldBack!==void 0&&t.heldBack.length>0?{heldBack:t.heldBack}:{},...Kt(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(p==="confirmed")return{go:!0,asked:!0,...z(a,a?.verdict==="asks")};let f=z(a,!1);return p==="declined"?{go:!1,code:"SYNC_WRITE_DECLINED",message:"The sync was cancelled before it wrote anything. Nothing was written.",...f}:{go:!1,code:"SYNC_CONFIRMATION_UNAVAILABLE",message:"The sync needed a confirmation before it wrote, and there was no one to ask. Nothing was written.",...f}}var Bs={notInTarget:n=>`${n} has no such object, or the user the run writes as cannot see it`,notCreateable:n=>`the user the run writes as may not create its records in ${n}`,notUpdateable:n=>`the user the run writes as may not edit its records in ${n}`,unread:n=>`${n} did not describe it, so what it takes could not be told`,notAKey:(n,e)=>`its upsert matches on ${e??"a field"}, neither an External ID nor an idLookup field in ${n}`};function Ls(n,e,t=[]){let r=n.map(({objectApiName:h,rows:w,why:A,key:R})=>`${h} (${w} record${w===1?"":"s"}): ${Bs[A](e,R)}`).join("; "),s=n.length===1?"it":"them",i=n.filter(({why:h})=>h==="notAKey"),o=n.filter(({why:h})=>h!=="notAKey"),a=i.length>0&&o.length>0,d=h=>h.map(({objectApiName:w})=>w).join(" and "),u=`give the user SandForge writes as access to ${a?d(o):s} in ${e}`,c=`match ${a?`${d(i)} `:""}on an External ID field of ${e}`,l=a?`${u}, or ${c}`:i.length>0?`or ${c}`:`or ${u}`,p=new Set(n.map(({objectApiName:h})=>h)),f=({parent:h,field:w})=>`whose ${w} names ${/^[aeiou]/i.test(h)?"an":"a"} ${h} record `+(p.has(h)?"left out":"held back"),g=t.flatMap(({objectApiName:h,rows:w,parent:A,field:R,parents:y})=>(y??[{parent:A,field:R,rows:w}]).map(S=>`${S.rows} ${h} record${S.rows===1?"":"s"}, ${f(S)}`)).join("; ");return`${e} would take no record of ${n.length===1?"one object":`${n.length} objects`} the sync writes \u2014 ${r}.`+(g!==""?` Left out, ${s==="it"?"it holds":"they hold"} back ${g}.`:"")+` Leave ${s} out of the run, ${l}. Nothing was written.`}function Bo(n,e){return{measure:async t=>(await tr(t,n)).check,hold:async t=>{let r=await tr(t,n),s=await $s(r,e);return{check:r.check,answer:await _s(r,s,n.checkpointFirst)}}}}async function _s(n,e,t){let r=n.checkpoint;if(!e.go||r===void 0||t===void 0)return e;let s=await Jt(()=>t.take(r));return"stop"in s?{go:!1,...s.stop}:{...e,checkpoint:s.checkpoint}}function Lo(n,e){return e==="insert"||e==="update"||e==="delete"}function _o(n,e,t,r,s){let i,o,a,d,u=n(async l=>{let p=i?.automation;return p&&l.every(f=>p.objectsRead.includes(f))?ir(p,l):e(l)},()=>i?.plan),c=l=>{if(!Tt(l))throw l;return{go:!1,code:l.code,message:l.message}};return{gate:{measure:l=>u.measure(l),hold:async l=>{let p=l.objects.filter(g=>g.rows>0).map(g=>g.objectApiName);if(!i&&p.length>0){d=await e(p).catch(g=>({unread:g instanceof Error?g.message:String(g)}));try{i=await t(d),a=i.muted}catch(g){return{check:await u.measure(l),answer:c(g)}}}let f=await u.hold(l);if(f.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(r),a=o.outcome}catch(y){let{checkpoint:S}=f.answer;return{check:f.check,answer:{...c(y),...S?{checkpoint:S}:{}}}}let{checkpoint:g,emails:h}=f.answer,{deliverability:w}=f.check,A=sr(l),R=i.plan&&d&&"objects"in d?tn({planned:w?.senders??[],held:st(Oe(d,Ft(i.plan,o.outcome),A),{writes:A}),...w?{reading:w.reading}:{},accepted:h?.accepted===!0,target:s.target,run:"sync"}):void 0;if(R)return{check:f.check,answer:{go:!1,code:R.code,message:xe(R.message,"sync",s.liftedBy),...g?{checkpoint:g}:{},...h?{emails:h}:{}}}}return f}},release:async()=>(o&&(a=await o.release()),a),lease:()=>{let l=o;if(l)return{assigned:l.outcome.assigned.length,giveBack:async()=>(a=await l.release(),a)}}}}function Uo(n,e){if(n.operation==="delete")return[];let t=ct(n.fieldMappings,n.excludedFields??[]),r=new Set([...dt(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),s=i=>!t.has(i.toLowerCase())||r.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&s(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function zo(n,e){let t=[...n].sort((y,S)=>y.insertOrder-S.insertOrder),r=new Map(t.map((y,S)=>[y.objectApiName,S])),s=new Set(t.filter(y=>y.operation!=="delete").map(y=>y.objectApiName)),i=new Map([...s].map(y=>[y.toLowerCase(),y])),o=[],a=new Set;for(let y of t){let S=y.objectApiName;if(s.has(S))for(let{field:m,referenceTo:b}of e.get(S)??[])for(let T of b){let I=i.get(T.toLowerCase());if(I===void 0||I===S)continue;let P=`${I}>${S}`;a.has(P)||(a.add(P),o.push({parent:I,child:S,field:m}))}}let d=Ws(t.map(y=>y.objectApiName),o),u=new Map;d.forEach((y,S)=>{for(let m of y)u.set(m,S)});let c=d.map(y=>[...y].sort((S,m)=>(r.get(S)??0)-(r.get(m)??0))),l=c.map(y=>r.get(y[0])??0),p=c.map(()=>new Set);for(let{parent:y,child:S}of o){let m=u.get(y)??0,b=u.get(S)??0;m!==b&&p[b].add(m)}let f=new Set,g=[];for(;f.size<c.length;){let y;if(c.forEach((S,m)=>{f.has(m)||[...p[m]].some(b=>!f.has(b))||(y===void 0||l[m]<l[y])&&(y=m)}),y===void 0)break;f.add(y),g.push(...c[y])}let h=new Map(t.map(y=>[y.objectApiName,y])),w=g.flatMap(y=>{let S=h.get(y);return S?[S]:[]}),A=new Map(g.map((y,S)=>[y,S])),R=[];for(let y of w){let S=y.objectApiName,m=o.filter(b=>b.child===S&&(r.get(b.parent)??0)>(r.get(S)??0)&&(A.get(b.parent)??0)<(A.get(S)??0)).sort((b,T)=>(A.get(T.parent)??0)-(A.get(b.parent)??0));m.length>0&&R.push({objectApiName:S,after:m[0].parent,field:m[0].field})}return{ordered:w,order:{objects:g,moved:R,cycles:c.filter(y=>y.length>1)}}}function Ws(n,e){let t=new Map(n.map(c=>[c,[]]));for(let{parent:c,child:l}of e)t.get(c)?.push(l);let r=0,s=new Map,i=new Map,o=[],a=new Set,d=[],u=c=>{s.set(c,r),i.set(c,r),r++,o.push(c),a.add(c);for(let f of t.get(c)??[])s.has(f)?a.has(f)&&i.set(c,Math.min(i.get(c)??0,s.get(f)??0)):(u(f),i.set(c,Math.min(i.get(c)??0,i.get(f)??0)));if(i.get(c)!==s.get(c))return;let l=[],p;do{if(p=o.pop(),p===void 0)break;a.delete(p),l.push(p)}while(p!==c);d.push(l)};for(let c of n)s.has(c)||u(c);return d}export{pe as a,ye as b,Js as c,Ys as d,ai as e,W as f,di as g,ci as h,ui as i,li as j,Dn as k,Cr as l,Ri as m,ki as n,Ti as o,xi as p,Di as q,vi as r,xr as s,Dr as t,ji as u,Nr as v,Ni as w,$i as x,$r as y,_e as z,$n as A,Uo as B,zo as C,Ur as D,Yi as E,Ln as F,Gn as G,Qn as H,ws as I,mo as J,ho as K,be as L,He as M,yo as N,Rs as O,So as P,bo as Q,Ro as R,$o as S,tr as T,Ns as U,$s as V,Ls as W,Bo as X,_s as Y,Lo as Z,_o as _};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{c as R}from"./chunk-K2FBZIXY.mjs";import{b as S}from"./chunk-T63U4OZJ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as m,e as h,k as y,l as b}from"./chunk-7EANH5PY.mjs";var G={kind:"master"};function E(i){return i.available&&i.active&&!i.master}function B(i){let t=i.find(n=>n.defaultRecordTypeMapping);if(t&&E(t))return{kind:"given",info:t,basis:"userDefault"};let e=i.filter(E);return e.length===1?{kind:"given",info:e[0],basis:"onlyOneOpen"}:G}function ie(i){if(i.kind!=="master")return{developerName:i.info.developerName,label:i.info.name,basis:i.basis}}var L=200,j=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/;function se(i,t){let e=t.filter(n=>j.test(n)).slice(0,L).map(n=>`'${n}'`);return`SELECT RecordTypeId, COUNT(Id) n FROM ${N(i)} WHERE Id IN (${e.join(", ")}) GROUP BY RecordTypeId`}var U=b({RecordTypeId:m().nullish(),n:h().int().nonnegative()});function oe(i,t){let e=y(U).safeParse(i);if(!e.success)return{read:0,types:[],unread:"the org answered rows that name no record type count"};let n=new Map;for(let{RecordTypeId:s,n:o}of e.data){let a=K(s??null,t),d=n.get(a.developerName);d?d.rows+=o:n.set(a.developerName,{...a,rows:o})}let r=[...n.values()].sort((s,o)=>o.rows-s.rows);return{read:r.reduce((s,o)=>s+o.rows,0),types:r}}function K(i,t){if(i===null||R(i)){let n=t.find(r=>r.master);return{developerName:n?.developerName??"Master",label:n?.name??"Master"}}let e=t.find(n=>n.recordTypeId.slice(0,15)===i.slice(0,15));return e?{developerName:e.developerName,label:e.name}:{developerName:i,label:i}}function ae(i){if(!i)return;let t=B(i);return t.kind==="given"?t.info.recordTypeId:i.find(e=>e.master)?.recordTypeId}import{createHash as w,createHmac as T}from"node:crypto";var p="SANDFORGE_FROZEN_SALT",le=["keep","clear","firstName","lastName","companyName","phoneE164","email","registrationSIV","contractNumber","postalCodeGeneralize","dateMonthStart","dateShift","geoRound1","kmRound10"],g=class extends Error{constructor(){super(`No pseudonymization salt. In VS Code, the first extraction makes one and keeps it in the editor's secret storage, which could not keep it here. On the command line, give it with --salt-file <file>, or set ${p} (bash or zsh: export ${p}="<salt>"; PowerShell: $env:${p} = "<salt>") and start VS Code from that shell. Use the salt the dataset was built with: another one gives the same records other pseudonyms.`),this.name="MissingSaltError"}},V=["Alix","Camille","Dominique","\xC9loi","Faustine","Gabin","H\xE9lo\xEFse","Ibrahim","Jasmine","Kylian","L\xE9a","Mathis","Nour","Oc\xE9ane","Paul","Quitterie","Rayan","Salom\xE9","Th\xE9o","Ursule","Victor","Wendy","Xavier","Yasmine","Zacharie","Ambre","Bastien","Chlo\xE9","Dorian","Emma","Fabien","Gabrielle","Hugo","In\xE8s","Jules","Klara","Louis","Manon","No\xE9","Oph\xE9lie"],H=["Arnaud","Berthelot","Chevallier","Deschamps","Etcheverry","Fontaine","Guibert","Hamonic","Imbert","Jacquin","Kermarrec","Lefebvre","Mignard","Noirot","Ollivier","Perrin","Quentin","Rochefort","Seguin","Thibault","Uberti","Vasseur","Wagner","Xuereb","Yverneau","Zimmermann","Aubry","Barbier","Charpentier","Delattre","Esnault","Fournier","Gosselin","Hervieux","Leloup","Marchand","Navarro","Pasquier","Renard","Sauvage"],k=["Aster","Boreal","C\xE9drat","Delta","Ellipse","Fulmen","Granit","Halcyon","Isatis","Jaspe","Kelvin","Lumen","M\xE9ridien","Noroit","Obsidienne","Pulsar"],$=["Conseil","Services","Industries","Solutions","Groupe","SAS","Partenaires","Logistique"],v="ABCDEFGHJKLMNPRSTUVWXYZ",A=/^(\d{4})-(\d{2})-(\d{2})$/,x=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/;function Z(i){return Date.parse(i.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"))}var C=864e5,u=class{salt;constructor(t){if(!t)throw new g;this.salt=t}get saltFingerprint(){return w("sha256").update(this.salt).digest("hex").slice(0,12)}get dateShiftDays(){return 200+w("sha256").update(`${this.salt}|dateShift-offset`).digest().readUInt32BE(0)%201}pseudonymize(t,e){if(e==null)return e;switch(t){case"keep":return e;case"clear":return"";case"firstName":return this.pick(t,String(e),V);case"lastName":return this.pick(t,String(e),H);case"companyName":return this.companyName(String(e));case"phoneE164":return this.phoneE164(String(e));case"email":return this.email(String(e));case"registrationSIV":return this.registrationSIV(String(e));case"contractNumber":return this.contractNumber(String(e));case"postalCodeGeneralize":return this.postalCodeGeneralize(String(e));case"dateMonthStart":return this.dateMonthStart(String(e));case"dateShift":return this.dateShift(e);case"geoRound1":return this.roundNumber(e,1);case"kmRound10":return this.roundTo(e,10)}}digest(t,e){return T("sha256",this.salt).update(`${t}|${e}`).digest()}*bytes(t,e){let n=this.digest(t,e),r=0;for(;;){for(let s of n)yield s;r+=1,n=T("sha256",this.salt).update(`${t}|${e}|#${r}`).digest()}}pick(t,e,n){let r=this.digest(t,e);return n[r.readUInt32BE(0)%n.length]}companyName(t){let e=this.digest("companyName",t),n=k[e.readUInt32BE(0)%k.length],r=$[e.readUInt32BE(4)%$.length];return`${n} ${r}`}phoneE164(t){let e=this.bytes("phoneE164",t),n="";for(let r=0;r<4;r++)n+=String(e.next().value%10);return`+3363998${n}`}email(t){return`user-${this.digest("email",t).subarray(0,4).toString("hex")}@example.invalid`}registrationSIV(t){let e=this.bytes("registrationSIV",t),n=()=>v[e.next().value%v.length],r=()=>String(e.next().value%10);return`${n()}${n()}-${r()}${r()}${r()}-${n()}${n()}`}contractNumber(t){let e=this.bytes("contractNumber",t),n="";for(let r of t)r>="0"&&r<="9"?n+=String(e.next().value%10):r>="A"&&r<="Z"?n+=String.fromCharCode(65+e.next().value%26):r>="a"&&r<="z"?n+=String.fromCharCode(97+e.next().value%26):n+=r;return n}postalCodeGeneralize(t){let e=t.trim();if(e.length<=2)return e;if(/^\d+$/.test(e))return e.slice(0,2)+"0".repeat(e.length-2);let n=e.slice(0,2);for(let r of e.slice(2))r>="0"&&r<="9"?n+="0":r>="A"&&r<="Z"||r>="a"&&r<="z"?n+="X":n+=r;return n}dateMonthStart(t){let e=A.exec(t)??x.exec(t);return e?`${e[1]}-${e[2]}-01`:""}dateShift(t){if(typeof t=="string"&&A.test(t))return new Date(Date.parse(`${t}T00:00:00Z`)-this.dateShiftDays*C).toISOString().slice(0,10);if(typeof t=="string"&&x.test(t)){let e=Z(t);if(Number.isFinite(e))return new Date(e-this.dateShiftDays*C).toISOString()}return""}roundNumber(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=10**e,s=Math.round(n*r)/r;return typeof t=="number"?s:String(s)}roundTo(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=Math.round(n/e)*e;return typeof t=="number"?r:String(r)}};import{createHash as Y,randomBytes as X}from"node:crypto";var z=80,W=40,D=1e4,q=64,I=".invalid",f=/\.invalid$/i,F=/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,J=/\+?(?<!\d)\d(?:[\s.()/-]{0,2}\d){6,}/g;function _(i){return/^(?:(?:00)?330?|0)63998\d{4}$/.test(i.replace(/\D/g,""))}function M(i){return`+3363998${i.replace(/\D/g,"").slice(-4)}`}var Q=/^[\d\s.()/+-]+$/;function O(i,t){if(!Q.test(i))return null;let e=t.slice(3),n=/^[\s(]*\+/.test(i)?[`33${e}`,`330${e}`]:[`0${e}`,`33${e}`,`330${e}`,`0033${e}`,`00330${e}`],r=i.replace(/\D/g,"").length,s=n.find(a=>a.length===r);if(s===void 0)return null;let o=0;return i.replace(/\d/g,()=>s[o++])}function ee(i,t={}){let e=[];for(let n of i){let r=(n.type??"").toLowerCase(),s=S(n.name,r);if(!s)continue;let o=r==="email"||r==="phone",a=r==="email"?z:r==="phone"?W:0,d=n.length!==void 0&&n.length>0?n.length:a;e.push({name:t[n.name]??n.name,kind:s,typed:o,...d>0?{maxLength:d}:{},...n.externalId===!0?{key:!0}:{}})}return e}var P=class{pseudonymizer;upsertKeys;drawnFor=new Map;taken=new Set;exhausted=0;counted=new Map;constructor(t=X(32).toString("hex"),e={}){this.pseudonymizer=new u(t),this.upsertKeys=e.upsertKeys===!0}forObject(t,e,n={}){let r=ee(e,n);if(r.length!==0)return s=>{for(let o of r){let a=s[o.name];if(typeof a!="string")continue;let d=this.neutralize(o,a);d!==a&&(d===null?delete s[o.name]:s[o.name]=d,this.count(t,o))}}}email(t,e=z,n=!1){let r=t.trim();if(r===""||f.test(r))return t;let s=`${r}${I}`;if(s.length<=e)return s;let o=this.shortAddress(r,n);return o.length<=e?o:null}phone(t,e){return/\d/.test(t)?_(t)?(this.taken.add(M(t)),t):this.fictional(t,e):t}report(){let t=[],e=0;for(let[n,r]of this.counted)for(let[s,{kind:o,values:a}]of r)t.push({objectApiName:n,field:s,kind:o,values:a}),e+=a;return{neutralized:!0,fields:t,values:e,...this.exhausted>0?{numbersExhausted:this.exhausted}:{}}}neutralize(t,e){let n=this.upsertKeys&&t.key===!0;return t.typed?t.kind==="email"?this.email(e,t.maxLength,n):this.phone(e,t.maxLength):t.kind==="email"?this.addressesIn(e,t.maxLength,n):this.numbersIn(e,t.maxLength)}addressesIn(t,e,n=!1){let r=a=>e===void 0||a.length<=e,s=t.replace(F,a=>f.test(a)?a:`${a}${I}`);if(s===t||r(s))return s;let o=t.replace(F,a=>f.test(a)?a:this.shortAddress(a,n));return r(o)?o:null}numbersIn(t,e){let n=d=>e===void 0||d.length<=e,r=!1,s=d=>t.replace(J,c=>{if(_(c))return this.taken.add(M(c)),c;let l=this.drawnNumber(c);return l===null?(r=!0,c):O(c,l)??(d?`0${l.slice(3)}`:l)}),o=s(!1);if(r)return null;if(o===t||n(o))return o;let a=s(!0);return n(a)?a:null}fictional(t,e){let n=this.drawnNumber(t);if(n===null)return null;let r=O(t,n);if(r!==null&&(e===void 0||r.length<=e))return r;if(e===void 0||n.length<=e)return n;let s=`0${n.slice(3)}`;return s.length<=e?s:null}drawnNumber(t){let e=t.replace(/[^\d+]/g,""),n=this.drawnFor.get(e);if(n!==void 0)return n;if(this.taken.size>=D)return this.exhausted+=1,null;let r=o=>String(this.pseudonymizer.pseudonymize("phoneE164",o)),s=r(e);for(let o=1;this.taken.has(s)&&o<=q;o+=1)s=r(`${e}#${o}`);for(let o=Number(s.slice(-4));this.taken.has(s);)o=(o+1)%D,s=`+3363998${String(o).padStart(4,"0")}`;return this.drawnFor.set(e,s),this.taken.add(s),s}shortAddress(t,e=!1){let n=t.toLowerCase();return e?`user-${Y("sha256").update(n).digest("hex").slice(0,16)}@example.invalid`:String(this.pseudonymizer.pseudonymize("email",n))}count(t,e){let n=this.counted.get(t)??new Map,r=n.get(e.name)??{kind:e.kind,values:0};r.values+=1,n.set(e.name,r),this.counted.set(t,n)}};function Se(i){if(typeof i!="object"||i===null)return!1;let{errorCode:t,name:e}=i;return t==="NOT_FOUND"||e==="NOT_FOUND"}export{p as a,le as b,g as c,u as d,z as e,D as f,ee as g,P as h,B as i,ie as j,L as k,se as l,oe as m,ae as n,Se as o};