sandforge 1.79.0 → 1.80.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 (192) hide show
  1. package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
  2. package/lib/chunk-2CNCDM56.mjs +7 -0
  3. package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
  4. package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
  5. package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
  6. package/lib/chunk-3F6Q5E7I.mjs +14 -0
  7. package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
  8. package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
  9. package/lib/chunk-4VS2V6WU.mjs +25 -0
  10. package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
  11. package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
  12. package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
  13. package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
  14. package/lib/chunk-7ABODJ4G.mjs +7 -0
  15. package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
  16. package/lib/chunk-7FFGJWHN.mjs +7 -0
  17. package/lib/chunk-7YDNUBO5.mjs +7 -0
  18. package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
  19. package/lib/chunk-ADOAS63R.mjs +7 -0
  20. package/lib/chunk-AEKONPF4.mjs +7 -0
  21. package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
  22. package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
  23. package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
  24. package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
  25. package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
  26. package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
  27. package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
  28. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
  29. package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
  30. package/lib/chunk-CION3VMZ.mjs +7 -0
  31. package/lib/chunk-COFG7Q6R.mjs +7 -0
  32. package/lib/chunk-CSBS5U5I.mjs +7 -0
  33. package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
  34. package/lib/chunk-DB7RBE5D.mjs +7 -0
  35. package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
  36. package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
  37. package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
  38. package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
  39. package/lib/chunk-EFR2Y7E4.mjs +7 -0
  40. package/lib/chunk-EHQ3FX6X.mjs +7 -0
  41. package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
  42. package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
  43. package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
  44. package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
  45. package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
  46. package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
  47. package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
  48. package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
  49. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
  50. package/lib/chunk-G35N4P7D.mjs +7 -0
  51. package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
  52. package/lib/chunk-GSG7WZHM.mjs +7 -0
  53. package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
  54. package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
  55. package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
  56. package/lib/chunk-HOJYWTP7.mjs +20 -0
  57. package/lib/chunk-HS4YRX4J.mjs +7 -0
  58. package/lib/chunk-IFETCRWE.mjs +10 -0
  59. package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
  60. package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
  61. package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
  62. package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
  63. package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
  64. package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
  65. package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
  66. package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
  67. package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
  68. package/lib/chunk-JWTSEDIQ.mjs +7 -0
  69. package/lib/chunk-K327QKMD.mjs +7 -0
  70. package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
  71. package/lib/chunk-KDGMAGQR.mjs +7 -0
  72. package/lib/chunk-KRCA6IPH.mjs +8 -0
  73. package/lib/chunk-KYEDBS54.mjs +7 -0
  74. package/lib/chunk-L5FGY6YA.mjs +7 -0
  75. package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
  76. package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
  77. package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
  78. package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
  79. package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
  80. package/lib/chunk-MFG4MUIO.mjs +9 -0
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
  82. package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
  83. package/lib/chunk-MJU2PGZQ.mjs +15 -0
  84. package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
  85. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  86. package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
  87. package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
  88. package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
  89. package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
  90. package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
  91. package/lib/chunk-OAZRPP4I.mjs +7 -0
  92. package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
  93. package/lib/chunk-OLSGVAIL.mjs +341 -0
  94. package/lib/chunk-OO6CLPEH.mjs +7 -0
  95. package/lib/chunk-OPXCV2KL.mjs +7 -0
  96. package/lib/chunk-P33PSCXK.mjs +7 -0
  97. package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
  98. package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
  99. package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
  100. package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
  101. package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
  102. package/lib/chunk-RMBPOTD7.mjs +7 -0
  103. package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
  104. package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
  105. package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
  106. package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
  107. package/lib/chunk-SOU4FRYN.mjs +7 -0
  108. package/lib/chunk-SU65Z2BA.mjs +7 -0
  109. package/lib/chunk-T62WNR54.mjs +7 -0
  110. package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
  111. package/lib/chunk-TTFDUKUS.mjs +47 -0
  112. package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
  113. package/lib/chunk-UCD54V2M.mjs +7 -0
  114. package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
  115. package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
  116. package/lib/chunk-VS7ZXUII.mjs +824 -0
  117. package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
  118. package/lib/chunk-VYXMVJL5.mjs +7 -0
  119. package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
  120. package/lib/chunk-W7U5E5ZL.mjs +9 -0
  121. package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
  122. package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
  123. package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
  124. package/lib/chunk-WXAQ7FK3.mjs +115 -0
  125. package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
  126. package/lib/chunk-XAMBCQPU.mjs +7 -0
  127. package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
  128. package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
  129. package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
  130. package/lib/chunk-YRQGKDHM.mjs +7 -0
  131. package/lib/chunk-ZM6OJGIG.mjs +7 -0
  132. package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
  133. package/lib/sandforge-autopilot.mjs +29 -24
  134. package/lib/sandforge-backup.mjs +25 -21
  135. package/lib/sandforge-checkpoint.mjs +15 -14
  136. package/lib/sandforge-cleanup.mjs +14 -10
  137. package/lib/sandforge-clone.mjs +1 -1
  138. package/lib/sandforge-compare.mjs +9 -8
  139. package/lib/sandforge-dataops.mjs +1 -1
  140. package/lib/sandforge-empty.mjs +15 -15
  141. package/lib/sandforge-env.mjs +88 -88
  142. package/lib/sandforge-frozen.mjs +43 -34
  143. package/lib/sandforge-mcp.mjs +12 -12
  144. package/lib/sandforge-monitor.mjs +7 -7
  145. package/lib/sandforge-seed.mjs +1 -1
  146. package/lib/sandforge-sync.mjs +1 -1
  147. package/lib/sandforge.mjs +4 -4
  148. package/package.json +1 -1
  149. package/lib/chunk-2S5OMIIA.mjs +0 -7
  150. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  151. package/lib/chunk-3F5YMM2F.mjs +0 -7
  152. package/lib/chunk-3RYLICRX.mjs +0 -7
  153. package/lib/chunk-4GL773D5.mjs +0 -7
  154. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  155. package/lib/chunk-5AJRHRXA.mjs +0 -20
  156. package/lib/chunk-5HMAPZBV.mjs +0 -7
  157. package/lib/chunk-6LAXTAVN.mjs +0 -7
  158. package/lib/chunk-6MUEPV7M.mjs +0 -9
  159. package/lib/chunk-75ADZS6B.mjs +0 -7
  160. package/lib/chunk-B45CNPUX.mjs +0 -47
  161. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  162. package/lib/chunk-D3QRXG63.mjs +0 -787
  163. package/lib/chunk-EEVVGGM6.mjs +0 -7
  164. package/lib/chunk-ENLBYECD.mjs +0 -7
  165. package/lib/chunk-EQOQASDQ.mjs +0 -7
  166. package/lib/chunk-FQBRBBY4.mjs +0 -7
  167. package/lib/chunk-GAM726CK.mjs +0 -7
  168. package/lib/chunk-HUMEKZT5.mjs +0 -8
  169. package/lib/chunk-I3JKJTLO.mjs +0 -110
  170. package/lib/chunk-KLX67VPL.mjs +0 -7
  171. package/lib/chunk-L776PUMV.mjs +0 -7
  172. package/lib/chunk-NEVXIGR6.mjs +0 -10
  173. package/lib/chunk-NHWE66K5.mjs +0 -7
  174. package/lib/chunk-OQOZAPCI.mjs +0 -7
  175. package/lib/chunk-PA3MKJVH.mjs +0 -7
  176. package/lib/chunk-RH3N2H7P.mjs +0 -7
  177. package/lib/chunk-SRQDABQ2.mjs +0 -15
  178. package/lib/chunk-SVS6UMDU.mjs +0 -323
  179. package/lib/chunk-TNXUU6W7.mjs +0 -14
  180. package/lib/chunk-VXHDBYMI.mjs +0 -7
  181. package/lib/chunk-WRU5FJFC.mjs +0 -7
  182. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  183. package/lib/chunk-XEFDB2R4.mjs +0 -7
  184. package/lib/chunk-XETCPL7E.mjs +0 -7
  185. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  186. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  187. package/lib/chunk-YMJVMFPY.mjs +0 -7
  188. package/lib/chunk-YPSRZRIT.mjs +0 -7
  189. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  190. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  191. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  192. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -4,10 +4,10 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{c as Xo}from"./chunk-VHI54FBK.mjs";import"./chunk-AAVJ5XVX.mjs";import"./chunk-WFEB5X4U.mjs";import"./chunk-AR7BE5O2.mjs";import"./chunk-3OHPD72J.mjs";import"./chunk-3RYLICRX.mjs";import"./chunk-PUOX4NBJ.mjs";import"./chunk-EQF2IJS2.mjs";import"./chunk-HTJ5OGP5.mjs";import"./chunk-QQZZMKU3.mjs";import"./chunk-PZTSVQSF.mjs";import"./chunk-W7KFAY55.mjs";import"./chunk-5HMAPZBV.mjs";import"./chunk-YPSRZRIT.mjs";import"./chunk-FOVVHGEP.mjs";import{o as $t}from"./chunk-SVS6UMDU.mjs";import"./chunk-AUTM6H6Z.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-RAAANPPG.mjs";import{a as Jt}from"./chunk-ZE6HKRR4.mjs";import{a as yo,b as wo,c as bo,d as Do,e as $o,f as It,g as xt,h as Nt,i as Xe,j as Lo,k as Ne,l as Fe}from"./chunk-LRFAIUN7.mjs";import"./chunk-OQOZAPCI.mjs";import"./chunk-RSYICMZG.mjs";import"./chunk-IAZB4WIL.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-XEFDB2R4.mjs";import"./chunk-H45UXY6G.mjs";import"./chunk-WRU5FJFC.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-GNC27UEU.mjs";import"./chunk-YBU4Z4QV.mjs";import"./chunk-5P4PHJRL.mjs";import{Ba as Dt,K as Qo,a as Ao,g as Ft,h as _o,i as qo,j as zo,k as Go,l as Uo,m as Wo,n as jt,o as Ho,p as Ko,t as je}from"./chunk-D3QRXG63.mjs";import{h as No,i as Fo,k as jo}from"./chunk-NM4MDLK4.mjs";import{a as Ro}from"./chunk-BS5T3MOQ.mjs";import"./chunk-TEOLMRDO.mjs";import"./chunk-FQBRBBY4.mjs";import"./chunk-YS4G22C2.mjs";import{a as Bo}from"./chunk-SCKUIE3R.mjs";import"./chunk-QROPNEGY.mjs";import{b as lt,e as Zt}from"./chunk-BZ24IAP5.mjs";import{c as tn,d as nn,f as on}from"./chunk-AV5SWEHP.mjs";import"./chunk-I7O6C2B5.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-YMJVMFPY.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import{b as rn,c as sn,d as Ge,e as an,f as ao,g as co,h as lo,i as uo,j as po,k as fo,l as vt,r as mo,s as ho,t as go}from"./chunk-36U7IQ6Y.mjs";import{h as ko,i as Po,j as Co,k as Mo,l as Mt,m as Io,n as xo}from"./chunk-XETCPL7E.mjs";import{a as So,b as Et,c as Pt,d as Oo,e as To,f as vo,g as Eo,h as Ct}from"./chunk-K2FBZIXY.mjs";import"./chunk-Z7X534S4.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import{d as zn}from"./chunk-T63U4OZJ.mjs";import{d as qn}from"./chunk-DBFJB2B6.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.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{b as dt,c as ze}from"./chunk-L776PUMV.mjs";import{A as Ye,r as Hn,s as At,w as xe,x as Kn,y as Yn}from"./chunk-6MUEPV7M.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import{a as ct,b as Xt}from"./chunk-RH3N2H7P.mjs";import{a as me,i as Ie,k as En,n as Pn,o as Cn,p as Mn,s as In,t as xn,u as Nn,v as Fn}from"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import{Ba as ro,D as Rt,Ia as ve,Ja as so,K as Xn,L as Vn,N as Jn,Q as St,S as Qe,T as Zn,W as eo,Wa as io,Xa as Tt,_ as Ot,ka as to,r as Gn,s as Un,w as Wn,wa as no,xa as oo,y as Qn}from"./chunk-VXHDBYMI.mjs";import{q as kt}from"./chunk-ENLBYECD.mjs";import{b as mt,d as ht,e as Tn}from"./chunk-PA3MKJVH.mjs";import{a as le}from"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import{a as jn,b as gt,c as yt,f as Dn,h as $n,j as He,l as Ln,m as Bn}from"./chunk-WIO4XO4F.mjs";import{a as We}from"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import{i as vn}from"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import{X as yn,Y as wn,Z as bn,_ as An,a as cn,b as oe,c as Ue,ca as Me,d as dn,e as ln,ea as kn,f as un,ha as Rn,ia as Sn,ja as On,l as pt,m as pn,n as fn,o as mn,p as ae,q as fe,r as ft,s as Ce,t as hn,y as gn}from"./chunk-CGWXQX75.mjs";import{a as he,h as ge}from"./chunk-TZE3Y7IQ.mjs";import{b as Ke,c as wt,j as bt,k as _n}from"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import{b as te}from"./chunk-CA5NAXSU.mjs";import{a as Vt,c as en,e as ut,g as Yo}from"./chunk-MTMH6H2A.mjs";import{Ab as Wt,Eb as Te,Fb as Ae,Gb as Be,Hb as Ee,Ib as Ht,Kb as at,Lb as _e,Mb as Pe,Rb as Kt,Tb as Yt,bd as qe,fc as Qt,vb as it,yb as Gt,zb as Ut}from"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-SBIMVCXT.mjs";import"./chunk-NTOVCTRS.mjs";var Bt=ho,_t=mo,ke=200;function wr(l,e){let t=new Set(e?.fields.map(o=>o.name)??[]),n=new Set(l.split(", "));for(let o of[me,Pe])t.has(o)&&n.add(o);return[...n].join(", ")}var br=10,Ar=new Set([ae]),ye="IsPersonAccount",Ve="IsStandard",Je=class{maxConcurrent;constructor(e=10){this.maxConcurrent=e}async listObjects(e,t,n){let[o,r]=await Promise.all([e.describeGlobal(),t.describeGlobal()]),s=new Set(o.sobjects.filter(c=>c.createable).map(c=>c.name)),i=ht(r.sobjects.filter(c=>!s.has(c.name)),await this.toolingObjects(t)),a=new Map(r.sobjects.map(c=>[c.name,c.createable!==!1]));return o.sobjects.filter(c=>c.queryable&&(c.createable||a.get(c.name)===!0)).filter(c=>n||c.custom).filter(c=>!mt(c.name,i)).map(c=>({apiName:c.name,label:c.label,custom:c.custom,...a.has(c.name)?a.get(c.name)===!1?{notCreateableInTarget:!0}:{}:{missingInTarget:!0}}))}async countObjects(e,t){return this.countRecords(e,t)}async scan(e,t,n,o,r={}){let s=Vo(r.maxDepth,Bt),i=Vo(r.maxObjects,_t),a=r.onProgress??(()=>{});if(n.length===0)throw new Error("Choose the objects to copy: a scan starts from them, and with none chosen it would describe and count every object of the org.");let c=await e.describeGlobal(),d=[...n],m=await t.describeGlobal(),u=ht(m.sobjects,await this.toolingObjects(t)),p=R=>mt(R,u);d=d.filter(R=>!p(R)),a(`describing ${d.length} selected object(s)\u2026`);let g=await this.describeAll(e,d),y=new Set(g.keys()),f=new Map(c.sobjects.map(R=>[R.name,R.custom])),A=new Map;for(let R of c.sobjects)R.keyPrefix&&A.set(R.keyPrefix,R.name);let w=await this.walkRecords(e,g,y,{isStandard:R=>f.get(R)===!1||!f.has(R)&&!R.includes("__"),includeStandardObjects:o,leftOut:p,keyPrefixes:A,maxDepth:s,maxObjects:i,say:a}),M=new Set(m.sobjects.map(R=>R.name)),I=[...g.keys()].filter(R=>!M.has(R)),q=await this.currenciesOf(e,t,g),Q=await this.personAccountsOf(e,g,y,w.parentIds,{cutShort:w.cutShort,cutAt:w.cutAt});return{objectDescribes:g,autoDiscoveredObjects:w.added,missingInTarget:I,recordCounts:w.recordCounts,totalObjectsScanned:g.size,parentIds:w.parentIds,personAccounts:Q,scope:{maxDepth:s,maxObjects:i,selected:[...y],parents:w.added.map(R=>({objectApiName:R,records:w.parentIds.get(R)?.length??0})),leftEmpty:w.leftEmpty,standardNeeded:w.standardNeeded,...w.followedByDefault.length>0?{followedByDefault:w.followedByDefault}:{},...q?{currencies:q}:{},...w.cutShort.length>0?{cutShort:w.cutShort}:{}}}}async readFitRows(e,t,n=()=>{}){let o=new Set(t.objectDescribes.keys()),r=new Map;for(let s of t.scope.selected){let i=t.objectDescribes.get(s);if(!i)continue;n(`reading the lookups of ${s} to fit it\u2026`);let a=new Set(i.fields.map(u=>u.name)),c=Ze(s,i).filter(u=>u.targets.some(p=>o.has(p))),d=["Id",...new Set(c.map(u=>u.field)),...(s===ae||s===fe)&&a.has(ye)?[ye]:[],...s===Ae&&a.has(Ve)?[Ve]:[]],m=await vn(`SELECT ${d.map(ge).join(", ")} FROM ${ge(s)} ORDER BY Id`,async u=>(await this.readAll(e,u)).records);r.set(s,m.filter(u=>typeof u.Id=="string"))}return r}async walkFrom(e,t,n,o=()=>{}){let r=new Map(t.objectDescribes),s=new Set(r.keys()),i=new Map;for(let[c,d]of r)d.keyPrefix&&i.set(d.keyPrefix,c);let a=await this.walkRecords(e,r,new Set(t.scope.selected),{isStandard:()=>!1,includeStandardObjects:!0,leftOut:c=>!s.has(c),keyPrefixes:i,maxDepth:t.scope.maxDepth,maxObjects:s.size,say:o},n);return{added:a.added,parentIds:a.parentIds,personAccounts:a.personAccounts,leftEmpty:a.leftEmpty,namingSelected:a.namingSelected}}async personAccountsOf(e,t,n,o,r){let s=new Map;for(let i of[ae,fe]){if(!t.get(i)?.fields.some(d=>d.name===ye))continue;let c=`SELECT COUNT() FROM ${ge(i)} WHERE ${ye} = true`;try{let d=r.cutShort.find(u=>u.objectApiName===i)?.copied;if(n.has(i)&&d!==void 0){let u=r.cutAt.get(i)??await this.lastIdOfTheFirst(e,i,d);s.set(i,u!==void 0?(await e.query(`${c} AND Id <= '${he(u)}'`)).totalSize:Math.min((await e.query(c)).totalSize,d));continue}if(n.has(i)){s.set(i,(await e.query(c)).totalSize);continue}let m=0;for(let u of this.chunk([...o.get(i)??[]],ke)){let p=u.map(g=>`'${he(g)}'`).join(", ");m+=(await e.query(`${c} AND Id IN (${p})`)).totalSize}s.set(i,m)}catch(d){le.warn("Autopilot could not count the person accounts it copies",{objectApiName:i,error:te(d)})}}return s}async lastIdOfTheFirst(e,t,n){let{records:o}=await this.readAll(e,`SELECT Id FROM ${ge(t)} ORDER BY Id`),r=o.length>=n?o[n-1]?.Id:void 0;return typeof r=="string"?r:void 0}async currenciesOf(e,t,n){let o=[...n.values()].filter(a=>a.fields.some(c=>c.name===me)).map(a=>a.name).sort();if(o.length===0)return;let r=await Ie(async a=>(await e.query(a)).records,async a=>(await t.query(a)).records),s=r?.target.corporate;if(!r||s===void 0)return;let i=[...r.source.active].filter(a=>!r.target.active.has(a));return i.length>0?{notInTarget:i.sort(),writtenIn:s,objects:o}:void 0}async walkRecords(e,t,n,o,r){let s=new Set(n),i=new Set,a=o.maxObjects,c=o.maxObjects*go,d=new Map,m=[],u=[],p=[],g=new Map,y=[],f=new Map,A=new Map,w=new Map,M=[],I=T=>{let L=t.get(T);return L?Ze(T,L).map(v=>({...v,targets:v.targets.filter(O=>!o.leftOut(O)&&!i.has(O))})).filter(v=>v.targets.length>0):[]},q=T=>["Id",...new Set(I(T).map(L=>L.field)),...r&&(T===ae||T===fe)&&t.get(T)?.fields.some(L=>L.name===ye)?[ye]:[]].map(ge).join(", "),Q=(T,L,v)=>{let O=`${T.objectApiName}.${T.field}>${L}`;d.has(O)||d.set(O,{objectApiName:T.objectApiName,fieldApiName:T.field,target:L,reason:v,...T.required?{required:!0}:{}})},R=new Map,S=(T,L,v)=>{let O=I(T);for(let x of L)for(let _ of O){let W=x[_.field];if(typeof W!="string"||W==="")continue;let U=kr(W,_.targets,o.keyPrefixes,r!==void 0&&_.polymorphic);if(!U)continue;if(n.has(U)){r&&v>0&&M.push({objectApiName:T,field:_.field,required:_.required,target:U,id:W});continue}let re={objectApiName:T,field:_.field,required:_.required};if(v>=o.maxDepth&&!_.required){s.has(U)||Q(re,U,"depth");continue}if(A.get(U)?.has(W))continue;let z=R.get(U)??{ids:new Set,required:!1,via:[]};z.ids.add(W),z.required||=_.required,z.via.some(V=>V.objectApiName===T&&V.field===_.field)||z.via.push(re),R.set(U,z)}},F=[];for(let T of n){if(r){S(T,r.get(T)??[],0);continue}let L=I(T).filter(v=>v.targets.some(O=>!n.has(O)));if(L.length===0){F.push(T);continue}o.say(`reading the lookups of ${T}\u2026`);try{let v=["Id",...new Set(L.map(_=>_.field))].map(ge).join(", "),{records:O,truncated:x}=await this.readAll(e,`SELECT ${v} FROM ${ge(T)} ORDER BY Id`);if(f.set(T,O.length),x){let _=(await this.countRecords(e,[T])).get(T);p.push({objectApiName:T,copied:O.length,..._!==void 0?{total:_}:{}});let W=O[O.length-1]?.Id;typeof W=="string"&&g.set(T,W)}S(T,O,0)}catch(v){le.warn("Autopilot could not read the lookups of a selected object",{objectApiName:T,error:te(v)}),F.push(T)}}for(let[T,L]of await this.countRecords(e,F))L>5e4?(f.set(T,5e4),p.push({objectApiName:T,copied:5e4,total:L})):f.set(T,L);let C=o.maxDepth+br;for(let T=1;R.size>0&&T<=C;T++){let L=R;R=new Map;let v=[];for(let[O,x]of L){if(s.has(O))continue;let _=o.isStandard(O)&&!o.includeStandardObjects,W=_&&!x.required&&Ar.has(O),U;if(_&&!x.required&&!W?U="standard":s.size>=a&&(x.required&&a<c?a++:U="objects"),U){for(let re of x.via)Q(re,O,U);L.delete(O);continue}if(s.add(O),v.push(O),W)u.push({objectApiName:O,referencedBy:x.via.map(re=>`${re.objectApiName}.${re.field}`)});else if(_){let re=x.via[0];m.push({objectApiName:O,neededBy:`${re.objectApiName}.${re.field}`})}}if(v.length>0){let O=v.filter(_=>!t.has(_));O.length>0&&o.say(`describing ${O.length} parent object(s) at depth ${T}\u2026`);let x=await this.describeAll(e,O);for(let _ of v){let W=t.get(_)??x.get(_);W?(t.set(_,W),y.push(_)):(s.delete(_),i.add(_),L.delete(_))}}for(let[O,x]of L){let _=[...x.ids].filter(V=>!A.get(O)?.has(V));if(_.length===0)continue;o.say(`reading ${_.length} ${O} record(s) by id\u2026`);let W=A.get(O)??new Set;A.set(O,W);let U=O===Te,re=U?wr(q(O),t.get(O)):q(O),z=[];for(let V of this.chunk(_,ke)){let ne=V.map(k=>`'${he(k)}'`).join(", "),be=(await e.query(`SELECT ${re} FROM ${ge(O)} WHERE Id IN (${ne})`)).records.filter(k=>typeof k.Id=="string");for(let k of be)W.add(k.Id);z.push(...be);let b=be.filter(k=>k[ye]===!0).length;r&&b>0&&w.set(O,(w.get(O)??0)+b),S(O,be,T)}if(U){let V=await this.standardPricesOf(e,re,z,W);if(V.length>0){o.say(`reading ${V.length} standard price(s) the prices need\u2026`);for(let ne of V)W.add(ne.Id);S(O,V.map(ne=>({...ne,[Be]:void 0})),T)}}}}let ee=new Map;for(let T of y){let L=[...A.get(T)??[]];ee.set(T,L),f.set(T,L.length)}return{added:y,leftEmpty:[...d.values()].filter(T=>!s.has(T.target)),standardNeeded:m,followedByDefault:u.filter(T=>s.has(T.objectApiName)),cutShort:p,cutAt:g,recordCounts:f,parentIds:ee,personAccounts:w,namingSelected:M}}async standardPricesOf(e,t,n,o){let r=s=>[s[_e],s[me],s[Pe]].map(i=>String(i??"")).join("|");try{let[s]=(await e.query(Ee)).records,i=s?.Id;if(typeof i!="string")return[];let a=n.filter(u=>u[Be]!==i),c=[...new Set(a.flatMap(u=>{let p=u[_e];return typeof p=="string"&&p!==""?[p]:[]}))];if(c.length===0)return[];let d=new Set(a.map(r)),m=[];for(let u of this.chunk(c,ke)){let p=u.map(y=>`'${he(y)}'`).join(", "),g=await e.query(`SELECT ${t} FROM ${Te} WHERE ${Be} = '${he(i)}' AND ${_e} IN (${p})`);for(let y of g.records){let f=y.Id;typeof f!="string"||o.has(f)||!d.has(r(y))||m.push(y)}}return m}catch(s){return le.warn("Autopilot could not read the standard prices its prices need",{error:te(s)}),[]}}async readAll(e,t){let{queryMore:n}=e;if(!n){let r=await e.query(t);return{records:r.records,truncated:r.done===!1}}let o=await We({query:r=>e.query(r),queryMore:r=>n.call(e,r)},t);return o.truncated&&le.warn("Autopilot read the lookups of a selected object to its bound only",{records:o.records.length}),{records:o.records,truncated:o.truncated}}async toolingObjects(e){if(!e.tooling)return[];try{return(await e.tooling.describeGlobal()).sobjects.map(n=>n.name)}catch(t){return le.warn("Autopilot could not ask the Tooling API which objects are metadata",{error:te(t)}),[]}}async describeAll(e,t){let n=new Map,o=this.chunk(t,this.maxConcurrent);for(let r of o){let s=await Promise.allSettled(r.map(i=>e.describe(i)));for(let i of s)i.status==="fulfilled"&&n.set(i.value.name,i.value)}return n}async countRecords(e,t){let n=new Map,o=this.chunk(t,this.maxConcurrent);for(let r of o){let s=await Promise.allSettled(r.map(async i=>{let a=await e.query(`SELECT COUNT() FROM ${ge(i)}`);return{name:i,count:a.totalSize}}));for(let i of s)i.status==="fulfilled"&&n.set(i.value.name,i.value.count)}return n}chunk(e,t){let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}};function Vo(l,e){return l!==void 0&&Number.isInteger(l)&&l>0?l:e}function Ze(l,e){return e.fields.filter(t=>t.referenceTo.length>0&&Wt(t)).map(t=>({field:t.name,targets:[...t.referenceTo],required:Ut(l,t.name,t.nillable),polymorphic:t.referenceTo.length>1}))}function kr(l,e,t,n=!1){if(e.length===1&&!n)return e[0];let o=t.get(l.slice(0,3));return o!==void 0&&e.includes(o)?o:void 0}var Jo=3,Rr="the source changed since the plan: plan again";function nr(l,e){return{holds:[...l.links.filter(t=>t.kind==="holds"),...l.requiredOfParents,...l.outward.filter(t=>t.required)],kept:e}}function Zo(l,e){return typeof l!="string"||l===""?!1:e===void 0||e!==null&&l.startsWith(e)}function or(l,e,t){let n=new Map(t.map((s,i)=>[s,i])),o=new Set(e),r={links:[],outward:[],requiredOfParents:[]};for(let[s,i]of l)for(let a of Ze(s,i))for(let c of a.targets.filter(d=>l.has(d))){let d=a.polymorphic?{prefix:l.get(c)?.keyPrefix??null}:{},m={objectApiName:s,field:a.field,parent:c,...d};if(!o.has(s))o.has(c)&&a.required&&r.requiredOfParents.push({...m,kind:"holds"});else if(!o.has(c))r.outward.push({...m,required:a.required});else if(a.required)r.links.push({...m,kind:"holds"});else if(c===s)r.links.push({...m,kind:"selfReference"});else{let u=(n.get(c)??0)<(n.get(s)??0);r.links.push({...m,kind:u?"holds":"owed"})}}return r}function rr(l,e){let t=new Set(l),n=new Set(e.links.filter(o=>o.kind!=="holds").map(o=>o.objectApiName));return(o,r)=>t.has(o)&&(r==="insert"||r==="update"&&(n.has(o)||Me[o]!==void 0))}function sr(l,e,t){return typeof l.unread=="string"?{perRecord:[],notCounted:[],unread:l.unread}:lo(qe(l,e,t),t)}function Sr(l){let e=new Map(l.order.map((t,n)=>[t,n]));return l.order.map(t=>{let n=l.rows.get(t)??[],o=l.lookups.links.filter(i=>i.objectApiName===t),r=l.lookups.outward.filter(i=>i.objectApiName===t),s={name:t,rows:n,at:new Map(n.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===ae||t===fe?n.flatMap((i,a)=>i[ye]===!0?[a]:[]):[])};return n.forEach((i,a)=>{let c=[],d=[],m=[];for(let u of o){let p=i[u.field];if(!Zo(p,u.prefix))continue;let g={link:u,id:p};u.kind!=="holds"?m.push(g):(e.get(u.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}s.heldBefore.push(c),s.heldAfter.push(d),s.loose.push(m),s.named.push(r.flatMap(u=>{let p=i[u.field];return Zo(p,u.prefix)?[{parent:u.parent,id:p}]:[]})),(c.length>0?s.followers:s.roots).push(a)}),s})}function er(l,e){let t=new Map(l.map(r=>[r.name,r])),n=new Map,o=[...e].flatMap(([r,s])=>[...s].map(i=>({name:r,id:i})));for(let r=o.pop();r;r=o.pop()){let s=t.get(r.name),i=s?.at.get(r.id);if(!s||i===void 0)continue;let a=n.get(r.name)??new Set;if(n.set(r.name,a),!a.has(i)){a.add(i);for(let c of[...s.heldBefore[i],...s.heldAfter[i]])o.push({name:c.link.parent,id:c.id})}}return n}function tr(l){return`${l} record${l===1?"":"s"}`}function Or(l,e){return[...l.parentIds].every(([t,n])=>{let o=new Set(e.get(t)?.ids??[]);return n.every(r=>o.has(r))})}async function ir(l){let{budget:e,room:t,mode:n,parents:o,maxRecords:r}=l,s=Sr(l),i=b=>{let k=n.caps?.[b]??n.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=s.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of s){if(b.name!==Ae)continue;let k=b.rows.filter(D=>D[Ve]===!0);k.length>0&&c.set(b.name,new Set(k.map(D=>D.Id)))}let d=er(s,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},D=new Set;for(let $ of s){let j=d.get($.name)??D,J=i($.name),N=$.roots.filter(Z=>!j.has(Z)),G=N.length===0?0:Math.max(1,Math.round(b*Math.min(N.length,J??1/0))),K=vt(N.length,G).map(Z=>N[Z]),B=new Map;for(let Z of $.followers){if(j.has(Z))continue;let we=$.heldBefore[Z].find(Oe=>!k.ids.get(Oe.link.parent)?.has(Oe.id));we?B.set(Z,we.link):K.push(Z)}K.sort((Z,we)=>Z-we);let ie=$.name===fe?K.filter(Z=>$.persons.has(Z)):[],H=ie.length>0?K.filter(Z=>!$.persons.has(Z)):K,se=J===void 0?H.length:Math.max(0,J-j.size-ie.length),de=H.length>se?vt(H.length,se).map(Z=>H[Z]):H,ue=new Set([...j,...ie,...de]);k.kept.set($.name,ue),k.ids.set($.name,new Set([...ue].map(Z=>$.rows[Z].Id))),k.cut.set($.name,B)}if(!a)return k;for(let $=!0;$;){$=!1;for(let j of s){let J=d.get(j.name)??D,N=k.kept.get(j.name)??new Set;for(let G of[...N]){if(J.has(G))continue;let K=[...j.heldAfter[G],...j.heldBefore[G]].find(B=>!k.ids.get(B.link.parent)?.has(B.id));K&&(N.delete(G),k.ids.get(j.name)?.delete(j.rows[G].Id),k.cut.get(j.name)?.set(G,K.link),$=!0)}}}return k},u=b=>{let k=new Map;for(let D of s){let $=0;for(let j of b.kept.get(D.name)??[])D.loose[j].some(N=>b.ids.get(N.link.parent)?.has(N.id))&&$++;$>0&&k.set(D.name,$)}return k},p=(b,k)=>{let D=new Map,$=0;for(let N of s){let G=b.kept.get(N.name)??new Set,K=0;for(let B of G)N.persons.has(B)&&K++;D.set(N.name,G.size),$+=Rt(N.name,{rows:G.size,personAccounts:K})}for(let[N,{records:G,personAccounts:K}]of k)D.set(N,(D.get(N)??0)+G),$+=Rt(N,{rows:G,...K!==void 0?{personAccounts:K}:{}});let j=u(b),J=uo(t,(N,G)=>{let K=D.get(N)??0;return G==="insert"||Me[N]!==void 0?K:j.get(N)??0});return{records:[...D.values()].reduce((N,G)=>N+G,0),bytes:$,roomBytes:J,requests:Jn([...D.values()].map(N=>({rows:N})))}},g=new Map;for(let b of s)for(let k of b.named)for(let{parent:D,id:$}of k){let j=g.get(D)??new Set;g.set(D,j),j.add($)}let y=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,D=0;for(let J of s)for(let N of b.kept.get(J.name)??[])for(let{parent:G,id:K}of J.named[N]){let B=k.get(G)??new Set;k.set(G,B),B.has(K)||D++,B.add(K)}let $=y>0?D/y:0,j=new Map;for(let[J,{ids:N,personAccounts:G}]of o){let K=Math.max(0,N.length-(g.get(J)?.size??0)),B=Math.min(N.length,(k.get(J)?.size??0)+Math.ceil(K*$));B!==0&&j.set(J,{records:B,...G!==void 0?{personAccounts:Math.ceil(G*B/N.length)}:{}})}return j},A=b=>new Map(b.added.map(k=>{let D=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...D!==void 0?{personAccounts:D}:{}}]})),w=b=>b.bytes+b.roomBytes<=e.bytes,M=b=>e.runRequests===void 0||b.requests<=e.runRequests,I=b=>r===void 0||b.records<=r,q=b=>w(b)&&M(b)&&I(b),Q=b=>w(b)?M(b)?"maxTotal":"apiRequests":e.terms.limitedBy,R=b=>w(b)?M(b)?{bound:"maxTotal",records:b.records,allowed:r??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},S=b=>{if(!w(b)){let k=so((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return M(b)?`${tr(b.records)}, past the ${r??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},F=b=>new Map(s.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((D,$)=>D-$).map(D=>k.rows[D])])),C=(b,k,D,$,j,J)=>{let N=s.map(B=>{let ie=k.cut.get(B.name)??new Map,H=new Map;for(let de of ie.values()){let ue=`${de.field}
8
- ${de.parent}`,Z=H.get(ue)??{field:de.field,parent:de.parent,count:0};H.set(ue,{...Z,count:Z.count+1})}let se=k.kept.get(B.name)?.size??0;return{objectApiName:B.name,inSource:B.rows.length,kept:se,cutSpread:B.rows.length-se-ie.size,cutWithParent:[...H.values()].sort((de,ue)=>ue.count-de.count)}}),G=new Map,K=(B,ie,H)=>{let se=`${B}
7
+ import{c as rr}from"./chunk-N652NMZ4.mjs";import"./chunk-SOGQW4IG.mjs";import"./chunk-W622GUAW.mjs";import"./chunk-WA7EYLAQ.mjs";import"./chunk-LKQ5RKIV.mjs";import"./chunk-XAMBCQPU.mjs";import"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-CHYDMRSV.mjs";import"./chunk-F6GUDTOB.mjs";import"./chunk-BXU6WFMH.mjs";import"./chunk-2GTBABKU.mjs";import"./chunk-P33PSCXK.mjs";import"./chunk-UCD54V2M.mjs";import"./chunk-BV6VTP3J.mjs";import{q as zt}from"./chunk-OLSGVAIL.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-ELFXJHU7.mjs";import{b as rn}from"./chunk-W7U5E5ZL.mjs";import{a as vo,b as Eo,c as Po,d as Wo,e as Ho,f as Lt,g as Dt,h as $t,i as Ve,j as Ko,k as xe,l as Fe}from"./chunk-E5ZB3LU5.mjs";import"./chunk-EFR2Y7E4.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-M3ROUWDX.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-ZM6OJGIG.mjs";import"./chunk-MHMH6MTP.mjs";import"./chunk-COFG7Q6R.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-PJ5I73CK.mjs";import"./chunk-BKDV4ENO.mjs";import"./chunk-X5JYBPXP.mjs";import"./chunk-5P4PHJRL.mjs";import{Na as qt,O as or,a as Co,g as Bt,h as Yo,i as Qo,j as Xo,k as Jo,l as Vo,m as Zo,n as _t,o as er,p as tr,t as je}from"./chunk-VS7ZXUII.mjs";import{a as Io}from"./chunk-SOU4FRYN.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-OO6CLPEH.mjs";import"./chunk-YS4G22C2.mjs";import"./chunk-QROPNEGY.mjs";import{b as mt,e as sn}from"./chunk-BZ24IAP5.mjs";import{a as ct}from"./chunk-SCKUIE3R.mjs";import{c as cn,d as dn,f as ln}from"./chunk-AV5SWEHP.mjs";import"./chunk-I7O6C2B5.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-2CNCDM56.mjs";import"./chunk-SIHORWVK.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import{b as un,c as pn,d as Ue,e as fn,f as yo,g as wo,i as bo,j as Ao,k as ko,l as Ro,m as It,s as So,t as Oo,u as To}from"./chunk-4VS2V6WU.mjs";import{h as Mo,i as Do,j as $o,k as Bo,l as Nt,m as _o,n as qo}from"./chunk-KYEDBS54.mjs";import{h as zo,i as Go,k as Uo}from"./chunk-6XYKJSGX.mjs";import{a as xo,b as xt,c as Ft,d as Fo,e as jo,f as No,g as Lo,h as jt}from"./chunk-K2FBZIXY.mjs";import"./chunk-F43REJDZ.mjs";import"./chunk-JPUR2CFX.mjs";import"./chunk-LPBMBW3O.mjs";import{d as Yn}from"./chunk-T63U4OZJ.mjs";import{d as Kn}from"./chunk-DBFJB2B6.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-DYFALGRT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-7FFGJWHN.mjs";import{o as to,p as no,q as Tt,r as oo,s as Xe}from"./chunk-G35N4P7D.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import{b as ft,c as Ge}from"./chunk-KDGMAGQR.mjs";import{B as Qe,s as Vn,t as Ot,x as Ie,y as Zn,z as eo}from"./chunk-MFG4MUIO.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import{b as pt,c as nn}from"./chunk-HS4YRX4J.mjs";import{a as he,i as Me,k as Fn,n as jn,o as Nn,p as Ln,s as Dn,t as $n,u as Bn,v as _n}from"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import{Ba as mo,D as Et,Ia as Te,Ja as ho,K as so,L as io,N as ao,Q as Pt,S as Je,T as co,W as lo,Wa as go,Xa as Mt,_ as Ct,ka as uo,r as Qn,s as Xn,w as Jn,wa as po,xa as fo,y as ro}from"./chunk-VYXMVJL5.mjs";import{q as vt}from"./chunk-AEKONPF4.mjs";import{b as wt,d as bt,e as In}from"./chunk-JWTSEDIQ.mjs";import{a as ae}from"./chunk-4TLYUZD5.mjs";import"./chunk-CION3VMZ.mjs";import{a as qn,b as At,c as kt,f as zn,h as Gn,j as Ke,l as Un,m as Wn}from"./chunk-WIO4XO4F.mjs";import{a as He}from"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import{i as xn}from"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import{X as Sn,Y as On,Z as Tn,_ as vn,a as mn,b as oe,c as We,ca as Ce,d as hn,e as gn,ea as En,f as yn,ha as Pn,ia as Cn,ja as Mn,l as gt,m as wn,n as bn,o as An,p as ce,q as fe,r as yt,s as Pe,t as kn,y as Rn}from"./chunk-A527W53V.mjs";import{a as ge,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as Ye,c as Rt,j as St,k as Hn}from"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{a as on,c as an,e as ht,g as nr}from"./chunk-MTMH6H2A.mjs";import{Bb as Qt,Cb as Xt,Db as Jt,Hb as Oe,Ib as Ae,Jb as _e,Kb as ve,Lb as Vt,Nb as lt,Ob as qe,Pb as Ee,Ub as Zt,Wb as en,ed as ze,ic as tn,ld as ut,yb as dt}from"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-NTOVCTRS.mjs";var Ut=Oo,Wt=So,ke=200;function Or(l,e){let t=new Set(e?.fields.map(n=>n.name)??[]),o=new Set(l.split(", "));for(let n of[he,Ee])t.has(n)&&o.add(n);return[...o].join(", ")}var Tr=10,vr=new Set([ce]),we="IsPersonAccount",Ze="IsStandard",et=class{maxConcurrent;constructor(e=10){this.maxConcurrent=e}async listObjects(e,t,o){let[n,r]=await Promise.all([e.describeGlobal(),t.describeGlobal()]),s=new Set(n.sobjects.filter(c=>c.createable).map(c=>c.name)),i=bt(r.sobjects.filter(c=>!s.has(c.name)),await this.toolingObjects(t)),a=new Map(r.sobjects.map(c=>[c.name,c.createable!==!1]));return n.sobjects.filter(c=>c.queryable&&(c.createable||a.get(c.name)===!0)).filter(c=>o||c.custom).filter(c=>!wt(c.name,i)).map(c=>({apiName:c.name,label:c.label,custom:c.custom,...a.has(c.name)?a.get(c.name)===!1?{notCreateableInTarget:!0}:{}:{missingInTarget:!0}}))}async countObjects(e,t){return this.countRecords(e,t)}async scan(e,t,o,n,r={}){let s=Gt(r.maxDepth,Ut),i=Gt(r.maxObjects,Wt),a=Gt(r.maxRecordsPerObject,5e4),c=r.onProgress??(()=>{});if(o.length===0)throw new Error("Choose the objects to copy: a scan starts from them, and with none chosen it would describe and count every object of the org.");let d=await e.describeGlobal(),m=[...o],u=await t.describeGlobal(),p=bt(u.sobjects,await this.toolingObjects(t)),g=A=>wt(A,p);m=m.filter(A=>!g(A)),c(`describing ${m.length} selected object(s)\u2026`);let y=await this.describeAll(e,m),f=new Set(y.keys()),R=new Map(d.sobjects.map(A=>[A.name,A.custom])),w=new Map;for(let A of d.sobjects)A.keyPrefix&&w.set(A.keyPrefix,A.name);let C=await this.walkRecords(e,y,f,{isStandard:A=>R.get(A)===!1||!R.has(A)&&!A.includes("__"),includeStandardObjects:n,leftOut:g,keyPrefixes:w,maxDepth:s,maxObjects:i,maxRecords:a,say:c}),v=new Set(u.sobjects.map(A=>A.name)),z=[...y.keys()].filter(A=>!v.has(A)),K=await this.currenciesOf(e,t,y),E=await this.personAccountsOf(e,y,f,C.parentIds,{cutShort:C.cutShort,cutAt:C.cutAt});return{objectDescribes:y,autoDiscoveredObjects:C.added,missingInTarget:z,recordCounts:C.recordCounts,totalObjectsScanned:y.size,parentIds:C.parentIds,personAccounts:E,scope:{maxDepth:s,maxObjects:i,selected:[...f],parents:C.added.map(A=>({objectApiName:A,records:C.parentIds.get(A)?.length??0})),leftEmpty:C.leftEmpty,standardNeeded:C.standardNeeded,...C.followedByDefault.length>0?{followedByDefault:C.followedByDefault}:{},...K?{currencies:K}:{},...C.cutShort.length>0?{cutShort:C.cutShort}:{}}}}async readFitRows(e,t,o=()=>{}){let n=new Set(t.objectDescribes.keys()),r=new Map;for(let s of t.scope.selected){let i=t.objectDescribes.get(s);if(!i)continue;o(`reading the lookups of ${s} to fit it\u2026`);let a=new Set(i.fields.map(u=>u.name)),c=tt(s,i).filter(u=>u.targets.some(p=>n.has(p))),d=["Id",...new Set(c.map(u=>u.field)),...(s===ce||s===fe)&&a.has(we)?[we]:[],...s===Ae&&a.has(Ze)?[Ze]:[]],m=await xn(`SELECT ${d.map(ye).join(", ")} FROM ${ye(s)} ORDER BY Id`,async u=>(await this.readAll(e,u)).records);r.set(s,m.filter(u=>typeof u.Id=="string"))}return r}async walkFrom(e,t,o,n=()=>{}){let r=new Map(t.objectDescribes),s=new Set(r.keys()),i=new Map;for(let[c,d]of r)d.keyPrefix&&i.set(d.keyPrefix,c);let a=await this.walkRecords(e,r,new Set(t.scope.selected),{isStandard:()=>!1,includeStandardObjects:!0,leftOut:c=>!s.has(c),keyPrefixes:i,maxDepth:t.scope.maxDepth,maxObjects:s.size,say:n},o);return{added:a.added,parentIds:a.parentIds,personAccounts:a.personAccounts,leftEmpty:a.leftEmpty,namingSelected:a.namingSelected}}async personAccountsOf(e,t,o,n,r){let s=new Map;for(let i of[ce,fe]){if(!t.get(i)?.fields.some(d=>d.name===we))continue;let c=`SELECT COUNT() FROM ${ye(i)} WHERE ${we} = true`;try{let d=r.cutShort.find(u=>u.objectApiName===i)?.copied;if(o.has(i)&&d!==void 0){let u=r.cutAt.get(i)??await this.lastIdOfTheFirst(e,i,d);s.set(i,u!==void 0?(await e.query(`${c} AND Id <= '${ge(u)}'`)).totalSize:Math.min((await e.query(c)).totalSize,d));continue}if(o.has(i)){s.set(i,(await e.query(c)).totalSize);continue}let m=0;for(let u of this.chunk([...n.get(i)??[]],ke)){let p=u.map(g=>`'${ge(g)}'`).join(", ");m+=(await e.query(`${c} AND Id IN (${p})`)).totalSize}s.set(i,m)}catch(d){ae.warn("Autopilot could not count the person accounts it copies",{objectApiName:i,error:ee(d)})}}return s}async lastIdOfTheFirst(e,t,o){let{records:n}=await this.readAll(e,`SELECT Id FROM ${ye(t)} ORDER BY Id`),r=n.length>=o?n[o-1]?.Id:void 0;return typeof r=="string"?r:void 0}async currenciesOf(e,t,o){let n=[...o.values()].filter(a=>a.fields.some(c=>c.name===he)).map(a=>a.name).sort();if(n.length===0)return;let r=await Me(async a=>(await e.query(a)).records,async a=>(await t.query(a)).records),s=r?.target.corporate;if(!r||s===void 0)return;let i=[...r.source.active].filter(a=>!r.target.active.has(a));return i.length>0?{notInTarget:i.sort(),writtenIn:s,objects:n}:void 0}async walkRecords(e,t,o,n,r){let s=new Set(o),i=new Set,a=n.maxRecords??5e4,c=n.maxObjects,d=n.maxObjects*To,m=new Map,u=[],p=[],g=[],y=new Map,f=[],R=new Map,w=new Map,C=new Map,v=[],z=T=>{let O=t.get(T);return O?tt(T,O).map(D=>({...D,targets:D.targets.filter(S=>!n.leftOut(S)&&!i.has(S))})).filter(D=>D.targets.length>0):[]},K=T=>["Id",...new Set(z(T).map(O=>O.field)),...r&&(T===ce||T===fe)&&t.get(T)?.fields.some(O=>O.name===we)?[we]:[]].map(ye).join(", "),E=(T,O,D)=>{let S=`${T.objectApiName}.${T.field}>${O}`;m.has(S)||m.set(S,{objectApiName:T.objectApiName,fieldApiName:T.field,target:O,reason:D,...T.required?{required:!0}:{}})},A=new Map,j=(T,O,D)=>{let S=z(T);for(let ne of O)for(let N of S){let _=ne[N.field];if(typeof _!="string"||_==="")continue;let V=Er(_,N.targets,n.keyPrefixes,r!==void 0&&N.polymorphic);if(!V)continue;if(o.has(V)){r&&D>0&&v.push({objectApiName:T,field:N.field,required:N.required,target:V,id:_});continue}let B={objectApiName:T,field:N.field,required:N.required};if(D>=n.maxDepth&&!N.required){s.has(V)||E(B,V,"depth");continue}if(w.get(V)?.has(_))continue;let Z=A.get(V)??{ids:new Set,required:!1,via:[]};Z.ids.add(_),Z.required||=N.required,Z.via.some(Y=>Y.objectApiName===T&&Y.field===N.field)||Z.via.push(B),A.set(V,Z)}},M=[];for(let T of o){if(r){j(T,r.get(T)??[],0);continue}let O=z(T).filter(D=>D.targets.some(S=>!o.has(S)));if(O.length===0){M.push(T);continue}n.say(`reading the lookups of ${T}\u2026`);try{let D=["Id",...new Set(O.map(N=>N.field))].map(ye).join(", "),{records:S,truncated:ne}=await this.readAll(e,`SELECT ${D} FROM ${ye(T)} ORDER BY Id`,a);if(R.set(T,S.length),ne){let N=(await this.countRecords(e,[T])).get(T);g.push({objectApiName:T,copied:S.length,...N!==void 0?{total:N}:{}});let _=S[S.length-1]?.Id;typeof _=="string"&&y.set(T,_)}j(T,S,0)}catch(D){ae.warn("Autopilot could not read the lookups of a selected object",{objectApiName:T,error:ee(D)}),M.push(T)}}for(let[T,O]of await this.countRecords(e,M))O>a?(R.set(T,a),g.push({objectApiName:T,copied:a,total:O})):R.set(T,O);let te=n.maxDepth+Tr;for(let T=1;A.size>0&&T<=te;T++){let O=A;A=new Map;let D=[];for(let[S,ne]of O){if(s.has(S))continue;let N=n.isStandard(S)&&!n.includeStandardObjects,_=N&&!ne.required&&vr.has(S),V;if(N&&!ne.required&&!_?V="standard":s.size>=c&&(ne.required&&c<d?c++:V="objects"),V){for(let B of ne.via)E(B,S,V);O.delete(S);continue}if(s.add(S),D.push(S),_)p.push({objectApiName:S,referencedBy:ne.via.map(B=>`${B.objectApiName}.${B.field}`)});else if(N){let B=ne.via[0];u.push({objectApiName:S,neededBy:`${B.objectApiName}.${B.field}`})}}if(D.length>0){let S=D.filter(N=>!t.has(N));S.length>0&&n.say(`describing ${S.length} parent object(s) at depth ${T}\u2026`);let ne=await this.describeAll(e,S);for(let N of D){let _=t.get(N)??ne.get(N);_?(t.set(N,_),f.push(N)):(s.delete(N),i.add(N),O.delete(N))}}for(let[S,ne]of O){let N=[...ne.ids].filter(Y=>!w.get(S)?.has(Y));if(N.length===0)continue;n.say(`reading ${N.length} ${S} record(s) by id\u2026`);let _=w.get(S)??new Set;w.set(S,_);let V=S===Oe,B=V?Or(K(S),t.get(S)):K(S),Z=[];for(let Y of this.chunk(N,ke)){let me=Y.map(x=>`'${ge(x)}'`).join(", "),b=(await e.query(`SELECT ${B} FROM ${ye(S)} WHERE Id IN (${me})`)).records.filter(x=>typeof x.Id=="string");for(let x of b)_.add(x.Id);Z.push(...b);let k=b.filter(x=>x[we]===!0).length;r&&k>0&&C.set(S,(C.get(S)??0)+k),j(S,b,T)}if(V){let Y=await this.standardPricesOf(e,B,Z,_);if(Y.length>0){n.say(`reading ${Y.length} standard price(s) the prices need\u2026`);for(let me of Y)_.add(me.Id);j(S,Y.map(me=>({...me,[_e]:void 0})),T)}}}}let se=new Map;for(let T of f){let O=[...w.get(T)??[]];se.set(T,O),R.set(T,O.length)}return{added:f,leftEmpty:[...m.values()].filter(T=>!s.has(T.target)),standardNeeded:u,followedByDefault:p.filter(T=>s.has(T.objectApiName)),cutShort:g,cutAt:y,recordCounts:R,parentIds:se,personAccounts:C,namingSelected:v}}async standardPricesOf(e,t,o,n){let r=s=>[s[qe],s[he],s[Ee]].map(i=>String(i??"")).join("|");try{let[s]=(await e.query(ve)).records,i=s?.Id;if(typeof i!="string")return[];let a=o.filter(u=>u[_e]!==i),c=[...new Set(a.flatMap(u=>{let p=u[qe];return typeof p=="string"&&p!==""?[p]:[]}))];if(c.length===0)return[];let d=new Set(a.map(r)),m=[];for(let u of this.chunk(c,ke)){let p=u.map(y=>`'${ge(y)}'`).join(", "),g=await e.query(`SELECT ${t} FROM ${Oe} WHERE ${_e} = '${ge(i)}' AND ${qe} IN (${p})`);for(let y of g.records){let f=y.Id;typeof f!="string"||n.has(f)||!d.has(r(y))||m.push(y)}}return m}catch(s){return ae.warn("Autopilot could not read the standard prices its prices need",{error:ee(s)}),[]}}async readAll(e,t,o=5e4){let{queryMore:n}=e;if(!n){let s=await e.query(t);return{records:s.records,truncated:s.done===!1}}let r=await He({query:s=>e.query(s),queryMore:s=>n.call(e,s)},t,o);return r.truncated&&ae.warn("Autopilot read the lookups of a selected object to its bound only",{records:r.records.length}),{records:r.records,truncated:r.truncated}}async toolingObjects(e){if(!e.tooling)return[];try{return(await e.tooling.describeGlobal()).sobjects.map(o=>o.name)}catch(t){return ae.warn("Autopilot could not ask the Tooling API which objects are metadata",{error:ee(t)}),[]}}async describeAll(e,t){let o=new Map,n=this.chunk(t,this.maxConcurrent);for(let r of n){let s=await Promise.allSettled(r.map(i=>e.describe(i)));for(let i of s)i.status==="fulfilled"&&o.set(i.value.name,i.value)}return o}async countRecords(e,t){let o=new Map,n=this.chunk(t,this.maxConcurrent);for(let r of n){let s=await Promise.allSettled(r.map(async i=>{let a=await e.query(`SELECT COUNT() FROM ${ye(i)}`);return{name:i,count:a.totalSize}}));for(let i of s)i.status==="fulfilled"&&o.set(i.value.name,i.value.count)}return o}chunk(e,t){let o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o}};function Gt(l,e){return l!==void 0&&Number.isInteger(l)&&l>0?l:e}function tt(l,e){return e.fields.filter(t=>t.referenceTo.length>0&&Jt(t)).map(t=>({field:t.name,targets:[...t.referenceTo],required:Xt(l,t.name,t.nillable),polymorphic:t.referenceTo.length>1}))}function Er(l,e,t,o=!1){if(e.length===1&&!o)return e[0];let n=t.get(l.slice(0,3));return n!==void 0&&e.includes(n)?n:void 0}var sr=3,Pr="the source changed since the plan: plan again";function dr(l,e){return{holds:[...l.links.filter(t=>t.kind==="holds"),...l.requiredOfParents,...l.outward.filter(t=>t.required)],kept:e}}function ir(l,e){return typeof l!="string"||l===""?!1:e===void 0||e!==null&&l.startsWith(e)}function lr(l,e,t){let o=new Map(t.map((s,i)=>[s,i])),n=new Set(e),r={links:[],outward:[],requiredOfParents:[]};for(let[s,i]of l)for(let a of tt(s,i))for(let c of a.targets.filter(d=>l.has(d))){let d=a.polymorphic?{prefix:l.get(c)?.keyPrefix??null}:{},m={objectApiName:s,field:a.field,parent:c,...d};if(!n.has(s))n.has(c)&&a.required&&r.requiredOfParents.push({...m,kind:"holds"});else if(!n.has(c))r.outward.push({...m,required:a.required});else if(a.required)r.links.push({...m,kind:"holds"});else if(c===s)r.links.push({...m,kind:"selfReference"});else{let u=(o.get(c)??0)<(o.get(s)??0);r.links.push({...m,kind:u?"holds":"owed"})}}return r}function ur(l,e){let t=new Set(l),o=new Set(e.links.filter(n=>n.kind!=="holds").map(n=>n.objectApiName));return(n,r)=>t.has(n)&&(r==="insert"||r==="update"&&(o.has(n)||Ce[n]!==void 0))}function pr(l,e,t){return typeof l.unread=="string"?{perRecord:[],notCounted:[],unread:l.unread}:bo(ze(l,e,t),t)}function Cr(l){let e=new Map(l.order.map((t,o)=>[t,o]));return l.order.map(t=>{let o=l.rows.get(t)??[],n=l.lookups.links.filter(i=>i.objectApiName===t),r=l.lookups.outward.filter(i=>i.objectApiName===t),s={name:t,rows:o,at:new Map(o.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===ce||t===fe?o.flatMap((i,a)=>i[we]===!0?[a]:[]):[])};return o.forEach((i,a)=>{let c=[],d=[],m=[];for(let u of n){let p=i[u.field];if(!ir(p,u.prefix))continue;let g={link:u,id:p};u.kind!=="holds"?m.push(g):(e.get(u.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}s.heldBefore.push(c),s.heldAfter.push(d),s.loose.push(m),s.named.push(r.flatMap(u=>{let p=i[u.field];return ir(p,u.prefix)?[{parent:u.parent,id:p}]:[]})),(c.length>0?s.followers:s.roots).push(a)}),s})}function ar(l,e){let t=new Map(l.map(r=>[r.name,r])),o=new Map,n=[...e].flatMap(([r,s])=>[...s].map(i=>({name:r,id:i})));for(let r=n.pop();r;r=n.pop()){let s=t.get(r.name),i=s?.at.get(r.id);if(!s||i===void 0)continue;let a=o.get(r.name)??new Set;if(o.set(r.name,a),!a.has(i)){a.add(i);for(let c of[...s.heldBefore[i],...s.heldAfter[i]])n.push({name:c.link.parent,id:c.id})}}return o}function cr(l){return`${l} record${l===1?"":"s"}`}function Mr(l,e){return[...l.parentIds].every(([t,o])=>{let n=new Set(e.get(t)?.ids??[]);return o.every(r=>n.has(r))})}async function fr(l){let{budget:e,room:t,mode:o,parents:n,maxRecords:r}=l,s=Cr(l),i=b=>{let k=o.caps?.[b]??o.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=s.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of s){if(b.name!==Ae)continue;let k=b.rows.filter(x=>x[Ze]===!0);k.length>0&&c.set(b.name,new Set(k.map(x=>x.Id)))}let d=ar(s,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},x=new Set;for(let $ of s){let L=d.get($.name)??x,X=i($.name),F=$.roots.filter(J=>!L.has(J)),G=F.length===0?0:Math.max(1,Math.round(b*Math.min(F.length,X??1/0))),W=It(F.length,G).map(J=>F[J]),q=new Map;for(let J of $.followers){if(L.has(J))continue;let be=$.heldBefore[J].find(Se=>!k.ids.get(Se.link.parent)?.has(Se.id));be?q.set(J,be.link):W.push(J)}W.sort((J,be)=>J-be);let ie=$.name===fe?W.filter(J=>$.persons.has(J)):[],U=ie.length>0?W.filter(J=>!$.persons.has(J)):W,re=X===void 0?U.length:Math.max(0,X-L.size-ie.length),le=U.length>re?It(U.length,re).map(J=>U[J]):U,ue=new Set([...L,...ie,...le]);k.kept.set($.name,ue),k.ids.set($.name,new Set([...ue].map(J=>$.rows[J].Id))),k.cut.set($.name,q)}if(!a)return k;for(let $=!0;$;){$=!1;for(let L of s){let X=d.get(L.name)??x,F=k.kept.get(L.name)??new Set;for(let G of[...F]){if(X.has(G))continue;let W=[...L.heldAfter[G],...L.heldBefore[G]].find(q=>!k.ids.get(q.link.parent)?.has(q.id));W&&(F.delete(G),k.ids.get(L.name)?.delete(L.rows[G].Id),k.cut.get(L.name)?.set(G,W.link),$=!0)}}}return k},u=b=>{let k=new Map;for(let x of s){let $=0;for(let L of b.kept.get(x.name)??[])x.loose[L].some(F=>b.ids.get(F.link.parent)?.has(F.id))&&$++;$>0&&k.set(x.name,$)}return k},p=(b,k)=>{let x=new Map,$=0;for(let F of s){let G=b.kept.get(F.name)??new Set,W=0;for(let q of G)F.persons.has(q)&&W++;x.set(F.name,G.size),$+=Et(F.name,{rows:G.size,personAccounts:W})}for(let[F,{records:G,personAccounts:W}]of k)x.set(F,(x.get(F)??0)+G),$+=Et(F,{rows:G,...W!==void 0?{personAccounts:W}:{}});let L=u(b),X=Ao(t,(F,G)=>{let W=x.get(F)??0;return G==="insert"||Ce[F]!==void 0?W:L.get(F)??0});return{records:[...x.values()].reduce((F,G)=>F+G,0),bytes:$,roomBytes:X,requests:ao([...x.values()].map(F=>({rows:F})))}},g=new Map;for(let b of s)for(let k of b.named)for(let{parent:x,id:$}of k){let L=g.get(x)??new Set;g.set(x,L),L.add($)}let y=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,x=0;for(let X of s)for(let F of b.kept.get(X.name)??[])for(let{parent:G,id:W}of X.named[F]){let q=k.get(G)??new Set;k.set(G,q),q.has(W)||x++,q.add(W)}let $=y>0?x/y:0,L=new Map;for(let[X,{ids:F,personAccounts:G}]of n){let W=Math.max(0,F.length-(g.get(X)?.size??0)),q=Math.min(F.length,(k.get(X)?.size??0)+Math.ceil(W*$));q!==0&&L.set(X,{records:q,...G!==void 0?{personAccounts:Math.ceil(G*q/F.length)}:{}})}return L},R=b=>new Map(b.added.map(k=>{let x=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...x!==void 0?{personAccounts:x}:{}}]})),w=b=>b.bytes+b.roomBytes<=e.bytes,C=b=>e.runRequests===void 0||b.requests<=e.runRequests,v=b=>r===void 0||b.records<=r,z=b=>w(b)&&C(b)&&v(b),K=b=>w(b)?C(b)?"maxTotal":"apiRequests":e.terms.limitedBy,E=b=>w(b)?C(b)?{bound:"maxTotal",records:b.records,allowed:r??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},A=b=>{if(!w(b)){let k=ho((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return C(b)?`${cr(b.records)}, past the ${r??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},j=b=>new Map(s.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((x,$)=>x-$).map(x=>k.rows[x])])),M=(b,k,x,$,L,X)=>{let F=s.map(q=>{let ie=k.cut.get(q.name)??new Map,U=new Map;for(let le of ie.values()){let ue=`${le.field}
8
+ ${le.parent}`,J=U.get(ue)??{field:le.field,parent:le.parent,count:0};U.set(ue,{...J,count:J.count+1})}let re=k.kept.get(q.name)?.size??0;return{objectApiName:q.name,inSource:q.rows.length,kept:re,cutSpread:q.rows.length-re-ie.size,cutWithParent:[...U.values()].sort((le,ue)=>ue.count-le.count)}}),G=new Map,W=(q,ie,U)=>{let re=`${q}
9
9
  ${ie}
10
- ${H}`,de=(G.get(se)?.count??0)+1;G.set(se,{objectApiName:B,field:ie,count:de,why:H})};for(let B of s)for(let ie of k.kept.get(B.name)??[])for(let H of B.loose[ie])k.ids.get(H.link.parent)?.has(H.id)||K(B.name,H.link.field,H.link.kind==="owed"?"owed":"selfReference");for(let B of j?.namingSelected??[])B.required||k.ids.get(B.target)?.has(B.id)||K(B.objectApiName,B.field,"onParent");return{heldBy:$,...J?{cannotFit:J.words}:{},kept:F(k),...j?{walk:j}:{},report:{mode:n,heldBy:$,...J?{cannotFit:J.said}:{},budget:{...po(e,D.roomBytes,t),...$==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:N,emptied:[...G.values()],parents:j?j.added.map(B=>({objectApiName:B,records:j.parentIds.get(B)?.length??0})):[...o].map(([B,{ids:ie}])=>({objectApiName:B,records:ie.length})),records:D.records,estimateMB:D.bytes/1048576}}},ee={words:Rr,said:{why:"sourceChanged"}},T=b=>({words:`with these caps the plan takes ${S(b)}: lower them, or fit by share`,said:{why:"caps",over:R(b)}}),L=Object.keys(n.caps??{}).find(b=>!s.some(k=>k.name===b)),v=s.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),O=m(1),x=p(O,f(O));if(L!==void 0)return C(void 0,O,x,"caps",void 0,{words:`the plan selects no ${L}: a cap holds an object it selects`,said:{why:"capNotSelected",object:L}});if(s.some(b=>b.rows.length>(l.planned.get(b.name)??0)))return C(void 0,O,x,e.terms.limitedBy,void 0,ee);let _=n.all!==void 0||Object.keys(n.caps??{}).length>0,W=n.share===!0||!_,U=b=>{let k=m(b/v);return p(k,f(k))};if(s.every(b=>O.kept.get(b.name)?.size===b.rows.length)&&q(x))return C(W?1:void 0,O,x,"whole",void 0);if(v===0)return C(void 0,O,x,e.terms.limitedBy,void 0,ee);let z=v;if(!q(x)){if(!W)return C(void 0,O,x,Q(x),void 0,T(x));if(z=fo(v,b=>q(U(b))),z===0){let b=m(1/v),k=p(b,f(b));return C(1/v,b,k,Q(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${tr(k.records)} \u2014 takes ${S(k)}`,said:{why:"least",over:R(k)}})}}let V=z<v?Q(U(z+1)):_?"caps":e.terms.limitedBy,ne=b=>W?b/v:void 0;if(o.size===0){let b=m(z/v);return C(ne(z),b,p(b,new Map),V,void 0)}for(let b=1;b<=Jo;b++){let k=m(z/v),D=await l.walk(F(k));if(!Or(D,o)){let N=p(k,A(D));return C(ne(z),k,N,V,void 0,ee)}let $=D.namingSelected.filter(N=>N.required&&s.find(G=>G.name===N.target)?.at.has(N.id)===!0&&!k.ids.get(N.target)?.has(N.id));if($.length>0){for(let{target:N,id:G}of $){let K=c.get(N)??new Set;c.set(N,K),K.add(G)}d=er(s,c);continue}let j=p(k,A(D));if(q(j))return C(ne(z),k,j,V,D);if(V=Q(j),!W)return C(void 0,k,j,V,D,T(j));if(z===1)return C(ne(z),k,j,V,D,{words:"the least it can be cut to, with the parents its records name, takes "+S(j),said:{why:"least",over:R(j)}});let J=Math.max((j.bytes+j.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?j.requests/Math.max(1,e.runRequests):0,r!==void 0?j.records/Math.max(1,r):0);z=Math.max(1,Math.min(z-1,Math.floor(z/J)))}let Se=m(z/v),be=p(Se,f(Se));return C(ne(z),Se,be,V,void 0,{words:`could not fit in ${Jo} rounds: fit by caps`,said:{why:"rounds"}})}function ar(l,e,t){let{selected:n}=l.scope,o=e.walk?.added??[],r=new Set([...n,...o]),s=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of n){let A=e.kept.get(f)??[];s.set(f,A.map(w=>w.Id)),i.set(f,A.length),l.personAccounts.has(f)&&a.set(f,A.filter(w=>w[ye]===!0).length)}for(let f of o)i.set(f,e.walk?.parentIds.get(f)?.length??0),l.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...l.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>r.has(f.objectApiName)&&!r.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:u,currencies:p}=l.scope,g=u?.filter(f=>r.has(f.objectApiName)),y=p?.objects.filter(f=>r.has(f));return{...l,objectDescribes:new Map([...l.objectDescribes].filter(([f])=>r.has(f))),autoDiscoveredObjects:o,missingInTarget:l.missingInTarget.filter(f=>r.has(f)),recordCounts:i,totalObjectsScanned:r.size,parentIds:s,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:n,parents:o.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:l.scope.standardNeeded.filter(f=>r.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...p&&y!==void 0&&y.length>0?{currencies:{...p,objects:y}}:{},fitted:t}}}var et=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,n){return this.deps.schemaScanner.listObjects(e,t,n)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,n,o){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let r=await this.deps.schemaScanner.scan(e,t,n.selectedObjects,n.includeStandardObjects,{...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxObjects!==void 0?{maxObjects:n.maxObjects}:{},...o?{onProgress:o}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),r}buildGraph(e,t){let n=new Map;for(let[o,r]of e.objectDescribes){let s=r.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));n.set(o,{name:r.name,fields:s})}return this.deps.graphBuilder.build(n,e.recordCounts,t)}buildCompliance(e,t,n=[]){let o=this.deps.complianceEngine.buildProfile(e,wo(n,t)),r=this.deps.complianceEngine.generateRules(o);return{profile:o,rules:r}}generatePlan(e,t,n,o){let r=bo(t,e.nodes.map(c=>c.objectApiName),n),s={...this.deps.complianceEngine.buildSummary(n),...r.length>0?{notCovered:r}:{}},i=this.deps.planGenerator.generate(e,t,s),a=o?{...i,scope:o}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:n,graph:o,plan:r,rules:s,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,u=0,p={describe:v=>e.describe(v),describeGlobal:()=>e.describeGlobal(),query:v=>(u++,e.query(v)),...e.queryMore?{queryMore:v=>(u++,e.queryMore.call(e,v))}:{}},g=r.waves.map(v=>v.objects),y=new Map,f=g.flatMap(v=>Ge(v,o.edges).groups.filter(O=>O.length>1));for(let v of new Set(f.flat()))y.set(v,await t.describeLookups?.(v).catch(()=>null)??null);let A=an(g,o.edges,v=>y.get(v)),{selected:w}=n.scope,M=or(n.objectDescribes,w,A),I=rr(A,M),q=sr(t.automation,t.mutePlan,I),Q=await m.readFitRows(p,n,d),R=await ir({order:A.filter(v=>w.includes(v)),rows:Q,planned:n.recordCounts,lookups:M,parents:new Map(n.scope.parents.map(({objectApiName:v})=>{let O=n.personAccounts.get(v);return[v,{ids:n.parentIds.get(v)??[],...O!==void 0?{personAccounts:O}:{}}]})),budget:a,room:q,mode:i,...c!==void 0?{maxRecords:c}:{},walk:v=>m.walkFrom(p,n,v,d)}),S=q.unread!==void 0?{automationUnread:q.unread}:{},F={...R.report,requestsRead:u,...S,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},C=new Map([...R.kept].map(([v,O])=>[v,O.map(x=>x.Id)])),ee={heldBy:R.heldBy,report:F,keptIds:C,...S};if(R.cannotFit!==void 0)return{...ee,cannotFit:R.cannotFit};if(R.heldBy==="whole")return ee;let T=ar(n,R,F),L=this.buildGraph(T,t.batchSize);return{...ee,fitted:{scan:T,graph:L,plan:this.generatePlan(L,r.complianceFramework,s,T.scope),run:nr(M,T.parentIds)}}}async executePlan(e,t,n,o,r,s,i,a){let c=Array.from(o.values()).reduce((A,w)=>A+w,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let u=this.deps.createExecutor(),p=()=>{},g=r?u.on("node-completed",r):p,y=r?u.on("node-failed",r):p;for(let A of this.pendingSkips)u.skip(A);this.pendingSkips.clear(),this.runningExecutors.push(u);let f;try{f=await u.execute(e,t.edges,n,o,s,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(u),1),g(),y()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:f.totalSuccess+f.totalSkipped,totalFailed:f.totalFailure}}),f}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,n,o,r,s){return this.deps.complianceEngine.generateReport(e,t,n,o,r,s)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var tt=class{build(e,t,n=200){let o=this.extractEdges(e),r=Tr(o,new Set(e.keys())),s=this.tarjanSCC(Array.from(e.keys()),r),i=this.resolveCycles(s,r),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),r,s),d=this.buildNodes(e,t,a,c,n),m=this.computeStats(d,o,i);return{nodes:d,edges:o,cycles:i,stats:m}}extractEdges(e){let t=[],n=new Set(e.keys());for(let[o,r]of e)for(let s of r.fields){if(s.type!=="reference"||s.referenceTo.length===0)continue;let i=s.referenceTo.filter(d=>n.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:o,fieldApiName:s.name,relationshipType:"polymorphic",required:!s.nillable});continue}let a=i[0],c;a===o?c="hierarchical":s.nillable?c="lookup":c="master_detail",t.push({from:a,to:o,fieldApiName:s.name,relationshipType:c,required:!s.nillable})}return t}tarjanSCC(e,t){let n=new Map;for(let s of e)n.set(s,[]);for(let s of t){let i=n.get(s.to);i&&i.push(s.from)}let o={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},r=[...e].sort();for(let s of r)o.indices.has(s)||this.tarjanStrongConnect(s,n,o);return o.sccs}tarjanStrongConnect(e,t,n){n.indices.set(e,n.index),n.lowLinks.set(e,n.index),n.index++,n.stack.push(e),n.onStack.add(e);let o=t.get(e)??[];for(let r of o)if(n.indices.has(r)){if(n.onStack.has(r)){let s=n.lowLinks.get(e)??0,i=n.indices.get(r)??0;n.lowLinks.set(e,Math.min(s,i))}}else{this.tarjanStrongConnect(r,t,n);let s=n.lowLinks.get(e)??0,i=n.lowLinks.get(r)??0;n.lowLinks.set(e,Math.min(s,i))}if(n.lowLinks.get(e)===n.indices.get(e)){let r=[],s;do s=n.stack.pop(),n.onStack.delete(s),r.push(s);while(s!==e);n.sccs.push(r.sort())}}resolveCycles(e,t){let n=[],o=new Set;for(let r of t)r.from===r.to&&r.relationshipType==="hierarchical"&&o.add(r.from);for(let r of o)n.push({objects:[r],strategy:"two_pass",description:`Insert ${r} without self-lookup, update in 2nd pass`});for(let r of e){if(r.length<=1)continue;let s=new Set(r),i=t.filter(d=>s.has(d.from)&&s.has(d.to)&&d.from!==d.to),a,c;r.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${r[0]} without ${r[1]} lookup, insert ${r[1]} with ${r[0]} lookup, update ${r[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),n.push({objects:[...r],strategy:a,description:c})}return n}topologicalSort(e,t,n){let o=new Map;for(let p=0;p<n.length;p++)for(let g of n[p])o.set(g,p);let r=n.length,s=new Map;for(let p=0;p<r;p++)s.set(p,new Set);for(let p of t){let g=o.get(p.from),y=o.get(p.to);g!==void 0&&y!==void 0&&g!==y&&s.get(y).add(g)}let i=new Map;for(let[p,g]of s)i.set(p,new Set(g));let a=[],c=new Map;for(;i.size>0;){let p=[];for(let[g,y]of i)y.size===0&&p.push(g);if(p.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}p.sort((g,y)=>g-y);for(let g of p){a.push(g);let y=s.get(g)??new Set,f=-1;for(let A of y)f=Math.max(f,c.get(A)??0);c.set(g,y.size===0?0:f+1),i.delete(g);for(let A of i.values())A.delete(g)}}let d=new Map,m=new Map,u=0;for(let p of a){let g=n[p],y=c.get(p)??0,f=[...g].sort();for(let A of f)d.set(A,u),m.set(A,y),u++}for(let p of e)d.has(p)||(d.set(p,u),m.set(p,0),u++);return{order:d,levels:m}}buildNodes(e,t,n,o,r){let s=[];for(let i of e.keys()){let a=t.get(i)??0;s.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/r),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:n.get(i)??0,level:o.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return s.sort((i,a)=>i.insertOrder-a.insertOrder),s}computeStats(e,t,n){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:n.length,maxDepth:Math.max(0,...e.map(o=>o.level)),totalRecords:e.reduce((o,r)=>o+r.recordCount,0),totalEstimatedApiCalls:e.reduce((o,r)=>o+r.estimatedApiCalls,0)}}};function Tr(l,e){let t=pn(e);return t.length===0?[...l]:[...l.filter(n=>!(n.to===oe&&n.fieldApiName==="ActivityId")),...t.map(n=>({from:n.sourceObject,to:n.targetObject,fieldApiName:n.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as vr,randomUUID as Er}from"node:crypto";var Pr=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],nt=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,n=[]){let o=this.builtInRules.get(e)??[];return{framework:e,rules:o,autoDetectedPII:t,userOverrides:n,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let o of e.userOverrides){let r=`${o.objectApiName}.${o.fieldApiName}`;t.set(r,o)}let n=[];for(let o of e.autoDetectedPII){let r=`${o.objectApiName}.${o.fieldApiName}`,s=t.get(r);if(s){if(s.method==="skip")continue;n.push({objectApiName:o.objectApiName,fieldApiName:o.fieldApiName,method:s.method,piiCategory:o.piiCategory,aiConfidence:o.confidence,userOverridden:!0,fieldType:o.fieldType});continue}let i=this.findMatchingRule(e.rules,o.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:o.suggestedMethod;n.push({objectApiName:o.objectApiName,fieldApiName:o.fieldApiName,method:a,piiCategory:o.piiCategory,aiConfidence:o.confidence,userOverridden:!1,fieldType:o.fieldType})}return n}buildSummary(e){let t={};for(let o of Pr)t[o]=0;for(let o of e)t[o.method]++;let n=[...new Set(e.map(o=>o.objectApiName))];return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:n}}generateReport(e,t,n,o,r,s){let i=new Set(e.userOverrides.map(y=>`${y.objectApiName}.${y.fieldApiName}`)),a=t.map(y=>{let f=this.findMatchingRule(e.rules,y.piiCategory),A=f?f.id:"custom",w=n.get(y.objectApiName)??0,M=`${y.objectApiName}.${y.fieldApiName}`;return{objectApiName:y.objectApiName,fieldApiName:y.fieldApiName,piiCategory:y.piiCategory,anonymizationMethod:y.method,recordsAnonymized:w,ruleApplied:A,userOverridden:i.has(M)||y.userOverridden}}),c=this.buildObjectSummaries(t,n,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),u=Er(),p=JSON.stringify(a),g=vr("sha256").update(p).digest("hex");return{id:u,framework:e.framework,generatedAt:m,sourceOrgId:o,targetOrgId:r,totalFieldsScanned:s,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(n=>n.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,n){let o=new Set;for(let s of e)o.add(s.objectApiName);for(let s of n.autoDetectedPII)o.add(s.objectApiName);let r=[];for(let s of o){let i=e.filter(p=>p.objectApiName===s),a=n.autoDetectedPII.filter(p=>p.objectApiName===s),c=[...new Set(i.map(p=>p.method))],d=t.get(s)??0,m=a.length>0&&a.every(p=>i.some(g=>g.fieldApiName===p.fieldApiName)),u=a.length===0||m?"pass":i.length>0?"partial":"fail";r.push({objectApiName:s,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:u})}return r}computeOverallStatus(e){return e.length===0||e.every(o=>o.status==="pass")?"pass":e.every(o=>o.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var ot=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,n){let o=this.buildWaves(e),r=e.stats.totalRecords,s=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(o,e);return{waves:o,totalRecords:r,estimatedDurationSec:i,estimatedApiCalls:s,complianceFramework:t,anonymizationSummary:n,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),n=new Map;for(let i of t){let a=n.get(i.level);a?a.push(i.objectApiName):n.set(i.level,[i.objectApiName])}let o=[...n.keys()].sort((i,a)=>i-a),r=new Map;for(let i=0;i<o.length;i++){let a=o[i],c=n.get(a);if(c)for(let d of c)r.set(d,i)}let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=n.get(a)??[],d=new Set;for(let u of c)for(let p of e.edges)if(p.to===u){let g=r.get(p.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((u,p)=>u-p);s.push({order:i,objects:c,dependsOn:m})}return s}estimateDuration(e,t){let n=new Map;for(let s of t.nodes)n.set(s.objectApiName,s.estimatedApiCalls);let o=new Map;t.cycles.forEach((s,i)=>{for(let a of s.objects)o.set(a,i)});let r=0;for(let s of e){let i=new Map;for(let a of s.objects){let c=o.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(n.get(a)??0))}r+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return r}};var $e=class{idMaps=new Map;registerMappings(e,t){let n=this.idMaps.get(e);n||(n=new Map,this.idMaps.set(e,n));for(let[o,r]of t)n.set(o,r)}remapRecords(e,t,n){let o=t.filter(c=>c.to===n),r=0,s=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,u=new Map;for(let p of o){let g=d[p.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(p.from)?.get(g);if(f!==void 0)d[p.fieldApiName]=f,m.add(p.fieldApiName),r++;else{let A=u.get(p.fieldApiName);A?A.parents.push(p.from):u.set(p.fieldApiName,{sourceId:g,parents:[p.from]}),s++}}for(let[p,{sourceId:g,parents:y}]of u)m.has(p)||(d[p]=null,a.push({index:c,fieldApiName:p,sourceId:g,parents:y}))}return{remapped:r,missing:s,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Cr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function mr(l,e,t){let n=Yt(l);if(e!==void 0&&!Cr.test(e))throw new Error(`Not a record id to read after: "${e}".`);let o=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${n}${o} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Mr={statusCode:Ke,message:"No result returned for the record",fields:[]},Ir={statusCode:Ke,message:"Refused without a reason",fields:[]},cr="PARENT_REFUSED",dr="PARENT_NOT_WRITTEN",zt="CUT_WITH_PARENT",lr={skipped:l=>`${l} was skipped in this run`,failed:l=>`the run's write of ${l} failed`},xr="PERSON_ACCOUNT_NOT_WRITTEN",Nr="PERSON_CONTACT_NOT_LOOKED_UP",Fr=`SELECT Id FROM RecordType WHERE SobjectType = '${ae}' AND IsPersonType = true`;function ce(l){return l.slice(0,15)}var Re=class{byReason=new Map;add(e){let t=new Set;for(let n of e){let o=`${n.statusCode}\0${n.fields.join(",")}`;if(t.has(o))continue;t.add(o);let r=this.byReason.get(o);this.byReason.set(o,r?{...r,count:r.count+1}:{statusCode:n.statusCode,fields:[...n.fields],count:1,message:n.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,n=this.byReason.get(t);this.byReason.set(t,n?{...n,count:n.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function ur(){return{written:0,linked:0,failed:0,errors:[],refusals:new Re,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map}}function jr(l){return{statusCode:jn,fields:["RecordTypeId"],count:l.recordCount,message:Ln(l)}}function Dr(l,e){return{objectApiName:l,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function pr(l){let e=0;for(let[t,n]of l)Pt(t)&&(e+=n);return e}function $r(l){let e=new Map;for(let t of l.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...l.kept].map(([t,n])=>[t,new Set(n.map(ce))])),stayedOut:new Map}}var Le=class extends Ao{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Nn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new ln;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let n=await this.deps.describeCreateableFields(e),o=n.size>0?n:null;return this.creatableByObject.set(e,o),o}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let n=this.lookupsByObject.get(e);return n||(n=t(e).catch(()=>null),this.lookupsByObject.set(e,n)),n}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let n=this.keyPrefixByObject.get(e);return n||(n=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,n)),n}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:n}=this.deps;if(!t||!n)return[];let o=await this.creatableFieldsOf(e);if(o&&!o.has("RecordTypeId"))return[];try{let r=await t(e);if(!r.some(i=>!i.available&&!i.master))return[];let s=this.inTargetRecordTypes(await n(e));return Dn(e,s,yt(r,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[n,o]of e){if(n===null)continue;let r=this.targetRecordTypeOf(n);t.set(r,(t.get(r)??0)+o)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,n=new Map,o=[]){await this.mapRecordTypes(e);let r=new Map;for(let s of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(s)??0;if(i===0)continue;let a=await this.givenRuleOf(s);if(!a)continue;let c=await this.creatableFieldsOf(s),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let u=await this.onMasterInSource(s,n.get(s));if(u===void 0)continue;d=o.find(g=>g.objectApiName===s)?Math.min(u,i):u}d!==0&&r.set(s,{objectApiName:s,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return r}async onMasterInSource(e,t){try{if(t===void 0){let r=this.deps.countRecordTypes;return r?pr(await r(e)):void 0}let n=this.deps.querySource;if(!n)return;let o=0;for(let r=0;r<t.length;r+=ke){let s=await n(Mt(e,t.slice(r,r+ke)));o+=pr(He(s))}return o}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let n=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!n?.some(s=>!s.master))return;let o=yt(n,this.targetRecordTypes),r=Co(Po(o));return{types:o,...r?{predicted:r}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let n=this.deps.describeRecordTypesAgain;if(!n||!this.lease||this.lease.assigned===0)return;let o=[...new Set(e.waves.flatMap(r=>r.objects))].filter(r=>(t.get(r)??0)>0);await Promise.all(o.map(async r=>{if((await this.deps.describeRecordTypes?.(r).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(r,await n(r))}catch{}}))}countCreatedWithoutRecordType(e,t,n,o){let r=this.recordTypesGiven.get(e);r||(r={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,r)),r.rows++,r.why[n]=(r.why[n]??0)+1,o&&r.ids.length<Mo&&r.ids.push(o)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,n]of this.recordTypesGiven){let o=e[t];o&&(e[t]={...o,recordTypeGiven:Dr(t,n)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){le.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${te(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await e(Mt(t,n.ids));n.readBack=Io(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:te(o)}}}))}holdOnClosedRecordTypes(e,t,n){let o=n.closedRecordTypes;if(!o)return t;let r=[];for(let s of t){let i=s.RecordTypeId,a=e===fe&&Ce(s),c=typeof i=="string"&&i.length>=15&&!a?o.get(ce(this.targetRecordTypeOf(i))):void 0;if(!c){r.push(s);continue}n.failed++;let d=n.heldForRecordType.get(c.recordTypeId);n.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=s.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(ce(m),e)}return r}async mapRecordTypes(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let o=[...new Set(e.waves.flatMap(s=>s.objects))];if(o.length===0)return;let r=`${So} AND SobjectType IN (${o.map(s=>`'${he(s)}'`).join(", ")})`;try{let[s,i]=await Promise.all([t(r),n(r)]),a=Et(s);this.targetRecordTypes=Et(i),this.recordTypeMappings=new Ct().buildMapping(a,this.targetRecordTypes);for(let c of vo(a,this.targetRecordTypes))le.warn(`[autopilot] ${Eo(c)}`)}catch(s){le.warn("Autopilot could not match the record types of the two orgs",{error:te(s)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let o=new Set(e.waves.flatMap(r=>r.objects));if(!(!o.has(Ae)&&!o.has(Te)))try{let[r,s]=await Promise.all([t(Ee),n(Ee)]),i=r[0]?.Id,a=s[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(Ae,[[i,a]])}catch(r){le.warn("Autopilot could not match the standard price books",{error:te(r)})}}async execute(e,t,n,o,r,s=new Map,i={}){if(!this.deps.queryByIds&&[...s.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=s,this.contactPoints=i.keepContactPoints===!0?void 0:new ko,this.lease=i.lease,this.fit=i.fit?$r(i.fit):void 0;let a=Date.now();this.signal=r;let c=()=>this.pauseResolve?.();r?.addEventListener("abort",c,{once:!0});let d={},m={},u={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},p=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await y(f),f===Ue&&await this.writeEmailsAfterTheirTask(t,u)},y=async f=>{if(this.skippedObjects.has(f)){let w=o.get(f)??0;u.skippedObjects.push(f),u.totalSkipped+=w,this.notWritten.set(f,"skipped");return}this.reached.add(f);let A=o.get(f)??0;if(await this.checkPause()){p.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...A>0?{notSent:A}:{}};return}try{let w=await this.executeObject(f,t,n,A);u.totalSuccess+=w.success,u.totalFailure+=w.failure,u.totalLinked=(u.totalLinked??0)+w.linked,w.cutSinceFit>0&&(u.cutSinceFit=(u.cutSinceFit??0)+w.cutSinceFit);let M=this.leftToThePlatform.counts(f);if(m[f]={written:w.success,linked:w.linked,failed:w.failure,refusals:w.refusals,...w.leftToDefault.length>0?{leftToDefault:w.leftToDefault}:{},...M.length>0?{leftToThePlatform:M}:{},...w.notSent!==void 0&&w.notSent>0?{notSent:w.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===fe&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...w.cutSinceFit>0?{cutSinceFit:w.cutSinceFit}:{},...w.threw!==void 0?{threw:w.threw}:{}},w.notSent!==void 0){p.push(f);return}let{threw:I}=w;if(I!==void 0||w.errors.length>0&&w.success+w.linked===0){u.failedObjects.push(f),I!==void 0&&this.notWritten.set(f,"failed");let q=I!==void 0?[I,...w.errors]:w.errors;d[f]=q[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:q,partialSuccessCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals}))}else u.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals,elapsedMs:w.elapsedMs,apiCallsUsed:w.apiCallsUsed}))}catch(w){u.failedObjects.push(f),this.notWritten.set(f,"failed");let M=te(w);d[f]=M,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[M],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,o),this.planned=new Set(e.waves.flatMap(w=>w.objects));let f={};for(let w of e.waves){if(await this.writeWave(w.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let w=new Set([...u.completedObjects,...u.failedObjects,...u.skippedObjects,...p]);for(let M of e.waves.flatMap(I=>I.objects)){if(w.has(M))continue;let I=o.get(M)??0;p.push(M),m[M]={written:0,linked:0,failed:0,refusals:[],...I>0?{notSent:I}:{}}}return u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,u}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,u),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let A=await this.applyDeferredStatuses();return Object.keys(A).length>0&&(u.statuses=A),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.stopped()&&(u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m)),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),u}catch(f){throw u.elapsedMs=Date.now()-a,u.fatalError=te(f),le.error("Autopilot execution crashed",{error:u.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:u.fatalError})),f}finally{r?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,n){let{within:o,deps:r,groups:s}=Ge(e,t),i=new Map;s.forEach((m,u)=>m.forEach(p=>i.set(p,u)));let a=[];for(let[m,u]of s.entries()){let p=new Set;for(let g of u)for(let y of r.get(g)??[]){let f=i.get(y);f!==void 0&&f!==m&&p.add(a[f])}a.push((async()=>{await Promise.all(p);let g=u.length>1?rn(u,await this.setAtInsert(u,o)):u;for(let y of g)await n(y)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let n=new Set(e),o=new Map;for(let r of t)!n.has(r.to)||!n.has(r.from)||o.has(r.to)||o.set(r.to,await this.lookupsOf(r.to));return sn(e,t,r=>o.get(r))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:n}=this.deps;if(!n||t.length===0)return;let o=new Ro;for(let r of t){let s=r.parents.map(i=>this.deps.remapper.getTargetId(i,r.sourceId)).find(i=>i!==void 0);if(!s){this.owedLookups.push(r);continue}o.add({objectApiName:r.objectApiName,recordId:r.recordId,fieldName:r.fieldApiName,value:s})}for(let[r,s]of o.updates()){let i=e[r],a=i?.filled??0,c=new Re;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<s.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(r,"lookups",s.slice(d).map(p=>String(p.Id)));break}let m=s.slice(d,d+this.batchSize),u=await fr(n,r,m);m.forEach((p,g)=>{let y=u[g];if(y?.success){a++;return}let f=Object.keys(p).filter(A=>A!=="Id");c.add(qt(y).map(A=>({...A,fields:f}))),this.noteLookupLeftEmpty(r,String(p.Id))})}e[r]=this.lookupOutcome(r,a,c)}}noteLookupLeftEmpty(e,t){let n=this.lookupsLeftEmpty.get(e);n||(n=new Set,this.lookupsLeftEmpty.set(e,n)),n.add(t)}lookupOutcome(e,t,n){let o=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:n.list(),...o>0?{leftEmpty:o}:{}}}async sayLookupsLeftOwed(e,t){let n=new Map;for(let o of this.owedLookups.splice(0,this.owedLookups.length)){let r=await this.whyLeftOwed(o,e);if(!r)continue;let s=n.get(o.objectApiName);if(!s){s=new Re;for(let i of t[o.objectApiName]?.refusals??[])s.addCounted(i);n.set(o.objectApiName,s)}s.add([{...r,fields:[o.fieldApiName]}]),this.noteLookupLeftEmpty(o.objectApiName,o.recordId)}for(let[o,r]of n){let s=t[o]?.filled??0;t[o]=this.lookupOutcome(o,s,r)}}async whyLeftOwed(e,t){let{fieldApiName:n,sourceId:o}=e,r=this.refusedRecords.get(ce(o)),s=e.parents.find(c=>c===r);if(s)return{statusCode:cr,message:`the ${s} record its ${n} names was refused in this run, and this record, written before it, keeps its ${n} empty.`};let i=this.fit?.stayedOut.get(ce(o)),a=e.parents.find(c=>c===i);if(a)return{statusCode:zt,message:`the ${a} record its ${n} names stayed out with a record the fit cut, and this record, written before it, keeps its ${n} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(u=>u.from===c&&u.to===e.objectApiName&&u.fieldApiName===n);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,o,e.parents.length)))return{statusCode:dr,message:`the ${c} record its ${n} names was not written: ${lr[d](c)}, and this record, written before it, keeps its ${n} empty.`}}}async executeObject(e,t,n,o){let r=Date.now(),s=ur(),i=()=>{let a=[...s.heldForRecordType.values()];return{success:s.written,linked:s.linked,failure:s.failed,errors:[...a.map(Bn),...s.errors],refusals:[...s.refusals.list(),...a.map(jr)].sort((c,d)=>d.count-c.count),apiCallsUsed:s.apiCallsUsed,elapsedMs:Date.now()-r,leftToDefault:[...s.defaulted].map(([c,d])=>({field:c,count:d})),...s.notSent!==void 0?{notSent:s.notSent}:{},cutSinceFit:s.cutSinceFit}};try{return await this.writeEveryPage(e,t,n,o,s,i)}catch(a){return{...i(),threw:te(a)}}}async writeEveryPage(e,t,n,o,r,s){let i=o>0?await this.recordTypesHeldBack(e):[];i.length>0&&(r.closedRecordTypes=new Map(i.map(u=>[ce(u.recordTypeId),u])));let a=u=>{let p=Math.min(u,o);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:o>0?Math.round(p/o*100):100,recordsProcessed:p,recordsTotal:o,apiCallsUsed:r.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(Ht(e)&&m){let u=[];for(;c<o;){if(await this.checkPause())return r.notSent=o,s();let{rows:I,advance:q,next:Q,last:R}=await this.readPage(e,c,d);if(r.apiCallsUsed++,q===0)break;c+=q,d=Q;let S=this.leaveToThePlatform(e,I,t);if(this.deps.anonymizer.anonymize(S,n,e),await this.neutralizeContactPoints(e,S),u.push(...S),R)break}let p=await this.pricesInOneCurrencyEach(u,m.source),{standard:g,custom:y}=at(p.rows,m.source),f=at(u.filter(I=>p.standsFor.has(String(I.Id))),m.source);p.said.length>0&&this.pricesSettled.set(e,Fo(p.said));let A=0,w=0,M=async I=>{for(let q=0;q<I.length;q+=this.batchSize){if(await this.checkPause())return r.notSent=u.length-A-w,!1;let Q=I.slice(q,q+this.batchSize);await this.writeBatch(e,Q,t,r),A+=Q.length,a(A+w)}return!0};for(let[I,q]of[[g,f.standard],[y,f.custom]]){if(!await M(I))return s();let Q=this.linkWhatStoodIn(q,p.standsFor,r);if(w+=q.length-Q.length,!await M(Q))return s()}return s()}for(;c<o;){if(await this.checkPause()){r.notSent=o-c;break}let{rows:u,advance:p,next:g,last:y}=await this.readPage(e,c,d);if(r.apiCallsUsed++,p===0)break;d=g;let f=this.leaveToThePlatform(e,u,t);if(this.deps.anonymizer.anonymize(f,n,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,r),c+=p,a(c),y)break}return s()}async neutralizeContactPoints(e,t){let{contactPoints:n}=this,o=this.deps.describeFields;if(!n||!o||t.length===0)return;let r=await o(e).catch(()=>{});if(!r)return;let s=n.forObject(e,r);if(s)for(let i of t)s(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,n){let o=this.parentIds.get(e);if(o&&this.deps.queryByIds){let i=o.slice(t,t+Math.min(this.batchSize,ke));return i.length===0?{rows:[],advance:0,next:n,last:!0}:{rows:await this.deps.queryByIds(e,i),advance:i.length,next:n,last:!1}}let r=await this.deps.query(e,n,this.batchSize),s=r.at(-1)?.Id;return{rows:r,advance:r.length,next:typeof s=="string"?s:n,last:r.length>0&&typeof s!="string"}}leaveToThePlatform(e,t,n){let o=new Set(n.filter(r=>r.to===e&&(r.required||Gt(r.to,r.fieldApiName))).map(r=>r.fieldApiName));return this.leftToThePlatform.keep(e,t,[...o])}async writeBatch(e,t,n,o){let r=[],s=t,i=this.standardPricebook;if(e===Ae&&i&&(s=t.filter(R=>R.Id!==i.source),o.linked+=t.length-s.length),s=this.holdOnClosedRecordTypes(e,s,o),s=await this.holdBehindRefusedParents(e,s,n,o),s=this.holdBehindCutParents(e,s,o),e===oe&&(s=this.holdEmailsForTheirTask(s)),e===fe&&(s=await this.linkPersonContacts(s,o,r)),s.length===0){this.register(e,r);return}let a=this.deps.remapper.remapRecords(s,n,e);await this.leaveToDefault(e,s,o);let c=await this.creatableFieldsOf(e),d=c?s.map(R=>{let S={};for(let F of Object.keys(R))(F==="Id"||F==="attributes"||c.has(F))&&(S[F]=R[F]);return S}):s;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((R,S)=>{if(R.RecordTypeId!==void 0)return;let F=s[S]?.RecordTypeId,C=!c||c.has("RecordTypeId");m.set(R,C&&Pt(F)?"masterInSource":"notRead")});for(let R of d)for(let S of Kt(e,R))delete R[S];let u=await this.replaceCurrencies(e,s,d,c);e===ae&&await this.leaveOutForAccountKind(s,d);let p=new Map;d.forEach((R,S)=>{let F=pt(e,R);for(let C of F)delete R[C];F.length>0&&p.set(S,F)});let g=await this.lookupsOwed(e,s,a.unresolved.filter(R=>!p.get(R.index)?.includes(R.fieldApiName)),c),y=this.deps.queryTarget,f=y?R=>(o.apiCallsUsed++,y(R)):void 0;if(e===cn&&f){let R=await kn(f,d);for(let[S,F]of R){let C=d[S].Id;typeof C=="string"&&r.push([C,F])}o.linked+=R.size,d=d.filter((S,F)=>!R.has(F))}if(yn[e]!==void 0&&f){let R=await wn(f,e,d);for(let[S,F]of R){let C=d[S].Id;typeof C=="string"&&r.push([C,F])}o.linked+=R.size,await this.giveFlagsBack(e,[...R].map(([S,F])=>[d[S],F]),o),d=d.filter((S,F)=>!R.has(F))}if(e===Ue&&f){let R=await this.tasksWrittenWithTheirEmail(d,f);for(let[S,F]of R)r.push([S,F]);o.linked+=R.size,d=d.filter(S=>!R.has(String(S.Id)))}if(d.length===0){this.register(e,r);return}let A=await this.startAsDrafts(e,d),w=m.size>0?await this.givenRuleOf(e):void 0,M=await this.deps.insert(e,d);o.apiCallsUsed++;let I=await this.keyPrefixOf(e),q=dn[e],Q=[];if(d.forEach((R,S)=>{let F=typeof R.Id=="string"?R.Id:void 0,C=M[S];if(!C){this.refuse(e,F,o,void 0);return}if(C.success){o.written++;let T=w?m.get(R):void 0;w&&T&&this.countCreatedWithoutRecordType(e,w,T,C.id);let L=u.get(R);this.currencyChanges.add(e,L),L&&C.id&&this.currencyChangesByWrittenId.set(C.id,L),F&&C.id&&r.push([F,C.id]);let v=A.get(S);v&&C.id&&this.deferredStatuses.push({objectApiName:e,id:C.id,status:v});let O=F?g.get(F):void 0;for(let x of C.id?O??[]:[])this.owedLookups.push({objectApiName:e,recordId:C.id,fieldApiName:x.fieldApiName,sourceId:x.sourceId,parents:x.parents});return}let ee=_n(C,I);if(ee.kind==="linked"){o.linked++,F&&r.push([F,ee.id]);return}if(ee.kind==="unidentified"&&q&&f){Q.push({payload:R,sourceId:F,outcome:C});return}this.refuse(e,F,o,C)}),q&&f&&Q.length>0){let R=await Rn(f,e,q,Q.map(S=>S.payload));Q.forEach((S,F)=>{let C=R[F];if(C&&S.sourceId){o.linked++,r.push([S.sourceId,C]);return}this.refuse(e,S.sourceId,o,S.outcome)})}this.register(e,r)}async giveFlagsBack(e,t,n){let o=this.deps.update;if(!o||t.length===0||!bn[e])return;let r=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),s=await An(e,t,i=>!r?.has(i),async i=>(n.apiCallsUsed++,o(e,i)),()=>this.stopped());s&&le.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:s})}holdEmailsForTheirTask(e){for(let n of e){let o=n.ActivityId;typeof n.Id=="string"&&typeof o=="string"&&o!==""&&this.taskOfEmail.set(n.Id,o)}if(this.taskTurnOver||!this.planned.has(Ue))return e;let t=[];for(let n of e)fn(n)?this.emailsAfterTheirTask.push(n):t.push(n);return t}async tasksWrittenWithTheirEmail(e,t){let n=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(oe,i);c&&n.set(a,c)}let o=e.map(i=>String(i.Id)).filter(i=>n.has(i));if(o.length===0)return new Map;let r;try{r=await mn(t,[...new Set(o.map(i=>n.get(i)??""))])}catch(i){return le.warn("Autopilot could not look up the tasks written with its emails",{error:te(i)}),new Map}let s=new Map;for(let i of o){let a=r.get(n.get(i)??"");a&&s.set(i,a)}return s}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(n.length===0)return;let o=ur();for(let d=0;d<n.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=n.length-d;break}await this.writeBatch(oe,n.slice(d,d+this.batchSize),e,o)}t.totalSuccess+=o.written,t.totalFailure+=o.failed,t.totalLinked=(t.totalLinked??0)+o.linked;let r=t.objectOutcomes??{};t.objectOutcomes=r;let s=r[oe],i=new Re;for(let d of[...s?.refusals??[],...o.refusals.list()])i.addCounted(d);let a=new Map((s?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of o.defaulted)a.set(d,(a.get(d)??0)+m);let c={...s,written:(s?.written??0)+o.written,linked:(s?.linked??0)+o.linked,failed:(s?.failed??0)+o.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};r[oe]=c,c.written+c.linked>0&&t.failedObjects.includes(oe)&&(t.failedObjects.splice(t.failedObjects.indexOf(oe),1),delete t.nodeErrors?.[oe],t.completedObjects.push(oe)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:oe,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:o.apiCallsUsed}))}async leaveToDefault(e,t,n){let o=await this.lookupsOf(e);if(!o)return;let r=Tn(o.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(r.size===0)return;let s=await this.creatableFieldsOf(e);for(let i of t)for(let a of r){let c=i[a];c!=null&&c!==""&&(!s||s.has(a))&&n.defaulted.set(a,(n.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,n,o){let r=new Map,{querySource:s,queryTarget:i}=this.deps;if(!s||!i)return r;let a=!o||o.has(me);if(!a&&this.currencyChangesByWrittenId.size===0)return r;let c=p=>typeof p?.[me]=="string"&&p[me]!=="";if(!(a?n.some(c):t.some(c)))return r;this.currencies??=Ie(s,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return r;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,u=a?[]:(await this.lookupsOf(e)??[]).map(p=>p.name);return n.forEach((p,g)=>{let y=t[g],f=y?.[me],A=a?Mn(p,{read:f,currencyFields:m,ratesOn:En(e,y)},d):xn(p,{read:f,parent:y?In(e,y,u,w=>this.currencyChangesByWrittenId.get(w)):void 0,currencyFields:m},d);A&&r.set(p,A)}),r}async pricesInOneCurrencyEach(e,t){let n={rows:e,standsFor:new Map,said:[]},{querySource:o,queryTarget:r}=this.deps;if(!o||!r)return n;let s=d=>typeof d[me]=="string"&&d[me]!=="";if(!e.some(s))return n;this.currencies??=Ie(o,r,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return n;let{target:a}=i,c=No({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[Pe]=="string"),writtenIn:d=>a.active.has(d)?d:Cn(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,n){let o=Te,r=[],s=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(o,c);if(d===void 0){s.push(i);continue}r.push([a,d]),n.linked++}return this.register(o,r),s}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(n=>n.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let n=this.recordTypeMappings;return!n||!t.some(o=>typeof o.RecordTypeId=="string")?t.map(Oo):new Ct().apply(t,n,o=>{this.unmappedRecordTypes.has(o)||(this.unmappedRecordTypes.add(o),To(e,o,"autopilot"))})}async lookupsOwed(e,t,n,o){let r=new Map;if(!this.deps.update||n.length===0)return r;let s=await this.lookupsOf(e);for(let i of n){if(o&&!o.has(i.fieldApiName))continue;let a=s?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&r.set(c,[...r.get(c)??[],i])}return r}refuse(e,t,n,o){n.failed++;let r=qt(o);n.errors.push(o?.errors[0]??Lr(r[0])),n.refusals.add(r),t&&this.refusedRecords.set(ce(t),e)}async holdBehindRefusedParents(e,t,n,o){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let r=n.filter(a=>a.to===e);if(r.length===0)return t;let s=new Map;for(let a of r)s.set(a.fieldApiName,(s.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=pt(e,a),d;for(let y of r){let f=a[y.fieldApiName];if(typeof f!="string"||f===""||c.includes(y.fieldApiName)||this.deps.remapper.getTargetId(y.from,f)!==void 0)continue;let A=this.refusedRecords.get(ce(f))===y.from,w=this.notWrittenOf(y.from);if(!A&&w===void 0)continue;let M=s.get(y.fieldApiName)??0;if(!A&&!await this.namesARecordOf(e,y,f,M))continue;let{from:I,fieldApiName:q}=y;d=A||w===void 0?{edge:y,statusCode:cr,message:`the ${I} record its ${q} names was refused in this run, and written without it this record would stand without its ${I}.`}:{edge:y,statusCode:dr,message:`the ${I} record its ${q} names was not written: ${lr[w](I)}, and written without it this record would stand without its ${I}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:u,edge:p}=d;o.failed++,o.errors.push(`${m}: ${u}`),o.refusals.add([{statusCode:m,message:u,fields:[p.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(ce(g),e)}return i}holdBehindCutParents(e,t,n){let o=this.fit,r=o?.holds.get(e);return!o||!r?t:t.filter(s=>{if(!r.some(c=>{let d=s[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let u=ce(d);return o.stayedOut.has(u)||o.kept.get(c.parent)?.has(u)!==!0}))return!0;n.cutSinceFit++;let a=s.Id;return typeof a=="string"&&a!==""&&o.stayedOut.set(ce(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,n,o){let r=(await this.lookupsOf(e))?.find(s=>s.name===t.fieldApiName);if(r?.referenceTo.length===1)return r.referenceTo[0]===t.from;if(r&&r.referenceTo.length>1){let s=await this.keyPrefixOf(t.from);return typeof s=="string"&&s!==""&&n.startsWith(s)}return o===1}async linkPersonContacts(e,t,n){let o=e.filter(Ce),r=this.deps.queryTarget;if(o.length===0||!r)return e;let s=await this.lookupsOf(ae);if(s&&!s.some(u=>u.name===ft))return e;let i=new Map;for(let u of o){let p=u.AccountId,g=typeof p=="string"&&p!==""?this.deps.remapper.getTargetId(ae,p):void 0;g&&i.set(u,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await gn(r,[...new Set(i.values())])}catch(u){c=te(u)}let d=(u,p,g)=>{t.failed++,t.errors.push(`${p}: ${g}`),t.refusals.add([{statusCode:p,message:g,fields:["AccountId"]}]);let y=u.Id;typeof y=="string"&&y!==""&&this.refusedRecords.set(ce(y),fe)},m=[];for(let u of e){if(!Ce(u)){m.push(u);continue}let p=i.get(u);if(p===void 0){d(u,xr,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(u,Nr,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(p),y=u.Id;if(g===void 0||typeof y!="string"){m.push(u);continue}n.push([y,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let o=e.some(Ce)?await this.takenAsBusiness(t):()=>!1,r=e.map((s,i)=>hn(s,o(t[i])));t.forEach((s,i)=>{for(let a of Object.keys(s))Qt(ae,a,r[i])&&delete s[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(ae);if(t&&!t.some(a=>a.name===ft))return()=>!0;let n=this.deps.queryTarget;if(!n)return()=>!1;this.personTypes??=n(Fr).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[ce(c.Id)]:[])),()=>{});let o=await this.personTypes;if(!o)return()=>!1;let r=await this.deps.describeRecordTypes?.(ae).catch(()=>{}),s=new Set((r??[]).map(a=>ce(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?xo(r):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=ce(d);return!o.has(m)&&s.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let n=new Map,o=Me[e],{queryTarget:r,update:s}=this.deps;if(!o||!r||!s)return n;let i=this.lifecycleByObject.get(e);i||(i=Sn(r,o),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=On(c.Status,a);m&&(n.set(d,String(c.Status)),c.Status=m)}),n}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let n=new Map;for(let o of this.deferredStatuses)n.set(o.objectApiName,[...n.get(o.objectApiName)??[],o]);for(let[o,r]of n){let s=0,i=0,a=new Re;for(let c=0;c<r.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(o,"statuses",r.slice(c).map(u=>u.id));break}let d=r.slice(c,c+this.batchSize),m=await fr(t,o,d.map(u=>({Id:u.id,Status:u.status})));d.forEach((u,p)=>{let g=m[p];if(g?.success){s++;return}i++,a.add(qt(g))})}e[o]={applied:s,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,n){if(n.length===0)return;let o=this.leftByStop.get(e);o||(o={lookups:new Set,statuses:new Set},this.leftByStop.set(e,o));for(let r of n)o[t].add(r)}countEmailsTheStopHeld(e,t,n){let o=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),r=this.emailsHeldAndNotSent+o.length;if(this.emailsHeldAndNotSent=0,r===0)return;let s=n[oe]??{written:0,linked:0,failed:0,refusals:[]};n[oe]={...s,notSent:(s.notSent??0)+r,heldForTheirTask:r};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(oe);m>=0&&d.splice(m,1)}if(t.includes(oe))return;let i=[...this.planned],a=i.indexOf(oe),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,oe)}countWhatTheStopLeft(e,t){let n=new Set(e);for(let r of this.owedLookups.splice(0,this.owedLookups.length))r.parents.some(i=>n.has(i)||this.deps.remapper.getTargetId(i,r.sourceId)!==void 0)?this.noteLeftByStop(r.objectApiName,"lookups",[r.recordId]):this.owedLookups.push(r);let o=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let r of o)this.noteLeftByStop(r.objectApiName,"statuses",[r.id]);for(let[r,s]of this.leftByStop){let i=t[r]??{written:0,linked:0,failed:0,refusals:[]};t[r]={...i,...s.lookups.size>0?{lookupsLeftEmpty:s.lookups.size}:{},...s.statuses.size>0?{statusesNotGivenBack:s.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function fr(l,e,t){try{return await l(e,t)}catch(n){let o=te(n);return t.map(()=>({id:"",success:!1,errors:[o],errorDetails:[wt(o)]}))}}function qt(l){return l?l.errorDetails&&l.errorDetails.length>0?l.errorDetails:l.errors.length>0?l.errors.map(e=>wt(e)):[Ir]:[Mr]}function Lr(l){return l.statusCode===Ke?l.message:`${l.statusCode}: ${l.message}`}var rt=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let n=[],o=0,r=0;for(;o<t;){let s=Math.min(this.partitionSize,t-o);n.push({id:`${e}-${r}`,objectApiName:e,offset:o,limit:s,recordCount:s}),o+=s,r++}return n}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var Br=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
10
+ ${U}`,le=(G.get(re)?.count??0)+1;G.set(re,{objectApiName:q,field:ie,count:le,why:U})};for(let q of s)for(let ie of k.kept.get(q.name)??[])for(let U of q.loose[ie])k.ids.get(U.link.parent)?.has(U.id)||W(q.name,U.link.field,U.link.kind==="owed"?"owed":"selfReference");for(let q of L?.namingSelected??[])q.required||k.ids.get(q.target)?.has(q.id)||W(q.objectApiName,q.field,"onParent");return{heldBy:$,...X?{cannotFit:X.words}:{},kept:j(k),...L?{walk:L}:{},report:{mode:o,heldBy:$,...X?{cannotFit:X.said}:{},budget:{...ko(e,x.roomBytes,t),...$==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:F,emptied:[...G.values()],parents:L?L.added.map(q=>({objectApiName:q,records:L.parentIds.get(q)?.length??0})):[...n].map(([q,{ids:ie}])=>({objectApiName:q,records:ie.length})),records:x.records,estimateMB:x.bytes/1048576}}},te={words:Pr,said:{why:"sourceChanged"}},se=b=>({words:`with these caps the plan takes ${A(b)}: lower them, or fit by share`,said:{why:"caps",over:E(b)}}),T=Object.keys(o.caps??{}).find(b=>!s.some(k=>k.name===b)),O=s.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),D=m(1),S=p(D,f(D));if(T!==void 0)return M(void 0,D,S,"caps",void 0,{words:`the plan selects no ${T}: a cap holds an object it selects`,said:{why:"capNotSelected",object:T}});if(s.some(b=>b.rows.length>(l.planned.get(b.name)??0)))return M(void 0,D,S,e.terms.limitedBy,void 0,te);let ne=o.all!==void 0||Object.keys(o.caps??{}).length>0,N=o.share===!0||!ne,_=b=>{let k=m(b/O);return p(k,f(k))};if(s.every(b=>D.kept.get(b.name)?.size===b.rows.length)&&z(S))return M(N?1:void 0,D,S,"whole",void 0);if(O===0)return M(void 0,D,S,e.terms.limitedBy,void 0,te);let B=O;if(!z(S)){if(!N)return M(void 0,D,S,K(S),void 0,se(S));if(B=Ro(O,b=>z(_(b))),B===0){let b=m(1/O),k=p(b,f(b));return M(1/O,b,k,K(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${cr(k.records)} \u2014 takes ${A(k)}`,said:{why:"least",over:E(k)}})}}let Z=B<O?K(_(B+1)):ne?"caps":e.terms.limitedBy,Y=b=>N?b/O:void 0;if(n.size===0){let b=m(B/O);return M(Y(B),b,p(b,new Map),Z,void 0)}for(let b=1;b<=sr;b++){let k=m(B/O),x=await l.walk(j(k));if(!Mr(x,n)){let F=p(k,R(x));return M(Y(B),k,F,Z,void 0,te)}let $=x.namingSelected.filter(F=>F.required&&s.find(G=>G.name===F.target)?.at.has(F.id)===!0&&!k.ids.get(F.target)?.has(F.id));if($.length>0){for(let{target:F,id:G}of $){let W=c.get(F)??new Set;c.set(F,W),W.add(G)}d=ar(s,c);continue}let L=p(k,R(x));if(z(L))return M(Y(B),k,L,Z,x);if(Z=K(L),!N)return M(void 0,k,L,Z,x,se(L));if(B===1)return M(Y(B),k,L,Z,x,{words:"the least it can be cut to, with the parents its records name, takes "+A(L),said:{why:"least",over:E(L)}});let X=Math.max((L.bytes+L.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?L.requests/Math.max(1,e.runRequests):0,r!==void 0?L.records/Math.max(1,r):0);B=Math.max(1,Math.min(B-1,Math.floor(B/X)))}let me=m(B/O),Be=p(me,f(me));return M(Y(B),me,Be,Z,void 0,{words:`could not fit in ${sr} rounds: fit by caps`,said:{why:"rounds"}})}function mr(l,e,t){let{selected:o}=l.scope,n=e.walk?.added??[],r=new Set([...o,...n]),s=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of o){let R=e.kept.get(f)??[];s.set(f,R.map(w=>w.Id)),i.set(f,R.length),l.personAccounts.has(f)&&a.set(f,R.filter(w=>w[we]===!0).length)}for(let f of n)i.set(f,e.walk?.parentIds.get(f)?.length??0),l.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...l.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>r.has(f.objectApiName)&&!r.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:u,currencies:p}=l.scope,g=u?.filter(f=>r.has(f.objectApiName)),y=p?.objects.filter(f=>r.has(f));return{...l,objectDescribes:new Map([...l.objectDescribes].filter(([f])=>r.has(f))),autoDiscoveredObjects:n,missingInTarget:l.missingInTarget.filter(f=>r.has(f)),recordCounts:i,totalObjectsScanned:r.size,parentIds:s,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:o,parents:n.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:l.scope.standardNeeded.filter(f=>r.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...p&&y!==void 0&&y.length>0?{currencies:{...p,objects:y}}:{},fitted:t}}}var nt=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,o){return this.deps.schemaScanner.listObjects(e,t,o)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,o,n){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let r=await this.deps.schemaScanner.scan(e,t,o.selectedObjects,o.includeStandardObjects,{...o.maxDepth!==void 0?{maxDepth:o.maxDepth}:{},...o.maxObjects!==void 0?{maxObjects:o.maxObjects}:{},...o.maxRecordsPerObject!==void 0&&o.maxRecordsPerObject>0?{maxRecordsPerObject:o.maxRecordsPerObject}:{},...n?{onProgress:n}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),r}buildGraph(e,t){let o=new Map;for(let[n,r]of e.objectDescribes){let s=r.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));o.set(n,{name:r.name,fields:s})}return this.deps.graphBuilder.build(o,e.recordCounts,t)}buildCompliance(e,t,o=[]){let n=this.deps.complianceEngine.buildProfile(e,Eo(o,t)),r=this.deps.complianceEngine.generateRules(n);return{profile:n,rules:r}}generatePlan(e,t,o,n){let r=Po(t,e.nodes.map(c=>c.objectApiName),o),s={...this.deps.complianceEngine.buildSummary(o),...r.length>0?{notCovered:r}:{}},i=this.deps.planGenerator.generate(e,t,s),a=n?{...i,scope:n}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:o,graph:n,plan:r,rules:s,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,u=0,p={describe:O=>e.describe(O),describeGlobal:()=>e.describeGlobal(),query:O=>(u++,e.query(O)),...e.queryMore?{queryMore:O=>(u++,e.queryMore.call(e,O))}:{}},g=r.waves.map(O=>O.objects),y=new Map,f=g.flatMap(O=>Ue(O,n.edges).groups.filter(D=>D.length>1));for(let O of new Set(f.flat()))y.set(O,await t.describeLookups?.(O).catch(()=>null)??null);let R=fn(g,n.edges,O=>y.get(O)),{selected:w}=o.scope,C=lr(o.objectDescribes,w,R),v=ur(R,C),z=pr(t.automation,t.mutePlan,v),K=await m.readFitRows(p,o,d),E=await fr({order:R.filter(O=>w.includes(O)),rows:K,planned:o.recordCounts,lookups:C,parents:new Map(o.scope.parents.map(({objectApiName:O})=>{let D=o.personAccounts.get(O);return[O,{ids:o.parentIds.get(O)??[],...D!==void 0?{personAccounts:D}:{}}]})),budget:a,room:z,mode:i,...c!==void 0?{maxRecords:c}:{},walk:O=>m.walkFrom(p,o,O,d)}),A=z.unread!==void 0?{automationUnread:z.unread}:{},j={...E.report,requestsRead:u,...A,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},M=new Map([...E.kept].map(([O,D])=>[O,D.map(S=>S.Id)])),te={heldBy:E.heldBy,report:j,keptIds:M,...A};if(E.cannotFit!==void 0)return{...te,cannotFit:E.cannotFit};if(E.heldBy==="whole")return te;let se=mr(o,E,j),T=this.buildGraph(se,t.batchSize);return{...te,fitted:{scan:se,graph:T,plan:this.generatePlan(T,r.complianceFramework,s,se.scope),run:dr(C,se.parentIds)}}}async executePlan(e,t,o,n,r,s,i,a){let c=Array.from(n.values()).reduce((R,w)=>R+w,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let u=this.deps.createExecutor(),p=()=>{},g=r?u.on("node-completed",r):p,y=r?u.on("node-failed",r):p;for(let R of this.pendingSkips)u.skip(R);this.pendingSkips.clear(),this.runningExecutors.push(u);let f;try{f=await u.execute(e,t.edges,o,n,s,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(u),1),g(),y()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:f.totalSuccess+f.totalSkipped,totalFailed:f.totalFailure}}),f}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,o,n,r,s){return this.deps.complianceEngine.generateReport(e,t,o,n,r,s)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var ot=class{build(e,t,o=200){let n=this.extractEdges(e),r=Ir(n,new Set(e.keys())),s=this.tarjanSCC(Array.from(e.keys()),r),i=this.resolveCycles(s,r),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),r,s),d=this.buildNodes(e,t,a,c,o),m=this.computeStats(d,n,i);return{nodes:d,edges:n,cycles:i,stats:m}}extractEdges(e){let t=[],o=new Set(e.keys());for(let[n,r]of e)for(let s of r.fields){if(s.type!=="reference"||s.referenceTo.length===0)continue;let i=s.referenceTo.filter(d=>o.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:n,fieldApiName:s.name,relationshipType:"polymorphic",required:!s.nillable});continue}let a=i[0],c;a===n?c="hierarchical":s.nillable?c="lookup":c="master_detail",t.push({from:a,to:n,fieldApiName:s.name,relationshipType:c,required:!s.nillable})}return t}tarjanSCC(e,t){let o=new Map;for(let s of e)o.set(s,[]);for(let s of t){let i=o.get(s.to);i&&i.push(s.from)}let n={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},r=[...e].sort();for(let s of r)n.indices.has(s)||this.tarjanStrongConnect(s,o,n);return n.sccs}tarjanStrongConnect(e,t,o){o.indices.set(e,o.index),o.lowLinks.set(e,o.index),o.index++,o.stack.push(e),o.onStack.add(e);let n=t.get(e)??[];for(let r of n)if(o.indices.has(r)){if(o.onStack.has(r)){let s=o.lowLinks.get(e)??0,i=o.indices.get(r)??0;o.lowLinks.set(e,Math.min(s,i))}}else{this.tarjanStrongConnect(r,t,o);let s=o.lowLinks.get(e)??0,i=o.lowLinks.get(r)??0;o.lowLinks.set(e,Math.min(s,i))}if(o.lowLinks.get(e)===o.indices.get(e)){let r=[],s;do s=o.stack.pop(),o.onStack.delete(s),r.push(s);while(s!==e);o.sccs.push(r.sort())}}resolveCycles(e,t){let o=[],n=new Set;for(let r of t)r.from===r.to&&r.relationshipType==="hierarchical"&&n.add(r.from);for(let r of n)o.push({objects:[r],strategy:"two_pass",description:`Insert ${r} without self-lookup, update in 2nd pass`});for(let r of e){if(r.length<=1)continue;let s=new Set(r),i=t.filter(d=>s.has(d.from)&&s.has(d.to)&&d.from!==d.to),a,c;r.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${r[0]} without ${r[1]} lookup, insert ${r[1]} with ${r[0]} lookup, update ${r[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),o.push({objects:[...r],strategy:a,description:c})}return o}topologicalSort(e,t,o){let n=new Map;for(let p=0;p<o.length;p++)for(let g of o[p])n.set(g,p);let r=o.length,s=new Map;for(let p=0;p<r;p++)s.set(p,new Set);for(let p of t){let g=n.get(p.from),y=n.get(p.to);g!==void 0&&y!==void 0&&g!==y&&s.get(y).add(g)}let i=new Map;for(let[p,g]of s)i.set(p,new Set(g));let a=[],c=new Map;for(;i.size>0;){let p=[];for(let[g,y]of i)y.size===0&&p.push(g);if(p.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}p.sort((g,y)=>g-y);for(let g of p){a.push(g);let y=s.get(g)??new Set,f=-1;for(let R of y)f=Math.max(f,c.get(R)??0);c.set(g,y.size===0?0:f+1),i.delete(g);for(let R of i.values())R.delete(g)}}let d=new Map,m=new Map,u=0;for(let p of a){let g=o[p],y=c.get(p)??0,f=[...g].sort();for(let R of f)d.set(R,u),m.set(R,y),u++}for(let p of e)d.has(p)||(d.set(p,u),m.set(p,0),u++);return{order:d,levels:m}}buildNodes(e,t,o,n,r){let s=[];for(let i of e.keys()){let a=t.get(i)??0;s.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/r),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:o.get(i)??0,level:n.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return s.sort((i,a)=>i.insertOrder-a.insertOrder),s}computeStats(e,t,o){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:o.length,maxDepth:Math.max(0,...e.map(n=>n.level)),totalRecords:e.reduce((n,r)=>n+r.recordCount,0),totalEstimatedApiCalls:e.reduce((n,r)=>n+r.estimatedApiCalls,0)}}};function Ir(l,e){let t=wn(e);return t.length===0?[...l]:[...l.filter(o=>!(o.to===oe&&o.fieldApiName==="ActivityId")),...t.map(o=>({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as xr,randomUUID as Fr}from"node:crypto";var jr=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],rt=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,o=[]){let n=this.builtInRules.get(e)??[];return{framework:e,rules:n,autoDetectedPII:t,userOverrides:o,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let n of e.userOverrides){let r=`${n.objectApiName}.${n.fieldApiName}`;t.set(r,n)}let o=[];for(let n of e.autoDetectedPII){let r=`${n.objectApiName}.${n.fieldApiName}`,s=t.get(r);if(s){if(s.method==="skip")continue;o.push({objectApiName:n.objectApiName,fieldApiName:n.fieldApiName,method:s.method,piiCategory:n.piiCategory,aiConfidence:n.confidence,userOverridden:!0,fieldType:n.fieldType});continue}let i=this.findMatchingRule(e.rules,n.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:n.suggestedMethod;o.push({objectApiName:n.objectApiName,fieldApiName:n.fieldApiName,method:a,piiCategory:n.piiCategory,aiConfidence:n.confidence,userOverridden:!1,fieldType:n.fieldType})}return o}buildSummary(e){let t={};for(let n of jr)t[n]=0;for(let n of e)t[n.method]++;let o=[...new Set(e.map(n=>n.objectApiName))];return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:o}}generateReport(e,t,o,n,r,s){let i=new Set(e.userOverrides.map(y=>`${y.objectApiName}.${y.fieldApiName}`)),a=t.map(y=>{let f=this.findMatchingRule(e.rules,y.piiCategory),R=f?f.id:"custom",w=o.get(y.objectApiName)??0,C=`${y.objectApiName}.${y.fieldApiName}`;return{objectApiName:y.objectApiName,fieldApiName:y.fieldApiName,piiCategory:y.piiCategory,anonymizationMethod:y.method,recordsAnonymized:w,ruleApplied:R,userOverridden:i.has(C)||y.userOverridden}}),c=this.buildObjectSummaries(t,o,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),u=Fr(),p=JSON.stringify(a),g=xr("sha256").update(p).digest("hex");return{id:u,framework:e.framework,generatedAt:m,sourceOrgId:n,targetOrgId:r,totalFieldsScanned:s,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(o=>o.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,o){let n=new Set;for(let s of e)n.add(s.objectApiName);for(let s of o.autoDetectedPII)n.add(s.objectApiName);let r=[];for(let s of n){let i=e.filter(p=>p.objectApiName===s),a=o.autoDetectedPII.filter(p=>p.objectApiName===s),c=[...new Set(i.map(p=>p.method))],d=t.get(s)??0,m=a.length>0&&a.every(p=>i.some(g=>g.fieldApiName===p.fieldApiName)),u=a.length===0||m?"pass":i.length>0?"partial":"fail";r.push({objectApiName:s,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:u})}return r}computeOverallStatus(e){return e.length===0||e.every(n=>n.status==="pass")?"pass":e.every(n=>n.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var st=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,o){let n=this.buildWaves(e),r=e.stats.totalRecords,s=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(n,e);return{waves:n,totalRecords:r,estimatedDurationSec:i,estimatedApiCalls:s,complianceFramework:t,anonymizationSummary:o,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),o=new Map;for(let i of t){let a=o.get(i.level);a?a.push(i.objectApiName):o.set(i.level,[i.objectApiName])}let n=[...o.keys()].sort((i,a)=>i-a),r=new Map;for(let i=0;i<n.length;i++){let a=n[i],c=o.get(a);if(c)for(let d of c)r.set(d,i)}let s=[];for(let i=0;i<n.length;i++){let a=n[i],c=o.get(a)??[],d=new Set;for(let u of c)for(let p of e.edges)if(p.to===u){let g=r.get(p.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((u,p)=>u-p);s.push({order:i,objects:c,dependsOn:m})}return s}estimateDuration(e,t){let o=new Map;for(let s of t.nodes)o.set(s.objectApiName,s.estimatedApiCalls);let n=new Map;t.cycles.forEach((s,i)=>{for(let a of s.objects)n.set(a,i)});let r=0;for(let s of e){let i=new Map;for(let a of s.objects){let c=n.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(o.get(a)??0))}r+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return r}};var De=class{idMaps=new Map;registerMappings(e,t){let o=this.idMaps.get(e);o||(o=new Map,this.idMaps.set(e,o));for(let[n,r]of t)o.set(n,r)}remapRecords(e,t,o){let n=t.filter(c=>c.to===o),r=0,s=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,u=new Map;for(let p of n){let g=d[p.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(p.from)?.get(g);if(f!==void 0)d[p.fieldApiName]=f,m.add(p.fieldApiName),r++;else{let R=u.get(p.fieldApiName);R?R.parents.push(p.from):u.set(p.fieldApiName,{sourceId:g,parents:[p.from]}),s++}}for(let[p,{sourceId:g,parents:y}]of u)m.has(p)||(d[p]=null,a.push({index:c,fieldApiName:p,sourceId:g,parents:y}))}return{remapped:r,missing:s,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Nr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Ar(l,e,t){let o=en(l);if(e!==void 0&&!Nr.test(e))throw new Error(`Not a record id to read after: "${e}".`);let n=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${o}${n} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Lr={statusCode:Ye,message:"No result returned for the record",fields:[]},Dr={statusCode:Ye,message:"Refused without a reason",fields:[]},hr="PARENT_REFUSED",gr="PARENT_NOT_WRITTEN",Yt="CUT_WITH_PARENT",yr={skipped:l=>`${l} was skipped in this run`,failed:l=>`the run's write of ${l} failed`},$r="PERSON_ACCOUNT_NOT_WRITTEN",Br="PERSON_CONTACT_NOT_LOOKED_UP",_r=`SELECT Id FROM RecordType WHERE SobjectType = '${ce}' AND IsPersonType = true`;function de(l){return l.slice(0,15)}var Re=class{byReason=new Map;add(e){let t=new Set;for(let o of e){let n=`${o.statusCode}\0${o.fields.join(",")}`;if(t.has(n))continue;t.add(n);let r=this.byReason.get(n);this.byReason.set(n,r?{...r,count:r.count+1}:{statusCode:o.statusCode,fields:[...o.fields],count:1,message:o.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,o=this.byReason.get(t);this.byReason.set(t,o?{...o,count:o.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function qr(l,e){let[t,...o]=l.errors,[n,...r]=l.errorDetails??[];return{...l,...t===void 0?{}:{errors:[Tt(t,e),...o]},...n===void 0?{}:{errorDetails:[{...n,message:Tt(n.message,e)},...r]}}}function wr(){return{written:0,linked:0,failed:0,errors:[],refusals:new Re,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map,sentAgainForALock:{rows:0,written:0,stillLocked:0}}}function zr(l){return{statusCode:qn,fields:["RecordTypeId"],count:l.recordCount,message:Un(l)}}function Gr(l,e){return{objectApiName:l,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function br(l){let e=0;for(let[t,o]of l)Ft(t)&&(e+=o);return e}function Ur(l){let e=new Map;for(let t of l.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...l.kept].map(([t,o])=>[t,new Set(o.map(de))])),stayedOut:new Map}}var $e=class extends Co{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Bn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new gn;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let o=await this.deps.describeCreateableFields(e),n=o.size>0?o:null;return this.creatableByObject.set(e,n),n}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let o=this.lookupsByObject.get(e);return o||(o=t(e).catch(()=>null),this.lookupsByObject.set(e,o)),o}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let o=this.keyPrefixByObject.get(e);return o||(o=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,o)),o}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:o}=this.deps;if(!t||!o)return[];let n=await this.creatableFieldsOf(e);if(n&&!n.has("RecordTypeId"))return[];try{let r=await t(e);if(!r.some(i=>!i.available&&!i.master))return[];let s=this.inTargetRecordTypes(await o(e));return zn(e,s,kt(r,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[o,n]of e){if(o===null)continue;let r=this.targetRecordTypeOf(o);t.set(r,(t.get(r)??0)+n)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,o=new Map,n=[]){await this.mapRecordTypes(e);let r=new Map;for(let s of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(s)??0;if(i===0)continue;let a=await this.givenRuleOf(s);if(!a)continue;let c=await this.creatableFieldsOf(s),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let u=await this.onMasterInSource(s,o.get(s));if(u===void 0)continue;d=n.find(g=>g.objectApiName===s)?Math.min(u,i):u}d!==0&&r.set(s,{objectApiName:s,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return r}async onMasterInSource(e,t){try{if(t===void 0){let r=this.deps.countRecordTypes;return r?br(await r(e)):void 0}let o=this.deps.querySource;if(!o)return;let n=0;for(let r=0;r<t.length;r+=ke){let s=await o(Nt(e,t.slice(r,r+ke)));n+=br(Ke(s))}return n}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let o=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!o?.some(s=>!s.master))return;let n=kt(o,this.targetRecordTypes),r=$o(Do(n));return{types:n,...r?{predicted:r}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let o=this.deps.describeRecordTypesAgain;if(!o||!this.lease||this.lease.assigned===0)return;let n=[...new Set(e.waves.flatMap(r=>r.objects))].filter(r=>(t.get(r)??0)>0);await Promise.all(n.map(async r=>{if((await this.deps.describeRecordTypes?.(r).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(r,await o(r))}catch{}}))}countCreatedWithoutRecordType(e,t,o,n){let r=this.recordTypesGiven.get(e);r||(r={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,r)),r.rows++,r.why[o]=(r.why[o]??0)+1,n&&r.ids.length<Bo&&r.ids.push(n)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,o]of this.recordTypesGiven){let n=e[t];n&&(e[t]={...n,recordTypeGiven:Gr(t,o)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){ae.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${ee(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,o])=>{if(o.ids.length!==0)try{let n=await e(Nt(t,o.ids));o.readBack=_o(n,o.types)}catch(n){o.readBack={read:0,types:[],unread:ee(n)}}}))}holdOnClosedRecordTypes(e,t,o){let n=o.closedRecordTypes;if(!n)return t;let r=[];for(let s of t){let i=s.RecordTypeId,a=e===fe&&Pe(s),c=typeof i=="string"&&i.length>=15&&!a?n.get(de(this.targetRecordTypeOf(i))):void 0;if(!c){r.push(s);continue}o.failed++;let d=o.heldForRecordType.get(c.recordTypeId);o.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=s.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(de(m),e)}return r}async mapRecordTypes(e){let{querySource:t,queryTarget:o}=this.deps;if(!t||!o)return;let n=[...new Set(e.waves.flatMap(s=>s.objects))];if(n.length===0)return;let r=`${xo} AND SobjectType IN (${n.map(s=>`'${ge(s)}'`).join(", ")})`;try{let[s,i]=await Promise.all([t(r),o(r)]),a=xt(s);this.targetRecordTypes=xt(i),this.recordTypeMappings=new jt().buildMapping(a,this.targetRecordTypes);for(let c of No(a,this.targetRecordTypes))ae.warn(`[autopilot] ${Lo(c)}`)}catch(s){ae.warn("Autopilot could not match the record types of the two orgs",{error:ee(s)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:o}=this.deps;if(!t||!o)return;let n=new Set(e.waves.flatMap(r=>r.objects));if(!(!n.has(Ae)&&!n.has(Oe)))try{let[r,s]=await Promise.all([t(ve),o(ve)]),i=r[0]?.Id,a=s[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(Ae,[[i,a]])}catch(r){ae.warn("Autopilot could not match the standard price books",{error:ee(r)})}}async execute(e,t,o,n,r,s=new Map,i={}){if(!this.deps.queryByIds&&[...s.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=s,this.contactPoints=i.keepContactPoints===!0?void 0:new Mo,this.lease=i.lease,this.fit=i.fit?Ur(i.fit):void 0;let a=Date.now();this.signal=r;let c=()=>this.pauseResolve?.();r?.addEventListener("abort",c,{once:!0});let d={},m={},u={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},p=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await y(f),f===We&&await this.writeEmailsAfterTheirTask(t,u)},y=async f=>{if(this.skippedObjects.has(f)){let w=n.get(f)??0;u.skippedObjects.push(f),u.totalSkipped+=w,this.notWritten.set(f,"skipped");return}this.reached.add(f);let R=n.get(f)??0;if(await this.checkPause()){p.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...R>0?{notSent:R}:{}};return}try{let w=await this.executeObject(f,t,o,R);u.totalSuccess+=w.success,u.totalFailure+=w.failure,u.totalLinked=(u.totalLinked??0)+w.linked,w.cutSinceFit>0&&(u.cutSinceFit=(u.cutSinceFit??0)+w.cutSinceFit);let C=this.leftToThePlatform.counts(f);if(m[f]={written:w.success,linked:w.linked,failed:w.failure,refusals:w.refusals,...w.leftToDefault.length>0?{leftToDefault:w.leftToDefault}:{},...C.length>0?{leftToThePlatform:C}:{},...w.notSent!==void 0&&w.notSent>0?{notSent:w.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===fe&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...w.cutSinceFit>0?{cutSinceFit:w.cutSinceFit}:{},...w.threw!==void 0?{threw:w.threw}:{},...w.sentAgainForALock.rows>0?{sentAgainForALock:w.sentAgainForALock}:{}},w.notSent!==void 0){p.push(f);return}let{threw:v}=w;if(v!==void 0||w.errors.length>0&&w.success+w.linked===0){u.failedObjects.push(f),v!==void 0&&this.notWritten.set(f,"failed");let z=v!==void 0?[v,...w.errors]:w.errors;d[f]=z[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:z,partialSuccessCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals}))}else u.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals,elapsedMs:w.elapsedMs,apiCallsUsed:w.apiCallsUsed}))}catch(w){u.failedObjects.push(f),this.notWritten.set(f,"failed");let C=ee(w);d[f]=C,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[C],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,n),this.planned=new Set(e.waves.flatMap(w=>w.objects));let f={};for(let w of e.waves){if(await this.writeWave(w.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let w=new Set([...u.completedObjects,...u.failedObjects,...u.skippedObjects,...p]);for(let C of e.waves.flatMap(v=>v.objects)){if(w.has(C))continue;let v=n.get(C)??0;p.push(C),m[C]={written:0,linked:0,failed:0,refusals:[],...v>0?{notSent:v}:{}}}return u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,u}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,u),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let R=await this.applyDeferredStatuses();return Object.keys(R).length>0&&(u.statuses=R),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.stopped()&&(u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m)),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),u}catch(f){throw u.elapsedMs=Date.now()-a,u.fatalError=ee(f),ae.error("Autopilot execution crashed",{error:u.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:u.fatalError})),f}finally{r?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,o){let{within:n,deps:r,groups:s}=Ue(e,t),i=new Map;s.forEach((m,u)=>m.forEach(p=>i.set(p,u)));let a=[];for(let[m,u]of s.entries()){let p=new Set;for(let g of u)for(let y of r.get(g)??[]){let f=i.get(y);f!==void 0&&f!==m&&p.add(a[f])}a.push((async()=>{await Promise.all(p);let g=u.length>1?un(u,await this.setAtInsert(u,n)):u;for(let y of g)await o(y)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let o=new Set(e),n=new Map;for(let r of t)!o.has(r.to)||!o.has(r.from)||n.has(r.to)||n.set(r.to,await this.lookupsOf(r.to));return pn(e,t,r=>n.get(r))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:o}=this.deps;if(!o||t.length===0)return;let n=new Io;for(let r of t){let s=r.parents.map(i=>this.deps.remapper.getTargetId(i,r.sourceId)).find(i=>i!==void 0);if(!s){this.owedLookups.push(r);continue}n.add({objectApiName:r.objectApiName,recordId:r.recordId,fieldName:r.fieldApiName,value:s})}for(let[r,s]of n.updates()){let i=e[r],a=i?.filled??0,c=new Re;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<s.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(r,"lookups",s.slice(d).map(p=>String(p.Id)));break}let m=s.slice(d,d+this.batchSize),u=await Ht(o,r,m);m.forEach((p,g)=>{let y=u[g];if(y?.success){a++;return}let f=Object.keys(p).filter(R=>R!=="Id");c.add(Kt(y).map(R=>({...R,fields:f}))),this.noteLookupLeftEmpty(r,String(p.Id))})}e[r]=this.lookupOutcome(r,a,c)}}noteLookupLeftEmpty(e,t){let o=this.lookupsLeftEmpty.get(e);o||(o=new Set,this.lookupsLeftEmpty.set(e,o)),o.add(t)}lookupOutcome(e,t,o){let n=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:o.list(),...n>0?{leftEmpty:n}:{}}}async sayLookupsLeftOwed(e,t){let o=new Map;for(let n of this.owedLookups.splice(0,this.owedLookups.length)){let r=await this.whyLeftOwed(n,e);if(!r)continue;let s=o.get(n.objectApiName);if(!s){s=new Re;for(let i of t[n.objectApiName]?.refusals??[])s.addCounted(i);o.set(n.objectApiName,s)}s.add([{...r,fields:[n.fieldApiName]}]),this.noteLookupLeftEmpty(n.objectApiName,n.recordId)}for(let[n,r]of o){let s=t[n]?.filled??0;t[n]=this.lookupOutcome(n,s,r)}}async whyLeftOwed(e,t){let{fieldApiName:o,sourceId:n}=e,r=this.refusedRecords.get(de(n)),s=e.parents.find(c=>c===r);if(s)return{statusCode:hr,message:`the ${s} record its ${o} names was refused in this run, and this record, written before it, keeps its ${o} empty.`};let i=this.fit?.stayedOut.get(de(n)),a=e.parents.find(c=>c===i);if(a)return{statusCode:Yt,message:`the ${a} record its ${o} names stayed out with a record the fit cut, and this record, written before it, keeps its ${o} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(u=>u.from===c&&u.to===e.objectApiName&&u.fieldApiName===o);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,n,e.parents.length)))return{statusCode:gr,message:`the ${c} record its ${o} names was not written: ${yr[d](c)}, and this record, written before it, keeps its ${o} empty.`}}}async executeObject(e,t,o,n){let r=Date.now(),s=wr(),i=()=>{let a=[...s.heldForRecordType.values()];return{success:s.written,linked:s.linked,failure:s.failed,errors:[...a.map(Wn),...s.errors],refusals:[...s.refusals.list(),...a.map(zr)].sort((c,d)=>d.count-c.count),apiCallsUsed:s.apiCallsUsed,elapsedMs:Date.now()-r,leftToDefault:[...s.defaulted].map(([c,d])=>({field:c,count:d})),...s.notSent!==void 0?{notSent:s.notSent}:{},cutSinceFit:s.cutSinceFit,sentAgainForALock:s.sentAgainForALock}};try{return await this.writeEveryPage(e,t,o,n,s,i)}catch(a){return{...i(),threw:ee(a)}}}async writeEveryPage(e,t,o,n,r,s){let i=n>0?await this.recordTypesHeldBack(e):[];i.length>0&&(r.closedRecordTypes=new Map(i.map(u=>[de(u.recordTypeId),u])));let a=u=>{let p=Math.min(u,n);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:n>0?Math.round(p/n*100):100,recordsProcessed:p,recordsTotal:n,apiCallsUsed:r.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(Vt(e)&&m){let u=[];for(;c<n;){if(await this.checkPause())return r.notSent=n,s();let{rows:v,advance:z,next:K,last:E}=await this.readPage(e,c,d);if(r.apiCallsUsed++,z===0)break;c+=z,d=K;let A=this.leaveToThePlatform(e,v,t);if(this.deps.anonymizer.anonymize(A,o,e),await this.neutralizeContactPoints(e,A),u.push(...A),E)break}let p=await this.pricesInOneCurrencyEach(u,m.source),{standard:g,custom:y}=lt(p.rows,m.source),f=lt(u.filter(v=>p.standsFor.has(String(v.Id))),m.source);p.said.length>0&&this.pricesSettled.set(e,Go(p.said));let R=0,w=0,C=async v=>{for(let z=0;z<v.length;z+=this.batchSize){if(await this.checkPause())return r.notSent=u.length-R-w,!1;let K=v.slice(z,z+this.batchSize);await this.writeBatch(e,K,t,r),R+=K.length,a(R+w)}return!0};for(let[v,z]of[[g,f.standard],[y,f.custom]]){if(!await C(v))return s();let K=this.linkWhatStoodIn(z,p.standsFor,r);if(w+=z.length-K.length,!await C(K))return s()}return s()}for(;c<n;){if(await this.checkPause()){r.notSent=n-c;break}let{rows:u,advance:p,next:g,last:y}=await this.readPage(e,c,d);if(r.apiCallsUsed++,p===0)break;d=g;let f=this.leaveToThePlatform(e,u,t);if(this.deps.anonymizer.anonymize(f,o,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,r),c+=p,a(c),y)break}return s()}async neutralizeContactPoints(e,t){let{contactPoints:o}=this,n=this.deps.describeFields;if(!o||!n||t.length===0)return;let r=await n(e).catch(()=>{});if(!r)return;let s=o.forObject(e,r);if(s)for(let i of t)s(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,o){let n=this.parentIds.get(e);if(n&&this.deps.queryByIds){let i=n.slice(t,t+Math.min(this.batchSize,ke));return i.length===0?{rows:[],advance:0,next:o,last:!0}:{rows:await this.deps.queryByIds(e,i),advance:i.length,next:o,last:!1}}let r=await this.deps.query(e,o,this.batchSize),s=r.at(-1)?.Id;return{rows:r,advance:r.length,next:typeof s=="string"?s:o,last:r.length>0&&typeof s!="string"}}leaveToThePlatform(e,t,o){let n=new Set(o.filter(r=>r.to===e&&(r.required||Qt(r.to,r.fieldApiName))).map(r=>r.fieldApiName));return this.leftToThePlatform.keep(e,t,[...n])}async writeBatch(e,t,o,n){let r=[],s=t,i=this.standardPricebook;if(e===Ae&&i&&(s=t.filter(E=>E.Id!==i.source),n.linked+=t.length-s.length),s=this.holdOnClosedRecordTypes(e,s,n),s=await this.holdBehindRefusedParents(e,s,o,n),s=this.holdBehindCutParents(e,s,n),e===oe&&(s=this.holdEmailsForTheirTask(s)),e===fe&&(s=await this.linkPersonContacts(s,n,r)),s.length===0){this.register(e,r);return}let a=this.deps.remapper.remapRecords(s,o,e);await this.leaveToDefault(e,s,n);let c=await this.creatableFieldsOf(e),d=c?s.map(E=>{let A={};for(let j of Object.keys(E))(j==="Id"||j==="attributes"||c.has(j))&&(A[j]=E[j]);return A}):s;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((E,A)=>{if(E.RecordTypeId!==void 0)return;let j=s[A]?.RecordTypeId,M=!c||c.has("RecordTypeId");m.set(E,M&&Ft(j)?"masterInSource":"notRead")});for(let E of d)for(let A of Zt(e,E))delete E[A];let u=await this.replaceCurrencies(e,s,d,c);e===ce&&await this.leaveOutForAccountKind(s,d);let p=new Map;d.forEach((E,A)=>{let j=gt(e,E);for(let M of j)delete E[M];j.length>0&&p.set(A,j)});let g=await this.lookupsOwed(e,s,a.unresolved.filter(E=>!p.get(E.index)?.includes(E.fieldApiName)),c),y=this.deps.queryTarget,f=y?E=>(n.apiCallsUsed++,y(E)):void 0;if(e===mn&&f){let E=await En(f,d);for(let[A,j]of E){let M=d[A].Id;typeof M=="string"&&r.push([M,j])}n.linked+=E.size,d=d.filter((A,j)=>!E.has(j))}if(Sn[e]!==void 0&&f){let E=await On(f,e,d);for(let[A,j]of E){let M=d[A].Id;typeof M=="string"&&r.push([M,j])}n.linked+=E.size,await this.giveFlagsBack(e,[...E].map(([A,j])=>[d[A],j]),n),d=d.filter((A,j)=>!E.has(j))}if(e===We&&f){let E=await this.tasksWrittenWithTheirEmail(d,f);for(let[A,j]of E)r.push([A,j]);n.linked+=E.size,d=d.filter(A=>!E.has(String(A.Id)))}if(d.length===0){this.register(e,r);return}let R=await this.startAsDrafts(e,d),w=m.size>0?await this.givenRuleOf(e):void 0,C=await this.insertSendingLocksAgain(e,d,n),v=await this.keyPrefixOf(e),z=hn[e],K=[];if(d.forEach((E,A)=>{let j=typeof E.Id=="string"?E.Id:void 0,M=C[A];if(!M){this.refuse(e,j,n,void 0);return}if(M.success){n.written++;let se=w?m.get(E):void 0;w&&se&&this.countCreatedWithoutRecordType(e,w,se,M.id);let T=u.get(E);this.currencyChanges.add(e,T),T&&M.id&&this.currencyChangesByWrittenId.set(M.id,T),j&&M.id&&r.push([j,M.id]);let O=R.get(A);O&&M.id&&this.deferredStatuses.push({objectApiName:e,id:M.id,status:O});let D=j?g.get(j):void 0;for(let S of M.id?D??[]:[])this.owedLookups.push({objectApiName:e,recordId:M.id,fieldApiName:S.fieldApiName,sourceId:S.sourceId,parents:S.parents});return}let te=Hn(M,v);if(te.kind==="linked"){n.linked++,j&&r.push([j,te.id]);return}if(te.kind==="unidentified"&&z&&f){K.push({payload:E,sourceId:j,outcome:M});return}this.refuse(e,j,n,M)}),z&&f&&K.length>0){let E=await Pn(f,e,z,K.map(A=>A.payload));K.forEach((A,j)=>{let M=E[j];if(M&&A.sourceId){n.linked++,r.push([A.sourceId,M]);return}this.refuse(e,A.sourceId,n,A.outcome)})}this.register(e,r)}async insertSendingLocksAgain(e,t,o){let n=async i=>(o.apiCallsUsed++,this.deps.insert(e,i)),r=await n(t),s=await oo({outcomes:r.slice(0,t.length),locked:i=>!i.success&&to(i.errors,i.errorDetails),written:i=>i.success,send:i=>Ht((a,c)=>n(c),e,i.map(a=>t[a])),note:qr,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return s.refused===0?r:(o.sentAgainForALock={rows:o.sentAgainForALock.rows+s.sentAgain,written:o.sentAgainForALock.written+s.written,stillLocked:o.sentAgainForALock.stillLocked+s.stillLocked},ae.info(`[autopilot] ${e}: ${Xe("record(s)",s)??""}`),[...s.outcomes,...r.slice(t.length)])}async giveFlagsBack(e,t,o){let n=this.deps.update;if(!n||t.length===0||!Tn[e])return;let r=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),s=await vn(e,t,i=>!r?.has(i),async i=>(o.apiCallsUsed++,n(e,i)),()=>this.stopped());s&&ae.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:s})}holdEmailsForTheirTask(e){for(let o of e){let n=o.ActivityId;typeof o.Id=="string"&&typeof n=="string"&&n!==""&&this.taskOfEmail.set(o.Id,n)}if(this.taskTurnOver||!this.planned.has(We))return e;let t=[];for(let o of e)bn(o)?this.emailsAfterTheirTask.push(o):t.push(o);return t}async tasksWrittenWithTheirEmail(e,t){let o=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(oe,i);c&&o.set(a,c)}let n=e.map(i=>String(i.Id)).filter(i=>o.has(i));if(n.length===0)return new Map;let r;try{r=await An(t,[...new Set(n.map(i=>o.get(i)??""))])}catch(i){return ae.warn("Autopilot could not look up the tasks written with its emails",{error:ee(i)}),new Map}let s=new Map;for(let i of n){let a=r.get(o.get(i)??"");a&&s.set(i,a)}return s}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let o=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(o.length===0)return;let n=wr();for(let d=0;d<o.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=o.length-d;break}await this.writeBatch(oe,o.slice(d,d+this.batchSize),e,n)}t.totalSuccess+=n.written,t.totalFailure+=n.failed,t.totalLinked=(t.totalLinked??0)+n.linked;let r=t.objectOutcomes??{};t.objectOutcomes=r;let s=r[oe],i=new Re;for(let d of[...s?.refusals??[],...n.refusals.list()])i.addCounted(d);let a=new Map((s?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of n.defaulted)a.set(d,(a.get(d)??0)+m);let c={...s,written:(s?.written??0)+n.written,linked:(s?.linked??0)+n.linked,failed:(s?.failed??0)+n.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};r[oe]=c,c.written+c.linked>0&&t.failedObjects.includes(oe)&&(t.failedObjects.splice(t.failedObjects.indexOf(oe),1),delete t.nodeErrors?.[oe],t.completedObjects.push(oe)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:oe,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:n.apiCallsUsed}))}async leaveToDefault(e,t,o){let n=await this.lookupsOf(e);if(!n)return;let r=In(n.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(r.size===0)return;let s=await this.creatableFieldsOf(e);for(let i of t)for(let a of r){let c=i[a];c!=null&&c!==""&&(!s||s.has(a))&&o.defaulted.set(a,(o.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,o,n){let r=new Map,{querySource:s,queryTarget:i}=this.deps;if(!s||!i)return r;let a=!n||n.has(he);if(!a&&this.currencyChangesByWrittenId.size===0)return r;let c=p=>typeof p?.[he]=="string"&&p[he]!=="";if(!(a?o.some(c):t.some(c)))return r;this.currencies??=Me(s,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return r;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,u=a?[]:(await this.lookupsOf(e)??[]).map(p=>p.name);return o.forEach((p,g)=>{let y=t[g],f=y?.[he],R=a?Ln(p,{read:f,currencyFields:m,ratesOn:Fn(e,y)},d):$n(p,{read:f,parent:y?Dn(e,y,u,w=>this.currencyChangesByWrittenId.get(w)):void 0,currencyFields:m},d);R&&r.set(p,R)}),r}async pricesInOneCurrencyEach(e,t){let o={rows:e,standsFor:new Map,said:[]},{querySource:n,queryTarget:r}=this.deps;if(!n||!r)return o;let s=d=>typeof d[he]=="string"&&d[he]!=="";if(!e.some(s))return o;this.currencies??=Me(n,r,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return o;let{target:a}=i,c=zo({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[Ee]=="string"),writtenIn:d=>a.active.has(d)?d:Nn(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,o){let n=Oe,r=[],s=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(n,c);if(d===void 0){s.push(i);continue}r.push([a,d]),o.linked++}return this.register(n,r),s}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(o=>o.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let o=this.recordTypeMappings;return!o||!t.some(n=>typeof n.RecordTypeId=="string")?t.map(Fo):new jt().apply(t,o,n=>{this.unmappedRecordTypes.has(n)||(this.unmappedRecordTypes.add(n),jo(e,n,"autopilot"))})}async lookupsOwed(e,t,o,n){let r=new Map;if(!this.deps.update||o.length===0)return r;let s=await this.lookupsOf(e);for(let i of o){if(n&&!n.has(i.fieldApiName))continue;let a=s?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&r.set(c,[...r.get(c)??[],i])}return r}refuse(e,t,o,n){o.failed++;let r=Kt(n);o.errors.push(n?.errors[0]??Wr(r[0])),o.refusals.add(r),t&&this.refusedRecords.set(de(t),e)}async holdBehindRefusedParents(e,t,o,n){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let r=o.filter(a=>a.to===e);if(r.length===0)return t;let s=new Map;for(let a of r)s.set(a.fieldApiName,(s.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=gt(e,a),d;for(let y of r){let f=a[y.fieldApiName];if(typeof f!="string"||f===""||c.includes(y.fieldApiName)||this.deps.remapper.getTargetId(y.from,f)!==void 0)continue;let R=this.refusedRecords.get(de(f))===y.from,w=this.notWrittenOf(y.from);if(!R&&w===void 0)continue;let C=s.get(y.fieldApiName)??0;if(!R&&!await this.namesARecordOf(e,y,f,C))continue;let{from:v,fieldApiName:z}=y;d=R||w===void 0?{edge:y,statusCode:hr,message:`the ${v} record its ${z} names was refused in this run, and written without it this record would stand without its ${v}.`}:{edge:y,statusCode:gr,message:`the ${v} record its ${z} names was not written: ${yr[w](v)}, and written without it this record would stand without its ${v}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:u,edge:p}=d;n.failed++,n.errors.push(`${m}: ${u}`),n.refusals.add([{statusCode:m,message:u,fields:[p.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(de(g),e)}return i}holdBehindCutParents(e,t,o){let n=this.fit,r=n?.holds.get(e);return!n||!r?t:t.filter(s=>{if(!r.some(c=>{let d=s[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let u=de(d);return n.stayedOut.has(u)||n.kept.get(c.parent)?.has(u)!==!0}))return!0;o.cutSinceFit++;let a=s.Id;return typeof a=="string"&&a!==""&&n.stayedOut.set(de(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,o,n){let r=(await this.lookupsOf(e))?.find(s=>s.name===t.fieldApiName);if(r?.referenceTo.length===1)return r.referenceTo[0]===t.from;if(r&&r.referenceTo.length>1){let s=await this.keyPrefixOf(t.from);return typeof s=="string"&&s!==""&&o.startsWith(s)}return n===1}async linkPersonContacts(e,t,o){let n=e.filter(Pe),r=this.deps.queryTarget;if(n.length===0||!r)return e;let s=await this.lookupsOf(ce);if(s&&!s.some(u=>u.name===yt))return e;let i=new Map;for(let u of n){let p=u.AccountId,g=typeof p=="string"&&p!==""?this.deps.remapper.getTargetId(ce,p):void 0;g&&i.set(u,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await Rn(r,[...new Set(i.values())])}catch(u){c=ee(u)}let d=(u,p,g)=>{t.failed++,t.errors.push(`${p}: ${g}`),t.refusals.add([{statusCode:p,message:g,fields:["AccountId"]}]);let y=u.Id;typeof y=="string"&&y!==""&&this.refusedRecords.set(de(y),fe)},m=[];for(let u of e){if(!Pe(u)){m.push(u);continue}let p=i.get(u);if(p===void 0){d(u,$r,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(u,Br,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(p),y=u.Id;if(g===void 0||typeof y!="string"){m.push(u);continue}o.push([y,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let n=e.some(Pe)?await this.takenAsBusiness(t):()=>!1,r=e.map((s,i)=>kn(s,n(t[i])));t.forEach((s,i)=>{for(let a of Object.keys(s))tn(ce,a,r[i])&&delete s[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(ce);if(t&&!t.some(a=>a.name===yt))return()=>!0;let o=this.deps.queryTarget;if(!o)return()=>!1;this.personTypes??=o(_r).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[de(c.Id)]:[])),()=>{});let n=await this.personTypes;if(!n)return()=>!1;let r=await this.deps.describeRecordTypes?.(ce).catch(()=>{}),s=new Set((r??[]).map(a=>de(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?qo(r):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=de(d);return!n.has(m)&&s.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let o=new Map,n=Ce[e],{queryTarget:r,update:s}=this.deps;if(!n||!r||!s)return o;let i=this.lifecycleByObject.get(e);i||(i=Cn(r,n),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=Mn(c.Status,a);m&&(o.set(d,String(c.Status)),c.Status=m)}),o}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let o=new Map;for(let n of this.deferredStatuses)o.set(n.objectApiName,[...o.get(n.objectApiName)??[],n]);for(let[n,r]of o){let s=0,i=0,a=new Re;for(let c=0;c<r.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(n,"statuses",r.slice(c).map(u=>u.id));break}let d=r.slice(c,c+this.batchSize),m=await Ht(t,n,d.map(u=>({Id:u.id,Status:u.status})));d.forEach((u,p)=>{let g=m[p];if(g?.success){s++;return}i++,a.add(Kt(g))})}e[n]={applied:s,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,o){if(o.length===0)return;let n=this.leftByStop.get(e);n||(n={lookups:new Set,statuses:new Set},this.leftByStop.set(e,n));for(let r of o)n[t].add(r)}countEmailsTheStopHeld(e,t,o){let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),r=this.emailsHeldAndNotSent+n.length;if(this.emailsHeldAndNotSent=0,r===0)return;let s=o[oe]??{written:0,linked:0,failed:0,refusals:[]};o[oe]={...s,notSent:(s.notSent??0)+r,heldForTheirTask:r};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(oe);m>=0&&d.splice(m,1)}if(t.includes(oe))return;let i=[...this.planned],a=i.indexOf(oe),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,oe)}countWhatTheStopLeft(e,t){let o=new Set(e);for(let r of this.owedLookups.splice(0,this.owedLookups.length))r.parents.some(i=>o.has(i)||this.deps.remapper.getTargetId(i,r.sourceId)!==void 0)?this.noteLeftByStop(r.objectApiName,"lookups",[r.recordId]):this.owedLookups.push(r);let n=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let r of n)this.noteLeftByStop(r.objectApiName,"statuses",[r.id]);for(let[r,s]of this.leftByStop){let i=t[r]??{written:0,linked:0,failed:0,refusals:[]};t[r]={...i,...s.lookups.size>0?{lookupsLeftEmpty:s.lookups.size}:{},...s.statuses.size>0?{statusesNotGivenBack:s.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}wait(e){return this.deps.wait?this.deps.wait(e):no(e,this.signal)}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function Ht(l,e,t){try{return await l(e,t)}catch(o){let n=ee(o);return t.map(()=>({id:"",success:!1,errors:[n],errorDetails:[Rt(n)]}))}}function Kt(l){return l?l.errorDetails&&l.errorDetails.length>0?l.errorDetails:l.errors.length>0?l.errors.map(e=>Rt(e)):[Dr]:[Lr]}function Wr(l){return l.statusCode===Ye?l.message:`${l.statusCode}: ${l.message}`}var it=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let o=[],n=0,r=0;for(;n<t;){let s=Math.min(this.partitionSize,t-n);o.push({id:`${e}-${r}`,objectApiName:e,offset:n,limit:s,recordCount:s}),n+=s,r++}return o}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var Hr=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
11
11
 
12
12
  Usage:
13
13
  npx sandforge autopilot \\
@@ -29,6 +29,9 @@ Options:
29
29
  each parent a record needs raises it, to twice
30
30
  (default: 50)
31
31
  --max-total <n> most records the run may write in all (default: 10000)
32
+ --max-records-per-object <n>
33
+ records of a selected object copied at most, the
34
+ first by Id, 1 to 1000000 (default: 50000)
32
35
  --compliance <name> none | gdpr | ccpa | hipaa | pci_dss (default: none)
33
36
  --keep-contact-points write emails and phone numbers as read. Without it,
34
37
  as in the panel, every address is written under
@@ -89,7 +92,7 @@ Options:
89
92
  it is not needed. --mute-automation keeps quiet what
90
93
  tests the org's bypass; what an Apex trigger sends is
91
94
  read nowhere (default: off)
92
- ${_o({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no removal: a rewind to this","checkpoint is what takes it back."]})}
95
+ ${Yo({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no removal: a rewind to this","checkpoint is what takes it back."]})}
93
96
  --json emit the run summary as JSON, with the id
94
97
  of every record the run created (default: off)
95
98
  --fail-on-partial exit 3, not 0, when the run was partial: the target
@@ -98,7 +101,8 @@ ${_o({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no remo
98
101
  status refused (default: off)
99
102
  --help this text
100
103
 
101
- A selected object is copied whole, unless the plan is fitted. Of any other
104
+ A selected object is copied whole up to --max-records-per-object records, its
105
+ first by Id past them, unless the plan is fitted. Of any other
102
106
  object, only the records the selection references are read, by id; a lookup
103
107
  past the bounds is left empty, and the plan says which. Before it writes, the
104
108
  run is held to --max-total, to the data storage and the daily API requests the
@@ -133,25 +137,26 @@ asked first refused or not taken, or it died or produced only failures -- a run
133
137
  that died prints no summary, and what it wrote before it died stays; 2 a bad
134
138
  command line; 3 the run was partial and --fail-on-partial was given; 130 Ctrl-C
135
139
  stopped the run, 143 a SIGTERM (a CI job cancelled or timed out), 129 a SIGHUP.
136
- `,_r=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,qr="MAX_TOTAL_EXCEEDED",zr="AUTOPILOT_EMAILS_EXCEEDED",Gr="AUTOPILOT_CANNOT_FIT",Ur={switches:["--standard-objects","--keep-contact-points","--plan-only","--json","--fail-on-partial","--mute-automation","--accept-emails",...Ft.switches],values:["--source","--target","--object","--max-depth","--max-objects","--max-total","--compliance","--batch-size","--fit","--fit-cap","--fit-within",...Ft.values]};function Wr(l){let e=l.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(Br),process.exit(0)),Vt(e,Ur);let t=(A,w)=>{let M=e.indexOf(A);return M>=0&&M+1<e.length?e[M+1]:w},n=A=>{let w=[];for(let M=0;M<e.length;M++)e[M]===A&&M+1<e.length&&w.push(e[M+1]);return w},o=t("--source"),r=t("--target"),s=n("--object");(!o||!r||s.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
137
- `),process.exit(2));for(let A of s)_r.test(A)||(process.stderr.write(`Not an SObject API name: "${A}"
140
+ `,Kr=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,Yr="MAX_TOTAL_EXCEEDED",Qr="AUTOPILOT_EMAILS_EXCEEDED",Xr="AUTOPILOT_CANNOT_FIT",Jr={switches:["--standard-objects","--keep-contact-points","--plan-only","--json","--fail-on-partial","--mute-automation","--accept-emails",...Bt.switches],values:["--source","--target","--object","--max-depth","--max-objects","--max-total","--max-records-per-object","--compliance","--batch-size","--fit","--fit-cap","--fit-within",...Bt.values]};function Vr(l){let e=l.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(Hr),process.exit(0)),on(e,Jr);let t=(w,C)=>{let v=e.indexOf(w);return v>=0&&v+1<e.length?e[v+1]:C},o=w=>{let C=[];for(let v=0;v<e.length;v++)e[v]===w&&v+1<e.length&&C.push(e[v+1]);return C},n=t("--source"),r=t("--target"),s=o("--object");(!n||!r||s.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
141
+ `),process.exit(2));for(let w of s)Kr.test(w)||(process.stderr.write(`Not an SObject API name: "${w}"
138
142
  `),process.exit(2));let i=["none","gdpr","ccpa","hipaa","pci_dss"],a=t("--compliance","none")??"none";i.includes(a)||(process.stderr.write(`--compliance takes ${i.join(", ")} \u2014 not "${a}".
139
143
  `),process.exit(2));let c=Number(t("--batch-size","200")??"200");(!Number.isInteger(c)||c<1||c>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
140
- `),process.exit(2));let d=(A,w)=>{let M=Number(t(A,String(w))??w);return(!Number.isInteger(M)||M<1)&&(process.stderr.write(`${A} takes a whole number, 1 or more.
141
- `),process.exit(2)),M},m=d("--max-depth",Bt),u=d("--max-objects",_t),p=d("--max-total",Qn),g=qo(e),y=A=>{process.stderr.write(`${A}
142
- `),process.exit(2)},f=Xo(e,y);for(let A of Object.keys(f?.caps?.objects??{}))s.includes(A)||y(`--fit-cap ${A}: give ${A} with --object too.`);return{source:o,target:r,objects:s,includeStandardObjects:e.includes("--standard-objects"),compliance:a,batchSize:c,maxDepth:m,maxObjects:u,maxTotal:p,planOnly:e.includes("--plan-only"),keepContactPoints:e.includes("--keep-contact-points"),json:e.includes("--json"),failOnPartial:e.includes("--fail-on-partial"),muteAutomation:e.includes("--mute-automation"),acceptEmails:e.includes("--accept-emails"),...g!==void 0?{checkpointFirst:g}:{},...f?{fit:f}:{}}}function Hr(l){return{...l.share?{share:!0}:{},...l.caps?.objects?{caps:l.caps.objects}:{},...l.caps?.all!==void 0?{all:l.caps.all}:{},...l.withinMB!==void 0?{withinMB:l.withinMB}:{}}}function Kr(l){return async e=>(await We({query:async t=>l.query(t),queryMore:async t=>l.queryMore(t)},e)).records}async function Yr(l=process.argv){let e=Date.now(),t=Wr(l),n=h=>{process[t.json?"stderr":"stdout"].write(`${h}
143
- `)};n(`sandforge autopilot ${t.source} -> ${t.target}`),n(`objects: ${t.objects.join(", ")}`);let o=ze(await dt(t.source)),r=await dt(t.target),s=ze(r),i=t.planOnly?void 0:await Jt(s,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?Go({module:"autopilot",operationId:`sandforge-autopilot-${e}`,request:t.checkpointFirst,session:r,org:zo(r,i??await ct(s)),connect:ze,journalDir:Qo(),say:n}):void 0,c=!1,d=new Map,m=new Map,u=async h=>{let E=m.get(h);if(E)return E;let P=await s.sobject(h).describe(),Y={creatable:new Set(P.fields.filter(X=>X.createable).map(X=>X.name)),recordTypes:gt(P.recordTypeInfos),keyPrefix:P.keyPrefix??null,lookups:$o(P.fields),currencyFields:Pn(P.fields),fields:P.fields.map(X=>({name:X.name,queryable:!0,createable:X.createable,isReference:X.type==="reference",type:X.type,...X.length>0?{length:X.length}:{},...X.externalId?{externalId:!0}:{}}))};return m.set(h,Y),Y},p=new qn,g=()=>({query:async(h,E,P)=>(await o.query(mr(h,E,P))).records,queryByIds:async(h,E)=>{let P=E.map(X=>`'${he(X)}'`).join(", ");return(await o.query(`SELECT FIELDS(ALL) FROM ${h} WHERE Id IN (${P}) LIMIT ${E.length}`)).records},insert:async(h,E)=>{let P=E.map(pe=>{let st={...pe};return delete st.Id,delete st.attributes,st}),Y=bt(await s.sobject(h).create(P,{headers:it()}),h);Y.some(pe=>pe.success)&&(c=!0);let X=Y.filter(pe=>pe.success&&pe.id).map(pe=>pe.id);return d.set(h,[...d.get(h)??[],...X]),Y},update:async(h,E)=>{let P=bt(await s.sobject(h).update(E,{headers:it()}),h);return P.some(Y=>Y.success)&&(c=!0),P},querySource:async h=>(await o.query(h)).records,queryTarget:Kr(s),toolingSource:async h=>(await o.tooling.query(h)).records,toolingTarget:async h=>(await s.tooling.query(h)).records,describeKeyPrefix:async h=>(await u(h)).keyPrefix,describeLookups:async h=>(await u(h)).lookups,describeFields:async h=>(await u(h)).fields,anonymizer:p,remapper:new $e,describeCreateableFields:async h=>(await u(h)).creatable,describeRecordTypes:async h=>(await u(h)).recordTypes,describeRecordTypesAgain:async h=>gt((await s.sobject(h).describe()).recordTypeInfos),describeCurrencyFields:async h=>(await u(h)).currencyFields,countRecordTypes:async h=>{let E=await o.query($n(h));return He(E.records)}}),y=new et({schemaScanner:new Je,graphBuilder:new tt,complianceEngine:new nt,anonymizer:p,planGenerator:new ot,remapper:new $e,createExecutor:()=>new Le(g()),grappeAdapter:new rt});n(`
144
- scanning\u2026`);let f=await y.scanSchemas(o,s,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects},h=>n(` ${h}`)),A=y.buildGraph(f,t.batchSize);n(`graph: ${A.nodes.length} node(s), ${A.edges.length} edge(s)`);let w=t.compliance==="none"?[]:yo(new zn,f.objectDescribes),{rules:M}=y.buildCompliance(t.compliance,[],w),I=y.generatePlan(A,t.compliance,M,f.scope),q=()=>{n(`plan: ${I.waves.length} wave(s), ${I.totalRecords} record(s)`),I.waves.forEach((h,E)=>{n(` wave ${E+1}: ${h.objects.join(", ")}`)});for(let h of Zr(f.scope))n(h);for(let h of es(I))n(h)};q();let Q=h=>new Map(h.map(E=>[E.objectApiName,E.recordCount])),R=Q(A.nodes),S=Nt(I,R,f.personAccounts),F=async()=>{try{return await Xn(s)}catch(h){return{unread:te(h)}}},C=await F(),ee=Ot(S,C),T,L=()=>T??=Vn(s),v,O=()=>v??=Dt(s).read(t.target,Xe(I)).catch(h=>({unread:h instanceof Error?h.message:String(h)})),x,_;if(t.muteAutomation){let h=await O();try{x=await Yn(async()=>Hn(s),h,{writes:(E,P)=>P==="insert"||P==="update"})}catch(E){if(!At(E))throw E;_={code:E.code,message:E.message.replace(/ Nothing was assigned\.$/,"")}}}let W=await Fe(S,C,L,void 0,{readBack:Ne(S),...xe(x?.plan)});n("");for(let h of Tt(S,ee,t.target))n(h);a||n(je(W,t.target));for(let h of yr(f.personAccounts))n(h);if(x)for(let h of Ye(x.muted,t.target))n(` ${h}`);let U,re;if(a&&S.totalRows>0){let h=new Set(S.objects.map(({objectApiName:Y})=>Y)),E=x?.automation??await O(),P={written:Xe(I).filter(Y=>h.has(Y)),running:typeof E.unread=="string"?{firing:[]}:{firing:qe(E,void 0,(Y,X)=>X==="insert"||X==="update").firing}};try{U={ask:P,estimate:await a.scope(P)}}catch(Y){re=kt(Y).replace(/ Nothing was written\.$/,"")}}if(a&&(W=await Fe(S,C,L,U?.estimate,{readBack:Ne(S),...xe(x?.plan)}),n(je(W,t.target)),U))for(let h of Uo(U.estimate))n(h);let z,V;if(t.fit){n(`
145
- fitting\u2026`);let h=co({storage:C,...t.fit.withinMB!==void 0?{withinMB:t.fit.withinMB}:{},api:"unread"in C?await L().catch(E=>({unread:te(E)})):C.dailyApiRequests??{unread:`${t.target}'s /limits did not list them`},otherRequests:Zn(U?.estimate)});if("unread"in h)V={code:xt.STORAGE_UNREAD,message:`The plan cannot be fitted to ${t.target}, whose data storage left could not be read (${h.unread}).`};else try{z=await y.fitPlan(o,{scan:f,graph:A,plan:I,rules:M,mode:Hr(t.fit),budget:h,automation:await O(),...x?.plan?{mutePlan:x.plan}:{},describeLookups:async P=>(await u(P)).lookups,maxRecords:t.maxTotal,batchSize:t.batchSize,onProgress:P=>n(` ${P}`)});let E=(x?.plan?.assign.length??0)>0;for(let P of Jr(z,t.target,E))n(P);z.cannotFit!==void 0&&(V={code:Gr,message:`The plan cannot be fitted to ${t.target}: ${z.cannotFit}.`})}catch(E){V={code:xt.READ_REFUSED,message:`The plan could not be fitted: the source refused a read of it (${te(E)}).`}}if(z?.fitted){({scan:f,graph:A,plan:I}=z.fitted),R=Q(A.nodes),S=Nt(I,R,f.personAccounts),C=await F(),ee=Ot(S,C),T=void 0;let E=new Set(S.objects.map(({objectApiName:P})=>P));if(a&&U){let{ask:P}=U,Y=P.written.filter(X=>E.has(X));if(Y.length<P.written.length){let X={written:Y,running:{firing:P.running.firing.filter(pe=>E.has(pe.objectApiName))}};try{U={ask:X,estimate:await a.scope(X)}}catch(pe){U=void 0,re=kt(pe).replace(/ Nothing was written\.$/,"")}}}W=await Fe(S,C,L,U?.estimate,{readBack:Ne(S),...xe(x?.plan)}),n(""),q(),n("");for(let P of Tt(S,ee,t.target))n(P);n(je(W,t.target));for(let P of yr(f.personAccounts))n(P)}}let ne=await Lo({plan:S,objects:Xe(I),readAutomation:async h=>{if(x?.automation)return x.automation;let E=v?await v:void 0;return E!==void 0&&typeof E.unread!="string"?E:Dt(s).read(t.target,h)},readLimits:()=>to(s)});for(let h of oo(ne.checks,t.target))n(h);ne.unread!==void 0&&n(` emails: not counted, ${ne.unread} could not be read`);let Se=new Set(S.objects.map(({objectApiName:h})=>h)),be=(h,E)=>Se.has(h)&&(E==="insert"||E==="update"),b=S.totalRows>0?await Wn({read:await O(),...x?.plan?{plan:x.plan}:{},writes:be,readDeliverability:async()=>Xt(i??await ct(s))?Gn:Un(s),accepted:t.acceptEmails,target:t.target,run:"autopilot",keepsAddresses:t.keepContactPoints,mayMute:!t.muteAutomation}):void 0,k=b?.gate;k?.line!==void 0&&n(` ${k.line}`);let D=ro(b?.ofRun);D.deliverability!==void 0&&(W=await Fe(S,C,L,U?.estimate,{readBack:Ne(S),...xe(x?.plan),...D}),n(je(W,t.target)));let $=(h,E)=>E===void 0?void 0:{code:h,message:E},j=[$(Qe,re??(U?.estimate.refusal!==void 0?Wo(U.estimate.refusal):void 0)),$(qr,S.totalRows>t.maxTotal?`The run would write ${S.totalRows} records, more than --max-total ${t.maxTotal}: narrow it (--object, --max-depth, --max-objects), or raise --max-total.`:void 0),$(It.STORAGE_EXCEEDED,io(ee,t.target)),$(It.API_BUDGET_EXCEEDED,St(W,t.target)?.replace(/ Nothing was written\.$/,"")),$(zr,no(ne.checks,t.target)),k?.stop?$(k.stop.code,k.stop.message.replace(/ Nothing was written\./,"")):void 0,_,V].filter(h=>h!==void 0),J=j.map(({message:h})=>h);if(!t.fit&&!("unread"in C)&&(ee.verdict==="exceeds"||S.totalRows>t.maxTotal||St(W,t.target)!==void 0)&&n(" --fit share keeps the largest share of the plan that fits, its records whole"),t.planOnly){let h=await new Le(g()).recordTypesGivenOf(I,R,f.parentIds,f.scope.cutShort);for(let P of A.nodes){let Y=h.get(P.objectApiName);Y&&(P.recordTypeGiven=Y)}let E=(x?.plan?.assign.length??0)>0;for(let P of $t(A.nodes,!0,E))n(P);for(let P of j)n(` ${nn(P)}`);t.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",planOnly:!0,graph:A,plan:I,writeGate:{records:S.totalRows,storage:ee,apiRequests:W,personAccounts:Object.fromEntries(f.personAccounts),emails:ne.checks,...ne.unread!==void 0?{emailsUnread:ne.unread}:{},...k?.deliverability?{deliverability:k.deliverability}:{},refusals:J,refusalCodes:j.map(({code:P})=>P)},...Kn(x),...U?{checkpoint:U.estimate}:{},...z?{fit:gr(z)}:{}},null,2)}
146
- `);return}let N=(h,E=[])=>{throw t.json&&process.stdout.write(on({tool:"sandforge-autopilot",source:t.source,target:t.target,elapsedMs:Date.now()-e},h,E)),new Error([h,...E].map(tn).join(`
147
- `))};if(j.length>0){let[h,...E]=j.map(({code:P,message:Y})=>({code:P,message:`${Y} Nothing was written.`}));N(h,E)}n(`
148
- executing\u2026 (REAL)`);let G=new AbortController,K,ie=Zt(h=>{K=h,process.stderr.write(`
144
+ `),process.exit(2));let d=(w,C)=>{let v=Number(t(w,String(C))??C);return(!Number.isInteger(v)||v<1)&&(process.stderr.write(`${w} takes a whole number, 1 or more.
145
+ `),process.exit(2)),v},m=d("--max-depth",Ut),u=d("--max-objects",Wt),p=d("--max-total",ro),g=d("--max-records-per-object",5e4);g>ut&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${ut}.
146
+ `),process.exit(2));let y=Qo(e),f=w=>{process.stderr.write(`${w}
147
+ `),process.exit(2)},R=rr(e,f);for(let w of Object.keys(R?.caps?.objects??{}))s.includes(w)||f(`--fit-cap ${w}: give ${w} with --object too.`);return{source:n,target:r,objects:s,includeStandardObjects:e.includes("--standard-objects"),compliance:a,batchSize:c,maxDepth:m,maxObjects:u,maxTotal:p,maxRecordsPerObject:g,planOnly:e.includes("--plan-only"),keepContactPoints:e.includes("--keep-contact-points"),json:e.includes("--json"),failOnPartial:e.includes("--fail-on-partial"),muteAutomation:e.includes("--mute-automation"),acceptEmails:e.includes("--accept-emails"),...y!==void 0?{checkpointFirst:y}:{},...R?{fit:R}:{}}}function Zr(l){return{...l.share?{share:!0}:{},...l.caps?.objects?{caps:l.caps.objects}:{},...l.caps?.all!==void 0?{all:l.caps.all}:{},...l.withinMB!==void 0?{withinMB:l.withinMB}:{}}}function es(l){return async e=>(await He({query:async t=>l.query(t),queryMore:async t=>l.queryMore(t)},e)).records}async function ts(l=process.argv){let e=Date.now(),t=Vr(l),o=h=>{process[t.json?"stderr":"stdout"].write(`${h}
148
+ `)};o(`sandforge autopilot ${t.source} -> ${t.target}`),o(`objects: ${t.objects.join(", ")}`);let n=Ge(await ft(t.source)),r=await ft(t.target),s=Ge(r),i=t.planOnly?void 0:await rn(s,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?Jo({module:"autopilot",operationId:`sandforge-autopilot-${e}`,request:t.checkpointFirst,session:r,org:Xo(r,i??await pt(s)),connect:Ge,journalDir:or(),say:o}):void 0,c=!1,d=new Map,m=new Map,u=async h=>{let P=m.get(h);if(P)return P;let I=await s.sobject(h).describe(),H={creatable:new Set(I.fields.filter(Q=>Q.createable).map(Q=>Q.name)),recordTypes:At(I.recordTypeInfos),keyPrefix:I.keyPrefix??null,lookups:Ho(I.fields),currencyFields:jn(I.fields),fields:I.fields.map(Q=>({name:Q.name,queryable:!0,createable:Q.createable,isReference:Q.type==="reference",type:Q.type,...Q.length>0?{length:Q.length}:{},...Q.externalId?{externalId:!0}:{}}))};return m.set(h,H),H},p=new Kn,g=()=>({query:async(h,P,I)=>(await n.query(Ar(h,P,I))).records,queryByIds:async(h,P)=>{let I=P.map(Q=>`'${ge(Q)}'`).join(", ");return(await n.query(`SELECT FIELDS(ALL) FROM ${h} WHERE Id IN (${I}) LIMIT ${P.length}`)).records},insert:async(h,P)=>{let I=P.map(pe=>{let at={...pe};return delete at.Id,delete at.attributes,at}),H=St(await s.sobject(h).create(I,{headers:dt()}),h);H.some(pe=>pe.success)&&(c=!0);let Q=H.filter(pe=>pe.success&&pe.id).map(pe=>pe.id);return d.set(h,[...d.get(h)??[],...Q]),H},update:async(h,P)=>{let I=St(await s.sobject(h).update(P,{headers:dt()}),h);return I.some(H=>H.success)&&(c=!0),I},querySource:async h=>(await n.query(h)).records,queryTarget:es(s),toolingSource:async h=>(await n.tooling.query(h)).records,toolingTarget:async h=>(await s.tooling.query(h)).records,describeKeyPrefix:async h=>(await u(h)).keyPrefix,describeLookups:async h=>(await u(h)).lookups,describeFields:async h=>(await u(h)).fields,anonymizer:p,remapper:new De,describeCreateableFields:async h=>(await u(h)).creatable,describeRecordTypes:async h=>(await u(h)).recordTypes,describeRecordTypesAgain:async h=>At((await s.sobject(h).describe()).recordTypeInfos),describeCurrencyFields:async h=>(await u(h)).currencyFields,countRecordTypes:async h=>{let P=await n.query(Gn(h));return Ke(P.records)}}),y=new nt({schemaScanner:new et,graphBuilder:new ot,complianceEngine:new rt,anonymizer:p,planGenerator:new st,remapper:new De,createExecutor:()=>new $e(g()),grappeAdapter:new it});o(`
149
+ scanning\u2026`);let f=await y.scanSchemas(n,s,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects,maxRecordsPerObject:t.maxRecordsPerObject},h=>o(` ${h}`)),R=y.buildGraph(f,t.batchSize);o(`graph: ${R.nodes.length} node(s), ${R.edges.length} edge(s)`);let w=t.compliance==="none"?[]:vo(new Yn,f.objectDescribes),{rules:C}=y.buildCompliance(t.compliance,[],w),v=y.generatePlan(R,t.compliance,C,f.scope),z=()=>{o(`plan: ${v.waves.length} wave(s), ${v.totalRecords} record(s)`),v.waves.forEach((h,P)=>{o(` wave ${P+1}: ${h.objects.join(", ")}`)});for(let h of is(f.scope,t))o(h);for(let h of as(v))o(h)};z();let K=h=>new Map(h.map(P=>[P.objectApiName,P.recordCount])),E=K(R.nodes),A=$t(v,E,f.personAccounts),j=async()=>{try{return await so(s)}catch(h){return{unread:ee(h)}}},M=await j(),te=Ct(A,M),se,T=()=>se??=io(s),O,D=()=>O??=qt(s).read(t.target,Ve(v)).catch(h=>({unread:h instanceof Error?h.message:String(h)})),S,ne;if(t.muteAutomation){let h=await D();try{S=await eo(async()=>Vn(s),h,{writes:(P,I)=>I==="insert"||I==="update"})}catch(P){if(!Ot(P))throw P;ne={code:P.code,message:P.message.replace(/ Nothing was assigned\.$/,"")}}}let N=await Fe(A,M,T,void 0,{readBack:xe(A),...Ie(S?.plan)});o("");for(let h of Mt(A,te,t.target))o(h);a||o(je(N,t.target));for(let h of Sr(f.personAccounts))o(h);if(S)for(let h of Qe(S.muted,t.target))o(` ${h}`);let _,V;if(a&&A.totalRows>0){let h=new Set(A.objects.map(({objectApiName:H})=>H)),P=S?.automation??await D(),I={written:Ve(v).filter(H=>h.has(H)),running:typeof P.unread=="string"?{firing:[]}:{firing:ze(P,void 0,(H,Q)=>Q==="insert"||Q==="update").firing}};try{_={ask:I,estimate:await a.scope(I)}}catch(H){V=vt(H).replace(/ Nothing was written\.$/,"")}}if(a&&(N=await Fe(A,M,T,_?.estimate,{readBack:xe(A),...Ie(S?.plan)}),o(je(N,t.target)),_))for(let h of Vo(_.estimate))o(h);let B,Z;if(t.fit){o(`
150
+ fitting\u2026`);let h=wo({storage:M,...t.fit.withinMB!==void 0?{withinMB:t.fit.withinMB}:{},api:"unread"in M?await T().catch(P=>({unread:ee(P)})):M.dailyApiRequests??{unread:`${t.target}'s /limits did not list them`},otherRequests:co(_?.estimate)});if("unread"in h)Z={code:Dt.STORAGE_UNREAD,message:`The plan cannot be fitted to ${t.target}, whose data storage left could not be read (${h.unread}): give --fit-within <MB>, the most it may take, to fit it to that.`};else try{B=await y.fitPlan(n,{scan:f,graph:R,plan:v,rules:C,mode:Zr(t.fit),budget:h,automation:await D(),...S?.plan?{mutePlan:S.plan}:{},describeLookups:async I=>(await u(I)).lookups,maxRecords:t.maxTotal,batchSize:t.batchSize,onProgress:I=>o(` ${I}`)});let P=(S?.plan?.assign.length??0)>0;for(let I of ss(B,t.target,P))o(I);B.cannotFit!==void 0&&(Z={code:Xr,message:`The plan cannot be fitted to ${t.target}: ${B.cannotFit}.`})}catch(P){Z={code:Dt.READ_REFUSED,message:`The plan could not be fitted: the source refused a read of it (${ee(P)}). Run it again; if the source refuses again, narrow the selection (--object, --max-depth), or run it without --fit where it fits.`}}if(B?.fitted){({scan:f,graph:R,plan:v}=B.fitted),E=K(R.nodes),A=$t(v,E,f.personAccounts),M=await j(),te=Ct(A,M),se=void 0;let P=new Set(A.objects.map(({objectApiName:I})=>I));if(a&&_){let{ask:I}=_,H=I.written.filter(Q=>P.has(Q));if(H.length<I.written.length){let Q={written:H,running:{firing:I.running.firing.filter(pe=>P.has(pe.objectApiName))}};try{_={ask:Q,estimate:await a.scope(Q)}}catch(pe){_=void 0,V=vt(pe).replace(/ Nothing was written\.$/,"")}}}N=await Fe(A,M,T,_?.estimate,{readBack:xe(A),...Ie(S?.plan)}),o(""),z(),o("");for(let I of Mt(A,te,t.target))o(I);o(je(N,t.target));for(let I of Sr(f.personAccounts))o(I)}}let Y=await Ko({plan:A,objects:Ve(v),readAutomation:async h=>{if(S?.automation)return S.automation;let P=O?await O:void 0;return P!==void 0&&typeof P.unread!="string"?P:qt(s).read(t.target,h)},readLimits:()=>uo(s)});for(let h of fo(Y.checks,t.target))o(h);Y.unread!==void 0&&o(` emails: not counted, ${Y.unread} could not be read`);let me=new Set(A.objects.map(({objectApiName:h})=>h)),Be=(h,P)=>me.has(h)&&(P==="insert"||P==="update"),b=A.totalRows>0?await Jn({read:await D(),...S?.plan?{plan:S.plan}:{},writes:Be,readDeliverability:async()=>nn(i??await pt(s))?Qn:Xn(s),accepted:t.acceptEmails,target:t.target,run:"autopilot",keepsAddresses:t.keepContactPoints,mayMute:!t.muteAutomation}):void 0,k=b?.gate;k?.line!==void 0&&o(` ${k.line}`);let x=mo(b?.ofRun);x.deliverability!==void 0&&(N=await Fe(A,M,T,_?.estimate,{readBack:xe(A),...Ie(S?.plan),...x}),o(je(N,t.target)));let $=(h,P)=>P===void 0?void 0:{code:h,message:P},L=[$(Je,V??(_?.estimate.refusal!==void 0?Zo(_.estimate.refusal):void 0)),$(Yr,A.totalRows>t.maxTotal?`The run would write ${A.totalRows} records, more than --max-total ${t.maxTotal}: narrow it (--object, --max-depth, --max-objects), or raise --max-total.`:void 0),$(Lt.STORAGE_EXCEEDED,go(te,t.target)),$(Lt.API_BUDGET_EXCEEDED,Pt(N,t.target)?.replace(/ Nothing was written\.$/,"")),$(Qr,po(Y.checks,t.target)),k?.stop?$(k.stop.code,k.stop.message.replace(/ Nothing was written\./,"")):void 0,ne,Z].filter(h=>h!==void 0),X=L.map(({message:h})=>h);if(!t.fit&&!("unread"in M)&&(te.verdict==="exceeds"||A.totalRows>t.maxTotal||Pt(N,t.target)!==void 0)&&o(" --fit share keeps the largest share of the plan that fits, its records whole"),t.planOnly){let h=await new $e(g()).recordTypesGivenOf(v,E,f.parentIds,f.scope.cutShort);for(let I of R.nodes){let H=h.get(I.objectApiName);H&&(I.recordTypeGiven=H)}let P=(S?.plan?.assign.length??0)>0;for(let I of zt(R.nodes,!0,P))o(I);for(let I of L)o(` ${dn(I)}`);t.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",planOnly:!0,graph:R,plan:v,writeGate:{records:A.totalRows,storage:te,apiRequests:N,personAccounts:Object.fromEntries(f.personAccounts),emails:Y.checks,...Y.unread!==void 0?{emailsUnread:Y.unread}:{},...k?.deliverability?{deliverability:k.deliverability}:{},refusals:X,refusalCodes:L.map(({code:I})=>I)},...Zn(S),..._?{checkpoint:_.estimate}:{},...B?{fit:Rr(B)}:{}},null,2)}
151
+ `);return}let F=(h,P=[])=>{throw t.json&&process.stdout.write(ln({tool:"sandforge-autopilot",source:t.source,target:t.target,elapsedMs:Date.now()-e},h,P)),new Error([h,...P].map(cn).join(`
152
+ `))};if(L.length>0){let[h,...P]=L.map(({code:I,message:H})=>({code:I,message:`${H} Nothing was written.`}));F(h,P)}o(`
153
+ executing\u2026 (REAL)`);let G=new AbortController,W,ie=sn(h=>{W=h,process.stderr.write(`
149
154
  interrupted: the run stops after the call under way, and says what it wrote (Ctrl-C again ends it at once)
150
- `),G.abort()}),H,se,de,ue;try{if(a&&U){let P=U,Y=await eo(()=>a.take(P.ask,P.estimate,{signal:G.signal}));if("stop"in Y){Y.stop.code===Qe&&N({code:Qe,message:jt(Y.stop)}),process.stderr.write(`${jt(Y.stop)}
151
- `),ut(lt(K??"SIGINT"));return}de=Y.checkpoint;for(let X of Ho(Y.checkpoint,t.target,t.muteAutomation))n(X)}let h=x?.prepared?await x.prepared.acquire(`sandforge autopilot ${e}`).catch(P=>{if(!At(P))throw P;return N(P.refusal)}):void 0;se=h?.outcome??x?.muted;let E=h?b?.afterLease(h.outcome,t.acceptEmails):void 0;if(h&&E){se=await h.release();for(let P of Ye(se,t.target))n(P);N({code:E.code,message:E.message})}H=await y.executePlan(I,A,M,R,void 0,G.signal,f.parentIds,{...t.keepContactPoints?{keepContactPoints:!0}:{},...h?{lease:{assigned:h.outcome.assigned.length,giveBack:()=>h.release()}}:{},...z?.fitted?{fit:z.fitted.run}:{}}).finally(async()=>{h&&(se=await h.release())})}finally{if(ie(),a&&de){let h=de;ue=await a.settle(h,c).catch(E=>(n(`warning: the checkpoint '${h.name}' taken before the run, which wrote nothing, could not be deleted (${te(E)}): delete it with ${Bo("checkpoint")} delete --org ${t.target} --checkpoint ${h.checkpointId}`),h));for(let E of Ko(ue))n(E)}}for(let h of se?Ye(se,t.target):[])n(h);let Z=Date.now()-e,we=G.signal.aborted,Oe=Do(H);if(ut(we?lt(K??"SIGINT"):en(Oe,t.failOnPartial)),t.json){let h={status:Oe,...H,...H.stopped===!0?{cancelled:!0}:{}};process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",source:t.source,target:t.target,result:h,created:Object.fromEntries(d),...se?{mutedAutomation:se}:{},...ue?{checkpoint:ue}:{},...z?{fit:gr(z)}:{},elapsedMs:Z,...we?{interrupted:!0}:{}},null,2)}
152
- `),we&&process.stderr.write(`${hr(H)}
153
- `);return}n(`
154
- status: ${Oe}`),n(`written: ${H.totalSuccess} linked: ${H.totalLinked??0} refused: ${H.totalFailure} skipped: ${H.totalSkipped}`),H.skippedObjects.length>0&&n(` skipped: ${H.skippedObjects.join(", ")}`),H.cutSinceFit!==void 0&&n(` cut since the fit: ${H.cutSinceFit}, read naming a record the fit cut`),H.fatalError&&n(` the run died with: ${H.fatalError}`);for(let h of Qr(H))n(h);for(let h of ts(H))n(h);if(we){process.stderr.write(`${hr(H)}
155
- `);return}n(`
156
- done in ${Z}ms`)}function hr(l){let e=l.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${l.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function Qr(l){let e=l.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(n=>`${n.objectApiName}.${n.field} ${n.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`]}function Xr(l){return`${Math.floor(l*1e3)/10} %`}function Vr(l){switch(l.kind){case"trigger":return`what Apex trigger ${l.name} on ${l.objectApiName} creates`;case"notRead":return`what "${l.name}" on ${l.objectApiName} creates: it was not read`;case"share":return`the ${l.name} rows the flows of ${l.objectApiName} create`}}function Jr(l,e,t){let{heldBy:n,report:o}=l,{budget:r}=o;if(l.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${l.cannotFit}`];if(n==="whole")return[`fit: the plan fits as it is, ${o.records} record(s), about ${ve(o.estimateMB)} MB: nothing cut`];let s=ve(r.budgetMB+r.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${r.withinMB??s} MB asked (--fit-within)`,storage:`the largest that fits ${s} MB: ${r.share*100} % of the ${r.remainingMB} MB ${e} says it has left of ${r.maxMB}, ${r.roundingMB} MB kept first for the rounding of what it says`},a=l.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${l.automationUnread})`:r.automationMB>0?`${ve(r.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=n==="caps"?`fit: the caps asked, within the ${s} MB that fit`:`fit: share ${Xr(o.share??1)}, ${i[n]}`,d=Math.max(...o.objects.map(p=>p.objectApiName.length)),m=p=>{let g=p.cutWithParent.reduce((A,w)=>A+w.count,0),y=p.cutSpread+g,f=[...p.cutWithParent.map(A=>`${A.count} with their ${A.parent} (${A.field})`),...p.cutSpread>0?[`${p.cutSpread} spread over the table`]:[]];return` ${p.objectApiName.padEnd(d)} ${p.kept} of ${p.inSource}`+(y>0?` cut ${y}: ${f.join(", ")}`:"")},u=o.emptied.map(p=>`${p.objectApiName}.${p.field} on ${p.count} (`+(p.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...o.objects.map(m),...o.parents.map(p=>` ${p.objectApiName}: ${p.records}, those the kept records name`),...u.length>0?[` left empty: ${u.join(", ")}`]:[],...(r.notCounted??[]).map(p=>` not counted: ${Vr(p)}`),` fitted plan: ${o.records} record(s), about ${ve(o.estimateMB)} MB`+(r.automationMB>0?` and ${ve(r.automationMB)} MB for what its flows create under them`:"")+`; ${o.requestsRead} requests read to fit it`,` ${ao(e)}`]}function gr(l){return{applied:l.fitted!==void 0,...l.report,heldBy:l.heldBy,...l.cannotFit!==void 0?{cannotFit:l.cannotFit}:{},...l.automationUnread!==void 0?{automationUnread:l.automationUnread}:{},...l.fitted?{keptIds:Object.fromEntries(l.keptIds)}:{}}}function Zr(l){let e=new Set((l.cutShort??[]).map(s=>s.objectApiName)),t=l.selected.filter(s=>!e.has(s)),n=[`scope: depth ${l.maxDepth}, at most ${l.maxObjects} object(s)`];if(l.fitted){let s=l.fitted.objects.map(i=>`${i.objectApiName} ${i.kept} of ${i.inSource}`);n.push(` fitted to the target's storage, read by id: ${s.join(", ")}`)}else(t.length>0||l.selected.length===0)&&n.push(` copied whole, as selected: ${t.join(", ")||"(none)"}`);for(let s of l.cutShort??[]){let i=s.total!==void 0?` of ${s.total}`:"";n.push(` ${s.objectApiName}: ${s.copied}${i} record(s) copied, the first by Id -- a run copies no more of a selected object`)}if(l.parents.length>0){n.push(" read by id, only the records the selection references:");for(let s of l.parents)n.push(` ${s.objectApiName.padEnd(40)}${String(s.records).padStart(8)}`)}for(let s of l.standardNeeded)n.push(` ${s.objectApiName} taken though standard objects are off: ${s.neededBy} cannot be left empty`);for(let s of l.followedByDefault??[])n.push(` ${s.objectApiName} followed by default though standard objects are off: ${s.referencedBy.join(", ")} reference${s.referencedBy.length===1?"s":""} it`);let o={depth:`further than ${l.maxDepth} lookup(s)`,objects:`past ${l.maxObjects} object(s)`,standard:"a standard object (--standard-objects to take it)"};if(l.leftEmpty.length>0){n.push(` left empty (${l.leftEmpty.length} lookup(s)):`);for(let s of l.leftEmpty)n.push(` ${s.objectApiName}.${s.fieldApiName} -> ${s.target}: ${o[s.reason]}`+(s.required?" \u2014 required: its records will be refused":""))}let r=l.currencies;return r&&n.push(` currencies the target does not hold active: ${r.notInTarget.join(", ")} \u2014 a record in one is written in ${r.writtenIn}, its corporate currency, its amounts converted at the source's rates (${r.objects.join(", ")})`),n}function yr(l){let e=l.get("Account")??0,t=l.get("Contact")??0;return e===0&&t===0?[]:[` sized as Salesforce counts them: ${[...e>0?[`${e} person account(s) at 4 KB each`]:[],...t>0?[`${t} contact(s) of person accounts at none of their own`]:[]].join(", ")}`]}function es(l){if(l.complianceFramework==="none")return[];let e=l.anonymizationSummary,t=[`anonymization (${l.complianceFramework}): ${e.totalFieldsToAnonymize} field(s) on ${e.objectsWithPii.join(", ")||"no object"}`];for(let n of e.notCovered??[])t.push(` ${n.objectApiName}: no rule for its ${n.missing.join(", ")} \u2014 copied as the source holds them`);return t}function ts(l){let e=[],t=n=>{for(let o of n){let r=o.fields.length>0?` [${o.fields.join(", ")}]`:"";e.push(` ${o.statusCode}${r} x${o.count}: ${o.message}`)}};for(let[n,o]of Object.entries(l.objectOutcomes??{})){let r=o.notSent??0;e.push(` ${n.padEnd(28)} written ${o.written} linked ${o.linked} refused ${o.failed}${r>0?` not sent ${r}`:""}`),t(o.refusals),o.threw!==void 0&&e.push(` FAILED part way: ${o.threw}`),o.lookupsLeftEmpty!==void 0&&e.push(` ${o.lookupsLeftEmpty} record(s) keep a lookup empty: the stop came before the second pass filled it`),o.statusesNotGivenBack!==void 0&&e.push(` ${o.statusesNotGivenBack} record(s) stay drafts: the stop came before their status was given back`);for(let s of o.leftToDefault??[])e.push(` left to the target's default: ${s.field} x${s.count}`);for(let s of o.leftToThePlatform??[])e.push(` ${un(s.count,s.why)}`);o.withTheirPersonAccount!==void 0&&o.withTheirPersonAccount>0&&e.push(` ${o.withTheirPersonAccount} contact(s) of person accounts left to the platform, which wrote each with its account: linked to it, not sent`),o.cutSinceFit!==void 0&&e.push(` ${zt} x${o.cutSinceFit}: read naming a record the fit cut, and left out with it: neither written nor refused`);for(let s of o.currenciesReplaced??[])e.push(` ${Fn(s)}`);for(let s of jo(o.pricesSettled??[]))e.push(` ${s}`)}for(let n of l.failedObjects)l.objectOutcomes?.[n]||e.push(` ${n.padEnd(28)} FAILED: ${l.nodeErrors?.[n]??"(no message)"}`);for(let[n,o]of Object.entries(l.lookups??{}))e.push(` ${n.padEnd(28)} lookups filled ${o.filled} refused ${o.leftEmpty??0}`),t(o.refusals);for(let[n,o]of Object.entries(l.statuses??{}))e.push(` ${n.padEnd(28)} statuses applied ${o.applied} refused ${o.leftDraft??0}`),t(o.refusals);return e.push(...$t(Object.values(l.objectOutcomes??{}),!1)),e}process.argv[1]?.includes("sandforge-autopilot")&&(Yo(),Yr().catch(l=>{process.stderr.write(`${l instanceof Error?l.message:String(l)}
157
- `),process.exit(1)}));export{es as anonymizationLines,gr as autopilotFitJson,Jr as autopilotFitLines,hr as autopilotInterruptedLine,Qr as contactPointLines,Kr as everyPage,Yr as main,ts as outcomeLines,Wr as parseArgs,yr as personAccountLines,Zr as scopeLines};
155
+ `),G.abort()}),U,re,le,ue;try{if(a&&_){let I=_,H=await lo(()=>a.take(I.ask,I.estimate,{signal:G.signal}));if("stop"in H){H.stop.code===Je&&F({code:Je,message:_t(H.stop)}),process.stderr.write(`${_t(H.stop)}
156
+ `),ht(mt(W??"SIGINT"));return}le=H.checkpoint;for(let Q of er(H.checkpoint,t.target,t.muteAutomation))o(Q)}let h=S?.prepared?await S.prepared.acquire(`sandforge autopilot ${e}`).catch(I=>{if(!Ot(I))throw I;return F(I.refusal)}):void 0;re=h?.outcome??S?.muted;let P=h?b?.afterLease(h.outcome,t.acceptEmails):void 0;if(h&&P){re=await h.release();for(let I of Qe(re,t.target))o(I);F({code:P.code,message:P.message})}U=await y.executePlan(v,R,C,E,void 0,G.signal,f.parentIds,{...t.keepContactPoints?{keepContactPoints:!0}:{},...h?{lease:{assigned:h.outcome.assigned.length,giveBack:()=>h.release()}}:{},...B?.fitted?{fit:B.fitted.run}:{}}).finally(async()=>{h&&(re=await h.release())})}finally{if(ie(),a&&le){let h=le;ue=await a.settle(h,c).catch(P=>(o(`warning: the checkpoint '${h.name}' taken before the run, which wrote nothing, could not be deleted (${ee(P)}): delete it with ${ct("checkpoint")} delete --org ${t.target} --checkpoint ${h.checkpointId}`),h));for(let P of tr(ue))o(P)}}for(let h of re?Qe(re,t.target):[])o(h);let J=Date.now()-e,be=G.signal.aborted,Se=Wo(U);if(ht(be?mt(W??"SIGINT"):an(Se,t.failOnPartial)),t.json){let h={status:Se,...U,...U.stopped===!0?{cancelled:!0}:{}};process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",source:t.source,target:t.target,result:h,created:Object.fromEntries(d),...re?{mutedAutomation:re}:{},...ue?{checkpoint:ue}:{},...B?{fit:Rr(B)}:{},elapsedMs:J,...be?{interrupted:!0}:{}},null,2)}
157
+ `),be&&process.stderr.write(`${kr(U)}
158
+ `);return}o(`
159
+ status: ${Se}`),o(`written: ${U.totalSuccess} linked: ${U.totalLinked??0} refused: ${U.totalFailure} skipped: ${U.totalSkipped}`),U.skippedObjects.length>0&&o(` skipped: ${U.skippedObjects.join(", ")}`),U.cutSinceFit!==void 0&&o(` cut since the fit: ${U.cutSinceFit}, read naming a record the fit cut`),U.fatalError&&o(` the run died with: ${U.fatalError}`);for(let h of ns(U))o(h);for(let h of cs(U))o(h);if(be){process.stderr.write(`${kr(U)}
160
+ `);return}o(`
161
+ done in ${J}ms`)}function kr(l){let e=l.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${l.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function ns(l){let e=l.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(o=>`${o.objectApiName}.${o.field} ${o.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`]}function os(l){return`${Math.floor(l*1e3)/10} %`}function rs(l){switch(l.kind){case"trigger":return`what Apex trigger ${l.name} on ${l.objectApiName} creates`;case"notRead":return`what "${l.name}" on ${l.objectApiName} creates: it was not read`;case"share":return`the ${l.name} rows the flows of ${l.objectApiName} create`}}function ss(l,e,t){let{heldBy:o,report:n}=l,{budget:r}=n;if(l.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${l.cannotFit}`];if(o==="whole")return[`fit: the plan fits as it is, ${n.records} record(s), about ${Te(n.estimateMB)} MB: nothing cut`];let s=Te(r.budgetMB+r.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${r.withinMB??s} MB asked (--fit-within)`,storage:`the largest that fits ${s} MB: ${r.share*100} % of the ${r.remainingMB} MB ${e} says it has left of ${r.maxMB}, ${r.roundingMB} MB kept first for the rounding of what it says`},a=l.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${l.automationUnread})`:r.automationMB>0?`${Te(r.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=o==="caps"?`fit: the caps asked, within the ${s} MB that fit`:`fit: share ${os(n.share??1)}, ${i[o]}`,d=Math.max(...n.objects.map(p=>p.objectApiName.length)),m=p=>{let g=p.cutWithParent.reduce((R,w)=>R+w.count,0),y=p.cutSpread+g,f=[...p.cutWithParent.map(R=>`${R.count} with their ${R.parent} (${R.field})`),...p.cutSpread>0?[`${p.cutSpread} spread over the table`]:[]];return` ${p.objectApiName.padEnd(d)} ${p.kept} of ${p.inSource}`+(y>0?` cut ${y}: ${f.join(", ")}`:"")},u=n.emptied.map(p=>`${p.objectApiName}.${p.field} on ${p.count} (`+(p.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...n.objects.map(m),...n.parents.map(p=>` ${p.objectApiName}: ${p.records}, those the kept records name`),...u.length>0?[` left empty: ${u.join(", ")}`]:[],...(r.notCounted??[]).map(p=>` not counted: ${rs(p)}`),` fitted plan: ${n.records} record(s), about ${Te(n.estimateMB)} MB`+(r.automationMB>0?` and ${Te(r.automationMB)} MB for what its flows create under them`:"")+`; ${n.requestsRead} requests read to fit it`,` ${yo(e)}`]}function Rr(l){return{applied:l.fitted!==void 0,...l.report,heldBy:l.heldBy,...l.cannotFit!==void 0?{cannotFit:l.cannotFit}:{},...l.automationUnread!==void 0?{automationUnread:l.automationUnread}:{},...l.fitted?{keptIds:Object.fromEntries(l.keptIds)}:{}}}function is(l,e){let t=new Set((l.cutShort??[]).map(a=>a.objectApiName)),o=l.selected.filter(a=>!t.has(a)),n=[`scope: depth ${l.maxDepth}, at most ${l.maxObjects} object(s)`];if(l.fitted){let a=l.fitted.objects.map(c=>`${c.objectApiName} ${c.kept} of ${c.inSource}`);n.push(` fitted to the target's storage, read by id: ${a.join(", ")}`)}else(o.length>0||l.selected.length===0)&&n.push(` copied whole, as selected: ${o.join(", ")||"(none)"}`);let r=`${ct("clone")} --depth all --source ${e.source} --target ${e.target} --fit share --dry-run`;for(let a of l.cutShort??[]){let c=a.total!==void 0?` of ${a.total}`:"";n.push(` ${a.objectApiName}: ${a.copied}${c} record(s) copied, the first by Id -- --max-records-per-object copies more, up to 1000000; a sample of the whole org that fits the target: ${r}`)}if(l.parents.length>0){n.push(" read by id, only the records the selection references:");for(let a of l.parents)n.push(` ${a.objectApiName.padEnd(40)}${String(a.records).padStart(8)}`)}for(let a of l.standardNeeded)n.push(` ${a.objectApiName} taken though standard objects are off: ${a.neededBy} cannot be left empty`);for(let a of l.followedByDefault??[])n.push(` ${a.objectApiName} followed by default though standard objects are off: ${a.referencedBy.join(", ")} reference${a.referencedBy.length===1?"s":""} it`);let s={depth:`further than ${l.maxDepth} lookup(s)`,objects:`past ${l.maxObjects} object(s)`,standard:"a standard object (--standard-objects to take it)"};if(l.leftEmpty.length>0){n.push(` left empty (${l.leftEmpty.length} lookup(s)):`);for(let a of l.leftEmpty)n.push(` ${a.objectApiName}.${a.fieldApiName} -> ${a.target}: ${s[a.reason]}`+(a.required?" \u2014 required: its records will be refused":""))}let i=l.currencies;return i&&n.push(` currencies the target does not hold active: ${i.notInTarget.join(", ")} \u2014 a record in one is written in ${i.writtenIn}, its corporate currency, its amounts converted at the source's rates (${i.objects.join(", ")})`),n}function Sr(l){let e=l.get("Account")??0,t=l.get("Contact")??0;return e===0&&t===0?[]:[` sized as Salesforce counts them: ${[...e>0?[`${e} person account(s) at 4 KB each`]:[],...t>0?[`${t} contact(s) of person accounts at none of their own`]:[]].join(", ")}`]}function as(l){if(l.complianceFramework==="none")return[];let e=l.anonymizationSummary,t=[`anonymization (${l.complianceFramework}): ${e.totalFieldsToAnonymize} field(s) on ${e.objectsWithPii.join(", ")||"no object"}`];for(let o of e.notCovered??[])t.push(` ${o.objectApiName}: no rule for its ${o.missing.join(", ")} \u2014 copied as the source holds them`);return t}function cs(l){let e=[],t=o=>{for(let n of o){let r=n.fields.length>0?` [${n.fields.join(", ")}]`:"";e.push(` ${n.statusCode}${r} x${n.count}: ${n.message}`)}};for(let[o,n]of Object.entries(l.objectOutcomes??{})){let r=n.notSent??0;e.push(` ${o.padEnd(28)} written ${n.written} linked ${n.linked} refused ${n.failed}${r>0?` not sent ${r}`:""}`),t(n.refusals);let s=n.sentAgainForALock,i=s&&Xe("record(s)",{refused:s.rows,sentAgain:s.rows,written:s.written,stillLocked:s.stillLocked,notSentAgain:0});i&&e.push(` ${i}`),n.threw!==void 0&&e.push(` FAILED part way: ${n.threw}`),n.lookupsLeftEmpty!==void 0&&e.push(` ${n.lookupsLeftEmpty} record(s) keep a lookup empty: the stop came before the second pass filled it`),n.statusesNotGivenBack!==void 0&&e.push(` ${n.statusesNotGivenBack} record(s) stay drafts: the stop came before their status was given back`);for(let a of n.leftToDefault??[])e.push(` left to the target's default: ${a.field} x${a.count}`);for(let a of n.leftToThePlatform??[])e.push(` ${yn(a.count,a.why)}`);n.withTheirPersonAccount!==void 0&&n.withTheirPersonAccount>0&&e.push(` ${n.withTheirPersonAccount} contact(s) of person accounts left to the platform, which wrote each with its account: linked to it, not sent`),n.cutSinceFit!==void 0&&e.push(` ${Yt} x${n.cutSinceFit}: read naming a record the fit cut, and left out with it: neither written nor refused`);for(let a of n.currenciesReplaced??[])e.push(` ${_n(a)}`);for(let a of Uo(n.pricesSettled??[]))e.push(` ${a}`)}for(let o of l.failedObjects)l.objectOutcomes?.[o]||e.push(` ${o.padEnd(28)} FAILED: ${l.nodeErrors?.[o]??"(no message)"}`);for(let[o,n]of Object.entries(l.lookups??{}))e.push(` ${o.padEnd(28)} lookups filled ${n.filled} refused ${n.leftEmpty??0}`),t(n.refusals);for(let[o,n]of Object.entries(l.statuses??{}))e.push(` ${o.padEnd(28)} statuses applied ${n.applied} refused ${n.leftDraft??0}`),t(n.refusals);return e.push(...zt(Object.values(l.objectOutcomes??{}),!1)),e}process.argv[1]?.includes("sandforge-autopilot")&&(nr(),ts().catch(l=>{process.stderr.write(`${l instanceof Error?l.message:String(l)}
162
+ `),process.exit(1)}));export{as as anonymizationLines,Rr as autopilotFitJson,ss as autopilotFitLines,kr as autopilotInterruptedLine,ns as contactPointLines,es as everyPage,ts as main,cs as outcomeLines,Vr as parseArgs,Sr as personAccountLines,is as scopeLines};