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
@@ -1,787 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ar,b as Vo,c as Ku,d as Vu,e as da,f as ca,g as la,h as ua,j as pa}from"./chunk-NM4MDLK4.mjs";import{b as wa,c as ap,d as dp}from"./chunk-BS5T3MOQ.mjs";import{b as ff}from"./chunk-TEOLMRDO.mjs";import{d as Wi,k as Zl,o as eu,q as Di,r as tu}from"./chunk-FQBRBBY4.mjs";import{a as Ju}from"./chunk-YS4G22C2.mjs";import{a as jr}from"./chunk-SCKUIE3R.mjs";import{a as Yu}from"./chunk-QROPNEGY.mjs";import{b as fr,e as Dn}from"./chunk-BZ24IAP5.mjs";import{a as eo,c as Qt,d as _n,e as Zs,f as hr,g as to,h as ei,j as ti}from"./chunk-AV5SWEHP.mjs";import{$ as yp,A as Fe,Aa as Mp,B as Xu,Ba as Bp,Bb as hf,C as Jo,Ca as Lp,Cb as Pa,D as ga,Da as Wp,Db as gf,E as ma,Ea as Dp,Eb as mf,F as Zu,Fa as ka,G as ep,Ga as Sa,Gb as xa,H as tp,Ha as Ta,Hb as Ca,I as np,Ia as _p,Ib as wf,J as rp,Ja as Aa,Jb as yf,K as op,Ka as Dt,Kb as bf,L as sp,La as zp,Lb as Rf,M as ip,N as Vn,Na as Gp,O as Yo,P as hn,Q as cp,Qa as ja,R as lp,Ra as qp,S as up,Sa as Up,T as ya,Ta as Hp,U as pp,Ua as va,V as fp,Va as Kp,W as hp,X as gp,Xa as Vp,Y as mp,Ya as Jp,Z as ba,Za as Yp,_ as wp,aa as ue,ba as Rt,bb as Qp,ca as bp,cb as Xp,da as Rp,db as Ia,ea as Op,fa as kp,fb as Zp,ga as Sp,h as oa,ha as Tp,hb as ef,ia as Qo,ib as tf,ja as Ap,jb as nf,k as xu,ka as Ra,kb as rf,la as Jn,lb as of,m as Cu,ma as jp,mb as $a,na as vp,nb as sf,oa as Ip,ob as af,pb as Ea,qb as df,r as Fu,ra as $p,rb as cf,sa as Ep,sb as lf,ta as Yn,tb as uf,u as Nu,ua as Pp,v as Mu,va as Oa,w as Bu,wa as xp,x as fa,xa as Cp,xb as pf,y as Qu,ya as Fp,z as Kn,za as Np}from"./chunk-36U7IQ6Y.mjs";import{e as Lu,f as Wu,g as sa,h as Uo,i as zu,j as Gu,k as qu,l as Uu,m as Hu,n as aa,o as ha}from"./chunk-XETCPL7E.mjs";import{c as ia,e as Ho,f as Du,g as _u,h as Ko}from"./chunk-K2FBZIXY.mjs";import{a as Ai,b as al,c as dl,d as cl,f as br,g as To,h as ji,n as yl}from"./chunk-Z7X534S4.mjs";import{$ as au,C as Si,H as ko,N as Gn,O as il,P as yr,Q as So,U as pl,V as fl,Z as iu,a as kc,m as ki}from"./chunk-6QSM2WIH.mjs";import{c as Lo,m as du}from"./chunk-WJY54JO7.mjs";import{a as gl,b as Ao,c as ml,d as wl}from"./chunk-T63U4OZJ.mjs";import{d as hl}from"./chunk-DBFJB2B6.mjs";import{h as vi}from"./chunk-NTDN2JQZ.mjs";import{a as Ti}from"./chunk-QSRAEUGZ.mjs";import{a as Yl}from"./chunk-F74IHMGL.mjs";import{b as Ql,c as Li,e as Xl}from"./chunk-M6P5ZZLE.mjs";import{b as Gl,c as kr,d as ql,e as Bo,g as Ul,h as Hl,i as Bi,j as Kl,k as Vl,l as Jl}from"./chunk-Y5CGXLUB.mjs";import{h as zl,i as Mi,j as Mo}from"./chunk-3F5YMM2F.mjs";import{a as bl}from"./chunk-YYZL7UGV.mjs";import{a as Zc,c as Ri,g as el,h as tl,i as nl}from"./chunk-SAR5622P.mjs";import{b as Sn,c as cn}from"./chunk-L776PUMV.mjs";import{A as qn,r as Ii,s as Rr,u as Sl,v as jo,x as $i,y as Ei}from"./chunk-6MUEPV7M.mjs";import{a as Cc,b as Fc,c as Tn,d as Hc,e as Kc,h as Vc,i as Jc,j as Yc,k as Qc,l as Xc,m as bi}from"./chunk-HJC7AIBK.mjs";import{d as An}from"./chunk-OTWRDD6L.mjs";import{c as Zr}from"./chunk-RH3N2H7P.mjs";import{a as Ge,i as Nc,k as lo,n as uo,o as Mc,p as po,q as Bc,r as fo,s as Lc,t as Wc,u as ho,v as Dc,w as go}from"./chunk-ZUTYVST5.mjs";import{a as ll,d as ul}from"./chunk-TUACWKIH.mjs";import{$ as bu,$a as na,Ba as Zi,C as uu,D as Wo,E as pu,Ea as ju,Fa as vu,Ia as Xt,K as Do,L as Sr,M as fu,Ma as Iu,Oa as $u,P as _o,Pa as qo,Q as hu,S as fn,Ta as bt,V as gu,W as mu,Wa as ea,X as wu,Xa as ta,Y as yu,Ya as Eu,Z as qi,_ as Ui,_a as Pu,aa as Ru,ab as ra,ba as Ou,c as pi,da as zo,e as Sc,ea as ku,fa as Tr,g as co,ga as Hi,ha as Su,i as Tc,ia as Tu,j as fi,ja as Go,k as hi,ka as Ki,l as Ac,m as gi,n as mi,pa as Vi,r as Rl,ra as Ji,s as Ol,sa as Yi,w as kl,wa as Qi,xa as Xi,y as Hn,ya as Au}from"./chunk-VXHDBYMI.mjs";import{i as zi,q as Gi,r as cu,s as lu}from"./chunk-ENLBYECD.mjs";import{a as bc,b as ao,c as Rc,e as Oc}from"./chunk-PA3MKJVH.mjs";import{a as Ze}from"./chunk-4TLYUZD5.mjs";import{B as Ml,C as Bl,Ca as su,D as Ll,E as Co,F as Ci,G as Wl,H as Wt,I as pn,J as Fi,K as Dl,L as Or,M as _l,N as Fo,O as jn,a as ac,ca as nu,d as Tl,e as vo,ea as ru,f as Un,g as Al,ga as _i,h as jl,i as Io,j as vl,k as $o,l as Eo,m as Il,n as Pi,o as xi,p as $l,q as El,r as Pl,s as un,t as xl,u as Po,v as Cl,w as Ve,x as Fl,y as Nl,ya as ou,z as xo}from"./chunk-ZLZRU6MO.mjs";import{b as _c,c as yo,d as zc,e as Gc,f as qc,g as bo,i as Uc,l as Ro,m as Oo}from"./chunk-WIO4XO4F.mjs";import{a as yi,c as xc}from"./chunk-EADHKH3A.mjs";import{a as mo,b as wo}from"./chunk-GCOB7K5N.mjs";import{a as wr,c as jc,d as wi,e as vc,f as Ic,g as $c,h as Ec,j as Pc}from"./chunk-INIT2UKJ.mjs";import{a as No,b as Ni}from"./chunk-HF6LAK3G.mjs";import{$ as ui,B as si,C as so,D as zn,E as ze,F as Ce,G as ii,H as mr,K as ai,L as di,M as gc,P as ci,W as li,aa as mc,b as Se,c as tt,ca as wc,e as cc,f as lc,g as uc,h as pc,ia as yc,ja as io,l as fc,m as ni,n as ro,o as ri,p as ye,q as ge,r as gr,s as ln,t as oo,v as oi,y as hc}from"./chunk-CGWXQX75.mjs";import{a as no,h as Me}from"./chunk-TZE3Y7IQ.mjs";import{c as rl,f as ol,j as Oi,k as sl}from"./chunk-SIOZXPFG.mjs";import{b as X}from"./chunk-CA5NAXSU.mjs";import{a as ic,c as dc,g as Of}from"./chunk-MTMH6H2A.mjs";import{Ab as dr,C as kn,Cb as cr,D as Kr,Dc as Js,Eb as Le,Ec as nc,Fb as mt,Gb as wt,Gc as rc,Hb as Vs,Ib as at,K as Ud,Kb as Yd,Lb as yt,Mb as Bt,Mc as Ys,Nb as lr,O as Hd,Ob as Lt,Pb as dt,Qb as ur,R as Vr,Rb as Qd,Rc as Qs,S as Kd,Ub as Xd,Uc as oc,Vb as Zd,W as dn,X as Vd,Zc as sc,_ as Ks,bd as pr,cd as Qr,da as Jd,dc as Wn,fc as Jr,hd as Xr,id as Xs,rc as ec,sc as tc,ub as ar,wc as Yr,zb as Qe}from"./chunk-B45CNPUX.mjs";import{A as W}from"./chunk-7EANH5PY.mjs";import{createHash as Lw,randomUUID as ks}from"node:crypto";import{existsSync as bn,readFileSync as yn,readdirSync as Ww,renameSync as ug,rmSync as kd,statSync as pg,writeFileSync as fg}from"node:fs";import{homedir as Dw}from"node:os";import{basename as _w,dirname as zw,join as Ss,resolve as Et,sep as Gw}from"node:path";function Qn(){let r=process.env[Ju]?.trim();return r===void 0||r===""?void 0:r}function Xn(){return Qn()?.startsWith("sandforge env")===!0}function vn(r,e){return Xn()?e:r}var qg=new Map([["sandforge env",["--sweep","--include-changed"]],["sandforge env, relayed by sandforge mcp",["--include-changed"]],["sandforge mcp",["--mute-automation","--leave-undeletable","--store","--include-changed"]]]);function ft(r){let e=Qn();return e===void 0||qg.get(e)?.includes(r)===!0}function gn(r,e){return ft(r)?r:e===void 0?`this script's own ${r}`:`this script's own ${e} with ${r}`}import{createReadStream as Ug,existsSync as Hg}from"node:fs";import{createInterface as Kg}from"node:readline";var kf=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Vg(r){let e=[],t=Kg({input:Ug(r,"utf8"),crlfDelay:1/0}),n=(o,s)=>{typeof s!="string"||!Number.isFinite(Date.parse(s))||(o.endedAt===void 0||Date.parse(s)>Date.parse(o.endedAt))&&(o.endedAt=s)};for await(let o of t){let s=e.at(-1);if(o.startsWith('{"part":')){try{let{part:p}=JSON.parse(o),f=typeof p?.startedAt=="string"?p.startedAt:void 0;e.push({...f?{startedAt:f}:{},wrote:[]})}catch{e.push({wrote:[]})}continue}if(!s)continue;if(o.startsWith('{"end":')){try{n(s,JSON.parse(o).end?.at)}catch{}continue}let i=du(o);if(i){n(s,i.at),(s.jobEndedAt===void 0||Date.parse(i.orgAt)>Date.parse(s.jobEndedAt))&&(s.jobEndedAt=i.orgAt);continue}if(!o.startsWith('["x"')&&!o.startsWith('["p"')&&!o.startsWith('["g"'))continue;let a;try{a=JSON.parse(o)}catch{continue}if(!Array.isArray(a))continue;let[d,c,l,u]=a;d==="x"?n(s,u):d==="p"&&typeof c=="string"&&kf.test(c)?s.wrote.push(c):d==="g"&&typeof l=="string"&&kf.test(l)&&s.wrote.push(l)}return e}async function Sf(r,e){if(!Hg(r))return[];let t;try{t=await Vg(r)}catch{return[]}let n=[];for(let[o,s]of t.entries()){let i=await e.readAt(r,o).catch(()=>{});if(!i)return[];n.push({part:o,created:i.created,linked:i.remap.linked.flatMap(a=>{let d=i.remap.table[a];return d!==void 0?[d]:[]}),wrote:s.wrote,...s.startedAt?{startedAt:s.startedAt}:{},...s.endedAt?{endedAt:s.endedAt}:{},...s.jobEndedAt?{jobEndedAt:s.jobEndedAt}:{}})}return n}function In(r){let e=Date.parse(r.endedAt??"");if(!Number.isFinite(e))return;let t=Date.parse(r.startedAt??""),n=Date.parse(r.jobEndedAt??"");return{runRecordedAt:new Date(e),runDurationMs:Number.isFinite(t)&&t<=e?e-t:0,endedByItsWrites:!0,...Number.isFinite(n)?{writtenUntil:new Date(n)}:{}}}function Zn(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=In(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function $n(r){return r.flatMap(e=>e.ids)}function Zt(r,e){if(e===void 0)return r.map(n=>({...n,ids:[...n.ids]}));let t=new Set(e.map(n=>n.slice(0,15)));return r.flatMap(n=>{let o=n.ids.filter(s=>t.has(s.slice(0,15)));return o.length>0?[{objectApiName:n.objectApiName,ids:o}]:[]})}function We(r,e=Date.now()){return Math.max(0,e-r)}var Fa=class{listenerMap=new Map;on(e,t){let n=this.listenerMap.get(e);return n||(n=new Set,this.listenerMap.set(e,n)),n.add(t),()=>{n.delete(t)}}emit(e,t){let n=this.listenerMap.get(e);if(n)for(let o of n)try{o(t)}catch(s){Ze.warn("Event listener threw an error",{eventType:String(e),error:X(s)})}}removeAllListeners(){this.listenerMap.clear()}};var vr=class r{constructor(e){this.store=e}store;map=new Map;existing=new Set;updated=new Set;objectOf=new Map;aliases=new Map;createdKeys=new Set;alias(e,t){e!==t&&this.aliases.set(e,t)}add(e,t,n){if(this.store){this.store.setMapping("created",e,t,n);return}this.forgetCreated(e),this.createdKeys.add(t.slice(0,15)),this.map.set(e,t),this.existing.delete(e),this.updated.delete(e),this.label(e,n)}addUpdated(e,t,n){if(this.store){this.store.setMapping("updated",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.delete(e),this.updated.add(e),this.label(e,n)}addExisting(e,t,n){if(this.store){this.store.setMapping("existing",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.add(e),this.updated.delete(e),this.label(e,n)}countsByObject(){if(this.store)return this.store.countsByObject();let e=new Map;for(let[t,n]of this.objectOf){let o=e.get(n)??{objectApiName:n,created:0,linked:0,updated:0};this.existing.has(t)?o.linked++:this.updated.has(t)?o.updated++:o.created++,e.set(n,o)}return[...e.values()].map(({updated:t,...n})=>t>0?{...n,updated:t}:n)}createdByObject(){let e=new Map;if(this.store){for(let{kind:t,sourceId:n,objectApiName:o,earlier:s}of this.store.mappings()){if(t!=="created"||s||!o)continue;let i=e.get(o)??[];i.push(n),e.set(o,i)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}for(let[t,n]of this.objectOf){if(this.existing.has(t)||this.updated.has(t))continue;let o=e.get(n)??[];o.push(t),e.set(n,o)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}forgetCreated(e){let t=this.map.get(e);t!==void 0&&!this.existing.has(e)&&!this.updated.has(e)&&this.createdKeys.delete(t.slice(0,15))}createdTarget(e){return this.store?this.store.createdTarget(e):this.createdKeys.has(e.slice(0,15))}label(e,t){t?this.objectOf.set(e,t):this.objectOf.delete(e)}isExisting(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&(t.kind==="existing"||t.earlier)}return this.existing.has(e)}isCreated(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&t.kind==="created"&&!t.earlier}return this.map.has(e)&&!this.existing.has(e)&&!this.updated.has(e)}wasCreated(e){return this.store?this.store.mapping(e)?.kind==="created":this.isCreated(e)}existingSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="existing"||t).map(({sourceId:e})=>e):[...this.existing]}updatedSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="updated"&&!t).map(({sourceId:e})=>e):[...this.updated]}get(e){let t=this.aliases.get(e)??e;return this.store?this.store.targetOf(t):this.map.get(t)}remapRecord(e,t){let n={...e};for(let o of t){let s=n[o];if(typeof s=="string"){let i=this.aliases.size>0?this.aliases.get(s)??s:s,a=this.store?this.store.targetOf(i):this.map.get(i);a!==void 0&&(n[o]=a)}}return n}persist(){this.store?.flush()}get count(){return this.store?this.store.mappedSize:this.map.size}clear(){this.aliases.clear(),this.map.clear(),this.existing.clear(),this.updated.clear(),this.objectOf.clear(),this.createdKeys.clear()}toJSON(){let e={};if(this.store){for(let{sourceId:t,targetId:n}of this.store.mappings())e[t]=n;return e}for(let[t,n]of this.map)e[t]=n;return e}static fromJSON(e){let t=new r;for(let[n,o]of Object.entries(e))n==="__proto__"||n==="constructor"||n==="prototype"||typeof o=="string"&&t.add(n,o);return t}};var Yg={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},Xo=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??Yg[e]??"Name",i=Me(e),a=Me(s),d=new Map;for(let b of t){let S=b.Id,R=b[s];typeof S=="string"&&typeof R=="string"&&R&&d.set(S,R)}if(d.size===0)return{mappings:[],unmatched:t.map(b=>({sourceId:typeof b.Id=="string"?b.Id:"",matchValue:typeof b[s]=="string"?b[s]:null})).filter(b=>b.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,l=wr(`${c})`),u=wr(", "),p=new Map,f=[],h=l,g=async()=>{if(f.length===0)return;let b=`${c}${f.join(", ")})`;f=[],h=l;for(let S of await this.query(n,b)){let R=S.Id,k=S[s];typeof R=="string"&&typeof k=="string"&&p.set(k,R)}};for(let b of new Set(d.values())){let S=`'${no(b)}'`,R=(f.length>0?u:0)+wr(S);f.length>=xl||f.length>0&&h+R>14e3?(await g(),h+=wr(S)):h+=R,f.push(S)}await g();let m=[],y=[];for(let[b,S]of d){let R=p.get(S);R?m.push({sourceId:b,targetId:R,matchedBy:s,matchValue:S}):y.push({sourceId:b,matchValue:S})}return{mappings:m,unmatched:y}}};function Na(r,e){let t=new Set(r.filter(s=>s.createable).map(s=>s.name)),n=new Set(r.filter(s=>s.updateable!==!1).map(s=>s.name)),o=new Map;for(let s of r)s.picklistValues&&s.picklistValues.length>0&&o.set(s.name,new Set(s.picklistValues));return{creatable:t,updateable:n,picklistValuesByField:o.size>0?o:null,picklistFields:Tl(r,e),fields:r}}async function en(r,e,t){return Na(await r(e,t),t)}function Ma(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function er(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var Qg=new Map;function Tf(r){let{objectApiName:e,records:t,fieldInfos:n,remapper:o,referenceFallback:s,failedObjects:i,writtenObjects:a,neverCopied:d,ownerMappings:c,resolvedLookups:l,targetLacks:u,inactiveOwners:p,excludedFields:f,fieldRename:h,creatableFields:g,updatableFields:m,picklistValuesByField:y,picklistFields:b,recordTypeValues:S,businessAccounts:R,contactPoints:k,decide:A,currencies:w,currencyFields:I=Qg,parentCurrencies:P,pricedIn:v,outsideTheSample:$}=r,E=n.filter(V=>V.isReference).map(V=>V.name),M=new Set(E),Z=k?.forObject(e,n,h),U=V=>g.has(V.name)||h[V.name]!==void 0,H=new Set(n.filter(V=>V.isReference&&(V.referenceTo??[]).some(fe=>i?.has(fe))).map(V=>V.name)),K=new Set(n.filter(V=>{let fe=V.referenceTo??[];return V.isReference&&fe.length===1&&a?.has(fe[0])===!0}).map(V=>V.name)),pe=Oc(n.filter(V=>V.isReference),d),le=b??new Map;return t.map(V=>{let fe=[],se=[],me=[],z=l?.get(V);for(let L of n){if(!L.isReference||f.has(L.name)||z?.[L.name]!==void 0)continue;let Te=U(L),De=Ma(L,m,h[L.name]);if(!Te&&!De)continue;let Ie=V[L.name];if($&&L.name!=="RecordTypeId"&&typeof Ie=="string"&&Ie!==""&&!o.get(Ie)&&$(L,Ie)){se.push(L.name),me.push(h[L.name]??L.name);continue}if(s!=="nullify"&&!H.has(L.name)&&!K.has(L.name)||L.name==="RecordTypeId"||pe.has(L.name))continue;let he=V[L.name];typeof he!="string"||!he||Te&&o.get(he)||(se.push(L.name),fe.push({field:h[L.name]??L.name,sourceRefId:he,targetObjects:L.referenceTo??[],...De?{}:{insertOnly:!0}}))}let Oe=E.filter(L=>L!=="RecordTypeId"),ne=o.remapRecord(V,Oe);for(let L of se)ne[L]=null;for(let[L,Te]of Object.entries(z??{}))ne[L]=Te;let q=ne.OwnerId,ee=!1;typeof q=="string"&&c[q]&&(ne.OwnerId=c[q],ee=!0);let ke=oo(ne,R?.has(V)===!0),te={},F=new Set,Y=[],B=[],G;for(let L of Object.keys(ne)){if(f.has(L))continue;let Te=h[L];if(Te){ne[L]!==null&&(te[Te]=ne[L]),F.add(Te);continue}if(!g.has(L))continue;if(z?.[L]!==void 0){te[L]=z[L];continue}if(L!=="RecordTypeId"&&pe.has(L)&&!(L==="OwnerId"&&ee)){if(s!=="keep")continue;let Ie=ne[L];if(typeof Ie=="string"&&u?.has(Ie)){Y.push(L);continue}if(L==="OwnerId"&&typeof Ie=="string"&&p?.has(Ie)){G=Ie;continue}}else if(s==="keep"&&L!=="RecordTypeId"&&M.has(L)){let Ie=ne[L];if(typeof Ie=="string"&&u?.has(Ie)){B.push(L);continue}}if(Jr(e,L,ke))continue;let De=ne[L];De!==null&&(te[L]=De)}let be=te.RecordTypeId;A?.(te,typeof be=="string"?be:void 0);for(let L of Qd(e,te))delete te[L];let Ae;w&&!F.has(Ge)?Ae=po(te,{read:V[Ge],currencyFields:I,recordTypeDefault:Un(S,be)?.picklists.get(Ge)?.defaultValue,ratesOn:lo(e,V),pricedIn:v?.(V)},w):P&&(Ae=Wc(te,{read:V[Ge],parent:Lc(e,V,E,P.changeOf),currencyFields:I},P.currencies));let ve=vo(te,y,le,Un(S,be),F),ot=fc(e,te);for(let L of ot)delete te[L];return Z?.(te),{source:V,cleaned:te,nullifiedFks:fe.filter(L=>!ot.includes(L.field)),picklistChanges:ve,...Ae?{currencyChange:Ae}:{},...Y.length>0?{lookupsNotCarried:Y}:{},...B.length>0?{lookupsOutsideTheRun:B}:{},...me.length>0?{lookupsOutsideTheSample:me}:{},...G!==void 0?{ownerInactive:G}:{}}})}var Xg=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,Af=Symbol("left to the platform"),Zo=class{constructor(e){this.deps=e}deps;expansionsUsed=0;failedOrphans=new Set;expansionErrors=[];async expandForNode(e){if(!e.enabled||this.expansionsUsed>=e.maxExpansions)return;let{fieldInfos:t,records:n,remapper:o,scopeCache:s}=e,i=new Map,a=t.filter(u=>u.isReference&&u.nillable===!1&&u.name!=="RecordTypeId");for(let u of n)for(let p of a){let f=u[p.name];if(typeof f!="string"||!f||o.get(f)||e.leftToThePlatform?.has(f))continue;let h=await this.parentObjectOf(e,p,f);if(!h)continue;let g=`${h}::${f}`;i.has(g)||i.set(g,{object:h,sourceId:f})}let d=4,c=[];for(let[,u]of i){if(this.expansionsUsed+c.length>=e.maxExpansions)break;let p=`${u.object}::${u.sourceId}`;this.failedOrphans.has(p)||o.get(u.sourceId)||c.push({...u,cacheKey:p})}let l=[c.filter(u=>u.object!==ge),c.filter(u=>u.object===ge)];for(let u of l){let p=[];for(let f=0;f<u.length;f+=d){let h=u.slice(f,f+d).filter(g=>!o.get(g.sourceId));await Promise.all(h.map(async g=>{try{let m=await this.expandSingleOrphanParent(e,g.object,g.sourceId);if(m===Af)return;m&&"id"in m?(this.expansionsUsed++,m.existing?o.addExisting(g.sourceId,m.id,g.object):(o.add(g.sourceId,m.id,g.object),m.owedStatus&&e.oweStatus?.(g.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(g.object,[g.sourceId]),g.object===ye&&ln(m.source)&&p.push(m.source)):(this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:[X(m)]})}}))}p.length>0&&await e.linkPersonContacts?.(p)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!bc(a)),i;return o.length===1?i=s[0]:s.length>0&&(i=await e.objectOf?.(n,s)),i===e.node.objectApiName?void 0:i}buildErrorReport(){return this.failedOrphans.size===0?null:{objectApiName:"__expandOrphanParents__",stage:"insert",failedCount:this.failedOrphans.size,attemptedCount:this.expansionsUsed+this.failedOrphans.size,samples:this.expansionErrors}}async expandSingleOrphanParent(e,t,n){let{sourceOrgId:o,targetOrgId:s,recordTypeMappings:i,recordTypeMapper:a}=e,{anonymize:d,withoutFileContent:c,startAsDraft:l,leftToThePlatform:u}=e;if(!Xg.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let p=Me(t),f=await this.deps.describeFields(o,p),h=c?c(p,f):f,g=Wt(h,e.fieldExclusions?.[p]);g.length===0&&g.push("Id");let m=`SELECT ${g.join(", ")} FROM ${p} WHERE Id = '${no(n)}'`,y=await this.deps.queryRecords(o,m);if(y.length===0)return null;if(u&&u.keep(p,y).length===0)return Af;let b=y[0],S=ln(b),R=S?await e.personAccountsInTarget?.():void 0;if(p===ge&&S&&R!==!1&&e.contactOnItsOwn?.(n)!==!0)throw new Error("Not copied: a person account's contact is written by the platform with its account, never on its own");let k=null;try{k=Na(await this.deps.describeFields(s,p),p)}catch(q){Ze.warn(`[forge] orphan-parent target describe failed for ${t}: ${q instanceof Error?q.message:String(q)}. Falling back to source createable.`)}let A=new Set(h.filter(q=>q.createable).map(q=>q.name)),w=k?er(A,k.creatable):A,I=new Set(e.fieldExclusions?.[p]??[]),P=e.fieldMappings?.[p]??{},v=new Set,$=new Set(await e.maskedFieldsOf?.(p).catch(()=>[])??[]),E=[],M=w.has("RecordTypeId")&&!I.has("RecordTypeId")&&P.RecordTypeId===void 0,Z=p===ye&&S&&(e.businessAccountsAmong?(await e.businessAccountsAmong([b],M)).has(b):R===!1),U=oo(b,Z),H={};for(let q of h){let ee=q.name;if(I.has(ee))continue;let ke=b[ee];if(ke==null)continue;if($.has(ee)){(P[ee]!==void 0||w.has(ee))&&E.push(ee);continue}if(q.isReference&&typeof ke=="string"&&ee!=="RecordTypeId")continue;let te=P[ee];if(te){H[te]=ke,v.add(te);continue}w.has(ee)&&(Jr(p,ee,U)||(H[ee]=ke))}if(e.contactPoints?.forObject(p,h,P)?.(H),k){let q=new Set([...w].filter(ee=>!I.has(ee)&&!P[ee]));await this.checkPicklists(e,p,b,H,k,q,v)}let K=a&&i?a.apply([H],i,q=>Ho(p,q))[0]:H,pe=d?d(p,K,n,h):K,le=l?await l(p,pe):void 0,V=await this.insertParent(e,p,n,pe),fe=V.written,se=V.callId;if(!fe)return null;let me=fe.success?void 0:Hl(fe,pe,void 0),z=fe.errors;if(me){let q=await this.insertParent(e,p,n,zl(pe,me));if(!q.written)return{refused:["No result returned for record",Bi(me,z)]};fe=q.written,se=q.callId}if(fe.success)return E.length>0&&e.onMaskedLeftOut?.(p,E),me&&e.onWrittenWithoutFields?.(p,{rows:1,fields:me.map(q=>({...q,rows:1}))}),{id:fe.id,existing:!1,owedStatus:le,source:b,...se!==void 0?{callId:se}:{}};let Oe=this.deps.describeObject?await this.deps.describeObject(s,p).then(q=>q.keyPrefix,()=>null):null,ne=sl(fe,Oe);return ne.kind==="linked"?{id:ne.id,existing:!0,source:b}:{refused:me?[...fe.errors,Bi(me,z)]:fe.errors}}async insertParent(e,t,n,o){let s=e.calls?.sending(t,[{sourceId:n,payload:o}]),i;try{i=(await this.deps.insertRecords(e.targetOrgId,t,[o]))[0]}catch(a){throw s!==void 0&&bl(a)!=="may-have-written"&&e.calls?.answered(s),a}return s===void 0?{written:i}:i?.success?{written:i,callId:s}:(e.calls?.answered(s),{written:i})}async checkPicklists(e,t,n,o,s,i,a){let d=e.recordTypePicklists?await e.recordTypePicklists.forRows({objectApiName:t,rows:[n],fields:s.picklistFields,written:f=>i.has(f),recordTypeMappings:e.recordTypeMappings,withoutRecordTypes:!s.fields.some(f=>f.name==="RecordTypeId")}):void 0;for(let f of d?.notes??[])e.onRecordTypeNote?.(t,f);let c=o.RecordTypeId,l=n[Ge],u=e.currencies&&i.has(Ge)&&typeof l=="string"&&l!==""?await e.currencies():void 0;if(u){let f=po(o,{read:l,currencyFields:uo(s.fields),recordTypeDefault:Un(d?.byRecordType,c)?.picklists.get(Ge)?.defaultValue,ratesOn:lo(t,n)},u);e.currencyChanges?.add(t,f);let h=n.Id;f&&typeof h=="string"&&e.currencyChangesById?.set(h,f)}let p=vo(o,s.picklistValuesByField,s.picklistFields,Un(d?.byRecordType,c),a);e.picklistChanges?.add(t,p)}};async function*es(r,e){let t=e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):0,n=0,o=[];for await(let s of r){if(t===0){if(s.length===0&&n>0)continue;n++,yield s;continue}for(o=o.length===0?[...s]:[...o,...s];o.length>=t;)n++,yield o.slice(0,t),o=o.slice(t)}(o.length>0||n===0)&&(yield o)}function _t(r,e,t,n,o,s){let{queryPages:i}=r;if(i)return es(s?.all?i(e,t,s):i(e,t),n);if(s?.all)throw new Error("The deps read no archived row: no cursor to read through queryAll.");return es((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function vf(r){let e=async(...n)=>{let[o,s,...i]=n,a=wi(s),d=vc(s,a===void 0?void 0:["Id",a.stamp]);if(!d)return r.queryRecords(...n);let c=await r.queryRecords(o,d.first,...i),l=u=>r.queryRecords(o,u);return a===void 0?$c(c,d,l):Ec(c,d,l,a)},t=(n,o,s)=>Pc(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??jf(),s?.all?i=>Zg(r.queryPages?.(n,i,s)??jf()):i=>r.queryRecords(n,i),wi(o));return new Proxy(r,{get(n,o,s){return o==="queryRecords"?e:o==="queryPages"?n.queryPages?t:void 0:Reflect.get(n,o,s)}})}async function Zg(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*jf(){}function ns(r,e,t={},n){if(!r)return;let o={};for(let s of e.nodes)Mu(s)&&(o[s.objectApiName]=[...s.anonymizeFields]);return{fields:o,methods:{...t},...n?{personalFieldsOf:n}:{}}}var em=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,tm=/@example\.com$/i,Ba="@example.invalid",nm=64,rm=new Set(["fake","mask","preserve_format","shuffle"]);function om(r,e,t){return typeof r!="string"||r===""?r:em.test(r)?e.email(r.replace(tm,Ba),t):`${r.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,nm).replace(/^[._]+|[._]+$/g,"")||"anonymized"}${Ba}`}var ts=class{smartAnonymizer;contactPoints;constructor(e,t){this.smartAnonymizer=new hl(e),this.contactPoints=new Uo(t)}categorizeField(e,t){let n=t.toLowerCase();if(n==="email")return"email";if(n==="phone")return"phone";let o=Ao(e,t);if(o)return o;let s=e.toLowerCase();return s.includes("email")?"email":s.includes("phone")||s.includes("fax")||s.includes("mobile")?"phone":s.includes("firstname")||s.includes("lastname")||s==="name"||gl(e)?"name":s.includes("street")||s.includes("address")||s.includes("city")||s.includes("state")||s.includes("postalcode")||s.includes("zip")||s.includes("country")?"address":s.includes("ssn")||s.includes("national_id")||s.includes("passport")||s.includes("driver")||s.includes("license")?"ssn_id":s.includes("credit")||s.includes("card")||s.includes("cvv")||s.includes("iban")||s.includes("routing")||s.includes("bank")?"financial":"other"}getDefaultMethod(e){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}[e]}getDefaults(){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}}anonymize(e){if(e.fields.length===0)return e.records;let t={...this.getDefaults(),...e.methods},n=e.records.map((a,d)=>({...a,Id:e.sourceIds[d]??""})),o=this.anonymizeRecords(n,e.fields,t,e.objectApiName),s=e.fields.filter(a=>this.categorizeField(a.name,a.type)==="email"),i=rm.has(t.phone)?e.fields.filter(a=>this.categorizeField(a.name,a.type)==="phone"):[];return o.map((a,d)=>{let c=e.records[d],l={...a};for(let u of s)l[u.name]=this.undeliverable(l[u.name],u);for(let u of i)l[u.name]=this.fictionalNumber(c[u.name],l[u.name],u);return"Id"in c?l.Id=c.Id:delete l.Id,l})}undeliverable(e,t){let n=t.length!==void 0&&t.length>0?t.length:void 0;return t.type.toLowerCase()==="email"?om(e,this.contactPoints,n??Lu):typeof e!="string"?e:this.contactPoints.addressesIn(e.replace(/@example\.com(?![\w.-])/gi,Ba),n)}fictionalNumber(e,t,n){if(typeof e!="string")return t;if(!/\d/.test(e))return e;let o=n.length!==void 0&&n.length>0?n.length:void 0;return this.contactPoints.phone(e,o)}anonymizeRecords(e,t,n,o){let s=t.map(a=>{let d=this.categorizeField(a.name,a.type);return{objectApiName:o,fieldApiName:a.name,method:n[d],piiCategory:"PII",aiConfidence:1,userOverridden:!1}}),i=e.map(a=>({...a}));return this.smartAnonymizer.anonymize(i,s,o)}};function sm(r,e){return r.created!==e.created?r.created===void 0?1:e.created===void 0?-1:e.created-r.created:Rt(e.id,r.id)}var im=1e6,Ir=class extends Error{constructor(t,n){super(`Drawing the sample read ${t} records, more than the ${n} it holds at once. Nothing was written. Lower the bound (--fit-within or --max-total), or leave objects out (--exclude-object) or narrow them (--filter).`);this.rows=t;this.most=n;this.name="SampleTooLarge"}rows;most},$r=class extends Error{constructor(){super("The sample was cancelled before it was drawn. Nothing was written."),this.name="SampleCancelled"}},am="AccountId",La=class{values=[];rows=[];get size(){return this.rows.length}push(e,t){let{values:n,rows:o}=this;n.push(e),o.push(t);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(n[i]<=n[s])break;[n[s],n[i]]=[n[i],n[s]],[o[s],o[i]]=[o[i],o[s]],s=i}}pop(){let{values:e,rows:t}=this,n=[e[0],t[0]],o=e.pop(),s=t.pop();if(t.length>0){e[0]=o,t[0]=s;let i=0;for(;;){let a=2*i+1,d=a+1,c=i;if(a<t.length&&e[a]<e[c]&&(c=a),d<t.length&&e[d]<e[c]&&(c=d),c===i)break;[e[i],e[c]]=[e[c],e[i]],[t[i],t[c]]=[t[c],t[i]],i=c}}return n}},rs=class{constructor(e,t,n){this.links=e;this.reader=t;this.options=n}links;reader;options;rows=[];objectOf=[];rootOf=[];whole=[];dead=[];out=[];index=new Map;absent=new Map;wholeRead=new Set;below=new Map;cuts=new Map;needs=new Map;waiting=new Map;pending=new Map;upCursor=0;optionalCursor=0;descended=[];toDescend=[];rowOf(e,t){return this.index.get(e)?.get(ue(t))}isAbsent(e,t){return this.absent.get(e)?.has(ue(t))===!0}wasReadWhole(e){return this.wholeRead.has(e)}alive(e){return this.dead[e]===void 0}get cut(){return this.cuts}belowOf(e){return this.below.get(e)??[]}async openWhole(){let e=new Set;for(let t of this.links.linksOf.values())for(let n of t)n.target==="whole"&&e.add(n.parent);for(let[t,n]of this.links.classes){if(n.kind!=="whole"||n.why==="referenceData"||!(this.links.linksOf.get(t)??[]).some(i=>i.target==="drawn"&&(i.required||this.options.parents==="all"))&&!e.has(t))continue;this.checkSignal();let s=await this.reader.whole(t);this.wholeRead.add(t);for(let i of s){let a=this.register(t,i);this.whole[a]=!0}this.told()}await this.close()}async addRoots(e,t){let n=new Map;e.forEach((o,s)=>{let i=n.get(o.objectApiName)??[];i.push({id:o.id,index:t+s}),n.set(o.objectApiName,i)});for(let[o,s]of[...n].sort(([i],[a])=>i<a?-1:1)){let i=s.filter(({id:a})=>this.rowOf(o,a)===void 0).map(({id:a})=>a).sort(Rt);if(i.length>0){this.checkSignal();let a=await this.reader.rows(o,i);for(let d of a)this.register(o,d);this.markAbsent(o,i),this.told()}for(let{id:a,index:d}of s){let c=this.rowOf(o,a);c===void 0||this.rootOf[c]>=0||(this.rootOf[c]=d,this.toDescend.push(c))}}await this.close()}async close(){for(;;)if(await this.readUp(),!await this.readOptionalParents()&&!await this.readDown())return}requiredHere(e,t){return e.required?!0:e.objectApiName===ge&&e.field===am&&e.parent===ye&&this.rows[t].personAccount===!0}requiredOf(e){let t=this.objectOf[e],{refs:n,also:o}=this.rows[e],s=[],i;for(let a of this.links.linksOf.get(t)??[]){if(!this.requiredHere(a,e))continue;let d=n[a.field];Yn(d,a)&&(a.target==="excluded"?i??="excludedObject":(a.target==="drawn"||this.wholeRead.has(a.parent))&&s.push({objectApiName:a.parent,id:d}))}for(let a of o??[])a.id===null?i??="noParentInSource":this.readable(a.objectApiName)&&s.push({objectApiName:a.objectApiName,id:a.id});return{named:s,...i?{dies:i}:{}}}readable(e){let t=this.links.classes.get(e);return t!==void 0&&(t.kind==="drawn"||this.wholeRead.has(e))}optionalOf(e){let t=this.objectOf[e],{refs:n}=this.rows[e],o=[];for(let s of this.links.linksOf.get(t)??[]){if(s.target!=="drawn"||this.requiredHere(s,e))continue;let i=n[s.field];Yn(i,s)&&o.push({objectApiName:s.parent,id:i})}return o}upTargets(e){let t=this.objectOf[e],{refs:n,also:o}=this.rows[e],s=[];for(let i of this.links.linksOf.get(t)??[]){if(i.target==="excluded"||i.target==="whole"&&!this.wholeRead.has(i.parent)||!this.requiredHere(i,e)&&this.options.parents!=="all")continue;let a=n[i.field];if(!Yn(a,i))continue;let d=this.rowOf(i.parent,a);d!==void 0&&s.push({row:d,field:i.field})}for(let i of o??[]){if(i.id===null||!this.readable(i.objectApiName))continue;let a=this.rowOf(i.objectApiName,i.id);a!==void 0&&s.push({row:a,field:`(${i.objectApiName})`})}return s}async readUp(){for(;;){for(;this.upCursor<this.rows.length;this.upCursor++){let e=this.upCursor,{named:t,dies:n}=this.requiredOf(e);n&&this.kill(e,n);for(let o of t)this.need(e,o)}if(this.pending.size===0)return;await this.readPending()}}async readOptionalParents(){if(this.options.parents!=="all")return!1;for(;this.optionalCursor<this.upCursor;this.optionalCursor++){let e=this.optionalCursor;if(this.alive(e))for(let t of this.optionalOf(e))this.ask(t)}return this.pending.size===0?!1:(await this.readPending(),!0)}async readDown(){let e=new Map,t=this.toDescend;this.toDescend=[];for(let n of t)if(!(this.descended[n]||!this.alive(n))){this.descended[n]=!0;for(let o of this.links.carriersInto.get(this.objectOf[n])??[]){let s=`${o.objectApiName}.${o.field}`,i=e.get(s);i||(i={masterDetail:o.masterDetail,parents:new Map,objects:new Set},e.set(s,i)),i.objects.add(o.parent),i.parents.set(ue(this.rows[n].id),n)}}if(e.size===0)return!1;for(let[n,o]of[...e].sort(([s],[i])=>s<i?-1:1)){let s=n.indexOf("."),i={objectApiName:n.slice(0,s),field:n.slice(s+1),parents:[...o.objects].sort(),masterDetail:o.masterDetail},a=i.masterDetail?"all":this.options.children,d=[...o.parents.values()].map(f=>this.rows[f].id).sort(Rt);this.checkSignal();let c=await this.reader.children(i,d,a),l=new Map;for(let f of c.rows){let h=f.refs[i.field];if(typeof h!="string"||h==="")continue;let g=o.parents.get(ue(h));if(g===void 0)continue;let m=l.get(g)??new Map;m.has(ue(f.id))||m.set(ue(f.id),f),l.set(g,m)}let u=new Map;for(let[f,h]of c.counts??[])u.set(ue(f),h);let p=this.cuts.get(n)??new Map;for(let[f,h]of[...l].sort(([g],[m])=>g-m)){let g=[...h.values()].sort(sm),m=a==="all"?g:g.slice(0,a),y=this.below.get(f)??[];for(let S of m){let R=this.register(i.objectApiName,S);y.push({child:R,relation:n}),this.descended[R]||this.toDescend.push(R)}this.below.set(f,y);let b=u.get(ue(this.rows[f].id))??h.size;b>m.length&&p.set(f,b-m.length)}p.size>0&&this.cuts.set(n,p),this.told()}return!0}need(e,t){let n=this.rowOf(t.objectApiName,t.id);if(n!==void 0){this.tie(n,e);return}if(this.isAbsent(t.objectApiName,t.id)){this.kill(e,"noParentInSource");return}let o=`${t.objectApiName}
8
- ${ue(t.id)}`,s=this.waiting.get(o)??[];s.push(e),this.waiting.set(o,s),this.ask(t)}ask(e){if(this.rowOf(e.objectApiName,e.id)!==void 0||this.isAbsent(e.objectApiName,e.id))return;let t=this.pending.get(e.objectApiName)??new Map;t.set(ue(e.id),e.id),this.pending.set(e.objectApiName,t)}async readPending(){let e=[...this.pending].sort(([t],[n])=>t<n?-1:1);this.pending.clear();for(let[t,n]of e){let o=[...n.values()].sort(Rt);this.checkSignal();let s=await this.reader.rows(t,o);for(let i of s)this.register(t,i);this.markAbsent(t,o),this.told()}}markAbsent(e,t){for(let n of t){if(this.rowOf(e,n)!==void 0)continue;let o=this.absent.get(e)??new Set;o.add(ue(n)),this.absent.set(e,o);let s=`${e}
9
- ${ue(n)}`;for(let i of this.waiting.get(s)??[])this.kill(i,"noParentInSource");this.waiting.delete(s)}}register(e,t){let n=this.index.get(e);n||(n=new Map,this.index.set(e,n));let o=ue(t.id),s=n.get(o);if(s!==void 0)return s;let i=this.rows.length;this.rows.push(t),this.objectOf.push(e),this.rootOf.push(-1),this.whole.push(!1),this.dead.push(void 0),this.out.push(!1),this.descended.push(!1),n.set(o,i);let a=this.options.maxRows??im;if(this.rows.length>a)throw new Ir(this.rows.length,a);if(t.outsideFilter)this.out[i]=!0,this.kill(i,"outsideFilter");else if(typeof t.recordTypeId=="string"&&t.recordTypeId!==""){let c=this.options.recordTypeVerdict?.(e,t.recordTypeId);c&&this.kill(i,c)}let d=this.waiting.get(`${e}
10
- ${o}`);if(d){this.waiting.delete(`${e}
11
- ${o}`);for(let c of d)this.tie(i,c)}return i}tie(e,t){let n=this.needs.get(e)??[];n.push(t),this.needs.set(e,n),this.alive(e)||this.kill(t,this.out[e]?"outsideFilter":"withoutParent")}kill(e,t){if(!this.alive(e))return;this.dead[e]=t;let n=[e];for(;n.length>0;){let o=n.pop(),s=this.out[o]?"outsideFilter":"withoutParent";for(let i of this.needs.get(o)??[])this.alive(i)&&(this.dead[i]=s,n.push(i))}}checkSignal(){if(this.options.signal?.aborted)throw new $r}told(){this.options.onRows?.(this.rows.length)}thresholds(e=new Set){let t=this.rows.length,n=new Float64Array(t).fill(1/0),o=new Array(t),s=new Array(t),i=new La;for(let c=0;c<t;c++){let l=this.rootOf[c];l>=0&&!e.has(l)&&(n[c]=l,i.push(l,c))}let a=new Uint8Array(t);for(;i.size>0;){let[c,l]=i.pop();if(!(a[l]||c>n[l]||!this.alive(l))){a[l]=1;for(let{child:u,relation:p}of this.below.get(l)??[])c<n[u]?(n[u]=c,s[u]=p,i.push(c,u)):c===n[u]&&p<(s[u]??"")&&(s[u]=p)}}let d=new Float64Array(n);for(let c=0;c<t;c++)this.whole[c]&&(d[c]=-1),d[c]!==1/0&&i.push(d[c],c),o[c]=s[c];for(a.fill(0);i.size>0;){let[c,l]=i.pop();if(!(a[l]||c>d[l]||!this.alive(l))){a[l]=1;for(let{row:u,field:p}of this.upTargets(l)){let f=`${this.objectOf[l]}.${p}`;c<d[u]?(d[u]=c,o[u]=f,i.push(c,u)):c===d[u]&&o[u]!==void 0&&f<o[u]&&(o[u]=f)}}}return{threshold:d,above:n,via:o}}};var Ef={bytes:(r,e)=>e.bytes??uu(r,e.personAccount?{IsPersonAccount:!0}:{}),wholeBytes:(r,e)=>Wo(r,{rows:e})},dm=[{objectApiName:ge,field:"AccountId",writes:"AccountContactRelation",ownField:"ContactId",pairField:"AccountId"},{objectApiName:"Opportunity",field:"ContactId",writes:"OpportunityContactRole",ownField:"OpportunityId",pairField:"ContactId"}],cm=.1,lm=256,um=5;function Wa(r,e){return e<0?-1/0:e===1/0?1/0:r[e].rank}function Pf(r,e){let t=r.rows[e];return t.matched||r.objectOf[e]===ge&&t.personAccount===!0?0:1}function pm(r,e,t){let n=new Map,{links:o}=r,s=t.filter(i=>o.classes.has(i.writes)&&(o.linksOf.get(i.objectApiName)??[]).some(a=>a.field===i.field));if(s.length===0)return n;for(let i=0;i<r.rows.length;i++)if(r.alive(i))for(let a of s){if(r.objectOf[i]!==a.objectApiName)continue;let d=r.rows[i];if(a.objectApiName===ge&&d.personAccount)continue;let c=d.refs[a.field],l=Cp(o,a.objectApiName,a.field,c);if(!l||typeof c!="string")continue;let u=r.rowOf(l.parent,c);if(u===void 0||!r.alive(u))continue;let p=Math.max(e.threshold[i],e.threshold[u]);p!==1/0&&n.set(`${a.writes}
12
- ${ue(d.id)}
13
- ${ue(c)}`,{objectApiName:a.writes,threshold:p,rows:[]})}for(let i=0;i<r.rows.length;i++)if(r.alive(i))for(let a of s){if(r.objectOf[i]!==a.writes)continue;let{refs:d}=r.rows[i],c=d[a.ownField],l=d[a.pairField];if(typeof c!="string"||typeof l!="string")continue;let u=n.get(`${a.writes}
14
- ${ue(c)}
15
- ${ue(l)}`);u&&u.rows.push(i)}for(let i of n.values())i.rows.sort((a,d)=>e.threshold[a]-e.threshold[d]||Rt(r.rows[a].id,r.rows[d].id));return n}function fm(r,e,t){let{measure:n,draw:o}=t,s=[],i=new Float64Array(r.rows.length),a=new Map,d=(u,p)=>{u>=0&&u!==1/0&&a.set(u,(a.get(u)??0)+p)},c=pm(r,e,t.platformPairs??dm),l=new Set;for(let u of c.values())u.rows.length>0&&l.add(u.rows[0]);for(let u=0;u<r.rows.length;u++){if(!r.alive(u))continue;let p=r.objectOf[u],f=r.rows[u],h=l.has(u)?0:Pf(r,u),m=(f.matched||l.has(u)?0:n.bytes(p,f))+h*(n.roomBytes?.(p)??0);i[u]=m;let y=e.threshold[u];y!==1/0&&(s.push({rank:Wa(o.roots,y),bytes:m,records:h,objectApiName:p}),d(y,m))}for(let u of c.values()){let p=n.bytes(u.objectApiName,{id:"",refs:{}});s.push({rank:Wa(o.roots,u.threshold),bytes:p,records:0,objectApiName:u.objectApiName}),d(u.threshold,p)}for(let[u,p]of r.links.classes){if(p.kind!=="whole"||r.wasReadWhole(u))continue;let f=t.sourceRows.get(u)??0,h=p.why==="referenceData",g=h?0:f;s.push({rank:-1/0,bytes:(h?0:n.wholeBytes(u,f))+g*(n.roomBytes?.(u)??0),records:g,objectApiName:u})}return s.sort((u,p)=>u.rank-p.rank),{items:s,rowBytes:i,parts:a,pairs:c}}function xf(r,e,t){let n=0,o=0,s=new Map;for(let i of r){if(i.rank>e)break;n+=i.bytes,o+=i.records,t&&i.records>0&&s.set(i.objectApiName,(s.get(i.objectApiName)??0)+i.records)}return{bytes:n,records:o,written:s}}function os(r,e,t){let n=xf(r,e,t.requests!==void 0);return n.bytes>t.bytes?t.bytesLimit:t.maxTotal!==void 0&&n.records>t.maxTotal?"maxTotal":t.requests?.(n.written)}function If(r,e,t){let n=cm*Math.max(0,e.roomBytes),o=new Set;e.draw.floor>0&&e.draw.roots.forEach((i,a)=>{i.rank===0&&o.add(a)});let s=Cf(r);for(s!==void 0&&o.add(s);;){let i=r.thresholds(t),a=fm(r,i,e),d=[...a.parts].filter(([c,l])=>l>n&&!t.has(c)&&!o.has(c)).map(([c])=>c);if(d.length===0)return{thresholds:i,weighed:a};for(let c of d)t.add(c)}}function Cf(r){let e;for(let t=0;t<r.rows.length;t++){let n=r.rootOf[t];n>=0&&r.alive(t)&&(e===void 0||n<e)&&(e=n)}return e}function $f(r,e,t,n){let o=xf(e,t,!1),s=new Map;for(let i of e){if(i.rank>t)break;let a=s.get(i.objectApiName)??{rows:0,storageBytes:0};a.rows+=i.records,a.storageBytes+=i.bytes,s.set(i.objectApiName,a)}return{kind:"cannotFit",limitedBy:os(e,t,n)??n.bytesLimit,rows:o.records,storageBytes:o.bytes,heaviest:[...s].sort(([i,a],[d,c])=>c.storageBytes-a.storageBytes||(i<d?-1:i>d?1:0)).slice(0,um).map(([i,a])=>({objectApiName:i,...a,...r.links.classes.get(i)?.kind==="whole"?{whole:!0}:{}}))}}async function Ff(r){let e=r.draw.roots.filter(c=>c.rank<r.draw.beyond),t={...r,draw:{...r.draw,roots:e}},{bounds:n}=t,o=new rs(t.links,t.reader,{...t.options,onRows:c=>{t.options.onRows?.(c),t.onStep?.("closing",c)}});await o.openWhole();let s=new Set,i=0,a=lm,d=If(o,t,s);for(;i<e.length;){let c=Math.min(e.length,i+a);for(;c<e.length&&e[c].rank===e[c-1].rank;)c++;if(await o.addRoots(e.slice(i,c),i),i=c,a*=2,d=If(o,t,s),os(d.weighed.items,e[i-1].rank,n)!==void 0)break}return t.onStep?.("fitting",o.rows.length),hm(o,d,s,t,e.slice(0,i),i===e.length)}function hm(r,e,t,n,o,s){let{bounds:i,draw:a}=n,{items:d}=e.weighed,c=[...new Set(o.map(m=>m.rank))].sort((m,y)=>m-y),l=a.floor>0&&c[0]===0?c:[-1/0,...c],u=xu(l.length,m=>os(d,l[m-1],i)===void 0);if(u===0)return $f(r,d,l[0],i);let p=l[u-1],f=Cf(r);if(f!==void 0&&o[f].rank>p)return{...$f(r,d,o[f].rank,i),noRoot:!0};let h=mm(r,e,t,n,p),g=u<l.length?os(d,l[u],i)??i.bytesLimit:!s||a.beyond!==1/0?a.heldBy:h.heavyRoots.length>0?"heavyRoots":"whole";return{kind:"sample",share:g==="whole"||g==="heavyRoots"?1:Math.max(0,p),limitedBy:g,wholeOrgFits:gm(r,n),...h}}function gm(r,e){let t=0,n=0,o=new Map;for(let[i,a]of r.links.classes){let d=e.sourceRows.get(i)??0;a.kind==="whole"&&a.why==="referenceData"||(t+=e.measure.wholeBytes(i,d),n+=d,o.set(i,d))}let{bounds:s}=e;return t<=s.bytes&&(s.maxTotal===void 0||n<=s.maxTotal)&&s.requests?.(o)===void 0}function mm(r,e,t,n,o){let{links:s}=r,{thresholds:i,weighed:a}=e,d=n.draw.roots,c=v=>Wa(d,v),l=v=>r.alive(v)&&c(i.threshold[v])<=o,u=v=>{if(r.whole[v])return"whole";let $=r.rootOf[v];return $>=0&&!t.has($)&&c($)<=o?"root":c(i.above[v])<=o?"below":"parent"},p=new Map,f=v=>{let $=p.get(v);return $||($={objectApiName:v,sourceRows:n.sourceRows.get(v)??0,kept:0,roots:0,below:0,asParents:0},s.classes.get(v)?.kind==="whole"&&($.whole=!0),p.set(v,$)),$},h=new Map,g=new Map,m=new Map,y=new Map,b=new Set;for(let v of a.pairs.values())v.rows.length>0&&b.add(v.rows[0]);let S=0,R=0,k=0,A=v=>n.measure.roomBytes?.(v)??0;for(let v=0;v<r.rows.length;v++){let $=r.objectOf[v];if(!r.alive(v)){let U=r.dead[v];if(r.out[v]||U===void 0||c(i.threshold[v])>o)continue;let H=`${$}
16
- ${U}`,K=m.get(H)??{objectApiName:$,rows:0,reason:U};K.rows++,m.set(H,K);continue}if(!l(v))continue;let E=r.rows[v],M=h.get($)??[];M.push(E.id),h.set($,M),R+=a.rowBytes[v];let Z=b.has(v)?0:Pf(r,v);if(S+=Z,k+=Z*A($),E.personAccount&&($===ye||$===ge)&&g.set($,(g.get($)??0)+1),!E.matched){let U=f($);U.kept++;let H=u(v);H==="root"?U.roots++:H==="below"?U.below++:H==="parent"&&U.asParents++}for(let U of s.linksOf.get($)??[]){if(U.target==="excluded"||U.target==="whole"&&!r.wasReadWhole(U.parent))continue;let H=E.refs[U.field];if(!Yn(H,U))continue;let K=r.rowOf(U.parent,H);if(K!==void 0&&l(K))continue;let pe=`${$}
17
- ${U.field}`,le=y.get(pe)??{objectApiName:$,field:U.field,rows:0};le.rows++,y.set(pe,le)}}for(let[v,$]of s.classes){if($.kind!=="whole"||r.wasReadWhole(v))continue;let E=n.sourceRows.get(v)??0,M=f(v);M.kept=E,$.why!=="referenceData"&&(S+=E,R+=n.measure.wholeBytes(v,E)+E*A(v),k+=E*A(v))}let w=new Map;for(let v of a.pairs.values()){if(c(v.threshold)>o)continue;let $=w.get(v.objectApiName)??{objectApiName:v.objectApiName,inPlan:0,beyond:0};v.rows.length>0&&l(v.rows[0])?$.inPlan++:$.beyond++,R+=n.measure.bytes(v.objectApiName,{id:"",refs:{}}),w.set(v.objectApiName,$)}for(let[v,$]of r.cut){let E=0;for(let[U,H]of $)l(U)&&c(i.above[U])<=o&&(E+=H);if(E===0)continue;let M=v.indexOf("."),Z=f(v.slice(0,M));Z.childrenCut=[...Z.childrenCut??[],{field:v.slice(M+1),rows:E}]}let I=[...p.values()].filter(v=>v.kept>0).sort((v,$)=>$.kept-v.kept||(v.objectApiName<$.objectApiName?-1:1)),P=[...s.classes].filter(([v,$])=>{let E=n.sourceRows.get(v)??0;return $.kind==="drawn"&&E>0&&(p.get(v)?.kept??0)===0}).map(([v])=>({objectApiName:v,sourceRows:n.sourceRows.get(v)??0})).sort((v,$)=>v.objectApiName<$.objectApiName?-1:1);return{rows:I.reduce((v,$)=>v+$.kept,0),storageBytes:R,automationBytes:k,written:S,objects:I,heavyRoots:ym(r,e,t,d,o),dropped:[...m.values()].sort(Da(v=>v.reason)),leftEmpty:[...y.values()].sort(Da(v=>v.field)),noRecordDrawn:P,partialMasters:wm(s,p,n.sourceRows),ids:new Map([...h].map(([v,$])=>[v,$.sort(Rt)])),personAccounts:g,byThePlatform:[...w.values()].sort((v,$)=>v.objectApiName<$.objectApiName?-1:1)}}function wm(r,e,t){let n=[];for(let[o,s]of r.linksOf){if(r.classes.get(o)?.kind!=="drawn")continue;let i=e.get(o)?.kept??0;for(let a of s){if(!a.masterDetail||a.target==="excluded"||a.parent===o)continue;let d=e.get(a.parent);if(!d||d.kept===0)continue;let c={objectApiName:a.parent,details:o,field:a.field};if(a.target==="whole"){let l=t.get(o)??0;i<l&&n.push({...c,kept:i,sourceRows:l})}else a.carries&&d.asParents>0&&n.push({...c,asParents:d.asParents})}}return n.sort(Da(o=>`${o.details}
18
- ${o.field}`))}function Da(r){return(e,t)=>{if(e.objectApiName!==t.objectApiName)return e.objectApiName<t.objectApiName?-1:1;let n=r(e),o=r(t);return n<o?-1:n>o?1:0}}function ym(r,e,t,n,o){let s=[...t].filter(a=>n[a].rank<=o).sort((a,d)=>a-d);if(s.length===0)return[];let i=[];for(let a of s){let d=new Set(t);d.delete(a);let c=r.thresholds(d),l=0,u=new Map;for(let h=0;h<r.rows.length;h++){if(!r.alive(h)||c.threshold[h]!==a)continue;l++;let g=c.via[h];g!==void 0&&u.set(g,(u.get(g)??0)+e.weighed.rowBytes[h])}let[p]=[...u].sort(([h,g],[m,y])=>y-g||(h<m?-1:h>m?1:0))[0]??[`${n[a].objectApiName}.Id`],f=p.indexOf(".");i.push({objectApiName:n[a].objectApiName,id:n[a].id,rows:l,relation:{objectApiName:p.slice(0,f),field:p.slice(f+1)}})}return i}var mn=class extends Error{constructor(t,n,o){super(n);this.code=t;this.heaviest=o;this.name="SampleRefusedError"}code;heaviest},_a=[wt,yt,dt,Bt,"IsActive"];function Nf(r){return r===!0||r==="true"}function ss(r){return typeof r=="string"&&r!==""?r:null}function bm(r){let e=r.CreatedDate,t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Mf(r){let e=t=>{let n=r[t];return typeof n=="string"?ue(n):""};return[e(wt),e(yt),e(Bt)].join(`
19
- `)}function Bf(r){let e=t=>{let n=r[t];return typeof n=="string"?n:""};return[ue(e(yt)),e(dt),ue(e(Bt))].join(`
20
- `)}var za=class{constructor(e,t,n,o){this.reader=e;this.links=t;this.sourceRows=n;this.priceCurrencyWrittenIn=o}reader;links;sourceRows;priceCurrencyWrittenIn;cappedByIds=new Set;columnsOf(e){let t=[...Oa(this.links,e),"RecordTypeId"];return(e===ye||e===ge)&&t.push("IsPersonAccount"),e===Le&&t.push(..._a),e===mt&&t.push("IsStandard"),t}rowOf(e,t,n=!1){let o={};for(let a of Oa(this.links,e))o[a]=ss(t[a]);let s=t.RecordTypeId,i=bm(t);return{id:String(t.Id),refs:o,...typeof s=="string"||s===null?{recordTypeId:ss(s)}:{},...(e===ye||e===ge)&&Nf(t.IsPersonAccount)?{personAccount:!0}:{},...e===mt&&Nf(t.IsStandard)?{matched:!0}:{},...n?{outsideFilter:!0}:{},...i!==void 0?{created:i}:{}}}async sampleRowsOf(e,t,n=[]){let o=[...t.map(l=>this.rowOf(e,l)),...n.map(l=>this.rowOf(e,l,!0))];if(e!==Le||t.length===0)return o;let s=[...new Set(t.flatMap(l=>{let u=ss(l[yt]);return u?[u]:[]}))],i=await this.reader.readStandardPrices(s,_a.slice(1)),a=new Set(i.map(l=>ue(String(l.Id)))),d=new Map;for(let l of i)d.set(Bf(l),String(l.Id));let c=await this.pricesWrittenFor(t);return o.map((l,u)=>{let p=t[u];if(p===void 0)return l;let f=[];a.has(ue(l.id))||f.push({objectApiName:Le,id:d.get(Bf(p))??null});let h=c.get(l.id);return h!==void 0&&f.push({objectApiName:Le,id:h}),f.length>0?{...l,also:f}:l})}async pricesWrittenFor(e){let t=new Map,n=this.priceCurrencyWrittenIn;if(!n)return t;let o=new Map;for(let s of e){let i=s[dt];if(typeof i!="string")continue;let a=n(i);a===void 0||a===i||o.set(a,[...o.get(a)??[],s])}for(let[s,i]of o){let a=l=>i.flatMap(u=>{let p=ss(u[l]);return p?[p]:[]}),d=await this.reader.readPricesIn(s,a(yt),a(wt),_a),c=new Map(d.map(l=>[Mf(l),String(l.Id)]));for(let l of i){let u=c.get(Mf(l));u!==void 0&&t.set(String(l.Id),u)}}return t}async rows(e,t){let[n]=await this.reader.readParents([{objectApiName:e,ids:t,columns:this.columnsOf(e)}]);return n?this.sampleRowsOf(e,n.rows,n.outsideFilter):[]}async children(e,t,n){let[o]=await this.reader.readChildren([{objectApiName:e.objectApiName,field:e.field,parentIds:t,columns:this.columnsOf(e.objectApiName),cap:n,sourceRows:this.sourceRows.get(e.objectApiName)??Number.MAX_SAFE_INTEGER}]);return o?(o.newestBy==="id"&&o.cut.some(s=>s.rows>0)&&this.cappedByIds.add(e.objectApiName),{rows:await this.sampleRowsOf(e.objectApiName,o.rows),counts:o.counts}):{rows:[]}}async whole(e){let t=[];return await this.reader.readWhole([{objectApiName:e,columns:this.columnsOf(e)}],(n,o)=>{for(let s of o)t.push(s)}),this.sampleRowsOf(e,t)}};function Rm(r,e){let{empty:t,told:n}=xp(r,e),o=r.linksOf.get(e)??[];return[...t.map(s=>({field:s})),...n.map(s=>({field:s,drawnPrefixes:new Set(o.flatMap(i=>i.field===s&&i.carries&&typeof i.prefix=="string"?[i.prefix]:[]))}))]}async function Lf(r){let{options:e,budget:t}=r,n=w=>r.averageBytes?.get(w),o=(w,I)=>{let P=n(w);return P!==void 0?I*P:Wo(w,{rows:I})},s=new Map(r.objects.flatMap(w=>w.rows===void 0?[]:[[w.objectApiName,w.rows]])),i=Pp({objects:r.objects,order:r.order,...r.excluded?{excluded:r.excluded}:{},...r.referenceData?{referenceData:r.referenceData}:{},...e.whole?{whole:e.whole}:{},roomBytes:t.roomBytes,...r.maxRecordsPerObject!==void 0?{maxRecordsPerObject:r.maxRecordsPerObject}:{},wholeBytes:(w,I)=>o(w,I)}),a=(w,I)=>r.fieldsOf(w)?.find(P=>P.name.toLowerCase()===I.toLowerCase()),d=new Fp(r.source,{fieldsOf:w=>r.fieldsOf(w)?.map(I=>I.name),...r.filterOf?{filterOf:r.filterOf}:{},countsBy:(w,I)=>{let P=a(w,"Id")?.aggregatable,v=a(w,I)?.groupable;return P===!1||v===!1?!1:P===!0&&v===!0?!0:void 0},sorts:(w,I)=>a(w,I)?.sortable,...r.onProgress?{onProgress:r.onProgress}:{},...r.signal?{signal:r.signal}:{}}),l=[...i.classes].filter(([,w])=>w.kind==="drawn"&&w.rooted).map(([w])=>w).sort().map(w=>({objectApiName:w,carriers:Rm(i,w)})),u=await d.countRoots(l),p=kp(t.budget.bytes,t.budget.maxTotal),f=u.map(w=>Math.min(w.rows,p)),h=u.reduce((w,I,P)=>w+Np(I,e.draw,f[P],d.readsNewestApart(I.objectApiName)),0),g=r.sourceRequestsLeft;if(g!==void 0&&d.requests+h>Math.floor(fu*g)){let w=d.requests+h;throw new bt(_o,`Drawing the sample reads about ${w} requests of the source, more than a tenth of the ${g} it has left today. Nothing was written, and no id was read past the counts. Draw the most recent records (--fit-draw recent), or narrow the large objects (--filter).`,void 0,void 0,void 0,{api:{kind:"requests",org:"source",estimate:w,remaining:g}})}let m=new Sp(p,e.floor),y=[];if(e.draw==="uniform")await d.drawUniform(l,(w,I)=>{for(let P of I)m.offer(w,P,bp(e.seed,P))});else{let w=new Map(u.map(v=>[v.objectApiName,v.rows])),I=new Map;y=(await d.drawRecent(l.map((v,$)=>({...v,take:f[$]})),(v,$)=>{let E=I.get(v)??0;for(let M of $)m.offer(v,M,Rp(E,w.get(v)??0)),E++;I.set(v,E)})).filter(v=>v.by==="id").map(v=>v.objectApiName)}let{maxTotal:b}=t.budget,S=b!==void 0&&b<Math.floor(t.budget.bytes/Op)?"maxTotal":t.bytesLimit,R=new za(d,i,s,r.priceCurrencyWrittenIn),k=await Ff({links:i,reader:R,draw:{roots:m.drawn(),beyond:m.beyond,heldBy:S,floor:e.floor},sourceRows:s,options:{parents:e.parents,children:e.children,...r.recordTypeVerdict?{recordTypeVerdict:r.recordTypeVerdict}:{},...r.maxRows!==void 0?{maxRows:r.maxRows}:{},...r.signal?{signal:r.signal}:{}},measure:{bytes:(w,I)=>I.bytes??n(w)??Ef.bytes(w,I),wholeBytes:o,...t.automationBytes?{roomBytes:t.automationBytes}:{}},bounds:{bytes:t.budget.bytes,bytesLimit:t.bytesLimit,...b!==void 0?{maxTotal:b}:{},...t.requests?{requests:t.requests}:{}},roomBytes:t.roomBytes,onStep:(w,I)=>r.onProgress?.({step:w,rows:I,requests:d.requests})}),A=[...new Set([...y,...R.cappedByIds])].sort();return{links:i,cut:k,planRequests:d.requests,newestByIds:A}}function Wf(r,e,t){let{cut:n,links:o}=r;return{seed:e.seed,draw:e.draw,floor:e.floor,parents:e.parents,children:e.children,share:n.share,budget:{...t,...n.automationBytes>0?{automationMB:n.automationBytes/1048576}:{},limitedBy:n.limitedBy},rows:n.rows,storageBytes:n.storageBytes,objects:n.objects,whole:o.whole,heavyRoots:n.heavyRoots,dropped:n.dropped,leftEmpty:n.leftEmpty,noRecordDrawn:n.noRecordDrawn,...n.partialMasters.length>0?{partialMasters:n.partialMasters}:{},planRequests:{source:r.planRequests},...r.newestByIds.length>0?{newestByIds:[...r.newestByIds]}:{}}}var Re=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},ad=kr,km={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},$t=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,_f=2e3;function Sm(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,failed:0,alreadyExists:0,unidentified:0,writtenBefore:0,withTheirAccount:0,withTheirEmail:0,teamOwners:0,teamOthers:0,teamValues:{notKept:new Map,unread:new Map},rolesOfTheirOpportunity:0,rolesGiven:0,personContactsUnlinked:0,sentOnTheirOwn:0,onTheirOwnWhy:"",withoutParent:0,withoutParentGroups:new Map,rowsLeft:()=>0,held:new Map,heldWholeRows:0,picklists:new Io,currencies:new ho,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,ownersInactive:0}}function zf(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function Gf(r){return[ui(r.flagsNotKept),Ph(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function Ga(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function qa(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var Tm=5e3,Am=2e3,qf="afterTask",Ua=3,Uf=1e3,Pn=2e3;function Er(r,e,t){return{objectApiName:r,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:e.filter(n=>n.createable).length,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}function jm(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(Le))}function vh(r,e){let t=[];for(let n of e){let o=n.referenceTo??[];if(!n.isReference||o.length!==1||!Qe(r,n.name,n.nillable))continue;let[s]=o;s!==r&&!Ve.has(s)&&t.push(s)}return t}function vm(r,e,t){return vh(r,e).find(n=>t.has(n))}function Im(r,e,t){let n=t.scopeCache;if(!n)return[];let o=new Set(t.graph.edges.filter(i=>i.targetObject===r).map(i=>i.sourceObject)),s=new Set;for(let i of e)if(i.isReference)for(let a of i.referenceTo??[])a!==r&&o.has(a)&&t.readObjects.has(a)&&!Ve.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var $m=3,Em=10,Pm=5;function xm(r,e){let t=e.rows.filter(({objectApiName:s,row:i})=>{let a=i.Id;return typeof a!="string"||!r.heldForExclusions.get(s)?.has(a)});if(t.length===e.rows.length)return e;let n=new Set,o=new Set;for(let{objectApiName:s,row:i,field:a}of t)n.add(String(i[a])),o.add(s);return{ids:n,neededBy:o,rows:t}}function Hf(r,e){let t=r.readAsParents.get(e);return!t||t.count===0?"":`, ${t.count} read by id for the ${[...t.neededBy].sort().join(", ")} records that cannot be written without ${t.count===1?"it":"them"}`}function Kf(r,e){let t=r.get(e)??new Set;if(!r.isRead(e))return new Set(t);let n=r.scopeOf(e);return new Set([...t].filter(o=>!n?.has(o)))}function Pr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function Vf(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function ls(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}function Jf(r){let e=ls(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function Cm(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function Fm(r,e,t){let n=t.filter(i=>i.isReference),o=i=>{let a=n.filter(d=>(d.referenceTo??[]).includes(i));return a.length>0&&a.every(d=>(d.referenceTo??[]).length>1)},s=new Set(Co(e,new Map([[r,t]])).edges.filter(i=>i.targetObject===r&&(i.required===!0||i.type==="master-detail")&&Ll(i)&&!o(i.sourceObject)).map(i=>i.sourceObject));for(let i of n){let a=i.referenceTo??[];a.length!==1||!dr(i)||!Qe(r,i.name,i.nillable)||s.add(a[0])}return s.delete(r),[...s]}function Nm(r,e){return rd(Fr(r.values()),e)}function Fr(r,e=new Map){for(let{field:t,parentObject:n,notInTarget:o,reason:s,recordType:i}of r){let a=`${t}|${n}|${o===!0?"outside":""}|${s??""}`,d=e.get(a)??{field:t,parentObject:n,...o?{notInTarget:o}:{},...s!==void 0?{reason:s}:{},...i?{recordType:i}:{},count:0};d.count++,e.set(a,d)}return e}function rd(r,e){return[...r.values()].sort((t,n)=>n.count-t.count).slice(0,3).map(({field:t,parentObject:n,notInTarget:o,reason:s,recordType:i,count:a})=>({recordSummary:i?`RecordType=${i.developerName} (${a} record${a===1?"":"s"})`:`${t} \u2192 ${n} (${a} record${a===1?"":"s"})`,messages:i?[Oo({...i,recordCount:a})]:[s!==void 0?`Not written: ${s}`:o?`Not written: ${t} may not be left empty, and the target holds no ${n} record of the id it names, outside the run.`:`Not written: ${t} may not be left empty, and the ${n} it points at `+(e.has(n)?"failed in this run.":"was not written by this run.")]}))}var Mm=3,Yf=5e4;function Bm(r,e){return!e||e.size===0?0:r.reduce((t,{node:n,read:o})=>t+(o>0?(e.get(n.objectApiName)??0)*Math.ceil(o/Pn):0),0)}var Qf={field:"",parentObject:"",reason:"the source does not hold it"};function Ha(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}function Lm(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function Wm(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function Xf(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function Dm(r,e,t,n=()=>!0){return t.flatMap(o=>{let s=o.referenceTo??[],[i]=s;return o.isReference&&s.length===1&&i!==e&&n(o.name)&&r.writtenObjects.has(i)&&!r.config.referenceDataObjects.has(i)&&r.turnsEnded.has(i)&&Qe(e,o.name,o.nillable)?[{field:o.name,parent:i}]:[]})}var _m="held back for a record type closed to the user the run writes as",zm="held back for a record type the target has none of";function Zf(r){let e=0,t=0,n=0;for(let o of r)o.recordType?.unmapped?t++:o.recordType?e++:n++;return[...e>0?[{count:e,why:_m}]:[],...t>0?[{count:t,why:zm}]:[],...n>0?[{count:n,why:od}]:[]]}function eh(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function th(r,e){return bi(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,xh(e))}function Gm(r,e,t){let n=r.leftAside.get(e)??new Map;Fr(t,n),r.leftAside.set(e,n)}function qm(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function Um(r){return[...r.leftAside].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t.values()].sort((n,o)=>o.count-n.count).slice(0,3).map(({field:n,parentObject:o,reason:s,count:i})=>({recordSummary:`${n} \u2192 ${o} (${i} record${i===1?"":"s"})`,messages:[`Left aside, not written: ${s??""}`]}))}))}function us(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${lc(n,t)}`).join("")+qm(r,e)}function Hm(r){return[...Km(r),...Um(r)]}function Km(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:uc(o,n),messages:[pc(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Nr(r){return r==="not-creatable"?", which the target org takes no insert of":r==="not-in-target"?", which the target org does not have":", excluded from this run"}function Vm(r){let e=new Map([[void 0,new Set],["not-creatable",new Set],["not-in-target",new Set]]);for(let{excluded:t,target:n}of r)e.get(n)?.add(t);return[...e].filter(([,t])=>t.size>0).map(([t,n])=>`${[...n].sort().join(", ")}${Nr(t)}`).join("; ")}function Jm({field:r,excluded:e,through:t,namedBy:n,target:o}){return n!==void 0?`Not written: the only records that name it are ${n} records held back for ${e}${Nr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Nr(o)}.`:o==="not-creatable"?`Not written: ${r} may not be left empty, and the target org takes no insert of ${e}.`:o==="not-in-target"?`Not written: ${r} may not be left empty, and the target org does not have ${e}.`:e===Lt?`Not written: a price sold under a selling model needs its product's option for that model, and ${e} is excluded from this run.`:`Not written: ${r} may not be left empty, and ${e} is excluded from this run.`}var od="held back for want of their parent",nh=" \u2014 the records that cannot be written without one of those not written are held back",rh={accountNotWritten:"not sent: a person account's contact goes in with its account, which this run did not write",contactNotFound:"not sent: a person account's contact goes in with its account, and the one the platform wrote was not found"};function ps(r){let e=new Map;for(let{excluded:n,namedBy:o,target:s}of r){let i=o!==void 0,a=`${i?"named":"needing"}|${s??""}`,d=e.get(a)??{namedOnly:i,target:s,objects:[]};d.objects.push(n),e.set(a,d)}let t=({namedOnly:n,target:o})=>(n?3:0)+(o===void 0?0:o==="not-creatable"?1:2);return[...e.values()].sort((n,o)=>t(n)-t(o)).map(({namedOnly:n,target:o,objects:s})=>{let i=`${[...new Set(s)].sort().join(", ")}${Nr(o)}`;return{count:s.length,why:n?`held back, named only by records held back for ${i}`:`held back for want of ${i}`}})}function Gt(r,e){return ps(r.heldForExclusions.get(e)?.values()??[])}function xn(r){return r.reduce((e,t)=>e+t.count,0)}function rn(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function fs(r,e=!1){let t=xn(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+rn(r)}function oh(r,e){return us(r,e)+fs(Gt(r,e))}function Ym(r){return[...r.heldForExclusions].map(([e,t])=>{let n=new Map;for(let o of t.values()){let s=`${o.field}|${o.through??""}|${o.namedBy??""}|${o.excluded}|`+(o.target??""),i=n.get(s)??{...o,count:0};i.count++,n.set(s,i)}return{objectApiName:e,stage:"scope",failedCount:t.size,attemptedCount:0,samples:[...n.values()].sort((o,s)=>s.count-o.count).slice(0,3).map(o=>{let s=`${o.count} record${o.count===1?"":"s"}`;return{recordSummary:o.namedBy!==void 0?`named by ${o.namedBy}.${o.field} (${s})`:`${o.field} \u2192 ${o.through??o.excluded} (${s})`,messages:[Jm(o)]}})}})}function Qm(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function sh(r,e,t){for(let n of t){let o=e[n.name];if(typeof o!="string"||o===""||r.remapper.get(o))continue;let s=Qm(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function wn(r,e,t=[]){let n=e+xn(t);return`Held back ${r}, nothing written, ${n} failed${rn(t)}`}function ih(r){return r>0?`, ${r} ${r===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:""}function xr(r,e,t){t<=0||r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t)}function sd(r,e){return r.writtenBefore.from==="resume"?`${e} already in the target, written before the run stopped`:`${e} already in the target from the run retried`}function Ih(r,e){let t=Math.min(r,Math.max(0,e)),n=r-t;return(n>0?`, ${n} linked to records already in the target`:"")+(t>0?`, ${t} linked to records the run created (the target refused them as copies of those)`:"")}var Xm=3;function Ka(r,e,t){let n=r.dryRun?"would be inserted":"succeeded",o=e.updated>0?`, ${e.updated} updated through their external id`:"",s=Ih(e.linked,e.linkedToCreated),i=e.withTheirAccount>0?`, ${e.withTheirAccount} written by the platform with their person account`:"",a=e.withTheirEmail>0?`, ${e.withTheirEmail} written by the platform with their email`:"",d=$h(e.teamOwners,e.teamOthers)+Eh(e.rolesOfTheirOpportunity,e.rolesGiven),c=e.writtenBefore>0?`, ${sd(r,e.writtenBefore)}`:"",l=e.unidentified>0?` (${e.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${e.succeeded} ${n}${o}${s}${a}${i}${d}${c}, ${e.failed+xn(t)} failed${l}${rn(t)}`}function $h(r,e){return(r>0?`, ${r} written by the platform with their opportunity, for its owner`:"")+(e>0?`, ${e} on the team of their opportunity in the target already`:"")}function Eh(r,e){if(r===0)return"";let t=e>0?`, ${e} given the source's fields ${e===1?"it":"they"} lacked`:"";return`, ${r} written by the platform with their opportunity, for its contact${t}`}function Zm(r,e,t){e.forEach(({source:n},o)=>{let s=n.Id,i=t[o]?.[Ce];typeof s=="string"&&(typeof i=="string"&&i!==""?r.contactSentWith.set(s,i):r.contactSentWith.delete(s))})}function ew(r,e){for(let t of["notKept","unread"])for(let[n,o]of e[t])r[t].set(n,(r[t].get(n)??0)+o)}function Ph(r){return[...[...r.notKept].map(([e,t])=>`${t} linked without the source's ${e}: the target's record keeps its own`),...[...r.unread].map(([e,t])=>`${t} linked whose ${e} was not read: the platform writes the record with the opportunity, which a dry run does not write`)].join(", ")}function Cr(r,e,t=!0){let n=[...e.values()].filter(d=>d.namedBy===void 0),o=[...e.values()].filter(d=>d.namedBy!==void 0),s=[...e.values()].every(d=>d.target===void 0),i=d=>s?[...new Set(d.map(c=>c.excluded))].sort().join(", "):Vm(d),a=o.length===0?`every record needs ${i(n)}`:n.length===0?`the only records that name its records are held back for ${i(o)}`:`${n.length} of its records need ${i(n)}, and the only records that name the rest are held back for ${i(o)}`;return`${wn(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function ah(r){let e=new Map(r.readAtItsTurn);for(let[s,i]of r.preread)e.set(s,i);let t=new Map,n=[];for(let[s,{records:i,fieldInfos:a}]of e){let d=a.filter(u=>u.isReference),c=Ve.has(s),l=r.scopeCache?.reachedOf(s);for(let u of i){let p=u.Id,f={row:u,lookups:d};c&&typeof p=="string"&&p!==r.config.rootRecordId&&l?.has(p)!==!0?t.set(p,f):n.push(f)}}let o=new Set;for(let s=n.pop();s;s=n.pop())for(let i of s.lookups){let a=s.row[i.name];if(typeof a!="string"||a===""||o.has(a))continue;o.add(a);let d=t.get(a);d&&n.push(d)}return o}function dh(r,e,t,n){let o=r.namedByRowsHeldBack.get(t);if(!(!o||n.has(t)||t===r.config.rootRecordId)&&!(t===r.standardPricebookId||r.config.writtenBefore.has(t))&&r.scopeCache?.reachedOf(e)?.has(t)!==!0)return o}function ch(r){for(let[e,t]of Object.entries(cr))if(t.object===r)return{parent:e,lookup:t.lookup}}function tw(r,e){return e.filter(t=>t.isReference&&Qe(r,t.name,t.nillable)).map(t=>t.name)}function nw(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function Va(r){return r.size===0?"":`, written without a lookup naming a record the target does not hold, which the platform fills (the owner with the user the run writes as): ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}`}function lh(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Ja(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the target holds no record of these ids, outside the run`}function Ya(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function rw(r){return[...r.lookupsOutsideTheRun].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the target holds no record of these ids, outside the run.`]}))}))}var uh=10;function Qa(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function ph(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function ow(r,e,t){let n=r.ownersInactive.get(e);for(let{ownerInactive:o}of t)o!==void 0&&(n??={rows:0,owners:new Set},n.rows+=1,n.owners.add(o));n&&r.ownersInactive.set(e,n)}function sw(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,uh).join(", "),i=o.length-uh;return{objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`OwnerId \u2192 User (${t} record${t===1?"":"s"})`,messages:[`Written with the user the run writes as for owner: the target holds these owners inactive (${i>0?`${s}, and ${i} more`:s}) and that user may not give a record an inactive owner (Update Records with Inactive Owners). Map them to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line) to give the records to that user.`]}]}})}function is(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function Xa(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function iw(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function En(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function aw(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function dw(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var hs=class extends Error{constructor(e,t){super(`Internal error: ${e} holds more rows than a clone of the whole org reads whole${t===void 0?"":` (${t})`}, which its gate should have refused before anything was written. The run stopped rather than write part of it: raise sandforge.forge.maxRecordsPerObject, or leave the object out.`),this.name="WholeReadPastBoundError"}},fh="files",Za=200,cw=Pn,ed=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function hh(r,e){let t=r.objects.find(n=>n.objectApiName===e);return t||(t={objectApiName:e,planned:0,plannedBytes:0,copied:0,failed:0},r.objects.push(t)),t}function lw(r,e){let t=[];for(let n of e){let o=n.Id,s=n.ParentId;if(typeof o!="string"||typeof s!="string"||!r.remapper.wasCreated(s))continue;let i=n.Name,a=typeof i=="string"&&i!==""?i:o,d=n.ContentType,c=n.BodyLength;t.push({objectApiName:"Attachment",sourceId:o,body:{objectApiName:"Attachment",id:o},name:a,bytes:typeof c=="number"&&Number.isFinite(c)?c:0,hosts:[{id:s}],fields:{Name:a,...typeof d=="string"&&d!==""?{ContentType:d}:{},IsPrivate:n.IsPrivate===!0}})}return t}function gh(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||X(r).includes("INVALID_QUERY_LOCATOR")}function mh(r){if(ac(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:X(r).includes("SERVER_UNAVAILABLE")}function wh(r){return new Promise(e=>setTimeout(e,r))}function uw(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function as(r,e){return ao(e)?Rc(e)?!0:!r.writtenObjects.has(e):!1}function nn(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function yh(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function pw(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(zc)}function xh(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var bh=200,Rh=200,Oh=/[\u0000-\u001f]/;function td(r,e){return!at(e)||r.pricesSwappedSaid.length===0?"":`, ${pa(r.pricesSwappedSaid).join("; ")}`}var fw=/^012000000000000(AAA)?$/;function kh(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var hw=["insert","upsert"],gw=["insert","upsert","update"];function Sh(r,e){let t="";for(let n of hw){let o=r.splitting.sizes.report({objectApiName:e,op:n});if(!o||o.to>=o.from)continue;let s=`${n}\0${e}`,i=o.rows-(r.smallerCallsSaid.get(s)??0);i<=0||(r.smallerCallsSaid.set(s,o.rows),t+=`, ${i} sent ${o.to} at a time after the target's automation hit a Salesforce limit`)}return t}function mw(r,e){let{objectApiName:t}=r,n=r.op==="update"?"lookup updates":"records",o=r.alone+r.notSplit+r.keptWhole,s=r.to<r.from&&r.rows>0?`${t}: ${r.rows} ${n} sent ${r.to} at a time`:`${t}: ${o} ${n} refused for a Salesforce limit`;return{objectApiName:t,stage:"scope",failedCount:0,attemptedCount:r.rows,samples:[{recordSummary:s,messages:[el(r),...r.notSplit>0?[tl(r.notSplit,e,"run")]:[]]}]}}function ww(r){return gw.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>mw(t,nl(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function ds(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=Bp(s),a=o===!0&&n===void 0?Wp(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:l},u)=>d===void 0?[]:[{sourceId:d,fingerprint:Lp(c,i),owes:l,...n!==void 0?{externalKey:Dp(c,n)}:{},...a[u]!==void 0?{jobKey:a[u]}:{}}]),new Date,n)},answered:e=>r.answered(e),opened:(e,t)=>r.jobOpened(e,t),unattributed:(e,t)=>r.createdUnattributed(e,t)}}function Th(r){let e=new Map;for(let{objectApiName:t,id:n,status:o}of r){let s=e.get(t)??[];s.push({id:n,status:o}),e.set(t,s)}return e}var yw=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],bw=new Set(["CreatedDate","LastModifiedDate"]),Rw=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function Ow(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function cs(r){return typeof r=="string"?Date.parse(r):Number.NaN}var Ah="005",id=class{ids=new Set;issued=0;idFor(e){this.issued++;let n=`${e&&/^[A-Za-z0-9]{3}$/.test(e)?e:"000"}SIM${String(this.issued).padStart(12,"0")}`;return this.ids.add(n),n}has(e){return this.ids.has(e)}};function kw(r,e,t){return{...r,bulkWriteRecords:void 0,insertRecords:async(n,o,s)=>{let i=await t(n,o);return s.map(()=>({id:e.idFor(i),success:!0,errors:[]}))}}}function Sw(r,e,t){if(!r||!e)return"notRead";let n=r.source.RecordTypeId;return typeof n=="string"&&n!==""&&t.get(n)?.to===null?"decidedDefault":"RecordTypeId"in r.source&&ia(n)?"masterInSource":"notRead"}function Tw(r,e){return{objectApiName:r,rows:e.rows,why:{...e.why},...e.predicted?{predicted:{...e.predicted}}:{},...e.readBack?{readBack:{...e.readBack,types:e.readBack.types.map(t=>({...t}))}}:{}}}function nd(r,e){return[r[yt],e?r[Bt]:"",r[dt]].map(t=>String(t??"")).join("|")}function jh(r,e){let t=new Set(e??[]);return r.filter(n=>n.createable&&n.queryable&&!n.isReference&&!t.has(n.name)&&(n.type===void 0||Rw.has(n.type)))}var Aw=200,jw="the standard price of its product, which it may not go without, changed since the sample";function vw(r){return r?{sample:r}:{}}function Iw(r){let e=r.options;return{seed:e.seed??dn.seed,draw:e.draw??dn.draw,parents:e.parents??dn.parents,children:e.children??dn.children,floor:e.floor??dn.floor,...e.whole&&e.whole.length>0?{whole:[...e.whole]}:{}}}var tr=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=vf(e)}summarySoFar(){return this.running?this.summaryOf(this.running):void 0}pause(){this.isPaused||(this.isPaused=!0)}resume(){this.isPaused=!1;let e=this.pauseResolve;this.pauseResolve=null,e?.()}abort(){this.isAborted=!0,this.bulkCancel.abort(),this.sampling.abort();let e=this.pauseResolve;this.pauseResolve=null,this.isPaused=!1,e?.()}async bulkTransportOf(e,t){if(e.writeApi!=="auto"||e.dryRun||!this.deps.bulkWriteRecords)return;let n=await this.deps.duplicateRuleObjects?.(t).catch(()=>{}),o=n??Ni;return Ze.info(`[forge] writing through the Bulk API: a job per ${kr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...No,...o].join(", ")}`+(n?"":" (the target did not say which objects its duplicate rules watch)")),this.bulkCancel=new AbortController,this.isAborted&&this.bulkCancel.abort(),{signal:this.bulkCancel.signal,restOnly:new Set([...No,...o]),bulkUnsupported:new Set,manager:new kc(1)}}bulkUpdatesOf(e){let{bulk:t}=e,n=this.deps.bulkWriteRecords;return!t||!n?{}:{bulkUpdate:(o,s)=>n(e.targetOrgId,o,"update",s,{bulkManager:t.manager,signal:t.signal}),restOnly:t.restOnly,bulkUnsupported:t.bulkUnsupported}}async waitIfPaused(){if(this.isAborted)throw new Re("Forge execution was aborted by user request. No further batches will be processed.");if(this.isPaused&&(await new Promise(e=>{this.pauseResolve=e}),this.isAborted))throw new Re("Forge execution was aborted while paused. No further batches will be processed.")}anonymizeRows(e,t,n,o,s,i){let a=e.config.anonymization;if(!e.anonymize||!a)return n;let d=a.fields[t]??this.detectedPersonalFields(e,a,t,s);if(d.length===0)return n;let c=new Map(s.map(l=>[l.name,l]));return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(l=>{let u=c.get(l);return{name:i[l]??l,type:u?.type??"",...u?.length!==void 0?{length:u.length}:{}}}),methods:a.methods})}detectedPersonalFields(e,t,n,o){let s=e.detectedPersonalFields.get(n);if(s)return s;let i=t.personalFieldsOf?.(o.map(a=>({name:a.name,type:a.type??""})))??[];return e.detectedPersonalFields.set(n,i),i}fileCopyUnwired(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return e&&t&&n?null:"This session cannot copy files: it reads no file content or file storage. Nothing was read or written."}fileCopyDeps(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return!e||!t||!n?null:{queryRecords:(o,s)=>this.deps.queryRecords(o,s),readFileBody:e,insertFile:t,insertRecords:this.deps.insertRecords,remainingFileStorageMB:n}}anonymizerForRun(){if(this.deps.anonymize)return this.deps.anonymize;let e=new ts;return t=>e.anonymize(t)}async execute(e,t,n,o,s){this.isAborted=!1,this.isPaused=!1,this.pauseResolve=null;let i=this.deps.requestsSent?.(),a=El(s);if(a.files){let w=Kr(a.anonymization!==void 0,a.files.acceptedAsIs);if(w)throw new hn(w,"FILES_NOT_ACCEPTED");let I=this.fileCopyUnwired();if(I)throw new hn(I,"FILES_NOT_COPYABLE")}let d=await Yo(a.ownerMappings,w=>this.deps.queryRecords(n,w),Vn);if(d)throw d;let c=new Map,l=await this.recordTypeDecisionsOf(s?.decisions?.recordTypeMappings??[],t,n,c),u=l.bySource.size===0?a:{...a,recordTypeMappings:$l(a.recordTypeMappings,l),recordTypeDecisions:l.bySource},p=u.dryRun?new id:null,f=u.excludedObjects,h=await this.withWhatStatusesNeed(xo(e,f),t,f),g=u.isScoped?await this.withWhatItsRecordsComeWith(h.graph,t,f):h.graph,m=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(g,t,f),t,f),y=this.deps.recordTypePicklists,b=u.dryRun?void 0:u.stream?.store,S=new Date;b?.beginPart(S);let R=Zc(),k=await this.bulkTransportOf(u,n),A={...k?{bulk:k}:{},config:u,sourceOrgId:t,targetOrgId:n,graph:m,onProgress:o,remapper:new vr(b),scopeCache:u.isScoped?new Qu:null,scopedBuilder:u.isScoped?new un:null,recordTypeMapper:u.recordTypeMappings?new Ko:null,referenceDataMapper:new Xo((w,I)=>this.deps.queryRecords(w,I)),orphanExpander:new Zo(p?kw(this.deps,p,async(w,I)=>this.deps.describeObject?this.deps.describeObject(w,I).then(P=>P.keyPrefix,()=>null):null):this.deps),batchWriter:new Vl(this.deps,this.deps.batchStrategy,void 0,R),splitting:R,smallerCallsSaid:new Map,failedObjects:new Set,failedInPart:new Set,heldInTheOrg:new Map,leftAside:new Map,turnsEnded:new Set,notCreatable:new Set,notInTarget:new Set,errors:[],truncatedObjects:new Set,cappedObjects:new Set,pendingFkUpdates:[],owedToRowsWrittenBefore:[],deferredNodes:[],turnsAhead:new Set,waitingFor:new Map,readAgainUnder:new Map,askedForRowsThatNeedThem:new Map,targetHolds:new Map,targetReadsRefused:new Set,inactiveUsers:new Set,writesInactiveOwners:ip(w=>this.deps.queryRecords(n,w)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:b?{add:w=>b.noteRead(w),has:w=>b.wasRead(w)}:new Set,catalogNodes:[],preread:new Map,readByObject:new Map,notSent:new Map,failedReads:new Set,sourceKeyPrefixes:new Map,cursors:new Map,counted:new Map,tableRecordTypes:new Map,keyPrefixesAsked:new Set,readObjects:new Set(m.nodes.filter(w=>w.included).map(w=>w.objectApiName)),writtenObjects:new Set,sellingModels:m.nodes.some(w=>w.included&&w.objectApiName===lr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...b?{store:b}:{},secondPassInStore:!1,statusesGiven:!1,leftDrafts:new Set,statusChildren:h.added,pastDraft:new Map,heldForExclusions:new Map,namedByRowsHeldBack:new Map,readAtItsTurn:new Map,statusChildrenRead:new Map,anonymize:u.anonymization?this.anonymizerForRun():null,contactPoints:u.keepContactPoints?null:new Uo(void 0,{upsertKeys:u.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:fl(pl(w=>this.deps.queryRecords(t,w)),async w=>({fields:await this.deps.describeFields(t,w)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new Al(y&&((w,I)=>y(n,w,I))),picklistChanges:new Io,currencyChanges:new ho,currencyChangesById:new Map,recordTypesGiven:new Map,recordTypesUnderTheLease:new Map,pricesSwappedSaid:[],prices:{standsFor:new Map,convertedInto:new Map,written:new Map,keys:new Map},readsEverythingFirst:!1,writtenWithoutFields:new Map,leftEmptyByFilter:new Map,contactsOnTheirOwn:new Set,withTheirRecord:new Set,startedAt:S,writtenByThePlatform:new Map,contactSentWith:new Map,leftToThePlatform:new cc,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,simulated:p,gaps:u.dryRun?new Kc:null,decisionsApplied:new Pi,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:c,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[w,I]of u.writtenBefore)A.remapper.addExisting(w,I);for(let{decision:w,reason:I}of l.unresolved)A.errors.push({objectApiName:w.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${w.from} \u2192 ${w.to??"the default"})`,messages:[`The decision was not applied: ${I}.`]}]});this.running=A;try{return await this.runPasses(A)}catch(w){throw this.endBeforeTheEmailsThatWaited(A,A.emailsAfterTheirTask.length+A.emailsLeftForTheirTask,w instanceof Re),this.saySyncedQuotesLeft(A),await this.readWrittenBetween(A),this.reportDraftsLeft(A),b?.settleReads(),wp(w,this.summaryOf(A)),w}finally{this.running===A&&(this.running=null),b?.settleReads(),b?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return xi([],[]);let s=this.deps.describeObject,i=async(c,l)=>s?s(c,l).then(u=>this.namedRecordTypes(o,c,u.recordTypes),()=>[]):[],a=[...new Set(e.map(c=>c.object))],d=await Promise.all(a.map(async c=>({objectApiName:c,source:await i(t,c),target:await i(n,c)})));return xi(e,d)}async namedRecordTypes(e,t,n){if(!n.some(s=>!s.master))return n;let o=e.get(t);return o||(o=this.deps.queryRecords(t,mo).then(s=>wo(s),()=>[]),e.set(t,o)),yo(n,await o)}async targetObjectInfoOf(e,t){let n=await this.objectInfoOf(e.targetOrgId,t);return!n||!(e.gaps!==null||n.recordTypes.some(s=>!s.available&&!s.master)||e.config.decisions.namesARecordTypeBare(t))?n:{...n,recordTypes:await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,n.recordTypes)}}async withMaskedLeftOut(e,t,n,o,s){if(o.length===0)return n;let i=await e.maskedSourceFields(t).catch(()=>[]),a=i.filter(d=>!n.has(d)&&s(d)&&o.some(c=>c[d]!==null&&c[d]!==void 0));return this.noteEncryptedLeftOut(e,t,a),i.length>0?new Set([...n,...i]):n}noteEncryptedLeftOut(e,t,n){if(n.length===0)return;let o=e.encryptedFieldsLeftOut.get(t)??new Set;for(let s of n)o.add(s);e.encryptedFieldsLeftOut.set(t,o)}withoutFileContent(e,t,n,o){let s=n.filter(i=>kn(i)&&i.createable);if(o&&s.length>0){let i=e.fileContentFieldsLeftOut.get(t)??new Set;for(let a of s)i.add(a.name);e.fileContentFieldsLeftOut.set(t,i)}return n.filter(i=>!kn(i))}async readWrittenBetween(e){if(e.config.dryRun||e.writtenBetween)return;if(e.config.stream?.everything===!0&&e.store){await this.readWrittenBetweenByObject(e,e.store);return}let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let{objectApiName:o,sourceIds:s}of e.remapper.createdByObject()){let i=s.flatMap(d=>{let c=e.remapper.get(d);return c?[c]:[]});if(i.length===0)continue;let a=await this.auditDatesCopied(e,o);for(let d of An(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let l of c){let u=cs(l.SystemModstamp),p=g=>{let m=a?Number.NaN:cs(l[g]);return Number.isFinite(m)?m:u},f=p("CreatedDate"),h=p("LastModifiedDate");Number.isFinite(f)&&(t=Math.min(t,f)),Number.isFinite(h)&&(n=Math.max(n,h))}}}Number.isFinite(t)&&Number.isFinite(n)&&(e.writtenBetween={first:new Date(t).toISOString(),last:new Date(Math.max(t,n)).toISOString()})}async readWrittenBetweenByObject(e,t){let n=Ow(e.startedAt.getTime()-Aa),o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=!1;for(let{objectApiName:a,created:d}of t.countsByObject()){if(d===0)continue;let c=Me(a),u=[...await this.auditDatesCopied(e,a)?[]:[`SELECT MIN(CreatedDate) f, MAX(SystemModstamp) l FROM ${c} WHERE CreatedDate >= ${n}`],`SELECT MIN(SystemModstamp) f, MAX(SystemModstamp) l FROM ${c} WHERE SystemModstamp >= ${n}`],p=!1;for(let f of u)try{let[h]=await this.deps.queryRecords(e.targetOrgId,f),g=cs(h?.f),m=cs(h?.l);Number.isFinite(g)&&(o=Math.min(o,g)),Number.isFinite(m)&&(s=Math.max(s,m)),p=!0;break}catch{}p||(i=!0)}i&&(o=Math.min(o,e.startedAt.getTime()),s=Math.max(s,Date.now()+Aa)),Number.isFinite(o)&&Number.isFinite(s)&&(e.writtenBetween={first:new Date(o).toISOString(),last:new Date(Math.max(o,s)).toISOString()})}async writtenDatesOf(e,t,n){let o=Me(t);for(let s of yw)try{return await this.deps.queryRecords(e,`SELECT Id, ${s.join(", ")} FROM ${o} WHERE Id IN (${n})`)}catch{}}async auditDatesCopied(e,t){let n=o=>o.some(s=>bw.has(s.name)&&s.createable);try{let[o,s]=await Promise.all([this.deps.describeFields(e.sourceOrgId,t),this.deps.describeFields(e.targetOrgId,t)]);return n(o)&&n(s)}catch{return!0}}async runPasses(e){let{config:t,graph:n,sourceOrgId:o,targetOrgId:s,onProgress:i}=e;e.scopeCache&&t.rootRecordId&&t.rootObjectApiName&&e.scopeCache.add(t.rootObjectApiName,[t.rootRecordId]);let a=Ml(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&nw(t);e.readsEverythingFirst=c,e.emailsInTwoPasses=d&&t.stream?.everything===!0,e.secondPassInStore=e.store!==void 0&&!c,c&&e.store&&e.pendingFkUpdates.push(...e.store.owedLeftByEarlierParts());let l=c?a:await this.singlePassOrder(e);if(c&&e.scopeCache)for(let S of l)S.included&&e.turnsAhead.add(S.objectApiName);if(n.nodes.some(S=>at(S.objectApiName)))try{let[S,R]=await Promise.all([this.deps.queryRecords(o,Vs),this.deps.queryRecords(s,Vs)]),k=S[0]?.Id,A=R[0]?.Id;typeof k=="string"&&typeof A=="string"&&(e.standardPricebookId=k,e.remapper.addExisting(k,A),e.scopeCache?.add(mt,[k]),e.readObjects.add(mt),n.nodes.some(w=>w.included&&w.objectApiName===mt)||e.scopeCache?.addRead(mt,[]))}catch(S){e.errors.push({objectApiName:Le,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[X(S)]}]})}let u=new Map,p=this.deps.isObjectCreatable;if(p){let S=[...new Set(a.filter(R=>R.included&&!t.referenceDataObjects.has(R.objectApiName)).map(R=>R.objectApiName))];for(let R=0;R<S.length&&!this.isAborted;R+=6){let k=S.slice(R,R+6),A=await Promise.allSettled(k.map(async w=>p(s,w)));k.forEach((w,I)=>u.set(w,A[I]))}}for(let[S,R]of u)R.status!=="rejected"||!ha(R.reason)||(e.notInTarget.add(S),e.readObjects.delete(S),e.turnsAhead.delete(S));for(let S of n.nodes){let R=u.get(S.objectApiName);!S.included||R?.status==="fulfilled"&&!R.value||e.notInTarget.has(S.objectApiName)||e.writtenObjects.add(S.objectApiName)}d&&await this.planTheSample(e,l),d&&t.beforeWrite&&await this.countBeforeWrite(e,l);for(let S of l){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");if(!S.included){e.skippedCount++,i({objectName:S.objectApiName,status:"skipped",progress:100,message:`Skipped ${S.objectApiName} (${Cm(S)})`});continue}if(e.notInTarget.has(S.objectApiName)){this.reportNotInTarget(S,e),await this.endTurn(S.objectApiName,e);continue}if(await this.skipForFailedParent(S,e)){await this.endTurn(S.objectApiName,e);continue}let R=u.get(S.objectApiName);if(R)if(R.status==="fulfilled")R.value||e.notCreatable.add(S.objectApiName);else{let k=R.reason;e.errors.push({objectApiName:S.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${k instanceof Error?k.message:String(k)}`]}]})}c?await this.readInTurn(S,e):d&&this.streamsNode(S,e)?(await this.streamNode(S,e),e.turnsEnded.add(S.objectApiName),S.objectApiName===tt&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(S,e,!1,!0)&&await this.writeNode(S,e),e.turnsEnded.add(S.objectApiName),S.objectApiName===tt&&await this.writeEmailsAfterTheirTask(e),S.objectApiName===ye&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,S.objectApiName))}let f=Bl(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),h=f.map(S=>Ve.has(S.objectApiName)).lastIndexOf(!0);for(let[S,R]of f.entries()){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(R,e)||(c?(e.scopeCache&&Ve.has(R.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,R.objectApiName)),await this.readNode(R,e,!1,!1),await this.readUnderWhatWaited(R.objectApiName,e,h>=0&&S>h?"after the catalog":"before the catalog")):await this.readNode(R,e,!1,!0)&&(await this.writeNode(R,e),e.turnsEnded.add(R.objectApiName),this.releaseRows(e,R.objectApiName)))}await this.readCatalogAgain(e,h<0?[]:f.slice(h+1));for(let S of[...e.preread.keys()])this.releaseRows(e,S,!0);if(c){do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e));if(await this.readParentsOutsideTheGraph(e))do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e))}let g=t.stream?.everything===!0,m=t.files&&!g?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let S=await this.pricesTheGateCounts(e),R=Jf(e).cappedObjects,k=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([I,P])=>this.toWriteAtTheGate(e,I,P,at(I)?S:0))))),A=t.dryRun?0:await this.readBackRequests(e,k),w=await t.beforeWrite({objects:k,...R?{capped:R}:{},...A>0?{readBack:A}:{},dryRun:t.dryRun});await this.afterTheGate(e,w,k)}if(c)for(let S of this.writeOrderOf(e)){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let R=e.preread.get(S.objectApiName);if(R&&!await this.skipForFailedParent(S,e,R.fieldInfos,R.records)&&(await this.writeNode(S,e),S.objectApiName===tt&&await this.writeEmailsAfterTheirTask(e),S.objectApiName===ye&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let k=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),A=[],w=await wa({pendingFkUpdates:k,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:A,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(I,P,v)=>this.noteLeftEmptyByFilter(e,I,P,v),...this.secondPassOfTheSample(e)});w&&e.errors.push(w),e.pendingFkUpdates.push(...A)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let y=e.secondPassInStore?await this.secondPassFromTheJournal(e):await wa({pendingFkUpdates:this.sayLookupsOutsideTheClone(e,e.pendingFkUpdates),remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!t.dryRun,onProgress:i,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(S,R,k)=>this.noteLeftEmptyByFilter(e,S,R,k),...this.secondPassOfTheSample(e)});if(y&&e.errors.push(y),this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");m.length>0&&!t.dryRun?await this.writeFiles(e,m):g&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let b=e.orphanExpander.buildErrorReport();return b&&e.errors.push(b),this.saySyncedQuotesLeft(e),await this.readWrittenBetween(e),await this.readBackRecordTypes(e),this.summaryOf(e)}async afterTheGate(e,t,n){let o=t?t.splitAllowance:void 0;o!==void 0&&e.splitting.allowance.limitTo(o);let s=t?t.lease:void 0;s&&(e.lease=s,s.assigned>0&&await this.readAgainUnderTheLease(e,n))}async readAgainUnderTheLease(e,t){let n=this.deps.describeObjectAgain;if(!n)return;let o=await Promise.all(t.map(async({objectApiName:s,rows:i,counted:a})=>{if(!await this.mayGoWithoutRecordType(e,s,i,a))return[];try{let d=await n(e.targetOrgId,s);return[[s,d.recordTypes]]}catch{return[]}}));for(let[s,i]of o.flat())e.recordTypesUnderTheLease.set(s,i)}async mayGoWithoutRecordType(e,t,n,o){if(n.length===0&&(o?.rows??0)===0||!(await this.objectInfoOf(e.targetOrgId,t))?.recordTypes.some(d=>!d.master))return!1;if(n.length===0)return!0;let{config:i}=e;return!(e.preread.get(t)?.createableSet.has("RecordTypeId")===!0&&!(i.fieldExclusions[t]??[]).includes("RecordTypeId")&&i.fieldMappings[t]?.RecordTypeId===void 0)||n.some(d=>{let c=d.RecordTypeId;return typeof c!="string"||ia(c)||i.recordTypeDecisions.get(c)?.to===null})}async readBackRequests(e,t){let o=(await Promise.all(t.map(({objectApiName:i,rows:a,counted:d})=>this.mayGoWithoutRecordType(e,i,a,d)))).filter(Boolean).length,s=e.recordTypeRows.has(e.targetOrgId)&&!e.config.dryRun;return o>0&&!s?o+1:o}async giveTheLeaseBack(e){let t=e.lease;if(t){e.lease=void 0;try{await t.giveBack()}catch(n){Ze.warn(`[forge] the mute's lease was not given back as the writes ended: ${X(n)}`)}}}async readBackRecordTypes(e){e.simulated||await Promise.all([...e.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await this.deps.queryRecords(e.targetOrgId,Uu(t,n.ids));n.readBack=Hu(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:X(o)}}}))}async recordTypeCounter(e,t,n,o){let s=e.recordTypesUnderTheLease.get(t)??n?.recordTypes??[];if(!s.some(c=>!c.master))return;let i=await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,s),a=Gu(zu(i)),d=e.config.recordTypeDecisions;return(c,l)=>{let u=e.recordTypesGiven.get(t);u||(u={rows:0,why:{},...a?{predicted:a}:{},types:i,ids:[]},e.recordTypesGiven.set(t,u));let p=Sw(c,o,d);u.rows++,u.why[p]=(u.why[p]??0)+1,l!==void 0&&u.ids.length<qu&&u.ids.push(l)}}streamsTheRun(e){let{config:t,graph:n}=e;return t.stream===void 0||t.isScoped?!1:t.stream.everything===!0?!0:t.files===void 0&&!n.nodes.some(o=>o.included&&o.objectApiName===Se)}async keysOfTheTable(e,t,n){let{config:o,sourceOrgId:s}=e;if(o.upsertMode!=="auto"||!this.deps.upsertRecords||e.simulated)return;let i=t.objectApiName,a={unique:new Set,sent:new Set};try{n.described??=await this.deps.describeFields(s,i);let d=new Set(o.fieldExclusions[i]??[]),c=o.fieldMappings[i]??{},l=n.described.filter(y=>y.externalId===!0&&y.createable&&y.queryable&&!d.has(y.name)&&c[y.name]===void 0);if(l.length===0)return a;let u=n.described.find(y=>y.name==="Id"),p=pn({node:t,edges:e.graph.edges,fieldInfos:[...u?[u]:[],...l],scopedBuilder:null,scopeCache:null,extraWhere:this.filterOf(e,i),maxRecordsPerObject:this.readBound(e,t),inIdOrder:{}});if(p.kind!=="query"||p.statements.length!==1)return a;let f=p.limit??1/0,h=new Map(l.map(y=>[y.name,new Set])),g=0,m=_t(this.deps,s,p.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let y of m){for(let b of y){if(g>=f)break;g++;for(let[S,R]of h){let k=b[S];typeof k!="string"||k.length===0||R.has(k)?h.delete(S):R.add(k)}}if(g>=f||h.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(h.keys()),sent:a.sent}}catch(d){return Ze.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+X(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!Ve.has(n)&&!at(n)&&(n!==tt||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(Ve.has(t)||at(t)))return;let o=e.preread.get(t);!o||o.records.length===0||e.preread.set(t,{...o,records:[]})}readsArchived(e,t){return e.config.stream?.everything===!0&&Cu.has(t)}filterOf(e,t){let n=e.config.objectSoqlFilters?.[t];return this.readsArchived(e,t)?n?`(${n}) AND IsDeleted = false`:"IsDeleted = false":n}readOptionsOf(e,t){return this.readsArchived(e,t)?{all:!0}:void 0}async readWholeOf(e,t,n,o){let s=this.readOptionsOf(e,t);if(!s)return this.deps.queryRecords(e.sourceOrgId,n,o);let i=[],a=_t(this.deps,e.sourceOrgId,n,void 0,void 0,s);for await(let d of a)for(let c of d)i.push(c);return i}readBound(e,t){if(e.sample?.drawn.has(t.objectApiName))return;let n=e.config.maxRecordsPerObject,o=n!==void 0&&n>0?Math.floor(n):void 0,s=this.streamsNode(t,e)?e.config.stream?.ceiling:void 0;return o===void 0?s:s===void 0?o:Math.min(o,s)}async planTheSample(e,t){let{config:n,store:o}=e,s=n.stream?.everything===!0?n.stream.sample:void 0,i=o?.samplePlan;if(!s){if(i)throw new mn("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+Vn);return}let a;if(i)try{a=await Jn.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof Qo?new mn("SAMPLE_PLAN_GONE",`The plan of the sample the run resumes is ${d.refusal==="gone"?"no longer on this machine":"no longer as it was drawn"}: it cannot go on with the same records. ${Vn} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new mn("SAMPLE_PLAN_MISMATCH",`The run this one resumes copied every record of the whole org, not a sample: resume it as it was set up. ${Vn}`);a=s.plan??await this.drawThePlan(e,t,s)}o&&!i&&o.nameSamplePlan({dir:a.dir,sha256:a.sha256}),e.sample=await this.runSampleOf(e,a)}async drawThePlan(e,t,n){let{config:o,sourceOrgId:s}=e,i=Iw(n),a=t.filter(R=>R.included&&(e.writtenObjects.has(R.objectApiName)||o.referenceDataObjects.has(R.objectApiName))),d=new Map;for(let R of a)d.set(R.objectApiName,await this.deps.describeFields(s,R.objectApiName));let c=(R,k)=>k.nillable===!1&&e.graph.edges.some(A=>A.type==="master-detail"&&A.targetObject===R&&(k.referenceTo??[]).includes(A.sourceObject)),l=[],u=new Map;for(let R of a){let k=R.objectApiName,A=new Set(o.fieldExclusions[k]??[]),w=(d.get(k)??[]).filter(I=>I.isReference&&!A.has(I.name)).map(I=>({name:I.name,referenceTo:I.referenceTo??[],isMasterDetail:c(k,I),...I.nillable!==void 0?{nillable:I.nillable}:{},createable:I.createable,...I.updateable!==void 0?{updateable:I.updateable}:{}}));if(l.push({objectApiName:k,rows:R.recordCount,keyPrefix:(await this.objectInfoOf(s,k))?.keyPrefix??e.sourceKeyPrefixes.get(k)??null,fields:w}),this.streamsNode(R,e)&&!o.referenceDataObjects.has(k)){let I=await this.recordTypesOfTable(e,R);I&&I.closedInSource.length>0&&u.set(k,{closed:new Set(I.closedInSource.map(ue)),lacking:new Set(I.lackingInSource.map(ue))})}}let p=await n.budget(),f=e.standardPricebookId&&a.some(R=>at(R.objectApiName))?await this.runCurrencies(e):void 0,h=f&&this.priceCurrencyWrittenIn(e,f.target),g=new Map;if(a.some(R=>R.objectApiName===Se)){let R=await this.averageEmailBytes(e,d.get(Se)??[]);R!==void 0&&g.set(Se,R)}let m=h?R=>f.target.active.has(R)?void 0:h(R):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let y;try{y=await Lf({source:{pages:(R,k)=>_t(this.deps,s,R,void 0,void 0,k),count:async(R,k)=>{let A=this.deps.countRecords;if(A)return k?A(s,R,k):A(s,R);let w=0,I=R.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let P of _t(this.deps,s,I,void 0,void 0,k))w+=P.length;return w}},objects:l,order:a.map(R=>R.objectApiName),excluded:new Map([...o.excludedObjects].map(R=>[R,null])),referenceData:o.referenceDataObjects,fieldsOf:R=>d.get(R)?.filter(k=>k.queryable).map(k=>({name:k.name,...k.groupable!==void 0?{groupable:k.groupable}:{},...k.sortable!==void 0?{sortable:k.sortable}:{},...k.aggregatable!==void 0?{aggregatable:k.aggregatable}:{}})),filterOf:R=>o.objectSoqlFilters?.[R],options:i,budget:p,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(R,k)=>{let A=u.get(R),w=ue(k);return A?.lacking.has(w)?"recordTypeNotInTarget":A?.closed.has(w)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...m?{priceCurrencyWrittenIn:m}:{},...g.size>0?{averageBytes:g}:{},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(R){throw R instanceof Ir?new mn("SAMPLE_TOO_LARGE",R.message):R instanceof $r||this.isAborted?new Re("Forge execution was aborted by user request. Remaining objects were not processed."):R}let{cut:b}=y;if(b.kind==="cannotFit"){let R=b.heaviest.map(w=>`${w.objectApiName} (${w.rows} records${w.whole?", copied whole":""})`).join(", "),k=b.noRoot?"the objects copied whole and the first root drawn with the records it brings":"the objects copied whole and the roots kept of each object",A=b.noRoot?"Leave objects out (--exclude-object)":"Keep no root of each object (--fit-floor 0), leave objects out (--exclude-object)";throw new mn("SAMPLE_CANNOT_FIT",`No sample of the whole org fits: ${k} take ${b.rows} records, ${(b.storageBytes/1048576).toFixed(1)} MB, past what the sample may take (${b.limitedBy}); the heaviest are ${R}. ${Vn} ${A}, or take more of the target (--fit-within).`,b.heaviest)}let S=Wf({...y,cut:b},i,p.budget);return jp(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:S,...y.newestByIds.length>0?{newestByIds:y.newestByIds}:{},ids:[...b.ids].map(([R,k])=>({objectApiName:R,ids:k})),counts:{personAccounts:Object.fromEntries(b.personAccounts),byThePlatform:b.byThePlatform.map(R=>({...R}))}})}async averageEmailBytes(e,t){let n=jh(t,e.config.fieldExclusions[Se]);if(n.length===0)return;let o=this.filterOf(e,Se);try{let s=await this.readWholeOf(e,Se,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${Se}${o?` WHERE ${o}`:""} LIMIT ${Aw}`);if(s.length===0)return;let i=0;for(let a of s)for(let[d,c]of Object.entries(a))d!=="Id"&&typeof c=="string"&&(i+=Buffer.byteLength(c,"utf8"));return Math.ceil(i/s.length)}catch(s){Ze.warn("[forge] the size of the emails could not be read before the sample was drawn: "+X(s));return}}async runSampleOf(e,t){let{manifest:n}=t,o=new Set(n.sample.whole.map(d=>d.objectApiName)),s=new Set([...e.writtenObjects].filter(d=>!o.has(d)&&!e.config.referenceDataObjects.has(d))),i=new Map,a=new Map;for(let d of s){let c=new Set;for await(let p of t.ids(d))for(let f of p)c.add(ue(f));i.set(d,c);let u=c.values().next().value?.slice(0,3)??(await this.objectInfoOf(e.sourceOrgId,d))?.keyPrefix??e.sourceKeyPrefixes.get(d);u&&a.set(d,u)}return{plan:t,report:{...n.sample,plan:t.place},drawn:s,ids:i,prefixes:a,counts:n.counts??{personAccounts:{},byThePlatform:[]},gone:new Map,changed:new Map,leftEmpty:new Map,reads:new Map,withoutStandard:new Set}}drawnObjectNamed(e,t,n){let o=t.filter(s=>e.drawn.has(s));if(o.length!==0)return t.length===1?o[0]:o.find(s=>{let i=e.prefixes.get(s);return i!==void 0&&n.startsWith(i)})}inThePlan(e,t,n){return e.ids.get(t)?.has(ue(n))===!0}outsideTheSample(e,t,n){let o=e.sample;if(!o)return!1;let s=this.drawnObjectNamed(o,t,n);return s===void 0?!1:!this.inThePlan(o,s,n)||o.gone.get(s)?.has(ue(n))===!0}secondPassOfTheSample(e){let t=e.sample;return t?{outsideTheSample:n=>{let o=n.sourceRefId,s=[...t.drawn].find(i=>{let a=t.prefixes.get(i);return a!==void 0&&o.startsWith(a)});return s!==void 0&&this.outsideTheSample(e,[s],o)},onLeftOutsideTheSample:(n,o)=>this.noteLeftOutsideTheSample(e,n,o)}:{}}noteLeftOutsideTheSample(e,t,n){let o=e.sample;if(!o)return;let s=o.leftEmpty.get(t)??new Map;s.set(n,(s.get(n)??0)+1),o.leftEmpty.set(t,s)}async countToWriteOfThePlan(e,t,n){let o=t.objectApiName,s=e.config.stream?.resumeAfter.get(o),i=n.ids.get(o)??new Set,a=s&&$t.test(s.lastId)?s.lastId:void 0,d=R=>a===void 0||Rt(R,a)>0,c=0;if(!s?.done)for(let R of i)d(R)&&c++;let l=Math.min(c,await this.writtenBeforeOf(e,t,s)),u=e.standardPricebookId,p=o===mt&&u&&i.has(ue(u))&&d(u)&&!e.config.writtenBefore.has(u)?Math.min(1,c-l):0,f=Math.max(0,c-l-p),h=Math.min(f,n.counts.personAccounts[o]??0),g=0;o===ge&&h>0&&await this.personAccountsInTarget(e)===!0&&(g=h);let m=n.counts.byThePlatform.find(R=>R.objectApiName===o);m&&(g+=Math.min(f-g,m.inPlan)),f-=g;let y=R=>n.report.dropped.filter(k=>k.objectApiName===o&&k.reason===R).reduce((k,A)=>k+A.rows,0),b={...l>0?{writtenBefore:l}:{},...p>0?{linkedToTarget:p}:{},...g>0?{byThePlatform:g}:{},...y("noParentInSource")>0?{noParentInSource:y("noParentInSource")}:{},...y("outsideFilter")>0?{outsideFilter:y("outsideFilter")}:{}},S=o===ge&&g>0?0:h;return{read:c,counted:{rows:f,...S>0?{personAccounts:Math.min(S,f)}:{}},...Object.keys(b).length>0?{leftOut:b}:{}}}async readOfThePlan(e,t,n,o){let s=n.objectApiName,i=t.reads.get(s);if(i)return i;let a=await this.deps.describeFields(e.sourceOrgId,s),d=Mp({objectApiName:s,columns:Wt(a.filter(c=>!kn(c)),e.config.fieldExclusions[s]),sourceRows:n.recordCount,planRows:o});return t.reads.set(s,d),d}planRowsAfter(e,t,n){let o=e.ids.get(t);if(!o)return 0;if(n===void 0)return o.size;let s=0;for(let i of o)Rt(i,n)>0&&s++;return s}async*pagesOfThePlanByIds(e,t,n,o,s,i=!1){let a=Me(n),d=this.filterOf(e,a),c=Math.max(1,Ic(a,jc(o),d?`(${d})`:void 0));for await(let l of t.plan.ids(a,{...s!==void 0?{after:s}:{},size:c})){if(this.isAborted)return;let u=l.filter(h=>$t.test(h));if(u.length===0)continue;let p=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${u.map(h=>`'${h}'`).join(", ")})`,f=await this.readWholeOf(e,a,p);if(f.sort((h,g)=>Rt(String(h.Id),String(g.Id))),i){let h=new Set(f.map(m=>ue(String(m.Id)))),g=t.gone.get(a)??new Set;for(let m of u)h.has(ue(m))||g.add(ue(m));g.size>0&&t.gone.set(a,g)}yield f}}async rowsOfThePlan(e,t,n,o,s,i=!1){let a=[];for await(let d of this.pagesOfThePlanByIds(e,t,n,o,s,i))for(let c of d)a.push(c);return a}async*pagesOfThePlan(e,t,n,o,s){let i=n.objectApiName,a=o.lastId??o.resumeAfter,d=await this.readOfThePlan(e,t,n,this.planRowsAfter(t,i,a)),c=/^SELECT (.+?) FROM /.exec(s)?.[1]?.split(", ")??["Id"],l=d.by==="ids"?this.pagesOfThePlanByIds(e,t,i,c,a,!0):this.cursorKeptToThePlan(e,t,i,s,a);yield*es(l,e.config.stream?.writeWindow??e.config.stream?.pageSize)}async*cursorKeptToThePlan(e,t,n,o,s){let i=t.ids.get(n)??new Set,a=new Set,d=_t(this.deps,e.sourceOrgId,o,void 0,()=>e.truncatedObjects.add(n),this.readOptionsOf(e,n));try{for await(let l of d){let u=l.filter(p=>{let f=ue(String(p.Id));return i.has(f)?(a.add(f),!0):!1});u.length>0&&(yield u)}}finally{await d.return(void 0)}let c=t.gone.get(n)??new Set;for(let l of i)!a.has(l)&&(s===void 0||Rt(l,s)>0)&&c.add(l);c.size>0&&t.gone.set(n,c)}sampleResultOf(e){let t=e.sample;if(!t||e.simulated)return;let n=new Map(e.remapper.countsByObject().map(s=>[s.objectApiName,s])),o=t.report;return{seed:o.seed,draw:o.draw,share:o.share,sha256:o.plan.sha256,drawnAt:o.plan.drawnAt,drawnBy:o.plan.drawnBy,objects:o.objects.map(s=>{let i=n.get(s.objectApiName),a=i?i.created+(i.linked??0):0,d=e.store?.earlierRecordsOf(s.objectApiName)??0;return{...s,written:Math.min(s.kept,a+d),goneSinceTheSample:t.gone.get(s.objectApiName)?.size??0,changedSinceTheSample:t.changed.get(s.objectApiName)??0}}),...t.leftEmpty.size>0?{leftEmpty:[...t.leftEmpty].flatMap(([s,i])=>[...i].map(([a,d])=>({objectApiName:s,field:a,rows:d})))}:{}}}async countBeforeWrite(e,t){let{config:n}=e,o=n.beforeWrite;if(!o)return;let s=n.stream?.everything===!0,i=[],a=[],d=new Set,c=[],l=[];for(let A of t){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let w=A.objectApiName;if(!A.included||!e.writtenObjects.has(w))continue;let I=s&&!this.streamsNode(A,e);if(n.referenceDataObjects.has(w)){I&&c.push({objectApiName:w,rows:await this.rowsOf(e,A)});continue}let{read:P,counted:v,leftOut:$,capped:E,partial:M}=e.sample?.drawn.has(w)?await this.countToWriteOfThePlan(e,A,e.sample):await this.countToWrite(e,A);e.counted.set(w,P),E&&a.push(w),M&&d.add(w),I&&!e.sample?.drawn.has(w)&&c.push({objectApiName:w,rows:P}),s&&l.push({node:A,read:P,whole:I}),i.push({objectApiName:w,rows:[],counted:v,...$?{leftOut:$}:{}})}let u=e.sample?.drawn.has(ze)?void 0:i.find(A=>A.objectApiName===ze),p=i.find(A=>A.objectApiName===Fe),f=u?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(u&&f!==void 0&&f>0){let A=Math.min(f,u.counted.rows);u.counted={...u.counted,rows:u.counted.rows-A},u.leftOut={...u.leftOut,byThePlatform:A}}let h=p?.leftOut?.writtenBefore??0,g=u?this.rolesThePlatformMayWriteOfTheCounts(e,u.counted.rows,(f===void 0?p?.counted.rows??0:0)+h):0;if(u&&g>0&&(u.mayBeByThePlatform=f!==void 0?{rows:g,before:!0}:{rows:g}),this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let m=s?await this.heldAtTheGate(e,t,i):void 0;m&&(m.requests+=await this.pricesReplacedAtTheGate(e,i));let y=s?await this.measureTheWholeOrg(e,i,c,l,m):void 0,b=y&&e.sample?{...y,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:y;if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let S=ls(n),R=n.dryRun&&!s?0:await this.readBackRequests(e,i),k=await o({objects:i,...S!==void 0&&a.length>0?{capped:{perObject:S,objects:a}}:{},...R>0?{readBack:R}:{},...b?{wholeOrg:b}:{},dryRun:n.dryRun});await this.afterTheGate(e,k,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(h=>h.included&&e.writtenObjects.has(h.objectApiName)&&!o.referenceDataObjects.has(h.objectApiName)),i=new Map(s.map((h,g)=>[h.objectApiName,g])),a=new Map,d=new Map,c=new Map,l=Yf,u=(h,g,m)=>{let y=a.get(h)??new Map;y.has(g)||l<=0||(y.set(g,m),a.set(h,y),l--)},p={requests:0,lookups:new Map},f=async(h,g)=>{let m=await this.idsUnder(e,h,g);return p.requests+=Math.max(1,Math.ceil((m?.length??0)/Pn)),m};for(let h of s){if(this.isAborted)break;let g=h.objectApiName;if(e.sample?.drawn.has(g))continue;if(l>0&&this.streamsNode(h,e)){let y=await this.recordTypesOfTable(e,h);if(y&&y.closed.length>0&&this.typesHeldRowByRow(e,y)){let b=new Set(y.lackingInSource);for(let[S,R]of[[y.closedInSource.filter(k=>!b.has(k)),d],[y.lackingInSource,c]]){let k=S.map(w=>`'${w}'`).join(", ");if(!k)continue;let A=a.get(g)?.size??0;for(let w of await f(g,`RecordTypeId IN (${k})`)??[])u(g,w,"held");R.set(g,(a.get(g)?.size??0)-A)}}}let m=await this.deps.describeFields(e.sourceOrgId,g).catch(()=>[]);for(let y of m){let[b]=y.referenceTo??[],S=b===void 0?void 0:i.get(b);if(!y.isReference||(y.referenceTo??[]).length!==1||S===void 0||S>=(i.get(g)??0)||!y.createable||(o.fieldExclusions[g]??[]).includes(y.name)||!Qe(g,y.name,y.nillable)||(p.lookups.set(g,(p.lookups.get(g)??0)+1),l<=0))continue;let R=Me(y.name),k=await f(g,`${R} != null AND ${R} NOT IN (SELECT Id FROM ${Me(b)})`);for(let P of k??[])u(g,P,{field:y.name,parentObject:b,reason:Ha(y.name,b)});let A=a.get(b);if(!A||A.size===0)continue;let w=[...A].filter(([,P])=>P==="held").map(([P])=>P),I=[...A].filter(([,P])=>P!=="held").map(([P])=>P);for(let[P,v]of[[w,"held"],[I,{field:y.name,parentObject:b,reason:Xf(y.name,b)}]])for(let $ of An(P)){if(l<=0)break;for(let E of await f(g,`${R} IN (${$})`)??[])u(g,E,v)}}}for(let h of n){let g=a.get(h.objectApiName);if(!g||g.size===0)continue;let m=d.get(h.objectApiName)??0,y=c.get(h.objectApiName)??0,b=[...g.values()].filter(A=>A==="held").length,S=g.size-b,R=Math.max(0,h.counted.rows-g.size),k=h.counted.personAccounts;h.counted={rows:R,...k!==void 0&&Math.min(k,R)>0?{personAccounts:Math.min(k,R)}:{}},h.leftOut={...h.leftOut,...m>0?{heldBack:(h.leftOut?.heldBack??0)+m}:{},...y>0?{recordTypeNotInTarget:(h.leftOut?.recordTypeNotInTarget??0)+y}:{},...b-m-y>0?{withoutParent:b-m-y}:{},...S>0?{noParentInSource:S}:{}}}for(let h of a.values())for(let[g,m]of h)e.heldInTheOrg.set(g,m);return p}async pricesReplacedAtTheGate(e,t){let n=t.find(g=>g.objectApiName===Le);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(Le)??0)>Yf)return 0;let o=await this.deps.describeFields(e.sourceOrgId,Le).catch(()=>[]);if(!o.some(g=>g.name===dt))return 0;let s=["Id",wt,yt,dt,...o.some(g=>g.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(g=>g.name===Bt)?[Bt]:[]],i=this.filterOf(e,Le),a=e.sample,d;try{d=a?.drawn.has(Le)?await this.rowsOfThePlan(e,a,Le,s):await this.readWholeOf(e,Le,`SELECT ${s.join(", ")} FROM ${Le}`+(i?` WHERE ${i}`:""))}catch(g){return Ze.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${X(g)}`),1}let c=Math.max(1,Math.ceil(d.length/Pn)),l=e.currencies===void 0,u=d.filter(g=>!e.heldInTheOrg.has(String(g.Id))),p=await this.priceCurrencyInput(e,u,o),f=c+(l&&e.currencies!==void 0?Mm:0);if(!p)return f;let h=Math.min(n.counted.rows,ua(p,[]).standsFor.size);return h===0||(n.counted={...n.counted,rows:n.counted.rows-h},n.leftOut={...n.leftOut,currencyReplaced:h}),f}async idsUnder(e,t,n){let o=e.config.stream?.resumeAfter.get(t),s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...o&&$t.test(o.lastId)?[`Id > '${o.lastId}'`]:[],n];try{return(await this.readWholeOf(e,t,`SELECT Id FROM ${Me(t)} WHERE ${i.join(" AND ")}`)).map(d=>String(d.Id))}catch(a){Ze.warn(`[forge] the ${t} records held back could not be counted at the gate: ${X(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:y})=>y>a).map(({objectApiName:y,rows:b})=>({objectApiName:y,rows:b,bound:a})),c=new Set(o.filter(y=>y.whole).map(y=>y.node.objectApiName)),{writes:l,restOnly:u}=await this.writesOfTheWholeOrg(e,t,c),p=o.find(({node:y})=>y.objectApiName===Se&&y.included),f=t.find(y=>y.objectApiName===Se)?.counted?.rows??0,h=p&&f>0?await this.emailBytesOf(e,p.node):void 0,g=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o);return{writes:l,...u?{restOnly:u}:{},...h!==void 0?{emailTextBytes:h}:{},...i.files?{files:g??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,g)+Bm(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=e.bulk?.restOnly??new Set;if(s&&!e.bulk){let c=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});i=new Set([...No,...c??Ni])}let a=o.stream?.writeWindow??o.stream?.pageSize??Pn,d=t.map(({objectApiName:c,counted:l})=>{let u=Math.max(0,l?.rows??0),p=s&&!i.has(c),f=n.has(c)?[u]:[...Array.from({length:Math.floor(u/a)},()=>a),...u%a>0?[u%a]:[]],h=0,g=0;for(let m of p?f:[])for(let y=0;y<m;y+=kr){let b=Math.min(kr,m-y);b<2e3||(h++,g+=b)}return{objectApiName:c,rows:u,jobs:h,jobRows:g,restRows:u-g}});return s?{writes:d,restOnly:i}:{writes:d}}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Pn)),i=new Map;for(let{node:c,read:l}of t)i.set(c.objectApiName,l);for(let{objectApiName:c,rows:l}of n)i.set(c,l);let a=0;for(let[c,l]of i){let u=t.find(p=>p.node.objectApiName===c)?.node;a+=e.sample?.drawn.has(c)&&u?(await this.readOfThePlan(e,e.sample,u,l)).requests:s(l)}let d=t.find(({node:c})=>c.objectApiName===Se);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===tt)){let c=await this.countOf(e,Se,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=ed.length+Math.ceil(c/Pn),a+=Math.ceil(c/Za)+c}return a}async rowsOf(e,t){return await this.countOf(e,t.objectApiName)??t.recordCount}async countOf(e,t,n){let o=this.deps.countRecords;if(!o)return;let s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...n?[n]:[]],a=i.length>0?` WHERE ${i.join(" AND ")}`:"",d=`SELECT COUNT() FROM ${Me(t)}${a}`,c=this.readOptionsOf(e,t);try{return await(c?o(e.sourceOrgId,d,c):o(e.sourceOrgId,d))}catch{return}}async emailBytesOf(e,t){let n=t.objectApiName;try{let o=await this.deps.describeFields(e.sourceOrgId,n),s=jh(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let h=0,g=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of g)for(let[y,b]of Object.entries(m))y!=="Id"&&typeof b=="string"&&(h+=Buffer.byteLength(b,"utf8"));return h}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&$t.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],l=c.length>0?` WHERE ${c.join(" AND ")}`:"",u=["Id",...s.map(h=>h.name)].join(", "),p=0,f=_t(this.deps,e.sourceOrgId,`SELECT ${u} FROM ${Me(n)}${l} ORDER BY Id`,e.config.stream?.pageSize,void 0,this.readOptionsOf(e,n));try{for await(let h of f){for(let g of h)for(let[m,y]of Object.entries(g))m!=="Id"&&typeof y=="string"&&(p+=Buffer.byteLength(y,"utf8"));if(this.isAborted)break}}finally{await f.return(void 0)}return p}catch(o){Ze.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+X(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of ed){let c=[d,`${a} <= ${t}`].filter(Boolean).join(" AND "),l=[d,`${a} > ${t}`].filter(Boolean).join(" AND "),u=await this.sumOfFiles(e,i,a,c);if(!u)return;n+=u.bytes,o+=u.count;let p=await this.deps.countRecords?.(e.sourceOrgId,`SELECT COUNT() FROM ${i} WHERE ${l}`).catch(()=>{});s+=p??0}return{bytes:n,count:o,overCeiling:s}}async sumOfFiles(e,t,n,o){try{let[s]=await this.deps.queryRecords(e.sourceOrgId,`SELECT SUM(${n}) total, COUNT(Id) n FROM ${t} WHERE ${o}`),i=Number(s?.total??0),a=Number(s?.n??0);if(Number.isFinite(i)&&Number.isFinite(a))return{bytes:i,count:a}}catch{}try{let s=0,i=0,a=_t(this.deps,e.sourceOrgId,`SELECT Id, ${n} FROM ${t} WHERE ${o} ORDER BY Id`,e.config.stream?.pageSize);try{for await(let d of a){for(let c of d){let l=c[n];s+=typeof l=="number"&&Number.isFinite(l)?l:0,i++}if(this.isAborted)break}}finally{await a.return(void 0)}return{bytes:s,count:i}}catch(s){Ze.warn(`[forge] the files of ${t} could not be measured: ${X(s)}`);return}}async phoneNumbersPastTheFiction(e,t){let n=0;for(let{node:o,read:s}of t){if(s===0||this.isAborted)continue;let i=o.objectApiName,a=new Set(e.config.fieldExclusions[i]??[]),c=(await this.deps.describeFields(e.sourceOrgId,i).catch(()=>[])).filter(l=>l.createable&&!a.has(l.name));for(let l of sa(c)){if(l.kind!=="phone")continue;let u=await this.countOf(e,i,`${Me(l.name)} != null`);n+=Math.min(u??s,s)}}return Math.max(0,n-Wu)}async countToWrite(e,t){let n=t.objectApiName,o=this.streamsNode(t,e),s=o?e.config.stream?.resumeAfter.get(n):void 0,i=this.filterOf(e,n),a=this.readOptionsOf(e,n),d=this.deps.countRecords,c=async H=>{if(!d)return;let K=[...i?[`(${i})`]:[],...H?[H]:[],...s&&$t.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],pe=K.length>0?` WHERE ${K.join(" AND ")}`:"",le=`SELECT COUNT() FROM ${Me(n)}${pe}`;try{return await(a?d(e.sourceOrgId,le,a):d(e.sourceOrgId,le))}catch{return}},l=this.readBound(e,t),u=l===void 0?void 0:Math.max(0,l-(s?.read??0)),p=await c(),f=p??t.recordCount,h=u===void 0?f:Math.min(f,u),g=ls(e.config),m=g===void 0?void 0:Math.max(0,g-(s?.read??0)),y=m!==void 0&&u===m&&f>m,b=o?await this.recordTypesOfTable(e,t):void 0;if(b&&b.closed.length>0&&!this.typesHeldRowByRow(e,b))return{read:h,counted:{rows:0},...h>0?{leftOut:eh(b.closed,h)}:{}};let S=Math.min(h,await this.writtenBeforeOf(e,t,s)),R=n===mt?Math.min(h-S,await this.standardBookOfTheTable(e,c)):0,k=h-S-R,A=S>0||R>0?{...S>0?{writtenBefore:S}:{},...R>0?{linkedToTarget:R}:{}}:void 0,w=H=>H===void 0?{rows:k}:{rows:k,personAccounts:H},I=h<f,P=H=>({read:h,counted:w(H),...A?{leftOut:A}:{},...y?{capped:!0}:{},...I?{partial:!0}:{}});if(n!==ye&&n!==ge||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(H=>H.name==="IsPersonAccount"))return P();let $=await c("IsPersonAccount = true"),E=$===void 0?void 0:Math.min($,k);if(n!==ge||$===void 0||p===void 0)return P(E);let M=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(M===void 0)return P(E);let Z=Math.max(0,$-M-(p-h)-S);if(Z===0)return P(E);let U=(E??0)-Z;return{read:h,counted:{rows:k-Z,...U>0?{personAccounts:U}:{}},leftOut:{...A,byThePlatform:Z},...y?{capped:!0}:{},...I?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!$t.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,mt)?Math.min(1,await t(`Id = '${n}'`)??0):1}async personContactsTakenAsBusinessAtTheGate(e,t){if(await this.personAccountsInTarget(e)!==!0)return;let n=await this.personRecordTypesInTarget(e);if(!n)return 0;let{config:o}=e;if(!((await this.deps.describeFields(e.sourceOrgId,ye).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[ye]??[]).includes("RecordTypeId")&&o.fieldMappings[ye]?.RecordTypeId===void 0)){let d=aa((await this.objectInfoOf(e.targetOrgId,ye))?.recordTypes);return d!==void 0&&!n.has(d.slice(0,15))?void 0:0}let a=(o.recordTypeMappings??[]).filter(d=>!n.has(d.targetId.slice(0,15))).map(d=>d.sourceId);if(a.length===0)return 0;if(a.every(d=>$t.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return op({lookups:t.filter(s=>s.isReference&&o(s.name)),rows:n,ownerMappings:e.config.ownerMappings,outsideTheRun:s=>this.isOutsideTheRun(e,s),mapped:s=>e.remapper.get(s)!==void 0,known:e.targetHolds,refused:e.targetReadsRefused,inactive:e.inactiveUsers,query:s=>this.deps.queryRecords(e.targetOrgId,s),neverCopied:s=>as(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=sp(t,e.inactiveUsers,e.config.ownerMappings);if(o.size!==0&&!await e.writesInactiveOwners())return o}isOutsideTheRun(e,t){return!e.writtenObjects.has(t)&&!e.failedObjects.has(t)&&!e.notInTarget.has(t)}noteLookupsOutsideTheRun(e,t,n,o){let s=Ya(new Map,o);if(s.size===0)return;let i=e.lookupsOutsideTheRun.get(t)??new Map;for(let[a,d]of s){let c=n.find(u=>u.name===a)?.referenceTo?.[0]??a,l=i.get(a)??{parent:c,rows:0};l.rows+=d,i.set(a,l)}e.lookupsOutsideTheRun.set(t,i)}async rowsWhoseParentTheTargetLacks(e,t,n,o,s){let i=new Map,{config:a}=t;if(a.referenceFallback!=="keep"||a.expandOrphanParents)return i;let d=n.filter(l=>{let u=l.referenceTo??[];return l.isReference&&s(l.name)&&u.length===1&&!as(t,u[0])&&this.isOutsideTheRun(t,u[0])&&Qe(e.objectApiName,l.name,l.nillable)});if(d.length===0||o.length===0)return i;let c=await this.idsTheTargetLacks(t,d,o,()=>!0);return c.size===0||o.forEach((l,u)=>{for(let p of d){let f=l[p.name];if(!(typeof f!="string"||!c.has(f)||t.remapper.get(f))){i.set(u,{field:p.name,parentObject:(p.referenceTo??[])[0],notInTarget:!0});return}}}),i}rowsOfClosedTypes(e,t,n,o){let{config:s}=e,i=new Map(o.map(c=>[c.recordTypeId,c])),a=n.map(c=>({RecordTypeId:s.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));e.recordTypeMapper&&s.recordTypeMappings&&(a=e.recordTypeMapper.apply(a,s.recordTypeMappings));let d=new Map;return n.forEach((c,l)=>{let u=a[l]?.RecordTypeId,p=typeof u=="string"?i.get(u):void 0;p&&d.set(c,{field:"RecordTypeId",parentObject:p.developerName,recordType:{...p,objectApiName:t.objectApiName}})}),d}async rowsHeldInTheWholeOrg(e,t,n,o,s){let i=new Map,a=new Map;if(t.config.stream?.everything!==!0||o.length===0)return{held:i,aside:a};let d=Dm(t,e.objectApiName,n,s),c=new Set,l=new Map;o.forEach((u,p)=>{let f=t.heldInTheOrg.get(String(u.Id));if(f!==void 0&&f!=="held"){a.set(p,f);return}if(t.sample?.withoutStandard.has(ue(String(u.Id)))){i.set(p,{field:yt,parentObject:Le,reason:jw}),c.add(p);return}for(let{field:h,parent:g}of d){let m=u[h];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let y=t.sample;if(y?.drawn.has(g)){this.inThePlan(y,g,m)?y.gone.get(g)?.has(ue(m))?a.set(p,{field:h,parentObject:g,reason:Wm(h,g)}):i.set(p,{field:h,parentObject:g}):(i.set(p,{field:h,parentObject:g,reason:Lm(h,g)}),c.add(p));return}let b=t.heldInTheOrg.get(m);if(b==="held"){i.set(p,{field:h,parentObject:g});return}if(b){let R=b===Qf?Ha(h,g):Xf(h,g);a.set(p,{field:h,parentObject:g,reason:R});return}let S=l.get(g)??new Map;S.set(m,[...S.get(m)??[],{index:p,field:h}]),l.set(g,S)}});for(let[u,p]of l){let f=await this.idsInTheSource(t,u,[...p.keys()]);for(let[h,g]of p){let m=f===void 0||f.has(h.slice(0,15));m||t.heldInTheOrg.set(h,Qf);for(let{index:y,field:b}of g)i.has(y)||a.has(y)||(m?i.set(y,{field:b,parentObject:u}):a.set(y,{field:b,parentObject:u,reason:Ha(b,u)}))}}for(let u of i.keys())a.delete(u);if(c.size>0&&t.sample){let u=e.objectApiName;t.sample.changed.set(u,(t.sample.changed.get(u)??0)+c.size)}return{held:i,aside:a}}async idsInTheSource(e,t,n){let o=new Set;try{for(let s of An(n)){let i=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Me(t)} WHERE Id IN (${s})`);for(let a of i)o.add(String(a.Id).slice(0,15))}return o}catch(s){Ze.warn(`[forge] whether the source holds the ${t} records named could not be read: ${X(s)}`);return}}async writtenBeforeOf(e,t,n){let{writtenBefore:o}=e.config,s=t.objectApiName,i=e.store?.earlierRecordsOf(s,n!==void 0)??0;if(e.store&&i>0)return i;if(o.size===0||n)return 0;let a=(await this.objectInfoOf(e.sourceOrgId,s))?.keyPrefix??e.sourceKeyPrefixes.get(s);if(!a)return 0;let d=[];for(let f of o.keys())f.startsWith(a)&&d.push(f);let c=e.config.objectSoqlFilters?.[s],l=this.deps.countRecords;if(!c||d.length===0||!l)return d.length;let u=this.readOptionsOf(e,s),p=this.filterOf(e,s)??c;try{let f=0;for(let h of An(d)){let g=`SELECT COUNT() FROM ${Me(s)} WHERE (${p}) AND Id IN (${h})`;f+=await(u?l(e.sourceOrgId,g,u):l(e.sourceOrgId,g))}return f}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===Se&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(Lo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:Sm(),...n?{pass:n}:{}},d=n?void 0:this.readBound(t,e);if(i?.done||d!==void 0&&a.read>=d)return;let c=n?void 0:await this.recordTypesOfTable(t,e);if(c&&c.closed.length>0&&!this.typesHeldRowByRow(t,c)){let p=d===void 0?c.rows:Math.min(c.rows,d-a.read);this.holdBackTableForRecordTypes(e,t,c,p);return}let l=n?n.expected:t.counted.get(o)??Vf(e,d);a.carry.rowsLeft=n?()=>Math.max(0,l-a.carry.rows):()=>Math.max(0,l-(a.read-(i?.read??0)));let u=n?.stopped??`Stopped ${e.objectApiName}`;t.cursors.set(o,a);try{let p=n?void 0:await this.keysOfTheTable(t,e,a);for(p&&(a.carry.tableKeys=p);;){if(this.isAborted)throw a.carry.pages>0&&a.carry.rowsLeft()>0?this.stopStreamedNode(e,t,a.carry,0,u):a.carry.pages>0&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),new Re("Forge execution was aborted by user request. Remaining objects were not processed.");if(!await this.readNode(e,t,!1,!0))break;let f=n?t.preread.get(o)?.records??[]:void 0;if(await this.writeNode(e,t,f,a.carry),o===ye&&await this.mapContactsOfPersonAccounts(t),s&&await this.linkTasksOfTheEmailsWritten(t),await this.tellPage(t,e,a),a.ended)break}}finally{t.cursors.delete(o),await a.pages?.return(void 0)}t.store&&a.ended&&!a.failed&&a.lastId!==void 0&&t.store.checkpoint(o,{lastId:a.lastId,read:a.read,done:!0},n?.name),a.carry.pages>0&&!a.failed&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),this.releaseRows(t,o)}endOfAStreamedNode(e,t,n){if(n)return{...n.end,again:!0};if(t!==Se||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${is(o)}`}:{}}}recordTypesOfTable(e,t){let n=t.objectApiName,o=e.tableRecordTypes.get(n);return o||(o=this.countRecordTypesOfTable(e,t),e.tableRecordTypes.set(n,o)),o}async countRecordTypesOfTable(e,t){let{config:n,sourceOrgId:o,targetOrgId:s}=e,i=t.objectApiName,a=await this.targetObjectInfoOf(e,i),d={closed:[],rows:0,target:a,closedInSource:[],lackingInSource:[]};if(!a||!a.recordTypes.some(c=>!c.available&&!c.master)&&!await this.mayLackRecordTypes(e,i,a)||(n.fieldExclusions[i]??[]).includes("RecordTypeId")||n.fieldMappings[i]?.RecordTypeId)return d;try{let[c,l]=await Promise.all([this.deps.describeFields(o,i),en(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(v=>v.name==="RecordTypeId"&&v.createable)||l&&!l.creatable.has("RecordTypeId"))return d;let p=n.stream?.resumeAfter.get(i),f=this.filterOf(e,i),h=[...f?[`(${f})`]:[],...p&&$t.test(p.lastId)?[`Id > '${p.lastId}'`]:[]],g=h.length>0?` WHERE ${h.join(" AND ")}`:"",m=`FROM ${Me(i)}${g}`,y=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),b=y.reduce((v,$)=>v+(typeof $.n=="number"&&$.n>0?$.n:0),0),S=Uc(y),R=async v=>[...qc(i,v,a.recordTypes),...await this.typesTheTargetLacks(e,i,v,a)],k=await R(this.recordTypesAsSent(e,S)),A=v=>{let $=new Set(v.map(E=>E.recordTypeId));return[...S.keys()].filter(E=>[...this.recordTypesAsSent(e,[[E,1]]).keys()].some(M=>$.has(M)))},w=(v,$)=>({closed:v,rows:$,target:a,closedInSource:A(v),lackingInSource:A(v.filter(E=>E.unmapped))}),I=this.readBound(e,t),P=I===void 0?void 0:Math.max(0,I-(p?.read??0));if(k.length>0&&P!==void 0&&b>P){let v=await this.recordTypesOfTheRowsRead(e,i,m,P);if(v)return w(await R(this.recordTypesAsSent(e,v.counts)),v.rows)}return w(k,b)}catch{return}}recordTypesAsSent(e,t){let{config:n}=e,o=new Map;for(let[s,i]of t){if(n.recordTypeDecisions.get(s)?.to===null)continue;let a=s;e.recordTypeMapper&&n.recordTypeMappings&&(a=e.recordTypeMapper.apply([{RecordTypeId:s}],n.recordTypeMappings)[0]?.RecordTypeId),typeof a=="string"&&o.set(a,(o.get(a)??0)+i)}return o}async typesTheTargetLacks(e,t,n,o){if(!e.recordTypeMapper||!e.config.recordTypeMappings)return[];if(!o||o.recordTypes.length===0)return[];if(bo(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),bo(t,n,o.recordTypes,i)}async mayLackRecordTypes(e,t,n){if(!e.recordTypeMapper||!e.config.recordTypeMappings||n.recordTypes.length===0)return!1;let s=((await this.objectInfoOf(e.sourceOrgId,t))?.recordTypes??[]).filter(a=>!a.master);if(s.length===0)return!1;let i=this.recordTypesAsSent(e,s.map(a=>[a.recordTypeId,1]));return bo(t,i,n.recordTypes,[]).length>0}async recordTypesOfTheRowsRead(e,t,n,o){let s=!1;try{let i=await this.readWholeOf(e,t,`SELECT RecordTypeId ${n} ORDER BY Id LIMIT ${o}`,()=>{s=!0});if(s)return;let a=new Map;for(let d of i){let c=d.RecordTypeId;typeof c=="string"&&c!==""&&a.set(c,(a.get(c)??0)+1)}return{counts:a,rows:i.length}}catch{return}}typesHeldRowByRow(e,t){if(e.config.stream?.everything!==!0)return!1;let n=t.closed.reduce((o,s)=>o+s.recordCount,0);return t.rows>n}holdBackTableForRecordTypes(e,t,n,o){let s=e.objectApiName;t.gaps?.knowRecordTypes(s,"target",n.target?.recordTypes??[]);for(let i of n.closed)t.gaps?.add(th(i,n.target));t.failedObjects.add(s),t.failedCount+=o,t.errors.push({objectApiName:s,stage:"scope",failedCount:o,attemptedCount:0,samples:n.closed.map(i=>({recordSummary:`RecordType=${i.developerName} (${i.recordCount} record${i.recordCount===1?"":"s"})`,messages:[Oo(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${wn(s,o,Gt(t,s))}: `+n.closed.map(Ro).join(" ")+" Objects that cannot be written without it will be skipped."})}async nextPage(e,t,n,o,s){if(n.ended)return[];let i=e.sample?.drawn.has(t.objectApiName)?e.sample:void 0,a=p=>i?this.pagesOfThePlan(e,i,t,n,p):_t(this.deps,e.sourceOrgId,p,e.config.stream?.writeWindow??e.config.stream?.pageSize,()=>e.truncatedObjects.add(t.objectApiName),this.readOptionsOf(e,t.objectApiName));n.pages??=a(o);let d=e.config.stream?.everything===!0?Ua:0,c;for(let p=0;;p++)try{c=await n.pages.next();break}catch(f){let h=gh(f);if(!h&&!mh(f)||p>=d||this.isAborted)throw f;let g=n.lastId===void 0?o:s?.(n.lastId);if(g===void 0)throw f;h||await wh(Uf*2**p),Ze.warn(`[forge] ${t.objectApiName}: the source ${h?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${p+1}/${d}): `+X(f)),n.pages=a(g)}if(c.done)return n.ended=!0,[];n.taken++;let l=c.value;n.room!==void 0&&(l.length>n.room&&(l=l.slice(0,n.room),n.ended=!0,(n.cutBy==="cap"?e.cappedObjects:e.truncatedObjects).add(t.objectApiName)),n.room-=l.length),n.read+=l.length;let u=l[l.length-1]?.Id;return typeof u=="string"&&(n.lastId=u),l}async readWhole(e,t,n){let o=e.sample;if(o?.drawn.has(t)){let d=/^SELECT (.+?) FROM /.exec(n)?.[1]?.split(", ")??["Id"];return this.rowsOfThePlan(e,o,t,d,void 0,!0)}let s=!1,i=()=>{s=!0,e.truncatedObjects.add(t)},a=await this.readWholeRows(e,n,i);if(s&&e.config.stream?.everything===!0)throw new hs(t,e.config.stream.wholeReadBound);return a}async readWholeRows(e,t,n){let{stream:o}=e.config,s=o?.pageSize;if(s===void 0||!this.deps.queryPages)return this.deps.queryRecords(e.sourceOrgId,t,n);let i=(o?.everything===!0?o.wholeReadBound:o?.ceiling)??5e4,a=[],d=_t(this.deps,e.sourceOrgId,t,s);try{for await(let c of d)if(a.push(...c),a.length>i)return n(),a.slice(0,i)}finally{await d.return(void 0)}return a}pagedLimit(e,t){let n=ls(e.config),o=n===void 0?void 0:n-t.read,s=e.config.stream?.ceiling,i=s===void 0?void 0:s-t.read;if(i===void 0&&o===void 0)return;let a=i!==void 0&&(o===void 0||i<o);return t.room=Math.max(0,(a?i:o)??0),t.cutBy=a?"ceiling":"cap",Math.max(1,t.room)}async tellPage(e,t,n){e.store&&n.lastId!==void 0&&e.store.checkpoint(t.objectApiName,{lastId:n.lastId,read:n.read},n.pass?.name);let o=e.config.stream?.onPage;if(!o)return;let s=e.preread.get(t.objectApiName)?.records??[],i=e.simulated?[]:s.flatMap(a=>{let d=a.Id;if(typeof d!="string"||!e.remapper.isCreated(d))return[];let c=e.remapper.get(d);return c?[{sourceId:d,targetId:c}]:[]});await o({objectApiName:t.objectApiName,...n.lastId!==void 0&&!n.pass?{checkpoint:{lastId:n.lastId,read:n.read}}:{},created:i})}endStreamedNode(e,t,n,o={}){let{config:s}=t,i=o.say??t.onProgress,a=e.objectApiName;this.mergePageReports(t,a,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=o.again?[]:Gt(t,a),c=o.again?void 0:t.heldForExclusions.get(a),l=[...qa(n),...d],u=xn(l),p=I=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:I})};if(n.heldWhole!==void 0){p(`${wn(a,n.heldWholeRows,d)}: ${n.heldWhole} Objects that cannot be written without it will be skipped.`);return}if(n.rows===0&&c&&c.size>0){p(Cr(a,c));return}let f=zf(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){p(`${wn(a,n.personContactsUnlinked,d)}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`);return}if(f===0&&n.failed===0&&n.sent===0&&n.withoutParent>0){p(`${wn(a,n.withoutParent,d)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`);return}let h=f+n.failed,g=h>0?n.failed/h:0,m=n.failed>0&&n.alreadyExists===n.failed,y=n.failed>0&&!m&&(f===0||g>.5),b=$o(n.picklists.list())+go(n.currencies.list())+Va(n.lookupsNotCarried)+Qa(n.ownersInactive)+Ja(n.lookupsOutsideTheRun)+td(t,a),S=Mo(n.writtenWithoutFields),R=Sh(t,a),k=Hf(t,a),A=ih(n.sentOnTheirOwn);if(y){f>0&&t.failedInPart.add(a),p(f===0?`Failed all ${a} records: ${n.failed+u} failed${rn(l)}${A}${b}${k}`:`${n.failed+u}/${h+u} ${a} records failed (>50%)${rn(l)}${A}${b}${S}${R}${k}`+nh);return}let w=Gf(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${Ka(s,n,l)}${o.note??""}${A}${w}${b}${S}${R}${us(t,a)}${k}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();Xa(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...qa(n),...Gt(t,i)],c=zf(n),l=c+n.failed,u=n.failed>0&&n.alreadyExists!==n.failed&&(c===0||n.failed/l>.5);u&&t.failedObjects.add(i),u&&c>0&&t.failedInPart.add(i),t.onProgress({objectName:i,status:u?"error":"stopped",progress:100,message:`${s}: ${Ka(t.config,n,d)}, ${a} not sent${ih(n.sentOnTheirOwn)}${Gf(n)}${$o(n.picklists.list())}${go(n.currencies.list())}${Va(n.lookupsNotCarried)}${Qa(n.ownersInactive)}${Ja(n.lookupsOutsideTheRun)}${td(t,i)}${Mo(n.writtenWithoutFields)}${us(t,i)}`})}mergePageReports(e,t,n){if(n.withoutParent>0&&!n.withoutParentSaid){let i={objectApiName:t,stage:"scope",failedCount:n.withoutParent,attemptedCount:0,samples:rd(n.withoutParentGroups,e.failedObjects)},a=e.errors.findIndex(d=>d.objectApiName===t&&d.stage==="insert");a===-1?e.errors.push(i):e.errors.splice(a,0,i),n.withoutParentSaid=!0}let o=e.errors.filter(i=>i.objectApiName===t&&i.stage==="insert");if(o.length>0){let[i]=o,a={...i,failedCount:o.reduce((l,u)=>l+u.failedCount,0),attemptedCount:n.succeeded+n.updated+n.linked+n.failed,samples:o.flatMap(l=>l.samples).slice(0,Xm)},d=e.errors.indexOf(i),c=e.errors.filter(l=>!o.includes(l));c.splice(d,0,a),e.errors.splice(0,e.errors.length,...c)}let s=e.existingRecords.filter(i=>i.objectApiName===t);if(s.length>1){let i=s.reduce((l,u)=>l+(u.linkedToCreated??0),0),a={objectApiName:t,linked:s.reduce((l,u)=>l+u.linked,0),...i>0?{linkedToCreated:i}:{},unidentified:s.reduce((l,u)=>l+u.unidentified,0)},d=e.existingRecords.indexOf(s[0]),c=e.existingRecords.filter(l=>!s.includes(l));c.splice(d,0,a),e.existingRecords.splice(0,e.existingRecords.length,...c)}}async startAsDrafts(e,t,n){let o=new Map;if(e.config.dryRun)return o;let s=await this.lifecycleOf(e,t);return s&&n.forEach((i,a)=>{let d=io(i.Status,s);d&&(o.set(a,String(i.Status)),i.Status=d)}),o}async oweStatusesFoundAfterStop(e,t,n){let{store:o}=e;if(!o)return;let s=n.filter(a=>{let d=a.Id;return typeof d=="string"&&o.wasFoundAfterStop(d)});if(s.length===0)return;let i=await this.lifecycleOf(e,t);if(i)for(let a of s){if(!io(a.Status,i))continue;let d=e.config.writtenBefore.get(String(a.Id));d&&this.oweStatus(e,t,d,String(a.Status))}}async lifecycleOf(e,t){let n=wc[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=yc(s=>this.deps.queryRecords(e.targetOrgId,s),n),e.lifecycles.set(t,o)),o}async notePastDraft(e,t,n){if(!([...e.statusChildren.values()].some(({parent:a})=>a===t)||e.config.excludedObjects.size>0&&cr[t]!==void 0))return;let s=await this.lifecycleOf(e,t);if(!s)return;let i=e.pastDraft.get(t)??new Map;for(let a of n){let d=a.Id;typeof d=="string"&&io(a.Status,s)&&i.set(d,String(a.Status))}e.pastDraft.set(t,i)}async restoreStatuses(e){let t=this.deps.updateRecords;if(t&&e.store){await this.restoreStatusesFromTheJournal(e,t);return}if(!t||e.deferredStatuses.length===0)return;let n=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[o,s]of Th(n)){let i=0,a=[];for(let d=0;d<s.length;d+=Bo.rest){let c=s.slice(d,d+Bo.rest),l;try{l=await t(e.targetOrgId,o,c.map(({id:u,status:p})=>({Id:u,Status:p})))}catch(u){l=c.map(({id:p})=>({id:p,success:!1,errors:[X(u)]}))}c.forEach(({id:u,status:p},f)=>{let h=l[f];h?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${u} Status=${p}`,messages:h?.errors??["No result returned for the status update"]}))})}e.onProgress({objectName:o,status:i>0?"error":"done",progress:100,message:`Restored the status of ${s.length-i}/${s.length} ${o} records written as drafts`}),i>0&&e.errors.push({objectApiName:o,stage:"insert",failedCount:i,attemptedCount:s.length,samples:a})}}async restoreStatusesFromTheJournal(e,t){let{store:n}=e;if(!n||e.statusesGiven||n.statusesOwed().size===0)return;e.statusesGiven=!0;let o=new Map,s=new Map,i=async a=>{let d=s.get(a)??[];if(s.set(a,[]),d.length===0)return;let c=o.get(a);if(!c)return;let l;try{l=await t(e.targetOrgId,a,d.map(({id:u,status:p})=>({Id:u,Status:p})))}catch(u){l=d.map(({id:p})=>({id:p,success:!1,errors:[X(u)]}))}d.forEach(({id:u,status:p},f)=>{let h=l[f];if(h?.success){n.gaveStatus(a,u);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${u} Status=${p}`,messages:h?.errors??["No result returned for the status update"]})})};for(let{objectApiName:a,id:d,status:c}of n.statusLines()){if(e.leftDrafts.has(d)||n.statusGiven(d))continue;let l=o.get(a)??{entries:0,failed:0,samples:[]};l.entries++,o.set(a,l);let u=s.get(a)??[];u.push({id:d,status:c}),s.set(a,u),u.length>=Bo.rest&&await i(a)}for(let[a,{entries:d,failed:c,samples:l}]of o)await i(a),e.onProgress({objectName:a,status:c>0?"error":"done",progress:100,message:`Restored the status of ${d-c}/${d} ${a} records written as drafts`}),c>0&&e.errors.push({objectApiName:a,stage:"insert",failedCount:c,attemptedCount:d,samples:l})}reportDraftsExclusionsLeave(e){let t=e.config.excludedObjects;if(t.size===0)return;let n=new Set;for(let[s,i]of Object.entries(cr)){let a=e.pastDraft.get(s);if(!a||a.size===0)continue;let d=e.statusChildrenRead.get(s),c=[];for(let[l,u]of a){let p=e.remapper.get(l);if(!e.config.dryRun&&!p)continue;let f;if(t.has(i.object))f=`${i.object} is excluded from this run`;else if(d&&!d.kept.has(l)){let g=d.held.get(l);g&&(f=`none of its ${i.object} records can be written without ${g.excluded}`+(g.target?Nr(g.target):", which is excluded from this run"))}if(!f)continue;p&&n.add(p);let h=p!==void 0&&!e.simulated?.has(p)?p:l;c.push({recordSummary:`${s} ${h} Status=${u}`,messages:[`Left a draft: the platform gives ${s} this status only with ${i.object} records under it, and ${f}.`]})}c.length!==0&&e.errors.push({objectApiName:s,stage:"insert",failedCount:c.length,attemptedCount:c.length,samples:c.slice(0,3)})}if(n.size===0)return;for(let s of n)e.leftDrafts.add(s);let o=e.deferredStatuses.splice(0,e.deferredStatuses.length);e.deferredStatuses.push(...o.filter(({id:s})=>!n.has(s)))}reportDraftsLeft(e){if(e.store){if(e.statusesGiven)return;e.statusesGiven=!0;for(let[n,{count:o,samples:s}]of e.store.statusesOwed())e.errors.push({objectApiName:n,stage:"insert",failedCount:o,attemptedCount:o,samples:s.map(({id:i,status:a})=>({recordSummary:`${n} ${i} Status=${a}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))});return}let t=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[n,o]of Th(t))e.errors.push({objectApiName:n,stage:"insert",failedCount:o.length,attemptedCount:o.length,samples:o.slice(0,3).map(({id:s,status:i})=>({recordSummary:`${n} ${s} Status=${i}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))})}async skipForFailedParent(e,t,n,o){let s=l=>Fm(e.objectApiName,t.graph,l).filter(u=>t.failedObjects.has(u)&&!t.failedInPart.has(u)),i=s(n??[]);if(i.length===0)return!1;if(!n)try{if(i=s(await this.deps.describeFields(t.sourceOrgId,e.objectApiName)),i.length===0)return!1}catch{}t.skippedCount++,t.failedObjects.add(e.objectApiName);let a=o?.filter(l=>!nn(t.config,l)).length??t.counted.get(e.objectApiName);a!==0&&(t.failedCount+=a??0,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:a??0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:[...i.map(l=>`Not written: its records cannot be written without ${l}, which failed in this run.`),...a===void 0?["Skipped before its records were read: how many there were is not known."]:[]]}]}));let d=Gt(t,e.objectApiName),c=(a??0)+xn(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${rn(d)}`:"")}),!0}async rowsWithoutTheirParent(e,t,n,o){let s=new Map;o.forEach((l,u)=>{for(let p of n){let[f]=p.referenceTo??[];if(!p.isReference||(p.referenceTo??[]).length!==1||f===e.objectApiName||!t.failedInPart.has(f)||!Qe(e.objectApiName,p.name,p.nillable))continue;let h=l[p.name];if(typeof h=="string"&&h&&!t.remapper.get(h)){s.set(u,{field:p.name,parentObject:f});return}}});let i=n.filter(l=>l.isReference&&(l.referenceTo??[]).length>1&&Qe(e.objectApiName,l.name,l.nillable)),a=[];if(o.forEach((l,u)=>{for(let p of i){let f=l[p.name];typeof f=="string"&&f&&!t.remapper.get(f)&&a.push({index:u,field:p.name,id:f})}}),a.length===0)return s;let d=new Set(t.graph.nodes.filter(l=>l.included).map(l=>l.objectApiName));d.delete(e.objectApiName);let c=await this.sourceKeyPrefixes(t,new Set(i.flatMap(l=>(l.referenceTo??[]).filter(u=>d.has(u)))));for(let{index:l,field:u,id:p}of a){let f=c.get(p.slice(0,3));f&&!s.has(l)&&s.set(l,{field:u,parentObject:f})}return s}async sourceKeyPrefixes(e,t){let n=[];for(let s of t){if(e.sourceKeyPrefixes.has(s))continue;let i=e.preread.get(s)?.records.find(a=>typeof a.Id=="string");i?e.sourceKeyPrefixes.set(s,String(i.Id).slice(0,3)):n.push(s)}for(let s=0;s<n.length;s+=6){let i=n.slice(s,s+6),a=await Promise.all(i.map(d=>this.objectInfoOf(e.sourceOrgId,d)));i.forEach((d,c)=>{let l=a[c]?.keyPrefix;l&&e.sourceKeyPrefixes.set(d,l)})}let o=new Map;for(let s of t){let i=e.sourceKeyPrefixes.get(s);i&&!o.has(i)&&o.set(i,s)}return o}async keyPrefixesNamedBy(e,t){let n=new Set(e.graph.nodes.map(s=>s.objectApiName)),o=new Set;for(let s of t){let i=s.isReference?s.referenceTo??[]:[];if(!(i.length<2))for(let a of i)n.has(a)&&!e.keyPrefixesAsked.has(a)&&o.add(a)}if(o.size>0){for(let s of o)e.keyPrefixesAsked.add(s);await this.sourceKeyPrefixes(e,o)}return e.sourceKeyPrefixes}async excludedByKeyPrefix(e,t,n){let o=e.config.excludedObjects;if(o.size===0)return new Map;let s=new Set;for(let d of n){let c=d.isReference?d.referenceTo??[]:[];if(!(c.length<2||!Qe(t,d.name,d.nillable)))for(let l of c)o.has(l)&&s.add(l)}let i=new Set([...s].filter(d=>!e.keyPrefixesAsked.has(d)));if(i.size>0){for(let d of i)e.keyPrefixesAsked.add(d);await this.sourceKeyPrefixes(e,i)}let a=new Map;for(let d of s){let c=e.sourceKeyPrefixes.get(d);c&&!a.has(c)&&a.set(c,d)}return a}async objectOfSourceId(e,t,n){let o=t.slice(0,3),s=n.find(l=>e.sourceKeyPrefixes.get(l)===o);if(s)return s;let i=new Set(e.graph.nodes.map(l=>l.objectApiName)),a=n.filter(l=>!e.sourceKeyPrefixes.has(l)),d=a.filter(l=>!i.has(l)),c=[a.filter(l=>i.has(l))];for(let l=0;l<d.length;l+=6)c.push(d.slice(l,l+6));for(let l of c){let u=(await this.sourceKeyPrefixes(e,new Set(l))).get(o);if(u)return u}}writeOrderOf(e){return this.orderByFields(e,new Map([...e.preread].map(([t,n])=>[t,n.fieldInfos])))}orderByFields(e,t){let n=e.parentsOutside.size>0?{...e.graph,nodes:[...e.graph.nodes,...e.parentsOutside.values()]}:e.graph,o=new Set(n.nodes.filter(c=>c.included).map(c=>c.objectApiName)),s=[],i=[];for(let[c,l]of t){jm(l)&&i.push(c);for(let u of l)if(!(!u.isReference||!dr(u)||!Qe(c,u.name,u.nillable)))for(let p of u.referenceTo??[])p===c||!o.has(p)||s.push({sourceObject:p,targetObject:c,relationshipName:u.name,type:"lookup",required:!0})}let a=Wl(o,i),d=t.get(Le)?.some(c=>c.name===dt);return Ci(Co(n,t),[...s,...a,...d?Ku(o,i,[...s,...a]):[],...ni(o),...oi(o,t),...Zu(o,t),...ci(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>at(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(ye)&&o.has(ge)&&(await Promise.allSettled([ye,ge].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([ye,ge][d],a.value)}),Ci(Co(e.graph,s),[...ni(o),...oi(o,s),...ci(o)])}let n=new Map;for(let o=0;o<t.length&&!this.isAborted;o+=6){let s=t.slice(o,o+6);(await Promise.allSettled(s.map(a=>this.deps.describeFields(e.sourceOrgId,a.objectApiName)))).forEach((a,d)=>{a.status==="fulfilled"&&n.set(s[d].objectApiName,a.value)})}return this.orderByFields(e,n)}async withWhatStatusesNeed(e,t,n){let o=new Set(e.nodes.map(d=>d.objectApiName)),s=new Map,i=[],a=[];for(let d of e.nodes){if(this.isAborted)break;let c=cr[d.objectApiName];if(!d.included||!c||o.has(c.object)||s.has(c.object)||n.has(c.object))continue;let l;try{l=await this.deps.describeFields(t,c.object)}catch{continue}let u=l.find(p=>p.name===c.lookup&&p.isReference&&(p.referenceTo??[]).includes(d.objectApiName));u&&(s.set(c.object,{parent:d.objectApiName,lookup:c.lookup}),i.push(Er(c.object,l,d.level+1)),a.push({sourceObject:d.objectApiName,targetObject:c.object,relationshipName:u.name,type:"lookup",required:Qe(c.object,u.name,u.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...a]},added:s}}async withWhatItsRecordsComeWith(e,t,n){let o=new Set(e.nodes.map(a=>a.objectApiName)),s=[],i=[];for(let a of e.nodes){if(this.isAborted)break;let d=km[a.objectApiName];if(!a.included||!d||o.has(d.object)||n.has(d.object))continue;let c;try{c=await this.deps.describeFields(t,d.object)}catch{continue}let l=c.find(u=>u.name===d.lookup&&u.isReference&&(u.referenceTo??[]).includes(a.objectApiName));l&&(o.add(d.object),s.push(Er(d.object,c,a.level+1)),i.push({sourceObject:a.objectApiName,targetObject:d.object,relationshipName:l.name,type:"lookup",required:Qe(d.object,l.name,l.nillable)}))}return s.length===0?e:{...e,nodes:[...e.nodes,...s],edges:[...e.edges,...i]}}async withTheCatalogItNeeds(e,t,n){let o=Nl(e,n);if(o.size===0)return e;let s=new Set(e.edges.map(l=>`${l.sourceObject}|${l.targetObject}`)),i=new Map,a=new Map,d=[],c=e.nodes.filter(l=>l.included);for(;c.length>0&&!this.isAborted;){let l=[];for(let u=0;u<c.length&&!this.isAborted;u+=6){let p=c.slice(u,u+6);(await Promise.allSettled(p.map(({objectApiName:h})=>this.deps.describeFields(t,h)))).forEach((h,g)=>{if(h.status!=="fulfilled")return;let{objectApiName:m,level:y}=p[g];a.set(m,h.value);for(let b of h.value){let S=b.referenceTo??[];if(!b.isReference||S.length!==1)continue;let[R]=S;R===m||!(o.has(R)||i.has(R))||Fl(m,b)&&(o.delete(R)&&(i.set(R,y+1),l.push({objectApiName:R,level:y+1})),!s.has(`${R}|${m}`)&&(s.add(`${R}|${m}`),d.push({sourceObject:R,targetObject:m,relationshipName:b.name,type:"lookup",required:Qe(m,b.name,b.nillable)})))}})}c=l}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([l,u])=>Er(l,a.get(l)??[],u))],edges:[...e.edges,...d]}}async withSellingModelOptions(e,t,n){let o=l=>e.nodes.find(u=>u.included&&u.objectApiName===l),s=o(Po),i=o(lr);if(!o(Le)||!s||!i||n.has(Lt)||e.nodes.some(l=>l.objectApiName===Lt))return e;let a;try{a=await this.deps.describeFields(t,Lt)}catch{return e}let d=Er(Lt,a,Math.max(s.level,i.level)+1),c=(l,u)=>({sourceObject:l,targetObject:Lt,relationshipName:u,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(Po,"Product2Id"),c(lr,"ProductSellingModelId")]}}summaryOf(e){let t=this.deps.requestsSent?.(),{simulated:n}=e,o=e.config.stream?.summaryBound;if(e.store&&o!==void 0&&e.remapper.count>o)return this.summaryOfTheJournal(e,t);let s=e.remapper.toJSON();if(n)for(let[c,l]of Object.entries(s))n.has(l)&&delete s[c];let i=c=>c in s,a=dw(e),d=[...e.mayHaveBeenWritten].map(([c,l])=>({objectApiName:c,sourceIds:[...l]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0&&!n?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...Ym(e),...Hm(e),...rw(e),...sw(e),...ww(e)],truncatedObjects:[...e.truncatedObjects],...Jf(e),remapTable:s,existingRecords:[...e.existingRecords],existingSourceIds:e.remapper.existingSourceIds().filter(i),updatedSourceIds:e.remapper.updatedSourceIds().filter(i),...a.length>0&&!n?{withTheirRecordSourceIds:a}:{},...e.writtenByThePlatform.size>0?{writtenByThePlatform:[...e.writtenByThePlatform].map(([c,l])=>({objectApiName:c,rows:l}))}:{},...e.leftEmptyByFilter.size>0&&!n?{lookupsLeftEmptyByFilter:[...e.leftEmptyByFilter].flatMap(([c,l])=>[...l].map(([u,{records:p,ids:f}])=>({objectApiName:c,field:u,records:p,recordIds:[...f]})))}:{},remapByObject:n?[]:e.remapper.countsByObject(),...e.notSent.size>0?{notSentByObject:[...e.notSent].map(([c,l])=>({objectApiName:c,notSent:l}))}:{},createdByObject:n?[]:e.remapper.createdByObject(),readByObject:[...e.readByObject].map(([c,l])=>({objectApiName:c,read:l})),failedReads:[...e.failedReads],...e.files?{files:structuredClone(e.files)}:{},...e.fileContentFieldsLeftOut.size>0?{fileContentFieldsLeftOut:[...e.fileContentFieldsLeftOut].map(([c,l])=>({objectApiName:c,fields:[...l].sort()}))}:{},...e.encryptedFieldsLeftOut.size>0?{encryptedFieldsLeftOut:[...e.encryptedFieldsLeftOut].map(([c,l])=>({objectApiName:c,fields:[...l].sort()}))}:{},...e.picklistChanges.size>0?{picklistValuesChanged:e.picklistChanges.list()}:{},...e.currencyChanges.size>0?{currenciesReplaced:e.currencyChanges.list()}:{},...e.recordTypesGiven.size>0?{recordTypesGiven:[...e.recordTypesGiven].map(([c,l])=>Tw(c,l))}:{},...e.writtenWithoutFields.size>0?{writtenWithoutFields:[...e.writtenWithoutFields].map(([c,{rows:l,fields:u}])=>({objectApiName:c,rows:l,fields:u.map(p=>({...p}))}))}:{},contactPoints:e.contactPoints?e.contactPoints.report():{neutralized:!1,fields:[],values:0},...e.writtenBetween?{writtenBetween:{...e.writtenBetween}}:{},...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},...n?{dryRun:!0}:{},...e.gaps?{gaps:e.gaps.list(e.config.decisions.ignoredGaps)}:{},...e.decisionsApplied.size>0?{decisionsApplied:e.decisionsApplied.list()}:{},...d.length>0?{mayHaveBeenWritten:d}:{},...vw(this.sampleResultOf(e))}}summaryOfTheJournal(e,t){let n=this.summaryOf({...e,config:{...e.config,stream:e.config.stream&&{...e.config.stream,summaryBound:void 0}},remapper:new vr,store:void 0,withTheirRecord:new Set,linkedToCreatedCount:0}),o=e.store?.withTheirRecordCount??0,s=e.store?.linkedToCreatedCount()??0;return{...n,remapCount:e.remapper.count,...o>0?{withTheirRecordCount:o}:{},...s>0?{linkedToCreatedCount:s}:{},remapByObject:e.remapper.countsByObject(),...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},remapInJournal:!0}}async prepareFiles(e){let{config:t,onProgress:n}=e,o=t.files,s=this.fileCopyDeps();if(!o||!s)return[];let i=await cp({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=lp(i);if(a&&!t.dryRun)throw new hn(`${a} Nothing was written.`,"FILES_UNREAD");e.errors.push(...i.errors);let d=await this.filesCopiedBefore(e,i.files,s),c={...i,files:d.filter(f=>f.into?.unchanged!==!0)},l;if(c.files.length>0)try{l=await hp(s,e.targetOrgId)}catch(f){let h=`The file storage the target has left could not be read (${X(f)}), so the files could not be checked against it.`;if(!t.dryRun)throw new hn(`${h} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(ya(h))}e.files=gp(c,o.maxFileBytes,l),a&&(e.files.lookupFailure=a);let u=pp(c.files),p=l===void 0?null:fp(u,l);if(p&&l!==void 0&&!t.dryRun)throw new hn(`${p} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:u,remainingBytes:l});if(p&&e.errors.push(ya(p)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:f,sourceId:h,name:g,bytes:m})=>({objectApiName:f,sourceId:h,name:g,bytes:m}));for(let f of e.files.objects)n({objectName:f.objectApiName,status:"done",progress:100,message:mp(f)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await up({files:t,targetOrgId:e.targetOrgId,copiedBefore:i=>{let a=o.mapping(i);return a?.earlier&&a.kind==="created"&&a.objectApiName?{objectApiName:a.objectApiName,targetId:a.targetId}:void 0},queryRecords:n.queryRecords});return e.errors.push(...s.errors),s.files}async writeFiles(e,t){let n=this.fileCopyDeps();if(!n||!e.files)return;let{remapper:o}=e;e.failedCount+=await ba({files:t,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:s=>o.wasCreated(s),get:s=>o.get(s),add:(s,i,a)=>o.add(s,i,a),persist:()=>o.persist()},deps:n,report:e.files,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:e.onProgress,...e.store?{calls:ds(e.store)}:{}})}async copyFilesOfTheOrg(e,t){let n=this.fileCopyDeps();if(!n)return;e.files??={maxFileBytes:t,objects:[],links:0,leftOut:[]};let o=e.files,s=0,i=(d,c)=>e.onProgress({objectName:d,status:"running",progress:50,message:c}),a=e.config.stream?.pageSize??cw;for(let d of ed){let{counted:c}=d,l=e.config.stream?.resumeAfter.get(Lo(c,fh));if(l?.done)continue;let p=`SELECT ${d.object==="ContentVersion"?"Id, ContentDocumentId, Title, PathOnClient, ContentSize, SharingPrivacy":"Id, ParentId, Name, ContentType, BodyLength, IsPrivate"} FROM ${d.object} WHERE `+[d.where,`${d.size} <= ${t}`].filter(Boolean).join(" AND "),f=l?.read??0,h=l&&$t.test(l.lastId)?l.lastId:void 0;for(let g=!1;!g;){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,p,h,a);if(!m)break;g=m.length<a;let y=!0;for(let S=0;S<m.length;S+=Za){let R=m.slice(S,S+Za),k=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,R):lw(e,R);if(!k){y=!1;break}if(k.length===0)continue;let A=await this.filesCopiedBefore(e,k,n);for(let I of A){if(I.into?.unchanged)continue;let P=hh(o,I.objectApiName);P.planned++,P.plannedBytes+=I.bytes}s+=A.filter(I=>I.into?.unchanged).length,e.failedCount+=await ba({files:A,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:I=>e.remapper.wasCreated(I),get:I=>e.remapper.get(I),add:(I,P,v)=>e.remapper.add(I,P,v),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:ds(e.store)}:{}});let w=hh(o,c);i(c,`Copying files: ${w.copied} of ${w.planned} copied so far`)}if(!y)break;f+=m.length;let b=m[m.length-1]?.Id;typeof b=="string"&&(h=b),h!==void 0&&e.store?.checkpoint(c,{lastId:h,read:f,...g?{done:!0}:{}},fh)}}for(let d of o.objects){let c=d.objectApiName==="Attachment"?"attachment":"file";e.onProgress({objectName:d.objectApiName,status:d.failed>0&&d.copied===0?"error":"done",progress:100,message:`Copied ${d.copied} ${c}${d.copied===1?"":"s"} of ${d.planned}`+(d.failed>0?`, ${d.failed} failed`:"")})}s>0&&Ze.info(`[forge] ${s} file(s) copied by the run this one takes up: linked to the records they lacked`)}async filesPageAfter(e,t,n,o,s){let i=n+(o?` AND Id > '${o}'`:"")+` ORDER BY Id LIMIT ${s}`;try{return await this.readOnPassingFailure(t,()=>this.deps.queryRecords(e.sourceOrgId,i))}catch(a){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:o?`(files after ${o})`:"(files)",messages:[`Not read, so not copied \u2014 a run taken up reads them again: ${X(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=gh(o);if(!s&&!mh(o)||n>=Ua||this.isAborted)throw o;s||await wh(Uf*2**n),Ze.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${Ua}): ${X(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&$t.test(c)&&n.set(c,d)}if(n.size===0)return[];let o=new Map,s=d=>{e.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(links of ${n.size} files)`,messages:[d]}]})},i=!1;try{let d=await this.readOnPassingFailure("ContentDocumentLink",()=>this.deps.queryRecords(e.sourceOrgId,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE ContentDocumentId IN (${[...n.keys()].map(c=>`'${c}'`).join(", ")})`,()=>i=!0));for(let c of d){let l=c.ContentDocumentId,u=c.LinkedEntityId;if(typeof l!="string"||typeof u!="string"||!e.remapper.wasCreated(u))continue;let p=o.get(l)??[];if(p.some(g=>g.id===u))continue;let f=c.ShareType,h=c.Visibility;p.push({id:u,...typeof f=="string"?{shareType:f}:{},...typeof h=="string"?{visibility:h}:{}}),o.set(l,p)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${X(d)}`);return}i&&s("More links than the source reads at once: the files were copied onto the records of the run among those read, and may lack a link to the others.");let a=[];for(let[d,c]of o){let l=n.get(d),u=l?.Id;if(!l||typeof u!="string")continue;let p=l.Title,f=typeof p=="string"&&p!==""?p:d,h=l.PathOnClient,g=l.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:u},name:f,bytes:typeof g=="number"&&Number.isFinite(g)?g:0,hosts:c,fields:{Title:f,PathOnClient:typeof h=="string"&&h!==""?h:f,...l.SharingPrivacy==="P"?{SharingPrivacy:"P"}:{}}})}return a}async readInTurn(e,t){t.turnsAhead.delete(e.objectApiName),await this.readNode(e,t,!0,!1),![...t.waitingFor.values()].some(o=>o.includes(e))&&(await this.readUnderWhatWaited(e.objectApiName,t,"at its turn"),await this.endTurn(e.objectApiName,t))}async readUnderWhatWaited(e,t,n){let o=t.scopeCache,s=t.readAgainUnder.get(e);if(!(!o||!s||!o.isRead(e))){t.readAgainUnder.delete(e);for(let{node:i,fieldInfos:a,whileWaiting:d}of s){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");t.failedObjects.has(i.objectApiName)||n==="at its turn"&&!d||n==="after the catalog"&&!d&&!vh(i.objectApiName,a).includes(e)||await this.readAgainUnderRowsOf(t,i,[...a],e)&&await this.readUnderRowsAdded(i.objectApiName,t,1)}}}async readAgainUnderRowsOf(e,t,n,o){let s=pn({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,extraWhere:e.config.objectSoqlFilters?.[t.objectApiName],fieldsLeftOut:e.config.fieldExclusions[t.objectApiName],readObjects:e.readObjects,catalog:Ve,under:new Set([o])});return s.kind!=="query"?!1:(await this.readMore(e,t,n,s.statements,`under the ${o} records read after it`)).length>0}async readUnderRowsAdded(e,t,n){let o=t.scopeCache;if(!o||n>=$m)return;let{config:s}=t,i=new Set(t.graph.edges.filter(a=>a.sourceObject===e&&a.targetObject!==e).map(a=>a.targetObject));for(let a of t.graph.nodes){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(!a.included||!i.has(d)||!o.isRead(d)||d===s.rootObjectApiName||Ve.has(d)||s.referenceDataObjects.has(d)||t.failedObjects.has(d)||t.notCreatable.has(d))continue;let c=await this.fieldsReadAgain(t,a);!c||!await this.readAgainUnderRowsOf(t,a,c.fields,e)||(c.described&&this.withoutFileContent(t,d,c.described,!0),await this.readUnderRowsAdded(d,t,n+1))}}async readWhatTheyCannotBeWrittenWithout(e,t,n,o){let s=e.scopeCache;if(!s||o.length===0)return;let{config:i}=e,a=new Set(i.fieldExclusions[t]??[]),d=new Map;for(let c of n){let l=c.referenceTo??[];if(!c.isReference||l.length!==1||a.has(c.name)||!dr(c)||!Qe(t,c.name,c.nillable))continue;let[u]=l;if(u===t||u===i.rootObjectApiName||Ve.has(u)||i.referenceDataObjects.has(u)||!e.readObjects.has(u)||e.failedObjects.has(u)||e.notCreatable.has(u)||!s.isRead(u))continue;let p=s.scopeOf(u),f=e.askedForRowsThatNeedThem.get(u),h=e.heldForExclusions.get(u);for(let g of o){let m=g[c.name];typeof m!="string"||m===""||p?.has(m)||f?.has(m)||h?.has(m)||e.remapper.get(m)||e.leftToThePlatform.has(m)||d.set(u,(d.get(u)??new Set).add(m))}}for(let[c,l]of d){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let u=e.graph.nodes.find(m=>m.included&&m.objectApiName===c);if(!u)continue;let p=e.askedForRowsThatNeedThem.get(c)??new Set;for(let m of l)p.add(m);e.askedForRowsThatNeedThem.set(c,p);let f=await this.fieldsReadAgain(e,u);if(!f)continue;let h=Wt(f.fields,i.fieldExclusions[c]);(await this.readMore(e,u,f.fields,new un().buildById({objectApiName:c,selectFields:h.length>0?h:["Id"],ids:l,extraWhere:i.objectSoqlFilters?.[c]}),`which the ${t} records read after it cannot be written without`)).length!==0&&(f.described&&this.withoutFileContent(e,c,f.described,!0),await this.readUnderRowsAdded(c,e,0))}}async readParentsOutsideTheGraph(e){let{config:t}=e;if(!e.scopeCache||t.referenceFallback!=="nullify")return!1;let n=new Map(e.graph.nodes.map(d=>[d.objectApiName,d])),o=new Map,s=new Map,i=!1,a=[...e.preread].filter(([d])=>!e.failedObjects.has(d)).map(([d,c])=>({objectApiName:d,fieldInfos:c.fieldInfos,records:c.records}));for(let d=0;d<Pm&&a.length>0;d++){let c=this.parentsWanted(e,a,d>0,n);c.size>0&&(i=!0);let l=[];for(let[p,f]of c){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let h=await this.refusalOf(e,p,n.get(p),o);h?await this.holdBackForARefusedParent(e,p,h,f,s):l.push([p,f])}let u=[];for(let[p,f]of l){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let h=xm(e,f);if(h.ids.size===0)continue;let g=await this.readParentsById(e,p,n.get(p),h);g&&u.push(g)}a=u}return i}parentsWanted(e,t,n,o){let{config:s}=e,i=new Map,a=new Map,d=c=>{let l=a.get(c);return l||(l=new Set((e.preread.get(c)?.records??[]).flatMap(u=>typeof u.Id=="string"?[u.Id]:[])),a.set(c,l)),l};for(let{objectApiName:c,fieldInfos:l,records:u}of t){let p=new Set(s.fieldExclusions[c]??[]);for(let f of l){let h=f.referenceTo??[];if(!f.isReference||h.length!==1||p.has(f.name)||!dr(f)||!Qe(c,f.name,f.nillable))continue;let[g]=h;if(g===c||g===s.rootObjectApiName||Ve.has(g)||s.referenceDataObjects.has(g)||s.excludedObjects.has(g)||as(e,g))continue;let m=o.get(g);if(m&&(!n||!m.included||e.failedObjects.has(g)))continue;let y=e.askedForRowsThatNeedThem.get(g),b=e.heldForExclusions.get(g);for(let S of u){let R=S[f.name];if(typeof R!="string"||R===""||nn(s,S)||e.remapper.get(R)||e.leftToThePlatform.has(R)||y?.has(R)||b?.has(R)||d(g).has(R))continue;let k=i.get(g);k||(k={ids:new Set,neededBy:new Set,rows:[]},i.set(g,k)),k.ids.add(R),k.neededBy.add(c),k.rows.push({objectApiName:c,row:S,field:f.name})}}}return i}async refusalOf(e,t,n,o){if(n)return e.notInTarget.has(t)?"not-in-target":e.notCreatable.has(t)?"not-creatable":void 0;let s=o.get(t);if(s!==void 0)return s??void 0;let i,a=this.deps.isObjectCreatable;if(a)try{await a(e.targetOrgId,t)||(i="not-creatable")}catch(d){ha(d)?i="not-in-target":e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${d instanceof Error?d.message:String(d)}`]}]})}return o.set(t,i??null),i}async holdBackForARefusedParent(e,t,n,o,s){let i=new Map;for(let{objectApiName:a,row:d,field:c}of o.rows){let l=d.Id;if(typeof l!="string"||i.get(a)?.has(l)||!await this.carriesTheLookup(e,a,c,s))continue;let u=i.get(a)??new Map;u.set(l,{row:d,why:{field:c,excluded:t,target:n}}),i.set(a,u)}for(let[a,d]of i){let c=e.preread.get(a);if(!c)continue;let l=c.records.filter(u=>typeof u.Id!="string"||!d.has(u.Id));this.holdBackRowsRead(e,a,c,l,[...d].map(([u,{row:p,why:f}])=>({id:u,row:p,why:f})))}}async carriesTheLookup(e,t,n,o){if(e.config.fieldMappings[t]?.[n])return!0;let s=o.get(t);if(s===void 0){try{s=await en(this.deps.describeFields,e.targetOrgId,t)}catch{s=null}o.set(t,s)}return s===null||s.creatable.has(n)}async readParentsById(e,t,n,o){let{config:s}=e,i=[...o.neededBy].sort().join(", "),a=s.maxRecordsPerObject?Math.floor(s.maxRecordsPerObject):0,d=a>0?a-(e.readByObject.get(t)??0):0;if(a>0&&d<=0){o.ids.size>0&&e.cappedObjects.add(t);return}let c=e.preread.get(t),l,u;if(c)l=[...c.fieldInfos];else{try{u=await this.deps.describeFields(e.sourceOrgId,t)}catch(w){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(describe, for the ${i} records that cannot be written without its records)`,messages:[X(w)]}]});return}l=u.filter(w=>!kn(w))}let p=e.askedForRowsThatNeedThem.get(t)??new Set;for(let w of o.ids)p.add(w);e.askedForRowsThatNeedThem.set(t,p);let f=Wt(l,s.fieldExclusions[t]),h=new un().buildById({objectApiName:t,selectFields:f.length>0?f:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]}),g;try{g=await Or(d>0?Fi(h,d,{byIdCount:h.length}):{kind:"query",statements:h,byIdCount:h.length},w=>this.deps.queryRecords(e.sourceOrgId,w,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(w){if(w instanceof Re)throw w;e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(read by id, for the ${i} records that cannot be written without them)`,messages:[X(w)]}]});return}Pr(e,g);let m=new Set((c?.records??[]).flatMap(w=>typeof w.Id=="string"?[w.Id]:[])),y=g.filter(w=>typeof w.Id!="string"||!m.has(w.Id)),b=w=>(e.graph.nodes.find(I=>I.objectApiName===w)??e.parentsOutside.get(w))?.level??0,S=n??e.parentsOutside.get(t)??Er(t,l,1+Math.max(0,...[...o.neededBy].map(b))),R=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,S,l,y,void 0,await this.excludedByKeyPrefix(e,t,l));let k=[...e.heldForExclusions.get(t)??[]].filter(([w])=>!R.has(w));if(this.leaveToThePlatform(e,t,y,l),y.length===0&&k.length===0)return;let A=c?.createableSet??new Set(l.filter(w=>w.createable).map(w=>w.name));if(y.length>0){e.preread.set(t,c?{...c,records:[...c.records,...y]}:{fieldInfos:l,createableSet:A,records:y,targetSetsPending:null}),u&&this.withoutFileContent(e,t,u,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,S),e.writtenObjects.add(t));let w=y.find(P=>typeof P.Id=="string")?.Id;typeof w=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,w.slice(0,3));let I=e.readAsParents.get(t)??{count:0,neededBy:new Set};I.count+=y.length;for(let P of o.neededBy)I.neededBy.add(P);e.readAsParents.set(t,I)}else if(!n){let w=e.heldForExclusions.get(t);w&&e.onProgress({objectName:t,status:"error",progress:100,message:Cr(t,w,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+y.length+k.length),s.dryRun){let w=y.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,y,A):0,I=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${y.length-w} ${I}record(s) would be inserted`+(w>0?`, ${w} ${I}would be written by the platform with ${zn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+fs(ps(k.map(([,P])=>P)),c!==void 0)})}return y.length>0?{objectApiName:t,fieldInfos:l,records:y}:void 0}async endTurn(e,t){t.turnsAhead.delete(e);let n=t.waitingFor.get(e);if(n){t.waitingFor.delete(e);for(let o of n){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");await this.readInTurn(o,t)}}}async readNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,onProgress:d,remapper:c}=t;t.readAtItsTurn.delete(e.objectApiName);let l=t.cursors.get(e.objectApiName);try{(!l||l.taken===0)&&d({objectName:e.objectApiName,status:"scanning",progress:0,message:`Querying ${e.objectApiName} records...`});let u=l?.described??await this.deps.describeFields(i,e.objectApiName);l&&(l.described=u);let p=u.filter(E=>!kn(E)),f=new Set(p.filter(E=>E.createable).map(E=>E.name));if(await this.skipForFailedParent(e,t,p))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let E=vm(e.objectApiName,p,t.turnsAhead);if(E)return t.waitingFor.set(E,[...t.waitingFor.get(E)??[],e]),!1}let h={node:e,edges:t.graph.edges,fieldInfos:p,scopedBuilder:t.scopedBuilder,scopeCache:t.scopeCache,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,extraWhere:uw(this.filterOf(t,e.objectApiName),l?.pass),fieldsLeftOut:s.fieldExclusions[e.objectApiName],maxRecordsPerObject:l?t.sample?.drawn.has(e.objectApiName)?void 0:this.pagedLimit(t,l):s.maxRecordsPerObject,...l?{inIdOrder:l.resumeAfter!==void 0?{afterId:l.resumeAfter}:{}}:{},readObjects:t.readObjects,catalog:Ve,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},g=pn(h);if(n&&this.waitsForWhatPointsAtIt(e,g,t))return t.catalogNodes.push({node:e,fieldInfos:p}),!1;if(g.kind==="skip"){if(n&&g.reason===Pl)return t.deferredNodes.push(e),!1;let E=t.heldForExclusions.get(e.objectApiName);return E&&E.size>0?(t.readByObject.set(e.objectApiName,E.size),d({objectName:e.objectApiName,status:"error",progress:100,message:Cr(e.objectApiName,E,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${g.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let E=pn({...h,maxRecordsPerObject:1}),M=E.kind==="query"?await Or(E,Z=>this.deps.queryRecords(i,Z)):[];return this.reportNotCreatable(e,t,M.length>0),!1}let y=o&&!s.referenceDataObjects.has(e.objectApiName)?l?.targetSets??en(this.deps.describeFields,a,e.objectApiName).then(E=>({ok:!0,sets:E}),E=>({ok:!1,error:E})):null;l&&(l.targetSets=y);let b=t.scopeCache?new Set:void 0,S=l?E=>{let M=pn({...h,maxRecordsPerObject:l.room===void 0?void 0:Math.max(1,l.room),inIdOrder:{afterId:E}});return M.kind==="query"&&M.statements.length===1?M.statements[0]:void 0}:void 0,R=await Or(g,E=>l?this.nextPage(t,e,l,E,S):this.readWhole(t,e.objectApiName,E),b,()=>t.cappedObjects.add(e.objectApiName));if(l?.ended&&R.length===0&&l.taken>0)return!1;let k=l?.pass?R.filter(l.pass.keep):R;Pr(t,k),this.keepWhatStatusesNeed(t,e,k,b);let A=this.holdBackWhatExclusionsCost(t,e,p,k,b,await this.excludedByKeyPrefix(t,e.objectApiName,p));b&&t.scopeCache?.addReached(e.objectApiName,b);let w=k.find(E=>typeof E.Id=="string")?.Id;if(typeof w=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,w.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,k.length);let E=await t.referenceDataMapper.resolve(e.objectApiName,k,a);for(let M of E.mappings)c.addExisting(M.sourceId,M.targetId);return E.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:E.unmatched.length,attemptedCount:k.length,referenceData:!0,samples:E.unmatched.slice(0,3).map(M=>({recordSummary:`Id=${M.sourceId} matchValue=${M.matchValue??"null"}`,messages:["Reference-data row not found on target org"]}))}),t.scopeCache&&_l(t.scopeCache,e.objectApiName,k),t.linkedCount+=E.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${E.mappings.length} resolved, ${E.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,k,p),e.objectApiName===mt&&t.standardPricebookId){let E=t.standardPricebookId,M=k.filter(Z=>Z.Id!==E);M.length!==k.length&&(k.length=0,k.push(...M))}let I=t.scopeCache;if(n&&I&&Ve.has(e.objectApiName))return Fo(I,e.objectApiName,k,p,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,p)}),t.catalogNodes.push({node:e,fieldInfos:p}),t.readAtItsTurn.set(e.objectApiName,{records:k,fieldInfos:p}),!1;let P=t.heldForExclusions.get(e.objectApiName);if(A>0&&k.length===0&&P&&!l)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,P.size),d({objectName:e.objectApiName,status:"error",progress:100,message:Cr(e.objectApiName,P)}),!1;if(at(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,k,p);let E=t.sample;if(E?.drawn.has(e.objectApiName)){let Z=k.filter(K=>this.inThePlan(E,e.objectApiName,String(K.Id)));k.length=0,k.push(...Z);let U=t.standardPricebookId,H=new Set(k.filter(K=>K[wt]===U).map(K=>nd(K,t.sellingModels)));for(let K of k)K[wt]!==U&&(H.has(nd(K,t.sellingModels))||E.withoutStandard.add(ue(String(K.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,k,p);let M=ur(k,{sellingModel:t.sellingModels});M.length!==k.length&&(k.length=0,k.push(...M))}t.scopeCache&&Fo(t.scopeCache,e.objectApiName,k,p,{keyPrefixes:await this.keyPrefixesNamedBy(t,p)}),await this.notePastDraft(t,e.objectApiName,k);let v=e.objectApiName===s.rootObjectApiName||Ve.has(e.objectApiName)?[]:Im(e.objectApiName,p,t),$=new Set(n?[...t.waitingFor.values()].flat().map(E=>E.objectApiName):[]);for(let E of v){let M=t.readAgainUnder.get(E)??[];t.readAgainUnder.set(E,[...M,{node:e,fieldInfos:p,whileWaiting:$.has(E)}])}if(s.files&&s.stream?.everything!==!0){let E=k.flatMap(M=>typeof M.Id=="string"&&!s.writtenBefore.retried(M.Id)?[M.Id]:[]);t.fileScope.set(e.objectApiName,E)}if(this.withoutFileContent(t,e.objectApiName,u,k.length>0),l&&(l.carry.rows+=k.length),l?.pass||t.readByObject.set(e.objectApiName,(l?l.carry.rows:k.length)+(P?.size??0)),t.preread.set(e.objectApiName,{fieldInfos:p,createableSet:f,records:k,targetSetsPending:y}),s.dryRun){let E=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,k,f),M=k.length-E;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${M} record(s) would be inserted`+(E>0?`, ${E} would be written by the platform with ${zn(e.objectApiName)}`:"")+oh(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,p,k),!0}catch(u){if(u instanceof Re||u instanceof hs)throw u;if(t.notCreatable.has(e.objectApiName))return this.reportNotCreatable(e,t,!0),!1;t.failedObjects.add(e.objectApiName),t.failedReads.add(e.objectApiName),l&&(l.failed=!0);let p=s.isScoped?0:Math.max(0,Vf(e,s.maxRecordsPerObject)-(l?.read??0));return t.failedCount+=p,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:p,attemptedCount:p,samples:[{recordSummary:"(stage failed before insert)",messages:[X(u)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${X(u)}`}),!1}}holdBackWhatExclusionsCost(e,t,n,o,s,i){let a=e.config.excludedObjects;if(a.size===0)return 0;let d=t.objectApiName,c=n.filter(R=>R.isReference&&Qe(d,R.name,R.nillable)),l=c.filter(R=>{let k=R.referenceTo??[];return k.length===1&&k[0]!==d&&a.has(k[0])}),u=c.filter(R=>{let k=R.referenceTo??[];return k.length>1&&k.some(A=>a.has(A))}),p=d===Le&&e.sellingModels&&a.has(Lt),f=ch(d),h=c.length>0&&e.heldForExclusions.size>0;if(l.length===0&&u.length===0&&!h&&!p&&!f)return 0;let g=R=>{for(let w of l){let I=R[w.name];if(typeof I=="string"&&I!==""&&!e.remapper.get(I))return{field:w.name,excluded:(w.referenceTo??[])[0]}}for(let w of u){let I=R[w.name];if(typeof I!="string"||I===""||e.remapper.get(I))continue;let P=i.get(I.slice(0,3));if(P!==void 0&&(w.referenceTo??[]).includes(P))return{field:w.name,excluded:P}}let k=h?sh(e,R,c):void 0;if(k)return k;let A=R[Bt];if(p&&typeof A=="string"&&A!=="")return{field:Bt,excluded:Lt}},m=e.heldForExclusions.get(d)??new Map,y=f?e.statusChildrenRead.get(f.parent)??{kept:new Set,held:new Map}:void 0,b=[];for(let R of o){let k=g(R),A=f?R[f.lookup]:void 0;if(!k){b.push(R),y&&typeof A=="string"&&y.kept.add(A);continue}y&&typeof A=="string"&&!y.held.has(A)&&y.held.set(A,k);let w=R.Id;typeof w=="string"&&(s?.delete(w),!m.has(w)&&(m.set(w,k),e.failedCount++))}y&&f&&e.statusChildrenRead.set(f.parent,y),m.size>0&&e.heldForExclusions.set(d,m);let S=o.length-b.length;return S>0&&(o.length=0,o.push(...b)),S}holdBackWhatHeldRowsCost(e){let{config:t}=e;if(e.heldForExclusions.size!==0)for(let n=!0;n&&!this.isAborted;){n=!1;for(let[o,s]of[...e.preread]){let i=s.fieldInfos.filter(c=>c.isReference&&Qe(o,c.name,c.nillable));if(i.length===0)continue;let a=[],d=[];for(let c of s.records){let l=c.Id,u=typeof l=="string"&&!nn(t,c)?sh(e,c,i):void 0;typeof l=="string"&&u?d.push({id:l,row:c,why:u}):a.push(c)}d.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,a,d))}}}holdBackWhatOnlyRowsHeldBackName(e){if(!e.scopeCache||e.namedByRowsHeldBack.size===0)return!1;let t=ah(e),n=!1;for(let[o,s]of[...e.preread]){if(!Ve.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,l=typeof c=="string"?dh(e,o,c,t):void 0;typeof c=="string"&&l?a.push({id:c,row:d,why:l}):i.push(d)}a.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,i,a))}return n}leaveOutWhatOnlyRowsHeldBackName(e,t){let n=e.scopeCache,o=n?.get(t);if(!n||!o||o.size===0||e.namedByRowsHeldBack.size===0)return;let s=ah(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=dh(e,t,d,s);c&&(a.push(d),!i.has(d)&&(i.set(d,c),e.failedCount++))}a.length!==0&&(e.heldForExclusions.set(t,i),n.forget(t,a))}holdBackRowsRead(e,t,n,o,s){let{config:i,onProgress:a}=e,d=e.heldForExclusions.get(t)??new Map;for(let{id:p,why:f}of s)d.set(p,f);e.heldForExclusions.set(t,d),e.failedCount+=s.length;let c=n.fieldInfos.filter(p=>p.isReference);for(let{row:p,why:f}of s)for(let h of c){let g=p[h.name];typeof g!="string"||g===""||e.namedByRowsHeldBack.has(g)||e.namedByRowsHeldBack.set(g,{field:h.name,excluded:f.excluded,namedBy:t})}let l=new Set(s.map(({id:p})=>p)),u=e.fileScope.get(t)??[];if(u.length>0&&e.fileScope.set(t,u.filter(p=>!l.has(p))),this.noteStatusRowsHeld(e,t,o,s),i.dryRun&&a({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${s.length} fewer would be inserted`+fs(ps(s.map(({why:p})=>p)))}),o.length>0){e.preread.set(t,{...n,records:o});return}e.preread.delete(t),e.failedObjects.add(t),a({objectName:t,status:"error",progress:100,message:Cr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=ch(t);if(!s)return;let i=e.statusChildrenRead.get(s.parent),a=new Map(i?.held??[]);for(let{row:c,why:l}of o){let u=c[s.lookup];typeof u=="string"&&!a.has(u)&&a.set(u,l)}let d=new Set;for(let c of n){let l=c[s.lookup];typeof l=="string"&&d.add(l)}e.statusChildrenRead.set(s.parent,{kept:d,held:a})}keepWhatStatusesNeed(e,t,n,o){let s=e.statusChildren.get(t.objectApiName);if(!s)return;let i=e.pastDraft.get(s.parent),a=[];for(let d of n){let c=d[s.lookup];typeof c=="string"&&i?.has(c)===!0?a.push(d):typeof d.Id=="string"&&o?.delete(d.Id)}a.length!==n.length&&(n.length=0,n.push(...a))}leaveToThePlatform(e,t,n,o){let s=e.leftToThePlatform.keep(t,n,tw(t,o)),i=n.length-s.length;return i>0&&(n.length=0,n.push(...s)),i}leaveWhatHangsFromThePlatform(e,t,n,o){let s=[...o],i=this.leaveToThePlatform(e,t.objectApiName,s,n),a=e.readByObject.get(t.objectApiName);return i>0&&a!==void 0&&e.readByObject.set(t.objectApiName,a-i),s}holdEmailsForTheirTask(e,t){if(e.taskTurnOver||!e.graph.nodes.some(s=>s.included&&s.objectApiName===tt))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(tt)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)ro(s)&&(n===void 0||n.has(String(s.ActivityId)))?e.emailsInTwoPasses?e.emailsLeftForTheirTask++:e.emailsAfterTheirTask.push(s):o.push(s);return o}async writeEmailsAfterTheirTask(e){if(e.emailsInTwoPasses){await this.streamEmailsAfterTheirTask(e);return}e.taskTurnOver=!0;let t=e.emailsAfterTheirTask.splice(0,e.emailsAfterTheirTask.length),n=e.graph.nodes.find(o=>o.objectApiName===Se);n&&t.length>0&&!this.isAborted&&(e.emailsAllWaiting=void 0,await this.writeNode(n,e,t)),this.endBeforeTheEmailsThatWaited(e,t.length,this.isAborted)}async streamEmailsAfterTheirTask(e){if(e.taskTurnOver)return;e.taskTurnOver=!0;let t=e.emailsLeftForTheirTask;e.emailsLeftForTheirTask=0;let n=e.graph.nodes.find(l=>l.included&&l.objectApiName===Se),o=e.config.stream?.resumeAfter,s=o?.has(Se)===!0||o?.has(Lo(Se,qf))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has(Se)&&e.graph.nodes.some(l=>l.included&&l.objectApiName===tt))||this.isAborted){this.endBeforeTheEmailsThatWaited(e,t,this.isAborted);return}let a=e.emailsWrittenFirst!==void 0,d=e.config.dryRun?"Simulated":"Completed";try{await this.streamNode(n,e,{name:qf,where:"ActivityId != null",keep:l=>ro(l),expected:t,stopped:`Stopped ${Se} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${Se} after their task`}})}catch(l){throw e.emailsWrittenFirst=void 0,l}let c=e.emailsWrittenFirst;c&&(e.emailsWrittenFirst=void 0,e.onProgress(c))}endBeforeTheEmailsThatWaited(e,t,n){let o=e.emailsWrittenFirst??e.emailsAllWaiting;e.emailsWrittenFirst=void 0,e.emailsAllWaiting=void 0,o&&(Xa(e,Se,t),e.onProgress(iw(o,t,n,oh(e,Se))))}endOfTheEmails(e,t){return n=>{if(n.status!=="done"&&n.status!=="error"&&n.status!=="stopped"){e.onProgress(n);return}if(!t){if(e.emailsAfterTheirTask.length===0&&e.emailsLeftForTheirTask===0){e.onProgress(n);return}e.emailsWrittenFirst=n,e.onProgress({...n,status:"running"});return}let o=e.emailsWrittenFirst;e.emailsWrittenFirst=void 0,e.onProgress(o?{...n,status:o.status==="error"?"error":n.status,message:`${o.message}; ${n.message}`}:n)}}async linkTasksWrittenWithEmails(e,t){if(e.emailsInTwoPasses)return this.tasksLinkedBeforeTheirTurn(e,t);let n=new Map;for(let c of e.preread.get(Se)?.records??[]){let l=c.ActivityId,u=c.Id;if(typeof l!="string"||l===""||typeof u!="string"||!e.remapper.isCreated(u))continue;let p=e.remapper.get(u);p&&n.set(l,p)}let o=[...new Set(t.flatMap(c=>n.get(String(c.Id))??[]))];if(o.length===0)return{rows:t,linked:0};let s,{simulated:i}=e;try{s=i?new Map(o.map(c=>[c,i.idFor(null)])):await ri(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:tt,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${X(c)}`]}]}),{rows:t,linked:0}}let a=t.filter(c=>{let l=String(c.Id),u=n.get(l),p=u===void 0?void 0:s.get(u);return p===void 0?!0:(e.remapper.addExisting(l,p,tt),En(e,l),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),xr(e,tt,d),{rows:a,linked:d}}tasksLinkedBeforeTheirTurn(e,t){let n=t.filter(s=>{let i=s.Id;return typeof i!="string"||e.remapper.get(i)===void 0}),o=t.length-n.length;return o>0&&(e.linkedCount+=o),xr(e,tt,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get(Se)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||ro(i)||!e.remapper.isCreated(d))continue;let c=e.remapper.get(d);c&&t.set(c,a)}if(t.size===0)return;let n=[...t.keys()],{simulated:o}=e,s;try{s=o?new Map(n.map(i=>[i,o.idFor(null)])):await ri(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:tt,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${X(i)}`]}]});return}for(let[i,a]of s){let d=t.get(i);d===void 0||e.remapper.get(d)!==void 0||(e.remapper.addExisting(d,a,tt),En(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!so(t)||n.length===0)return{rows:n,lookups:new Map,held:new Map,linked:0,owners:0,values:i};let{config:a,remapper:d,simulated:c}=e,l=si[t],u=a.decisions.defaultOf(t,l),p=c?await this.writesAs(e):void 0,f=await li(t,n,{source:y=>this.deps.queryRecords(e.sourceOrgId,y),target:y=>this.deps.queryRecords(e.targetOrgId,y),targetIdOf:y=>d.get(y),mappedUser:y=>a.ownerMappings[y],...u!==void 0?{defaultUser:u}:{},written:s,...c?{simulated:{ownerOf:y=>a.ownerMappings[y]??(p??=c.idFor(Ah)),idFor:()=>c.idFor(o)}}:{}});f.defaulted.size>0&&u!==void 0&&e.decisionsApplied.add({kind:"set_default",objectApiName:t,field:l,to:u},f.defaulted.size);for(let[,{field:y,parentObject:b}]of f.held)b==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:y,rows:1,detail:{type:"reference"},decisions:[...Hc.required_field_missing??[]]});let h=0,g=0;for(let[y,{id:b,owners:S,notKept:R,unread:k=[]}]of f.linked){let A=String(y.Id);d.addExisting(A,b,t),d.isCreated(String(y.OpportunityId))&&(En(e,A),g++),S&&h++;for(let w of R)i.notKept.set(w,(i.notKept.get(w)??0)+1);for(let w of k)i.unread.set(w,(i.unread.get(w)??0)+1)}let m=f.linked.size;return m>0&&(e.linkedCount+=m),xr(e,t,g),m>g&&e.existingRecords.push({objectApiName:t,linked:m-g,unidentified:0}),{rows:m>0?n.filter(y=>!f.linked.has(y)):n,lookups:f.lookups,held:f.held,linked:m,owners:h,values:i}}async takeTheSyncCopies(e,t,n,o,s){let i={taken:0,given:0};if(!e.readsEverythingFirst)return i;let{remapper:a,simulated:d,config:c}=e,l=g=>a.wasCreated(g)||c.writtenBefore.has(g),u=[];if(t.forEach(({source:g},m)=>{let y=g[ga],b=g[ma];if(typeof y!="string"||typeof b!="string"||!l(y)||!l(b))return;let S=a.get(y),R=a.get(b);S&&R&&u.push({index:m,quote:S,product:R})}),u.length===0)return i;let p=g=>s.updatable?s.updatable.has(g):s.fields?.find(m=>m.name===g)?.updateable!==!1,f;if(d)f=this.copiesASimulationFinds(e,t,u,s.keyPrefix);else{let g=S=>s.fields===void 0||s.fields.some(R=>R.name===S&&R.queryable!==!1),m=[...new Set(u.flatMap(({index:S})=>Object.keys(n[S]??{})))].filter(S=>p(S)&&g(S)),y;try{y=await ep(S=>this.deps.queryRecords(e.targetOrgId,S),u,m)}catch(S){return e.errors.push({objectApiName:Kn,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(quote lines the platform copied from their opportunity products)",messages:[`Not looked up, so written as read: a quote that syncs with its opportunity may hold a line twice. ${X(S)}`]}]}),i}let b=new Set;for(let S of o){let R=a.get(String(S.Id));R&&b.add(R.slice(0,15))}f=tp(u,y,b)}if(f.size===0)return i;let h=d?0:await this.giveTheCopiesTheirFields(e,t,n,f,p);for(let[g,m]of f){let y=t[g],b=typeof y.source.Id=="string"?y.source.Id:void 0,S=String(m.Id);b!==void 0&&a.add(b,S,Kn),y.nullifiedFks.length>0&&this.oweToTheSecondPass(e,y.nullifiedFks.map(R=>({objectApiName:Kn,newId:S,sourceId:b,fieldName:R.field,sourceRefId:R.sourceRefId,...R.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let g of[...f.keys()].sort((m,y)=>y-m))t.splice(g,1),n.splice(g,1);return{taken:f.size,given:h}}copiesASimulationFinds(e,t,n,o){let s=new Map,{simulated:i}=e;if(!i)return s;let a=u=>typeof u=="string"&&u!==""?u.slice(0,15):void 0,d=new Map;for(let u of e.pendingFkUpdates){let p=a(u.sourceId),f=a(u.sourceRefId);u.objectApiName===Fe&&u.fieldName===Jo&&p&&f&&d.set(p,f)}if(d.size===0)return s;let c=new Map;for(let u of e.preread.get(Xu)?.records??[]){let p=a(u.Id),f=a(u.OpportunityId);p&&f&&c.set(p,f)}let l=new Set;for(let{index:u}of n){let{source:p}=t[u],f=a(p[ma]),h=a(p[ga]),g=f?c.get(f):void 0;!f||!h||!g||d.get(g)!==h||l.has(f)||(l.add(f),s.set(u,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:Kn,recordSummary:"(quote lines the platform copied from their opportunity products)",leftAs:"Taken, and left as the platform copied them, without the fields of the source's lines"}){let a=[];for(let[u,p]of o){let f=new Set(t[u].nullifiedFks.map(g=>g.field)),h=np(n[u]??{},p,s,f);Object.keys(h).length>0&&a.push({Id:p.Id,...h})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],l=0;for(let u=0;u<a.length;u+=Rh){let p=a.slice(u,u+Rh);if(!d||this.isAborted){c.push(`${p.length} not sent: ${d?"the run was cancelled first":"the run sends no update"}`);continue}try{let f=await d(e.targetOrgId,i.objectApiName,p);p.forEach((h,g)=>{let m=f[g];m?.success?l++:c.push(`${String(h.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(f){c.push(`${p.length} not updated: ${X(f)}`)}}return c.length>0&&e.errors.push({objectApiName:i.objectApiName,stage:"insert",failedCount:0,attemptedCount:a.length,samples:[{recordSummary:i.recordSummary,messages:[`${i.leftAs}: ${c.slice(0,3).join(" | ")}`]}]}),l}async linkTheRolesThePlatformWrote(e,t,n,o){let s={linked:0,given:0};if(t.length===0)return s;let{remapper:i,simulated:a,config:d}=e,c=new Map;if(d.writtenBefore.size>0&&t.forEach(({source:y},b)=>{let S=y.OpportunityId,R=n[b]?.[Ce];typeof S!="string"||typeof R!="string"||R===""||ii(y)&&d.writtenBefore.has(S)&&c.set(S,R)}),e.contactSentWith.size===0&&c.size===0)return s;let l=mr(t.map(({source:y},b)=>({OpportunityId:y.OpportunityId,[Ce]:n[b]?.[Ce],IsPrimary:y.IsPrimary})),y=>i.isCreated(y)?e.contactSentWith.get(y):c.get(y));if(l.length===0)return s;let u=y=>o.updatable?o.updatable.has(y):o.fields?.find(b=>b.name===y)?.updateable!==!1,p=a?l.filter(y=>i.isCreated(String(t[y].source.OpportunityId))):[],f=l.filter(y=>!p.includes(y)),h=new Map(p.map(y=>[y,{Id:a?.idFor(o.keyPrefix)??""}]));if(f.length>0){let y=w=>o.fields===void 0||o.fields.some(I=>I.name===w&&I.queryable!==!1),b=a?[]:[...new Set(f.flatMap(w=>Object.keys(n[w]??{})))].filter(w=>u(w)&&y(w)),S=new Map(f.map(w=>[w,{opportunity:String(i.get(String(t[w].source.OpportunityId))),contact:String(n[w]?.[Ce])}])),R;try{R=await ai(w=>this.deps.queryRecords(e.targetOrgId,w),[...new Set([...S.values()].map(({opportunity:w})=>w))],b)}catch(w){e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[`Not looked up, so written as read: an opportunity may hold the role of its contact twice. ${X(w)}`]}]}),R=[]}let{found:k,alike:A}=di(S,R);for(let[w,I]of k)h.set(w,I);if(A.length>0){for(let w of A)e.contactSentWith.delete(String(t[w].source.OpportunityId));e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[gc(A.length)]}]})}}if(h.size===0)return s;let g=a?0:await this.giveTheCopiesTheirFields(e,t,n,h,u,{objectApiName:ze,recordSummary:"(contact roles the platform wrote with their opportunities)",leftAs:"Linked, and left as the platform wrote them, without the fields of the source's roles"}),m=0;for(let[y,b]of h){let S=t[y],R=typeof S.source.Id=="string"?S.source.Id:void 0,k=String(b.Id);if(R===void 0)continue;let A=String(S.source.OpportunityId);e.contactSentWith.delete(A),i.addExisting(R,k,ze),i.wasCreated(A)&&(En(e,R),m++),S.nullifiedFks.length>0&&this.oweToTheSecondPass(e,S.nullifiedFks.map(w=>({objectApiName:ze,newId:k,sourceId:R,fieldName:w.field,sourceRefId:w.sourceRefId,...w.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let y of[...h.keys()].sort((b,S)=>S-b))t.splice(y,1),n.splice(y,1);return e.linkedCount+=h.size,xr(e,ze,m),h.size>m&&e.existingRecords.push({objectApiName:ze,linked:h.size-m,unidentified:0}),{linked:h.size,given:g}}async mapContactsOfPersonAccounts(e,t=e.preread.get(ye)?.records??[]){let n=new Map;for(let i of t){let a=i[gr],d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||e.remapper.get(a))continue;let c=e.remapper.get(d);c&&n.set(c,{contact:a,account:d})}if(n.size===0||await this.personAccountsInTarget(e)===!1)return;let{simulated:o}=e;if(o){for(let[,{contact:i,account:a}]of n)e.contactsOnTheirOwn.has(i)||(e.remapper.addExisting(i,o.idFor(null)),e.remapper.isCreated(a)&&En(e,i));return}let s;try{s=await hc(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:ye,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contacts the platform wrote with the person accounts)",messages:[`Not looked up, so what points at them is left empty: ${X(i)}`]}]});return}for(let[i,{contact:a,account:d}]of n){let c=s.get(i);if(!c){e.contactsOnTheirOwn.add(a);continue}e.remapper.addExisting(a,c),e.remapper.isCreated(d)&&En(e,a)}}writesAs(e){let{runningUser:t}=this.deps;return e.writesAs??=t?t(e.targetOrgId).then(n=>typeof n=="string"&&n!==""?n:void 0,()=>{}):Promise.resolve(void 0),e.writesAs}personAccountsInTarget(e){return e.personAccountsInTarget??=this.deps.describeFields(e.targetOrgId,ye).then(t=>t.some(n=>n.name===gr),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${ye}'`).then(t=>t.length===0?void 0:new Set(t.filter(n=>n.IsPersonType===!0||n.IsPersonType==="true").map(n=>String(n.Id).slice(0,15))),()=>{}),e.personRecordTypes}async takenAsBusinessAccounts(e,t,n){let o=t.filter(ln);if(o.length===0)return new Set;let s=await this.personAccountsInTarget(e);if(s!==!0)return new Set(s===!1?o:[]);let i=await this.personRecordTypesInTarget(e);if(!i)return new Set;let a=new Map((e.config.recordTypeMappings??[]).map(l=>[l.sourceId,l.targetId])),d=l=>{let u=l.RecordTypeId;return n&&typeof u=="string"&&u!==""?u:void 0},c=o.some(l=>d(l)===void 0)?aa((await this.objectInfoOf(e.targetOrgId,ye))?.recordTypes):void 0;return new Set(o.filter(l=>{let u=d(l),p=u===void 0?c:a.get(u);return p!==void 0&&!i.has(p.slice(0,15))}))}async noteContactsOfBusinessAccounts(e,t,n){let o=n.has("RecordTypeId")&&!(e.config.fieldExclusions[ye]??[]).includes("RecordTypeId")&&e.config.fieldMappings[ye]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[gr];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if(so(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!nn(e.config,a)).map(a=>String(a.Id)));return n.length===0||i.size===0?0:(await this.teamThePlatformWrites(e,t,n,i)).size}if(t===ze)return(await this.rolesThePlatformWritesOfTheRead(e,e.preread.get(Fe)?.records??[],e.preread.get(ge)?.records??[],n)).size;if(t===ye)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==ge)return 0;let s=n.filter(i=>ln(i)&&!e.contactsOnTheirOwn.has(String(i.Id))).length;return s>0&&await this.personAccountsInTarget(e)!==!1?s:0}async personContactsOnTheirOwn(e,t){if(t.length===0)return{rows:new Set,why:""};let n=await this.personAccountsInTarget(e);return{rows:new Set(t.filter(i=>n===!1||e.contactsOnTheirOwn.has(String(i.Id)))),why:n===!1?"the target has no person accounts":"their account is no person account in the target"}}saySentOnTheirOwn(e,t,n){t!==0&&e.errors.push({objectApiName:ge,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`IsPersonAccount=true (${t} record${t===1?"":"s"})`,messages:[`Sent as contacts of their own: ${n}, and wrote no contact with it.`]}]})}linkPersonContacts(e,t){let n=0,o=0,s=0,i=0;for(let c of t){let l=String(c.Id),u=e.remapper.get(l);if(u){e.remapper.addExisting(l,u,ge),n++,aw(e,l)&&o++;continue}let p=c.AccountId;typeof p=="string"&&e.remapper.get(p)?i++:s++}n>0&&(e.linkedCount+=n),xr(e,ge,o),n>o&&e.existingRecords.push({objectApiName:ge,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:rh.accountNotWritten}]:[],...i>0?[{count:i,why:rh.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:ge,stage:"scope",failedCount:d,attemptedCount:0,samples:a.map(({count:c,why:l})=>({recordSummary:`IsPersonAccount=true (${c} record${c===1?"":"s"})`,messages:[`Not written: ${l.replace(/^not sent: /,"")}.`]}))})),{linked:n,notSent:a}}reportNotCreatable(e,t,n){t.skippedCount++,n&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not createable on target org"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:n?`Skipped ${e.objectApiName} (target org rejects inserts on this entity)`:`Skipped ${e.objectApiName} (target org rejects inserts on this entity; the clone holds none of its records)`})}reportNotInTarget(e,t){t.skippedCount++,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not in the target org, or the user the run writes as cannot see it: none of its records can be written there"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (not in the target org)`})}waitsForWhatPointsAtIt(e,t,n){return!n.scopeCache||!Ve.has(e.objectApiName)?!1:t.kind==="skip"||!Dl(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=Cl.flatMap(d=>e.catalogNodes.filter(({node:c})=>c.objectApiName===d)).filter(({node:d})=>!e.failedObjects.has(d.objectApiName)&&!e.notCreatable.has(d.objectApiName)&&!o.referenceDataObjects.has(d.objectApiName));if(!s.some(({node:d})=>Kf(n,d.objectApiName).size>0))return;let i=new Map([...n.entries()].map(([d,c])=>[d,new Set(c)])),a=new Set;for(let{node:d,fieldInfos:c}of s){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let l=d.objectApiName,u=[...c],p=o.objectSoqlFilters?.[l],f=async m=>l===mt&&e.standardPricebookId?m.filter(y=>y.Id!==e.standardPricebookId):at(l)&&e.standardPricebookId?(await this.addStandardPricebookEntries(d,e,m,u),e.readsEverythingFirst||await this.pricesInTheCurrencyWritten(d,e,m,u),ur(m,{sellingModel:e.sellingModels})):m;if(l===Lt){if(!a.has(Po)&&!a.has(lr))continue;let m=pn({node:d,edges:e.graph.edges,fieldInfos:u,scopedBuilder:e.scopedBuilder,scopeCache:n,rootObjectApiName:o.rootObjectApiName,rootRecordId:o.rootRecordId,extraWhere:p,fieldsLeftOut:o.fieldExclusions[l],readObjects:e.readObjects,catalog:Ve});if(m.kind!=="query")continue;(await this.readMore(e,d,u,m.statements,"named by records read after the catalog",f)).length>0&&a.add(l);continue}let h=Wt(u,o.fieldExclusions[l]),g=new Set;for(let m=0;m<Em;m++){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let y=[...Kf(n,l)].filter(S=>!g.has(S));if(y.length===0)break;for(let S of y)g.add(S);if((await this.readMore(e,d,u,new un().buildById({objectApiName:l,selectFields:h.length>0?h:["Id"],ids:new Set(y),extraWhere:p}),m===0?"named by records read after the catalog":"named by its own records read before them",f)).length===0)break;a.add(l)}}a.size>0&&await this.readAfterTheCatalogAgain(e,t,i)}async readAfterTheCatalogAgain(e,t,n){let o=e.scopeCache;if(!o)return;let{config:s}=e,i=new Set;for(let a of t){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(e.failedObjects.has(d)||e.notCreatable.has(d)||s.referenceDataObjects.has(d))continue;let c=n.get(d),l=o.isRead(d)?o.scopeOf(d):void 0,u=new Set([...o.get(d)??[]].filter(b=>!c?.has(b)&&!l?.has(b))),p=new Set(e.graph.edges.filter(b=>b.targetObject===d&&i.has(b.sourceObject)).map(b=>b.sourceObject));if(u.size===0&&p.size===0)continue;let f=await this.fieldsReadAgain(e,a);if(!f)continue;let{fields:h}=f,g=s.objectSoqlFilters?.[d],m=[];if(u.size>0){let b=Wt(h,s.fieldExclusions[d]);m.push(...new un().buildById({objectApiName:d,selectFields:b.length>0?b:["Id"],ids:u,extraWhere:g}))}if(p.size>0){let b=pn({node:a,edges:e.graph.edges,fieldInfos:h,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,extraWhere:g,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:Ve,under:p});b.kind==="query"&&m.push(...b.statements)}m.length===0||(await this.readMore(e,a,h,m,"for what the catalog read again brought")).length===0||(i.add(d),f.described&&this.withoutFileContent(e,d,f.described,!0))}}async fieldsReadAgain(e,t){let n=e.preread.get(t.objectApiName);if(n)return{fields:[...n.fieldInfos]};try{let o=await this.deps.describeFields(e.sourceOrgId,t.objectApiName);return{fields:o.filter(s=>!kn(s)),described:o}}catch{return}}async readMore(e,t,n,o,s,i=async a=>a){let a=e.scopeCache;if(!a)return[];let{config:d}=e,c=t.objectApiName,l=d.maxRecordsPerObject?Math.floor(d.maxRecordsPerObject):0,u=l>0?l-(e.readByObject.get(c)??0):0;if(l>0&&u<=0)return o.length>0&&e.cappedObjects.add(c),[];let p=a.isRead(c),f=new Set(p?a.scopeOf(c)??[]:[]),h=m=>typeof m.Id!="string"||!f.has(m.Id),g;try{let m=await Or(u>0?Fi(o,u,{byIdCount:o.length}):{kind:"query",statements:o,byIdCount:o.length},$=>this.deps.queryRecords(e.sourceOrgId,$,()=>e.truncatedObjects.add(c)),void 0,()=>e.cappedObjects.add(c));Pr(e,m);let y=m.filter(h);this.keepWhatStatusesNeed(e,t,y,void 0);let b=e.heldForExclusions.get(c),S=0;for(let $ of b?y:[]){let E=$.Id;typeof E!="string"||b?.get(E)?.namedBy===void 0||(b.delete(E),S++)}S>0&&(b?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=S,e.readByObject.set(c,(e.readByObject.get(c)??S)-S));let R=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,y,void 0,await this.excludedByKeyPrefix(e,c,n));let k=[...e.heldForExclusions.get(c)??[]].filter(([$])=>!R.has($));if(this.leaveToThePlatform(e,c,y,n),g=(await i(y)).filter(h),Fo(a,c,g,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,g.flatMap($=>typeof $.Id=="string"?[$.Id]:[])),await this.notePastDraft(e,c,g),g.length===0&&k.length===0)return[];if(d.files&&d.stream?.everything!==!0){let $=g.flatMap(E=>typeof E.Id=="string"?[E.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...$])}p||e.skippedCount--;let A=e.preread.get(c),w=A?.records??[],I=at(c)?ur([...w,...g],{sellingModel:e.sellingModels}):[...w,...g],P=I.length-w.length,v=A?.createableSet??new Set(n.filter($=>$.createable).map($=>$.name));if(e.preread.set(c,A?{...A,records:I}:{fieldInfos:n,createableSet:v,records:I,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+P+k.length),d.dryRun){let $=await this.writtenWithTheirAccountOnADryRun(e,c,at(c)?[]:g,v);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${P-$} more record(s) would be inserted`+($>0?`, ${$} more would be written by the platform with ${zn(c)}`:"")+`, ${s}`+fs(ps(k.map(([,E])=>E)),!0)})}}catch(m){if(m instanceof Re)throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[X(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,g),g}async addStandardPricebookEntries(e,t,n,o){let s=t.standardPricebookId;if(!s)return;let i=l=>nd(l,t.sellingModels),a=new Set,d=new Set,c=new Set;for(let l of n){let u=l.Id;if(typeof u=="string"&&c.add(u),l[wt]===s)continue;let p=l[yt];typeof p=="string"&&p&&(a.add(p),d.add(i(l)))}if(a.size!==0)try{let l=new un().buildJoining({objectApiName:e.objectApiName,selectFields:Wt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:yt,ids:a},whole:{field:wt,ids:new Set([s])}}),u=0;for(let p of l)for(let f of await this.deps.queryRecords(t.sourceOrgId,p)){let h=f.Id;typeof h=="string"&&c.has(h)||d.has(i(f))&&(n.push(f),Pr(t,[f]),u++)}u>0&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:`Added ${u} standard price book entr${u===1?"y":"ies"} the custom prices depend on`})}catch(l){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book entries)",messages:[X(l)]}]})}}async pricesInTheCurrencyWritten(e,t,n,o,s){let i=await this.priceCurrencyInput(t,n,o);if(!i)return;let a={...i,...s?{wanted:s}:{}},d=s?t.pricesTheGateCounted:void 0,c=la(a).filter(g=>!d||d.has(ca(g))),l=[],u=[...new Set(c.map(({currency:g})=>g))].filter(g=>/^[A-Z]{3}$/.test(g));if(u.length>0)try{let g=new un().buildJoining({objectApiName:e.objectApiName,selectFields:Wt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:yt,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:wt,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${dt} IN (${u.map(m=>`'${m}'`).join(", ")})`});for(let m of g)l.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(g){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[X(g)]}]});return}let p=t.sample;if(p?.drawn.has(e.objectApiName)){let g=l.filter(m=>this.inThePlan(p,e.objectApiName,String(m.Id)));l.length=0,l.push(...g)}let f=ua(a,d?l.filter(g=>d.has(da(Vu(g,t.sellingModels),String(g[dt])))):l),h=new Set(n);n.length=0,n.push(...f.rows),Pr(t,f.rows.filter(g=>!h.has(g)));for(let[g,m]of f.standsFor)t.remapper.alias(g,m),t.prices.standsFor.set(g,m);for(let[g,m]of t.prices.standsFor){let y=f.standsFor.get(m);y!==void 0&&(t.remapper.alias(g,y),t.prices.standsFor.set(g,y))}for(let[g,m]of f.convertedInto)t.prices.convertedInto.set(g,m);for(let[g,m]of f.written)t.prices.written.set(g,m);for(let[g,m]of f.keys)t.prices.keys.set(g,m);t.pricesSwappedSaid.push(...f.said),!(f.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:pa(f.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===dt)||!t.some(d=>typeof d[dt]=="string"))return;let s=await this.runCurrencies(e);if(!s)return;let{target:i}=s,a=this.priceCurrencyWrittenIn(e,i);return{prices:t,standardBookId:o,sellingModels:e.sellingModels,writtenIn:a,active:i.active}}priceCurrencyWrittenIn(e,t){return n=>{let o={[dt]:n};e.config.decisions.applyToRow(Le,o,void 0,new Pi);let s=o[dt];return typeof s=="string"&&t.active.has(s)?s:Mc(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(Le);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=la({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(ca)),o.length}currenciesTheirLinesMayWant(e,t,n){let o=new Set(t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[])),{decisions:s}=e.config,i=d=>{if(s.changesRowsOf(d))return!0;if(!fo(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(l=>l.name===Bc[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:l}]of Object.entries(Vo)){let u=i(c);for(let p of e.preread.get(d)?.records??[]){let f=p[Ar];if(typeof f!="string"||typeof p[l]!="string")continue;let h=e.prices.standsFor.get(f)??f;if(!o.has(h))continue;let g=p[Ge],m=!u&&typeof g=="string"&&n.has(g)?[g]:[...n],y=a.get(h)??new Set;for(let b of m)y.add(b);a.set(h,y)}}return a}currenciesTheirLinesWant(e,t){let n=new Set(t.flatMap(s=>typeof s.Id=="string"?[s.Id]:[])),o=new Map;for(let[s,{field:i}]of Object.entries(Vo))for(let a of e.preread.get(s)?.records??[]){let d=a[Ar];if(typeof d!="string")continue;let c=e.prices.standsFor.get(d)??d;if(!n.has(c))continue;let l=this.currencyTheirRecordWentIn(e,a,i);if(l===void 0)continue;let u=o.get(c)??new Set;u.add(l),o.set(c,u)}return o}currencyTheirRecordWentIn(e,t,n){let o=t[n];if(typeof o!="string"||e.remapper.get(o)===void 0)return;let s=e.currencyChangesById.get(o)?.to;if(s!==void 0)return s;let i=t[Ge];return typeof i=="string"&&i!==""?i:void 0}pricedInTheirRecordsCurrency(e,t,n){let o=Vo[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[Ar];if(typeof i!="string")return s;let a=e.prices.standsFor.get(i)??i,d=e.prices.keys.get(a),c=d?this.currencyTheirRecordWentIn(e,s,o):void 0;if(d===void 0||c===void 0)return s;let l=e.prices.written.get(da(d,c));return l===void 0||l===a||l===i||e.remapper.get(l)===void 0?s:{...s,[Ar]:l}})}async objectInfoOf(e,t){if(!this.deps.describeObject)return null;try{return await this.deps.describeObject(e,t)}catch{return null}}async toWriteAtTheGate(e,t,n,o=0){let s=n.records.filter(l=>!nn(e.config,l)),i=n.records.length-s.length,a=s.length>0?await this.heldBackAtTheGate(e,t,n,s):[],d=a.length>0,c={...i>0?{writtenBefore:i}:{},...d?eh(a,s.length):{}};return{objectApiName:t,rows:d?[]:s,...Object.keys(c).length>0?{leftOut:c}:{},...o>0&&!d?{mayAdd:o}:{}}}async withoutWhatThePlatformWrites(e,t){let n=l=>t.find(u=>u.objectApiName===l)?.rows??[],o=new Map,s=new Set(n("Opportunity").map(l=>String(l.Id)));for(let l of t)if(!(!so(l.objectApiName)||l.rows.length===0)){if(s.size===0)break;o.set(l.objectApiName,await this.teamThePlatformWrites(e,l.objectApiName,l.rows,s))}let i=await this.personContactsThePlatformWrites(e,n(ye),n(ge));i.size>0&&o.set(ge,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(Fe),n(ge),n(ze)),d=await this.rolesOfOpportunitiesWrittenBefore(e,n(ze).filter(l=>!a.has(l))),c=new Set([...a,...d.linked]);return c.size>0&&o.set(ze,c),t.map(l=>{let u=o.get(l.objectApiName),p=l.objectApiName===ze&&d.mayBe>0?{mayBeByThePlatform:{rows:d.mayBe,before:!0}}:{};return!u||u.size===0?{...l,...p}:{...l,rows:l.rows.filter(f=>!u.has(f)),leftOut:{...l.leftOut,byThePlatform:u.size},...p}})}async withoutWhatTheTargetHoldsByValue(e,t){let{config:n}=e,o=[];for(let s of t){let{objectApiName:i,rows:a}=s,d=e.preread.get(i);if(a.length===0||s.counted||!d){o.push(s);continue}let c=await(d.targetSetsPending??en(this.deps.describeFields,e.targetOrgId,i).then(k=>({ok:!0,sets:k}),k=>({ok:!1,error:k})));if(!c.ok){o.push(s);continue}let l=er(d.createableSet,c.sets.creatable),u=new Set(n.fieldExclusions[i]??[]),p=n.fieldMappings[i]??{},f=new Set(Object.values(p)),h=new Set(await e.maskedSourceFields(i).catch(()=>[])),g=n.anonymization,m=new Set(e.anonymize&&g?g.fields[i]??this.detectedPersonalFields(e,g,i,d.fieldInfos):[]),y=new Set(e.contactPoints?sa(d.fieldInfos).map(({name:k})=>k):[]),b=n.decisions.truncatedFieldsOf(i),S=c.sets.fields.filter(({name:k,unique:A,externalId:w})=>A===!0&&l.has(k)&&!(n.upsertMode==="auto"&&w===!0)&&!u.has(k)&&p[k]===void 0&&!f.has(k)&&!h.has(k)&&!m.has(k)&&!y.has(k)&&!b.has(k)&&!(i===ye&&k.endsWith("__pc"))),R=new Map;for(let k of S){let{name:A}=k,w=new Map;for(let v of a){let $=v[A];if(typeof $!="string"||$===""||Oh.test($))continue;let E=Tn(k,$);w.has(E)||w.set(E,$)}let I=[...w.values()];if(I.length===0)continue;let P=new Set;try{let v=Me(i),$=Me(A);for(let E of An(I,bh)){let M=await this.deps.queryRecords(e.targetOrgId,`SELECT ${$} FROM ${v} WHERE ${$} IN (${E})`);for(let Z of M){let U=Z[A];typeof U=="string"&&P.add(Tn(k,U))}}}catch{continue}for(let v of a){let $=v[A];typeof $=="string"&&P.has(Tn(k,$))&&!R.has(v)&&R.set(v,A)}}if(R.size===0){o.push(s);continue}o.push({...s,rows:a.filter(k=>!R.has(k)),leftOut:{...s.leftOut,linkedByValue:{rows:R.size,fields:[...new Set(R.values())]}}})}return o}async rolesOfOpportunitiesWrittenBefore(e,t){let{config:n}=e,o={linked:new Set,mayBe:0};if(n.writtenBefore.size===0)return o;let s=l=>l.slice(0,15),i=new Map;for(let l of t){let u=l.OpportunityId,p=l[Ce];typeof u!="string"||typeof p!="string"||p===""||ii(l)&&n.writtenBefore.has(u)&&i.set(s(u),p)}if(i.size===0)return o;let a=mr(t,l=>i.get(s(l))),d=l=>typeof l=="string"&&l!==""?n.writtenBefore.get(l)??e.remapper.get(l):void 0,c=new Map;for(let l of a){let u=d(t[l].OpportunityId),p=d(t[l][Ce]);u!==void 0&&p!==void 0&&c.set(l,{opportunity:u,contact:p})}if(c.size===0)return{...o,mayBe:a.length};try{let l=await ai(p=>this.deps.queryRecords(e.targetOrgId,p),[...new Set([...c.values()].map(({opportunity:p})=>p))]),{found:u}=di(c,l);return{linked:new Set([...u.keys()].map(p=>t[p])),mayBe:a.length-c.size}}catch{return{...o,mayBe:a.length}}}async rolesThePlatformWritesOfTheTables(e,t,n,o){let{config:s}=e,i=new Set(n.map(l=>l.objectApiName));if(!i.has(Fe)||(s.fieldExclusions[Fe]??[]).includes(Ce)||s.fieldMappings[Fe]?.[Ce]!==void 0)return 0;if([Fe,ze,ge].some(l=>o.has(l)))return;let d=l=>t.findIndex(u=>u.objectApiName===l),c=i.has(ge)&&d(ge)<d(Fe);try{if(!(await this.deps.describeFields(e.sourceOrgId,Fe)).some(k=>k.name===Ce&&k.createable)||!(await en(this.deps.describeFields,e.targetOrgId,Fe)).creatable.has(Ce))return 0;let p=k=>s.objectSoqlFilters?.[k],f=s.stream?.resumeAfter.get(ze),h=p(Fe),g=p(ge),m=[...p(ze)?[`(${p(ze)})`]:[],`Opportunity.${Ce} != null`,...f&&$t.test(f.lastId)?[`Id > '${f.lastId}'`]:[],...h?[`OpportunityId IN (SELECT Id FROM ${Fe} WHERE (${h}))`]:[],...c&&g?[`${Ce} IN (SELECT Id FROM ${ge} WHERE (${g}))`]:[]],y=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${Ce}, IsPrimary, Opportunity.${Ce} FROM ${ze} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${_f+1}`);if(y.length>_f)return;let b=k=>c||s.writtenBefore.has(k)||e.remapper.get(k)!==void 0,S=k=>{let A=k.Opportunity,w=A!==null&&typeof A=="object"?A[Ce]:void 0;return typeof w=="string"&&w!==""?w:void 0},R=new Map;for(let k of y){let A=k.OpportunityId,w=S(k);typeof A!="string"||w===void 0||s.writtenBefore.has(A)||!b(w)||R.set(A.slice(0,15),w)}return mr(y,k=>R.get(k.slice(0,15))).length}catch{return}}rolesThePlatformMayWriteOfTheCounts(e,t,n){let{config:o}=e;return(o.fieldExclusions[Fe]??[]).includes(Ce)||o.fieldMappings[Fe]?.[Ce]!==void 0?0:Math.min(t,n)}async rolesThePlatformWritesOfTheRead(e,t,n,o){if(o.length===0||t.length===0)return new Set;let{config:s,remapper:i}=e;if((s.fieldExclusions[Fe]??[]).includes(Ce)||s.fieldMappings[Fe]?.[Ce]!==void 0)return new Set;let a=e.preread.get(Fe);if(!a?.createableSet.has(Ce))return new Set;let d=await(a.targetSetsPending??en(this.deps.describeFields,e.targetOrgId,Fe).then(p=>({ok:!0,sets:p}),p=>({ok:!1,error:p})));if(!d.ok||!d.sets.creatable.has(Ce))return new Set;let c=p=>p.slice(0,15),l=new Set(n.map(p=>c(String(p.Id)))),u=new Map;for(let p of t){let f=p.Id,h=p[Ce];typeof f!="string"||typeof h!="string"||h===""||nn(s,p)||!l.has(c(h))&&i.get(h)===void 0||u.set(c(f),h)}return u.size===0?new Set:new Set(mr(o,p=>u.get(c(p))).map(p=>o[p]))}async teamThePlatformWrites(e,t,n,o){let{config:s}=e,i=s.decisions.defaultOf(t,si[t]),a=await this.writesAs(e);try{let d=await li(t,n,{source:c=>this.deps.queryRecords(e.sourceOrgId,c),target:c=>this.deps.queryRecords(e.targetOrgId,c),targetIdOf:c=>o.has(c)?c:void 0,mappedUser:c=>s.ownerMappings[c],...i!==void 0?{defaultUser:i}:{},written:[],simulated:{ownerOf:c=>s.ownerMappings[c]??a??`${Ah}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>ln(d)&&!e.contactsOnTheirOwn.has(String(d.Id)));if(o.length===0)return new Set;if(await this.personAccountsInTarget(e)===!1)return new Set;let i=(e.preread.get(ye)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[ye]??[]).includes("RecordTypeId")&&e.config.fieldMappings[ye]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[gr])));return new Set(o.filter(d=>!a.has(String(d.Id))))}async heldBackAtTheGate(e,t,n,o){let s=e.graph.nodes.find(l=>l.objectApiName===t);if(!s)return[];let i=await this.objectInfoOf(e.targetOrgId,t);if(!i||i.recordTypes.length===0)return[];if(!(e.recordTypeMapper!==null&&e.config.recordTypeMappings!==void 0)&&!i.recordTypes.some(l=>!l.available&&!l.master))return[];let d=await(n.targetSetsPending??en(this.deps.describeFields,e.targetOrgId,t).then(l=>({ok:!0,sets:l}),l=>({ok:!1,error:l}))),c=d.ok?er(n.createableSet,d.sets.creatable):n.createableSet;return this.recordTypesHeldBack(s,o,i,c,e)}async recordTypesHeldBack(e,t,n,o,s){let{config:i}=s;if(!n||n.recordTypes.length===0)return[];if(!o.has("RecordTypeId"))return[];if((i.fieldExclusions[e.objectApiName]??[]).includes("RecordTypeId"))return[];if(i.fieldMappings[e.objectApiName]?.RecordTypeId)return[];let a=t.map(c=>({RecordTypeId:i.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));s.recordTypeMapper&&i.recordTypeMappings&&(a=s.recordTypeMapper.apply(a,i.recordTypeMappings));let d=new Map;for(let c of a){let l=c.RecordTypeId;typeof l=="string"&&d.set(l,(d.get(l)??0)+1)}return[...Gc(e.objectApiName,a,n.recordTypes),...await this.typesTheTargetLacks(s,e.objectApiName,d,n)]}oweToTheSecondPass(e,t){let n=this.withoutSyncedQuotes(e,t);if(e.secondPassInStore&&e.store){for(let o of n)e.store.owe(o);return}if(e.store)for(let o of n)e.store.owe(o);e.pendingFkUpdates.push(...n)}withoutSyncedQuotes(e,t){if(e.config.stream?.everything!==!0)return t;let n=t.filter(o=>o.objectApiName!==Fe||o.fieldName!==Jo);return e.syncedQuotesLeft+=t.length-n.length,n.length===t.length?t:n}saySyncedQuotesLeft(e){let t=e.syncedQuotesLeft;t!==0&&(e.syncedQuotesLeft=0,e.errors.push({objectApiName:Fe,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(${Fe}.${Jo})`,messages:[`Left empty on ${t} opportunit${t===1?"y":"ies"}: filled in, the target syncs the quote at once and writes its lines over the opportunity's products the run copied. Start the sync in the target to fill it in.`]}]}))}patchedInTheJournal(e){let{store:t}=e;if(!(!t||e.secondPassInStore))return kh(t)}oweStatus(e,t,n,o){e.store?e.store.oweStatus(t,n,o):e.deferredStatuses.push({objectApiName:t,id:n,status:o})}countWrites(e,t,n){e.simulated?e.wouldInsertCount+=n.successCount:e.successCount+=n.successCount,e.updatedCount+=n.updatedCount,n.mayHaveBeenWritten&&n.mayHaveBeenWritten.length>0&&e.mayHaveBeenWritten.set(t,[...e.mayHaveBeenWritten.get(t)??[],...n.mayHaveBeenWritten]),e.linkedCount+=n.linkedExistingCount,e.linkedToCreatedCount+=n.linkedToCreatedCount??0,e.failedCount+=n.failureCount,this.oweToTheSecondPass(e,n.pendingFkUpdates),n.writtenWithoutFields&&this.countWrittenWithoutFields(e,t,n.writtenWithoutFields);for(let{field:o,recordId:s}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,o,s);for(let o of n.withTheirRecord??[])En(e,o);(n.linkedExistingCount>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:n.linkedExistingCount,...n.linkedToCreatedCount?{linkedToCreated:n.linkedToCreatedCount}:{},unidentified:n.unidentifiedExistingCount}),n.failureCount>0&&e.errors.push({objectApiName:t,stage:"insert",failedCount:n.failureCount,attemptedCount:n.successCount+n.updatedCount+n.linkedExistingCount+n.failureCount,samples:n.errorSamples})}countWrittenWithoutFields(e,t,n){e.writtenWithoutFields.set(t,Mi(e.writtenWithoutFields.get(t),n))}noteLeftEmptyByFilter(e,t,n,o){let s=e.leftEmptyByFilter.get(t);s||(s=new Map,e.leftEmptyByFilter.set(t,s));let i=s.get(n)??{records:0,ids:[]};i.records++,i.ids.length<Tm&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[jl(n)]})}oweLookupsOfRowsWrittenBefore(e,t,n,o,s){let{config:i}=e,a=new Set(e.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName)),d=new Set(i.fieldExclusions[t.objectApiName]??[]),c=i.fieldMappings[t.objectApiName]??{},l=o.filter(u=>u.isReference&&u.name!=="RecordTypeId"&&!d.has(u.name)&&Ma(u,s,c[u.name])&&(u.referenceTo??[]).some(p=>a.has(p)));if(l.length!==0)for(let u of n){let p=u.Id;if(typeof p!="string")continue;let f=i.writtenBefore.get(p);if(f)for(let h of l){let g=u[h.name];if(typeof g!="string"||!g||i.writtenBefore.has(g)&&!e.store?.owesUntold(p))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:f,sourceId:p,fieldName:c[h.name]??h.name,sourceRefId:g}]);m&&(e.secondPassInStore&&e.store?e.store.owe(m,!0):e.owedToRowsWrittenBefore.push(m))}}}owedNowWritten(e){if(e.owedToRowsWrittenBefore.length===0)return[];let t=[],n=[];for(let o of e.owedToRowsWrittenBefore)e.remapper.get(o.sourceRefId)?t.push(o):n.push(o);return e.owedToRowsWrittenBefore=n,t}sayLookupsOutsideTheClone(e,t){let n=new Map,o=this.keepLookupsInTheClone(e,t,n);return this.sayLeftEmpty(e,n),o}keepLookupsInTheClone(e,t,n){let o=[];for(let s of t){if(e.remapper.get(s.sourceRefId)||e.idsRead.has(s.sourceRefId)){o.push(s);continue}let i=this.objectPointedAt(e,s);if(i!==void 0&&(e.failedObjects.has(i)||e.notCreatable.has(i)||e.notInTarget.has(i))){o.push(s);continue}let a=n.get(s.objectApiName)??new Map,d=`${s.fieldName}|${i??""}`,c=a.get(d)??{field:s.fieldName,parent:i,count:0};c.count++,a.set(d,c),n.set(s.objectApiName,a)}return o}sayLeftEmpty(e,t){for(let[n,o]of t)e.errors.push({objectApiName:n,stage:"scope",failedCount:0,attemptedCount:0,samples:[...o.values()].sort((s,i)=>i.count-s.count).slice(0,3).map(({field:s,parent:i,count:a})=>({recordSummary:`${i===void 0?s:`${s} \u2192 ${i}`} (${a} record${a===1?"":"s"})`,messages:[`Written with the lookup empty: the ${i===void 0?"":`${i} `}record it points at is not in the clone.`]}))})}async secondPassFromTheJournal(e){let{store:t}=e;if(!t)return null;let n=new dp({remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:e.targetOrgId,enabled:!e.config.dryRun,onProgress:e.onProgress,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:kh(t),onAnswered:()=>t.flush(),onRefusedByFilter:(u,p,f)=>this.noteLeftEmptyByFilter(e,u,p,f),...this.secondPassOfTheSample(e)}),o=new Map,s=e.config.stream?.secondPassPageSize??Am,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=u=>t.wasPatched(u.newId,u.fieldName),d=new ap;for(let u of i)d.note(0,u.newId);let c=1;for(let u of t.owedPages(s)){for(let{update:p}of u)a(p)||d.note(c,p.newId);c++}let l=u=>d.spans(u.newId);await n.patch(this.keepLookupsInTheClone(e,i,o),l);for(let u of t.owedPages(s)){let p=u.filter(({update:f,toRowWrittenBefore:h})=>!a(f)&&(!h||e.remapper.get(f.sourceRefId)!==void 0)).map(({update:f})=>f);await n.patch(this.keepLookupsInTheClone(e,p,o),l)}return await n.sendHeld(),this.sayLeftEmpty(e,o),n.finish()}objectPointedAt(e,t){let n=e.config.fieldMappings[t.objectApiName]??{},s=e.preread.get(t.objectApiName)?.fieldInfos.find(a=>a.isReference&&(n[a.name]??a.name)===t.fieldName)?.referenceTo??[];if(s.length===1)return s[0];let i=t.sourceRefId.slice(0,3);return s.find(a=>e.sourceKeyPrefixes.get(a)===i)}applyRecordTypeDecisions(e,t,n,o){let{config:s}=e,i=new Map,a=e.recordTypeMapper&&s.recordTypeMappings?new Set(s.recordTypeMappings.map(d=>d.sourceId)):void 0;return o.forEach((d,c)=>{let l=n[c]?.cleaned.RecordTypeId;if(typeof l!="string"||l===""||!("RecordTypeId"in d))return;let u=s.recordTypeDecisions.get(l);if(u){u.to===null&&delete d.RecordTypeId,e.decisionsApplied.add({kind:"map_record_type",objectApiName:t,from:u.from,...u.to!==null?{to:u.to}:{}});return}!e.simulated||!a||fw.test(l)||a.has(l)||i.set(l,(i.get(l)??0)+1)}),i}simulateWrite(e,t,n,o,s,i,a,d,c=new Map){let{simulated:l}=e;if(!l)return;let u=t.objectApiName,p=new Set,f=0;i({objectName:u,status:"running",progress:0,recordCount:n.records.length,message:`Simulating the write of ${n.records.length} ${u} records: nothing is sent...`});for(let[h,g]of n.cleaned.entries()){let m=n.records[h]??{},y=d?Jc(u,m,g.source,d):[];if(y.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:Jl(m),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${y.map(k=>k.name).join(", ")}]`]});continue}let b=l.idFor(o),S=typeof g.source.Id=="string"?g.source.Id:void 0,R=c.get(m);if(R!==void 0){s.linkedExistingCount++,f++,p.add(R),S!==void 0&&e.remapper.addExisting(S,b,u);continue}s.successCount++,a&&!Ul(n.records[h]??{})&&a(g),S!==void 0&&e.remapper.add(S,b,u);for(let k of g.nullifiedFks)s.pendingFkUpdates.push({objectApiName:u,newId:b,sourceId:S,fieldName:k.field,sourceRefId:k.sourceRefId,...k.insertOnly?{insertOnly:!0}:{}})}f>0&&i({objectName:u,status:"running",progress:0,message:`[dry-run] ${u}: ${f} fewer would be inserted, linked to the record${f===1?"":"s"} the target holds under the same ${[...p].join(", ")}, which its refusal of the row names`})}holdBackSkippedRows(e,t,n,o,s){let{config:i}=e;if(!i.decisions.skipsRowsOf(t.objectApiName))return n;let a=new Set(i.fieldExclusions[t.objectApiName]??[]),d=new Map(Object.entries(i.fieldMappings[t.objectApiName]??{}).map(([u,p])=>[p,u])),c=n.filter(u=>{let p=u.RecordTypeId;return!i.decisions.holdsBack(t.objectApiName,f=>{let h=d.get(f)??f;return a.has(h)?void 0:u[h]},yh(i,typeof p=="string"?p:void 0),e.decisionsApplied,s)}),l=n.length-c.length;return l>0&&o({objectName:t.objectApiName,status:"running",progress:0,message:`${t.objectApiName}: ${l} record${l===1?"":"s"} held back, as decided on the gaps`}),c}async findGaps(e,t,n){let{gaps:o}=e;if(!o)return new Map;let s=t.objectApiName,i=new Map([...n.recordTypes?.values()??[]].map(d=>[d.recordType,d]));for(let{picklistChanges:d=[]}of n.cleanedRecords){let c=Vc(s,d,l=>{if(l.recordType!==void 0)return i.get(l.recordType)?.picklists.get(l.field)?.values;let u=n.picklistValuesByField?.get(l.field);return u?[...u]:void 0});for(let l of c)o.add(l)}if(n.unmapped.size>0){let d=await this.sourceRecordTypesOf(e,s);o.knowRecordTypes(s,"source",d);for(let[c,l]of n.unmapped){let u=d.find(p=>p.recordTypeId.slice(0,15)===c.slice(0,15))?.developerName??c;o.add(bi("record_type_unmapped",s,u,l,xh(n.targetObject)))}}let a=n.targetFields;return a?(Yc({objectApiName:s,rows:n.recordsToInsert.map((d,c)=>{let l=n.cleanedRecords[c]?.cleaned.RecordTypeId;return{payload:d,source:n.cleanedRecords[c]?.source??{},typed:typeof l=="string"&&n.recordTypes?.has(l)===!0}}),targetFields:a,picklistValuesByField:n.picklistValuesByField,picklistFields:n.picklistFields??new Map},o),await this.currencyGaps(e,s,a,n.cleanedRecords),this.uniqueValueGaps(e,s,a,n.recordsToInsert)):new Map}sourceRecordTypesOf(e,t){let n=e.sourceRecordTypes.get(t);if(!n){let o=this.deps.describeObject;n=o?o(e.sourceOrgId,t).then(s=>this.namedRecordTypes(e.recordTypeRows,e.sourceOrgId,s.recordTypes),()=>[]):Promise.resolve([]),e.sourceRecordTypes.set(t,n)}return n}currenciesFor(e,t,n,o){return t?.some(i=>i.name===Ge&&i.createable)===!0&&o(Ge)&&n.some(i=>typeof i[Ge]=="string"&&i[Ge]!=="")?this.runCurrencies(e):Promise.resolve(void 0)}async parentCurrenciesFor(e,t,n,o){if(e.currencyChangesById.size===0)return;let s=n?.find(a=>a.name===Ge);if(!s||s.createable&&!fo(t)||!o.some(a=>typeof a[Ge]=="string"&&a[Ge]!==""))return;let i=await e.currencies;return{changeOf:a=>e.currencyChangesById.get(a),...i?{currencies:i}:{}}}runCurrencies(e){let t=this.deps.queryTooling;return e.currencies??=Nc(n=>this.deps.queryRecords(e.sourceOrgId,n),n=>this.deps.queryRecords(e.targetOrgId,n),t?{source:n=>t(e.sourceOrgId,n),target:n=>t(e.targetOrgId,n)}:{}),e.currencies}async currencyGaps(e,t,n,o){if(!n.some(d=>d.name===Ge&&d.createable))return;let s=new Map,i=new Map;for(let{source:d,currencyChange:c}of o){let l=d[Ge];if(typeof l!="string"||l===""||(s.set(l,(s.get(l)??0)+1),!c||c.chosenBy==="decision"))continue;let u=i.get(l)??{to:new Set,fields:new Set,kept:!1};u.to.add(c.to);for(let p of c.fields)u.fields.add(p);c.notConverted&&(u.kept=!0),i.set(l,u)}if(s.size===0)return;let a=(await e.currencies)?.target.active;if(!(!a||a.size===0))for(let[d,c]of s){if(a.has(d))continue;let l=i.get(d);e.gaps?.add(Qc(t,d,c,l&&{to:[...l.to].sort(),converted:[...l.fields].sort(),asRead:l.kept}))}}async uniqueValueGaps(e,t,n,o){let s=new Map,i=n.filter(a=>a.unique===!0&&a.createable&&!(e.config.upsertMode==="auto"&&a.externalId===!0));for(let a of i){let d=new Map;for(let p of o){let f=p[a.name];if(typeof f!="string"||f===""||Oh.test(f))continue;let h=Tn(a,f),g=d.get(h);g?g.rows++:d.set(h,{value:f,rows:1})}if(d.size===0)continue;let c=new Set;try{let p=Me(t),f=Me(a.name),h=[...d.values()].map(({value:g})=>g);for(let g of An(h,bh)){let m=await this.deps.queryRecords(e.targetOrgId,`SELECT ${f} FROM ${p} WHERE ${f} IN (${g})`);for(let y of m){let b=y[a.name];typeof b=="string"&&c.add(Tn(a,b))}}}catch{continue}let l=0,u=0;for(let[p,{rows:f}]of d)c.has(p)&&(l+=f,u++);l>0&&e.gaps?.add(Xc(t,a.name,l,u));for(let p of o){let f=p[a.name];typeof f=="string"&&c.has(Tn(a,f))&&!s.has(p)&&s.set(p,a.name)}}return s}async writeNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,remapper:d}=t;o&&o.pages++;let c=e.objectApiName===Se?this.endOfTheEmails(t,n!==void 0):t.onProgress,l=s.dryRun?"Simulated":"Completed",u=n===void 0?`${l} ${e.objectApiName}`:t.emailsWrittenFirst?"after their task":`${l} ${e.objectApiName} after their task`,p=n===void 0?`Stopped ${e.objectApiName}`:t.emailsWrittenFirst&&!o?"stopped after their task":`Stopped ${e.objectApiName} after their task`,f=t.preread.get(e.objectApiName);if(!f)return;let{fieldInfos:h,createableSet:g,targetSetsPending:m}=f;if(at(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,f.records,h,this.currenciesTheirLinesWant(t,f.records));let P=ur(f.records,{sellingModel:t.sellingModels});P.length!==f.records.length&&(f.records.length=0,f.records.push(...P))}let y=n??f.records,b=y.filter(P=>nn(s,P)),S=e.objectApiName===ge?y.filter(P=>ln(P)&&!nn(s,P)):[],R=await this.personContactsOnTheirOwn(t,S),k=new Set(S.filter(P=>!R.rows.has(P))),A=b.length>0||k.size>0?y.filter(P=>!nn(s,P)&&!k.has(P)):y,w=A,I=[];try{let P=null,v,$=null,E,M,Z=await(m??en(this.deps.describeFields,a,e.objectApiName).then(j=>({ok:!0,sets:j}),j=>({ok:!1,error:j})));if(Z.ok)P=Z.sets.creatable,v=Z.sets.updateable,$=Z.sets.picklistValuesByField,E=Z.sets.picklistFields,M=Z.sets.fields;else{let j=Z.error;t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed \u2014 falling back to source schema)",messages:[j instanceof Error?j.message:String(j)]}]})}let U=P?er(g,P):g,H=this.linkPersonContacts(t,[...k]);if(o&&(o.withTheirAccount+=H.linked,Ga(o,H.notSent),H.linked===0&&(o.personContactsUnlinked+=k.size)),k.size>0&&H.linked===0&&A.length===0&&b.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${wn(e.objectApiName,k.size,Gt(t,e.objectApiName))}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`});return}if(b.length>0&&(t.linkedCount+=b.length,o&&(o.writtenBefore+=b.length),this.oweLookupsOfRowsWrittenBefore(t,e,b,h,v),await this.oweStatusesFoundAfterStop(t,e.objectApiName,b),A.length===0&&k.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${u}: 0 succeeded, ${sd(s,b.length)}, 0 failed`});return}let K=await this.targetObjectInfoOf(t,e.objectApiName),pe=pw(K);t.gaps?.knowRecordTypes(e.objectApiName,"target",K?.recordTypes??[]);let le=await this.recordTypesHeldBack(e,A,K,U,t),V=le.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,A,le):void 0,fe=V!==void 0&&V.size>0&&(o!==void 0||V.size<A.length);if(fe){w=A.filter(_=>!V.has(_)),t.failedCount+=V.size;for(let _ of V.keys())t.heldInTheOrg.set(String(_.Id),"held");let j=[...V.values()];if(I.push(...j),o?(o.withoutParent+=j.length,Fr(j,o.withoutParentGroups),Ga(o,Zf(j))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:j.length,attemptedCount:0,samples:rd(Fr(j),t.failedObjects)}),o&&w.length===0)return}else if(o?.heldWhole!==void 0&&le.length===0){t.failedCount+=A.length,o.heldWholeRows+=A.length;return}if(le.length>0&&!fe){for(let _ of le)t.gaps?.add(th(_,K));if(t.failedObjects.add(e.objectApiName),t.failedCount+=A.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:A.length,attemptedCount:0,samples:le.map(_=>({recordSummary:`RecordType=${_.developerName} (${_.recordCount} record${_.recordCount===1?"":"s"})`,messages:[Oo(_)]}))}),o){o.heldWhole??=le.map(Ro).join(" "),o.heldWholeRows+=A.length;return}let j=Gt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${wn(e.objectApiName,A.length,j)}: `+le.map(Ro).join(" ")+" Objects that cannot be written without it will be skipped."});return}w=this.holdBackSkippedRows(t,e,w,c,pe),w=this.leaveWhatHangsFromThePlatform(t,e,h,w);let se=0;if(e.objectApiName===Se&&n===void 0){let j=this.holdEmailsForTheirTask(t,w);if(se=w.length-j.length,w=j,se>0&&w.length===0){let _={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${is(se)}`};c(_),o||(t.emailsAllWaiting={..._,status:"done",progress:100});return}}let me=0;if(e.objectApiName===tt){let j=await this.linkTasksWrittenWithEmails(t,w);w=j.rows,me=j.linked,o&&(o.withTheirEmail+=j.linked)}let z=new Set(s.fieldExclusions[e.objectApiName]??[]),Oe=s.fieldMappings[e.objectApiName]??{},ne=await this.teamOfTheOpportunities(t,e.objectApiName,w,K?.keyPrefix,h.flatMap(j=>!j.isReference&&U.has(j.name)&&!z.has(j.name)&&Oe[j.name]===void 0?[j.name]:[]));w=ne.rows,o&&(o.teamOwners+=ne.owners,o.teamOthers+=ne.linked-ne.owners,ew(o.teamValues,ne.values));let q=await this.rowsWithoutTheirParent(e,t,h,w);for(let[j,_]of await this.rowsWhoseParentTheTargetLacks(e,t,h,w,ae=>U.has(ae)&&!z.has(ae)&&Oe[ae]===void 0))q.has(j)||q.set(j,_);let ee=await this.rowsHeldInTheWholeOrg(e,t,h,w,j=>U.has(j)&&!z.has(j)&&Oe[j]===void 0);for(let[j,_]of ee.held)q.has(j)||q.set(j,_);if(ee.aside.size>0){for(let de of q.keys())ee.aside.delete(de);Gm(t,e.objectApiName,ee.aside.values()),w.forEach((de,je)=>{let Xe=ee.aside.get(je);Xe&&t.heldInTheOrg.set(String(de.Id),Xe)});let j=w.filter((de,je)=>!ee.aside.has(je)),_=new Map;w.forEach((de,je)=>{ee.aside.has(je)||_.set(je,_.size)});let ae=new Map;for(let[de,je]of q){let Xe=_.get(de);Xe!==void 0&&ae.set(Xe,je)}q.clear();for(let[de,je]of ae)q.set(de,je);w=j}if(w.forEach((j,_)=>{let ae=ne.held.get(j);ae&&!q.has(_)&&q.set(_,{field:ae.field,parentObject:ae.parentObject,reason:ae.why})}),q.size>0&&(s.stream?.everything===!0&&w.forEach((j,_)=>{q.has(_)&&t.heldInTheOrg.set(String(j.Id),"held")}),w=w.filter((j,_)=>!q.has(_)),t.failedCount+=q.size,o?(o.withoutParent+=q.size,Fr(q.values(),o.withoutParentGroups),Ga(o,[{count:q.size,why:od}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:q.size,attemptedCount:0,samples:Nm(q,t.failedObjects)}),w.length===0&&ne.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let j=se===0?Gt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${wn(e.objectApiName,q.size,j)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`});return}await t.orphanExpander.expandForNode({node:e,fieldInfos:h,records:w,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?(j,_,ae,de)=>this.anonymizeRows(t,j,[_],[ae],de,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:(j,_)=>this.withoutFileContent(t,j,_,!0),startAsDraft:async(j,_)=>(await this.startAsDrafts(t,j,[_])).get(0),oweStatus:(j,_,ae)=>this.oweStatus(t,j,_,ae),objectOf:(j,_)=>this.objectOfSourceId(t,j,_),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:(j,_)=>this.sayRecordTypeNote(t,j,_),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:(j,_)=>this.countWrittenWithoutFields(t,j,_),linkPersonContacts:j=>this.mapContactsOfPersonAccounts(t,j),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:j=>t.maskedSourceFields(j),onMaskedLeftOut:(j,_)=>this.noteEncryptedLeftOut(t,j,_),businessAccountsAmong:(j,_)=>this.takenAsBusinessAccounts(t,j,_),contactOnItsOwn:j=>t.contactsOnTheirOwn.has(j),...t.store?{calls:ds(t.store)}:{}}),w=this.leaveWhatHangsFromThePlatform(t,e,h,w);let ke=s.fieldMappings[e.objectApiName]??{},te=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),w,j=>U.has(j)||ke[j]!==void 0),F=E?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:w,fields:E,written:j=>U.has(j)&&!te.has(j)&&ke[j]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:M!==void 0&&!M.some(j=>j.name==="RecordTypeId")}):void 0;for(let j of F?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,j);let Y=U.has("RecordTypeId")&&!te.has("RecordTypeId")&&ke.RecordTypeId===void 0,B=e.objectApiName===ye?await this.takenAsBusinessAccounts(t,w,Y):void 0,G=fo(e.objectApiName)?void 0:await this.currenciesFor(t,M,w,j=>U.has(j)&&!te.has(j)&&ke[j]===void 0),be=G?void 0:await this.parentCurrenciesFor(t,e.objectApiName,M,w);w=this.pricedInTheirRecordsCurrency(t,e.objectApiName,w);let Ae=at(e.objectApiName)?j=>t.prices.convertedInto.get(String(j.Id)):void 0,ve=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,h,w,j=>U.has(j)&&!te.has(j)&&ke[j]===void 0):void 0,ot=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,w,U.has("OwnerId")&&!te.has("OwnerId")&&ke.OwnerId===void 0):void 0,L=Tf({objectApiName:e.objectApiName,records:w,...Ae?{pricedIn:Ae}:{},fieldInfos:h,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:j=>as(t,j),ownerMappings:s.ownerMappings,...ne.lookups.size>0?{resolvedLookups:ne.lookups}:{},...ve&&ve.size>0?{targetLacks:ve}:{},...ot?{inactiveOwners:ot}:{},...t.sample?{outsideTheSample:(j,_)=>this.outsideTheSample(t,j.referenceTo??[],_)}:{},excludedFields:te,fieldRename:ke,creatableFields:U,updatableFields:v,picklistValuesByField:$,picklistFields:E,recordTypeValues:F?.byRecordType,businessAccounts:B,contactPoints:t.contactPoints??void 0,decide:(j,_)=>s.decisions.applyToRow(e.objectApiName,j,yh(s,_),t.decisionsApplied,pe),...G||be?{currencyFields:uo(M??[])}:{},...G?{currencies:G}:{},...be?{parentCurrencies:be}:{}}),Te=new Io,De=new ho;for(let{picklistChanges:j=[],currencyChange:_,source:ae}of L){Te.add(e.objectApiName,j),t.picklistChanges.add(e.objectApiName,j),o?.picklists.add(e.objectApiName,j),De.add(e.objectApiName,_),t.currencyChanges.add(e.objectApiName,_),o?.currencies.add(e.objectApiName,_);let de=ae.Id;_&&typeof de=="string"&&t.currencyChangesById.set(de,_)}let Ie=$o(Te.list())+go(De.list())+Va(lh(new Map,L))+Qa(ph(L))+Ja(Ya(new Map,L))+(o?"":td(t,e.objectApiName));o&&(lh(o.lookupsNotCarried,L),Ya(o.lookupsOutsideTheRun,L),o.ownersInactive+=ph(L)),this.noteLookupsOutsideTheRun(t,e.objectApiName,h,L);for(let j of L)for(let _ of j.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,_);ow(t,e.objectApiName,L);let he=L.map(j=>j.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(he=t.recordTypeMapper.apply(he,s.recordTypeMappings,j=>Ho(e.objectApiName,j)));let Ut=this.applyRecordTypeDecisions(t,e.objectApiName,L,he);he=this.anonymizeRows(t,e.objectApiName,he,L.map(j=>String(j.source.Id??"")),h,s.fieldMappings[e.objectApiName]??{});let Pt=new Map((M??[]).flatMap(j=>j.length!==void 0&&j.length>0?[[j.name,j.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let j of he)s.decisions.truncate(e.objectApiName,j,Pt,t.decisionsApplied);let an=new Map;t.gaps&&(an=await this.findGaps(t,e,{cleanedRecords:L,recordsToInsert:he,targetFields:M,targetObject:K,picklistValuesByField:$,picklistFields:E,recordTypes:F?.byRecordType,unmapped:Ut}));let ct=e.objectApiName===Kn?await this.takeTheSyncCopies(t,L,he,b,{fields:M,updatable:v,keyPrefix:K?.keyPrefix}):{taken:0,given:0};e.objectApiName===Fe&&Zm(t,L,he);let Ot=e.objectApiName===ze?await this.linkTheRolesThePlatformWrote(t,L,he,{fields:M,updatable:v,keyPrefix:K?.keyPrefix}):{linked:0,given:0},lt=await this.startAsDrafts(t,e.objectApiName,he),Je=new Map;if(t.store)for(let[j,_]of lt){let ae=L[j];ae&&Je.set(ae,_)}let et=[];if(at(e.objectApiName)&&t.standardPricebookId){let j=L.map((de,je)=>je),{standard:_,custom:ae}=Yd(j.map(de=>({index:de,[wt]:L[de].source[wt]})),t.standardPricebookId);for(let de of[_,ae])de.length!==0&&et.push({records:de.map(je=>he[je.index]),cleaned:de.map(je=>L[je.index])})}et.length===0&&(he.length>0||ct.taken===0&&Ot.linked===0)&&et.push({records:he,cleaned:L});let Be=await this.recordTypeCounter(t,e.objectApiName,K,Y),$e=Kl();$e.successCount+=ct.taken;let ht;try{for(let j of et){if(t.simulated){this.simulateWrite(t,e,j,K?.keyPrefix,$e,c,Be,M,an);continue}await t.batchWriter.writeNode({node:e,records:j.records,cleanedRecords:j.cleaned,fieldInfos:h,creatableFields:U,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:K?.keyPrefix,picklistFields:E,remapper:d,...t.store?{oweLookups:_=>this.oweToTheSecondPass(t,_)}:{},...t.store?{calls:ds(t.store)}:{},...Je.size>0?{onWritten:(_,ae)=>{let de=Je.get(_);de!==void 0&&(Je.delete(_),this.oweStatus(t,e.objectApiName,ae,de))}}:{},...Be?{onCreatedWithoutRecordType:Be}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(_=>_.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},$e)}}catch(j){if(!(j instanceof Re))throw j;ht=j}finally{for(let[j,_]of lt){let ae=L[j];if(ae&&t.store&&!Je.has(ae))continue;let de=ae?.source.Id;if(typeof de!="string")continue;let je=d.get(de);!je||d.isExisting(de)||this.oweStatus(t,e.objectApiName,je,_)}this.countWrites(t,e.objectApiName,$e)}let D=$e.successCount,J=$e.updatedCount,re=$e.linkedExistingCount,we=$e.failureCount,Q=$e.unidentifiedExistingCount;if(o){let j=et.reduce((Xe,Nt)=>Xe+Nt.records.length,0),_=et.flatMap(Xe=>Xe.cleaned);o.sent+=j,o.succeeded+=D,o.updated+=J,o.linked+=re,o.linkedToCreated+=$e.linkedToCreatedCount??0,o.failed+=we,o.alreadyExists+=$e.alreadyExistsCount,o.unidentified+=Q,o.rolesOfTheirOpportunity+=Ot.linked,o.rolesGiven+=Ot.given,o.writtenWithoutFields=$e.writtenWithoutFields?Mi(o.writtenWithoutFields,$e.writtenWithoutFields):o.writtenWithoutFields,$e.flagsNotKept&&(o.flagsNotKept=mc(o.flagsNotKept,$e.flagsNotKept));let ae=ht?j-(D+J+re+we):0,de=_.slice(0,j-ae).filter(Xe=>R.rows.has(Xe.source)).length;o.sentOnTheirOwn+=de,de>0&&(o.onTheirOwnWhy=R.why);let je=[...qa(o),...Gt(t,e.objectApiName)];if(ht)throw this.stopStreamedNode(e,t,o,ae,p),ht;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${Ka(s,o,je)}`});return}let ie=D+J+re+b.length+H.linked+ne.linked+Ot.linked,_e=ie+we,Pe=_e>0?we/_e:0,ut=we>0&&$e.alreadyExistsCount===we,pt=we>0&&!ut&&(ie===0||Pe>.5),st=Ih(re,$e.linkedToCreatedCount??0),Fn=J>0?`, ${J} updated through their external id`:"",jt=Q>0?` (${Q} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",Ht=j=>[...Zf(I),...q.size>0?[{count:q.size,why:od}]:[],...H.notSent,...j?Gt(t,e.objectApiName):[]],kt=Ht(se===0),Nn=me>0?`, ${me} written by the platform with their email`:"",Ye=H.linked>0?`, ${H.linked} written by the platform with their person account`:"",gt=$h(ne.owners,ne.linked-ne.owners)+Eh(Ot.linked,Ot.given),Ue=et.flatMap(j=>j.cleaned),Ne=j=>Ue.slice(0,j).filter(_=>R.rows.has(_.source)).length,Kt=j=>j>0?`, ${j} ${j===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",xt=Kt(Ne(Ue.length)),Rn=b.length>0?`, ${sd(s,b.length)}`:"",Vt=se>0?`, ${is(se)}`:"",Ct=[ui($e.flagsNotKept),Ph(ne.values)].flatMap(j=>j?[`, ${j}`]:[]).join(""),Ft=Mo($e.writtenWithoutFields),On=Sh(t,e.objectApiName),_r=us(t,e.objectApiName),rr=n===void 0?Hf(t,e.objectApiName):"",Bs=s.dryRun?"would be inserted":"succeeded",Ls=ct.taken>0?` (${rp(ct.taken,ct.given,s.dryRun)})`:"",Mn=j=>`${D} ${Bs}${Ls}${Fn}${st}${Nn}${Ye}${gt}${Rn}, ${we+xn(j)} failed${jt}${rn(j)}`,Bn=`${xt}${Vt}${Ct}${Ie}${Ft}${On}${se===0?_r:""}${rr}`;if(ht){let j=et.reduce((je,Xe)=>je+Xe.records.length,0),_=j-(D+J+re+we)+se;Xa(t,e.objectApiName,_);let ae=se>0?` (${is(se)})`:"",de=Ne(j-_+se);throw this.saySentOnTheirOwn(t,de,R.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:pt?"error":"stopped",progress:100,message:`${p}: ${Mn(Ht(!0))}, ${_} not sent${ae}${Kt(de)}${Ct}${Ie}${Ft}${On}${_r}`}),ht}if(this.saySentOnTheirOwn(t,Ne(Ue.length),R.why),pt){t.failedObjects.add(e.objectApiName),ie>0&&t.failedInPart.add(e.objectApiName);let j=xn(kt);c({objectName:e.objectApiName,status:"error",progress:100,message:ie===0?`Failed all ${e.objectApiName} records: ${we+j} failed${rn(kt)}${xt}${Ie}${rr}`:`${we+j}/${_e+j} ${e.objectApiName} records failed (>50%)${rn(kt)}${xt}${Ie}${Ft}${On}${rr}${nh}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${u}: ${Mn(kt)}${Bn}`})}catch(P){if(P instanceof Re)throw P;t.failedObjects.add(e.objectApiName),t.failedCount+=w.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:w.length,attemptedCount:w.length,samples:[{recordSummary:"(stage failed before insert)",messages:[X(P)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${X(P)}`})}}};function $w(r,e){if(r.sample===void 0){if(e===void 0)return;throw new Error("A sample was handed to a run whose config copies every record, or walks from a record: run it as its config says, or ask the sample in its config. Nothing was read or written.")}if(r.inputMode!=="org"||e===void 0)throw new Error("The config asks a sample of the whole org, and the run was handed nothing to keep or take up its plan with: it would have copied every record. Nothing was read or written.");return{...e,options:r.sample}}function dd(r,e,t,n){let o=t?.recordTypeMappings,s=ns(e.anonymizePII,r,t?.anonymizationRules,n),i=t?.files?{maxFileBytes:t.files.maxFileSizeMB*1048576,acceptedAsIs:t.files.acceptedAsIs}:void 0,a=t?.writtenBefore,d=t?.beforeWrite,c=e.inputMode==="org",l=t?.stream,u=$w(e,l?.sample),p=c?{...l,everything:!0,writeWindow:ad,secondPassPageSize:ad,ceiling:void 0,wholeReadBound:l?.wholeReadBound??l?.ceiling??Xr,...u?{sample:u}:{}}:l,f=[...new Set([...r.nodes.filter(nc).map(S=>S.objectApiName),...e.excludedObjects??[]])],h=f.length>0?f:void 0,g=e.dryRun===!0?!0:void 0,m=Eo(e),y=e.keepContactPoints===!0?!0:void 0;return e.inputMode==="record"&&typeof e.recordId=="string"?{rootRecordId:e.recordId,rootObjectApiName:r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:y,files:i,writtenBefore:a,beforeWrite:d,stream:p,dryRun:g,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||h||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||y||i||a||d||p||g||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:y,files:i,writtenBefore:a,beforeWrite:d,stream:p,dryRun:g,decisions:m}:void 0}var Br="--checkpoint-first",cd={switches:[Br],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},Ew=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function Fh(r){return[` --checkpoint-first ${r.step??""}take a checkpoint of what ${r.run} writes before its`," first write: each object it writes, and each the"," target's flows that still run create as it writes"," them, held whole, as every checkpoint holds an object."," Its cost is that of the tables, not of the records",` written, and is said first. A rewind to it takes ${r.run}`," back (sandforge checkpoint rewind), and the work of"," anyone else on those objects since with it. Refused",` \u2014 another run writing, a limit, the disk \u2014 ${r.run}`," writes nothing, exit 1; deleted again when it writes",` nothing; with ${r.simulation}, says what it would hold and`," cost, and takes nothing (default: off)",...(r.note??[]).map(t=>` ${t}`)," --checkpoint-keep-days <n>"," the days that checkpoint is kept on this machine,"," 0 to 3650, 0 until it is deleted (default: 7)"," --checkpoint-exclude-object <ApiName>"," leave an object out of that checkpoint, named; a"," rewind leaves its records as they are; repeat for more"].join(`
21
- `)}function Mr(r){process.stderr.write(`${r}
22
- `),process.exit(2)}function Nh(r,e=[]){let t=a=>{let d=[];for(let c=0;c<r.length;c++)r[c]===a&&c+1<r.length&&d.push(r[c+1]);return d},n=t("--checkpoint-keep-days"),o=t("--checkpoint-exclude-object");if(!r.includes(Br)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Mr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${Br}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Mr(`${Br} does not go with ${a}: ${d}`);n.length>1&&Mr(`--checkpoint-keep-days is given ${n.length} times: give it once.`);let s;if(n.length===1){let a=n[0];s=/^\d{1,4}$/.test(a)?Number(a):Number.NaN;try{zi(s,void 0)}catch{Mr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)Ew.test(a)||Mr(`--checkpoint-exclude-object takes an object's API name, not "${a}".`),i.some(d=>d.toLowerCase()===a.toLowerCase())||i.push(a);return{...s!==void 0?{keepDays:s}:{},...i.length>0?{excluded:i}:{}}}function Ch(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function Pw(r){let e=r.self??ll,t=r.elsewhere??(s=>ul(s,e)),n=`A SandForge run is writing to ${r.orgName}: start this run once it has ended. No record was read.`,o=s=>s.writer!==void 0&&s.writer.pid===e.pid&&Date.parse(s.writer.hostStartedAt)===Date.parse(e.startedAt);return async s=>{let i=r.envLock?.(s);if(i!==void 0)return`${i}: start this run once it has ended. No record was read.`;for(let a of r.runs)for(let d of await a.list()){if(d.end!==void 0||!(Ch(d.targetOrganizationId,s)||Ch(d.targetOrgId,s)||d.targetOrgId===r.alias))continue;let l=r.own?.runId!==void 0&&d.runId===r.own.runId;if(o(d)?!l:t(d))return n}}}function Mh(r,e){return{id:e.id,orgType:Zd({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function xw(r){let e=r.reason==="notAFolder"?"it is a file, not a folder":r.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${r.detail!==void 0?` (${r.detail})`:""}`;return`the checkpoints cannot be kept in ${r.path}: ${e}`}function Cw(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${lu(t)}`))}}function Bh(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-EQOQASDQ.mjs"),{openCheckpointStore:i}=await import("./chunk-2S5OMIIA.mjs"),{nodeSyncRunCreations:a}=await import("./chunk-NGSMZZDA.mjs"),{nodeSeedRunCreations:d}=await import("./chunk-HV2MXMGI.mjs"),{envLockHolder:c,envLockLine:l}=await import("./chunk-4SNDMJP2.mjs"),u=i({root:r.storeRoot??o(r.journalDir,"checkpoints"),...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in u)throw new Error(xw(u.refusal));let{store:p}=u,{session:f}=r,h=r.connect(f),g={id:r.org.id,alias:f.alias,username:f.username,instanceUrl:f.instanceUrl,orgType:r.org.orgType,metadata:{apiVersion:h.version,...r.org.edition!==void 0?{edition:r.org.edition}:{}}},m={log:y=>{y.startsWith("[WARN] ")&&r.say(`warning: ${y.slice(7)}`)},orgManager:{getOrg:y=>y===g.id?g:void 0},orgRegistry:{getCredentials:async y=>y===g.id?{accessToken:f.accessToken,instanceUrl:f.instanceUrl}:void 0}};return{deps:{org:s(h),store:p,handler:m,runWriting:Pw({orgName:f.alias,alias:f.alias,runs:[a(r.journalDir),d(r.journalDir)],envLock:y=>{let b=c(p.locksDir,y);return b!==void 0?l(b):void 0},...r.own?{own:r.own}:{}}),...r.freeBytes?{freeBytes:r.freeBytes}:{}},org:{orgId:r.org.id,orgName:f.alias,alias:f.alias,username:f.username,instanceUrl:f.instanceUrl,registered:{orgType:r.org.orgType,...r.org.edition!==void 0?{metadata:{edition:r.org.edition}}:{}}}}})(),n=o=>({module:r.module,written:o.written,running:o.running,request:r.request,operationId:r.operationId,tool:"cli",keepDays:zi(r.request.keepDays,void 0)});return{async scope(o){let s=await import("./chunk-X65MT4W3.mjs"),{deps:i,org:a}=await t();return s.scopeBeforeRun(i,a,n(o))},async take(o,s,i={}){let a=await import("./chunk-X65MT4W3.mjs"),{deps:d,org:c}=await t();return a.takeBeforeRun({...d,...i.signal?{signal:i.signal}:{},onProgress:Cw(r.say)},c,n(o),s)},async settle(o,s){let i=await import("./chunk-X65MT4W3.mjs"),{deps:a}=await t(),d=await i.settleBeforeRun(a.store,o,s);return d.notDeleted!==void 0&&r.say(`warning: ${d.notDeleted}`),d.info}}}function ld(r){return yl(r).map(e=>` ${e}`)}var Fw=new Set(["TOO_MANY_RECORDS","API_BUDGET","DISK"]);function gs(r){let e=r.message.replace(/\s*No record was read\.$/,""),t=Fw.has(r.code)?"leave an object out of it (--checkpoint-exclude-object <ApiName>), ":"";return`The checkpoint before the run was refused: ${e} Fix what refuses it, ${t}or run without ${Br} to write without one.`}function ud(r){return r.code!==fn?gu:r.refusal!==void 0?`${gs(r.refusal)} Nothing was written.`:r.message}function Nw(r){return r===null?"kept until it is deleted":`kept until ${r.slice(0,10)}`}function Lh(r,e,t){return[`checkpoint before the run: ${r.checkpointId} '${r.name}', ${r.objects.length} object(s), ${r.records} record(s), ${Nw(r.expiresAt)}`,` rewind to it: ${jr("checkpoint")} rewind --org ${e} --checkpoint ${r.checkpointId}${t?" --mute-automation":""}`,...r.notHeld.map(({objectApiName:n,reason:o})=>` not in the checkpoint: ${n} \u2014 ${o}`)]}function pd(r){return r.state==="deleted"?[cu]:[]}async function Jk(r,e,t,n,o){try{let s=await r.settle(e,t);for(let i of pd(s))o(i);return s}catch(s){return o(`warning: the checkpoint '${e.name}' taken before the run, which wrote nothing, could not be deleted (${s instanceof Error?s.message:String(s)}): delete it with ${jr("checkpoint")} delete --org ${n} --checkpoint ${e.checkpointId}`),e}}var ms="--leave-undeletable",fd="UNDELETABLE_NOT_LEFT";function Mw(r,e){let t=r.map(o=>`${o.objectApiName} (${o.records} records)`).join(", "),n=ft(ms)?`run again with ${ms}`:`run ${gn(ms,"removal")}`;return{code:fd,message:`The user SandForge connects as may not delete the records of ${t} in ${e}. Nothing was removed. Give that user Delete on those objects, or ${n} to remove the rest and leave them.`}}function Wh(r,e,t,n=o=>process.stderr.write(`${o}
23
- `)){return async o=>{if(!r)return t(Mw(o,e)),!1;let s=o.map(i=>`${i.objectApiName} (${i.records} records)`).join(", ");return n(`The user SandForge connects as may not delete the records of ${s} in ${e}.`),n(`Those stay, with the records they hang from; the rest is removed (${ms}).`),!0}}function Dh(r,e){let t;return async n=>{let o=await r.describeObject?.(e,n);return!o||!o.recordTypes.some(s=>!s.master)?o?.recordTypes:(t??=r.queryRecords(e,mo).then(wo,()=>[]),yo(o.recordTypes,await t))}}var $d=`sandforge clone \u2014 Forge a clone of one record, or of whole tables, from a source org
24
- to a target sandbox, or remove what a run of it created.
25
-
26
- Usage:
27
- npx sandforge clone \\
28
- --record <id> --source <alias> --target <alias> [options]
29
- npx sandforge clone \\
30
- --object <ApiName> [--where <condition>] [--object <ApiName> [--where <condition>]]... \\
31
- --source <alias> --target <alias> [options]
32
- npx sandforge clone \\
33
- --depth all --source <alias> --target <alias> [--fit share] [--dry-run] [--yes]
34
- [options]
35
- npx sandforge clone \\
36
- --remove <summary.json> --target <alias> [--include-changed] [--accept-automation]
37
- [--mute-automation] [--leave-undeletable] [--json]
38
- [--preview] [--sweep | --sweep-list] [--sweep-late] [--sweep-untied] [--audit <file>]
39
- npx sandforge clone \\
40
- --verify <summary.json> --target <alias> [--source <alias>] [--json] [--audit <file>]
41
-
42
- The target must be a sandbox or a Developer Edition org (a Trailhead
43
- playground is one). Its Organization record says which, and any other
44
- org, an org whose edition it does not say included, is refused as a
45
- production org before anything is written or deleted. --dry-run and
46
- --list-objects only read, and run against any org.
47
-
48
- Before it reads a row, the clone says what the target runs on the objects
49
- it writes: its active record-triggered flows, Apex triggers, Process
50
- Builder processes and workflow rules, per object and write, with what of
51
- them sends messages (SENDS MESSAGES) or runs after commit; its assignment
52
- and duplicate rules; and what keeps a flow from starting for the user the
53
- run writes as, and whether that user holds it (with --json, under
54
- targetAutomation). When any of them fires as the clone inserts its
55
- records, or as it updates those it writes a second time \u2014 a lookup
56
- filled in once its record exists, an order or a contract given back its
57
- status \u2014 or the target would not say what it runs, nothing is written
58
- unless --accept-automation is given. A bypass the user does not hold is
59
- given with the permission set of the target that holds it, which
60
- --mute-automation assigns for the run alone, under a lease.
61
-
62
- It then says what the target holds against the rows, read from its
63
- metadata: its active validation rules and what keeps them quiet, its
64
- active duplicate rules and whether each blocks an insert or lets it
65
- through, the fields only the target requires that the clone does not
66
- write, the lookup filters of the lookups it writes, and the daily API
67
- requests the target has left against those the run takes (with --json,
68
- under targetGaps). A gap a decision of --config or --template answers \u2014
69
- a default given to a field only the target requires \u2014 is said answered
70
- by it, as Review shows it decided, and no longer BLOCKING (answeredBy,
71
- with --json). None of it stops the clone. With --dry-run --json,
72
- adminChanges lists, for whoever administers the target, the changes to its
73
- metadata that would let the rows go in as they are \u2014 a picklist value to
74
- add to a record type, a field to lengthen, a rule to turn off \u2014 grouped by
75
- object and record type, each with its step in Setup; the clone makes none.
76
-
77
- Once every row is read and before the first is written, the clone counts
78
- the records it is about to write, per object, and the data storage they
79
- take by the sizes Salesforce documents, and the daily API requests they
80
- take, with those of a checkpoint taken first and of the record types read
81
- back after. It writes nothing past --max-total, nor more than the target's
82
- data storage or its daily API requests have left. It says the emails the
83
- target's flows send as the records go in, against the daily limits it has
84
- left \u2014 a Developer Edition's email alerts counted against its single emails
85
- too \u2014 and writes nothing past them: a record whose flow fails in the save
86
- is refused there, and the org's own emails stop for the day. What sends
87
- and could not be read \u2014 a flow's definition refused or past the read's
88
- bound, a flow a package installed, which the org lets no one read \u2014 is
89
- said not counted (with --dry-run --json, under writePlan.emailsUncounted),
90
- and refuses nothing: --accept-automation already covers it.
91
-
92
- Required:
93
- --record <id> Source record ID (any object type \u2014 prefix detected automatically);
94
- may come from --template instead; --object (below)
95
- clones whole tables instead
96
- --source <alias> sf CLI alias of the source org
97
- --target <alias> sf CLI alias of the target sandbox
98
-
99
- Clone whole tables, in place of --record:
100
- --object <ApiName> a table to clone; repeat for more. The first is where
101
- discovery starts, and each other must be in its graph
102
- (--depth, --max-nodes): a parent one of them points at,
103
- or a child that hangs from one. Every other object
104
- discovery reaches is left out.
105
- --where <condition> the rows of the --object before it: a SOQL condition,
106
- written without WHERE (default: every row)
107
- The run is the panel's run of a query: each table read
108
- with the org's cursor in the order of its ids and
109
- written a page at a time, so the run holds a page of
110
- rows whatever a table holds, and keeps what it wrote in
111
- its journal as it goes; --resume reads each table after
112
- the last row the run wrote. Parents go before the tables
113
- that point at them, their lookups given the records the
114
- run created. With --upsert, every page of a table goes
115
- by one external id, the first whose value each row
116
- the run reads of it holds and no two share. A run that
117
- copies files (--files) reads each table whole. Not
118
- with --record, --expand-orphans or --rehearse. With
119
- --template, the template's choices go with the
120
- tables, its record or query aside.
121
-
122
- Clone the whole org, in place of --record:
123
- --depth all every object of the source the target can take, from
124
- no record and no table, each read a page at a time in
125
- the order of its ids and written ten thousand records
126
- at a time: as a Bulk API job from 2000 of them, by REST
127
- under that and for an object no job writes (an active
128
- duplicate rule watches it, the Bulk API refuses it).
129
- What it leaves out is said with why: setup, metadata,
130
- what only the platform writes, what the target cannot
131
- take, an empty table. Past 1950 objects or 20000 pairs
132
- of related objects, discovery refuses it, never cuts it.
133
- Its dry run stops at the write gate once the source is
134
- counted, and reads no row: per object the records it
135
- would insert and how many go in jobs, the API requests
136
- of both orgs, the Bulk API batches, the data and file
137
- storage, what it leaves out and why, the personal
138
- fields it copies as they are, and each refusal a real
139
- run would meet, exit 1 when there is one (with --json,
140
- under wholeOrg and wouldBeRefused).
141
- A real run asks before its first write, naming the
142
- records and objects, the requests and batches, the
143
- objects of managed packages (the mute reaches none of
144
- what they run), the phone numbers it writes empty and
145
- the personal fields it copies as they are: --yes writes
146
- without the question; with no terminal to answer it,
147
- the run is refused (CONFIRMATION_UNAVAILABLE). It keeps
148
- its journal, which --resume takes it up from and
149
- --remove takes it back from, and exits 3 when the
150
- target refused part of it. --max-total holds it as any
151
- run: give it what the dry run counted. --exclude-object
152
- leaves an object out, --filter narrows one; --files,
153
- off unless given, copies the org's files. Not with
154
- --record, --object, --where, --template, --custom-depth,
155
- --max-nodes, --max, --expand-orphans, --rehearse or
156
- --upsert.
157
- --no-anonymize with --depth all, copy the personal data as the source
158
- holds it, a production org's too
159
- --yes with --depth all, write without the question
160
-
161
- Copy a sample of the whole org that fits the target, with --depth all:
162
- --fit share rather than every record, a sample: roots drawn of
163
- each object, each with its children and the records
164
- it names, none without a record it cannot be written
165
- without; the largest share of the roots that fits
166
- what the target has left \u2014 80 % of the data storage
167
- its /limits say, half a MB off for their rounding,
168
- less what its automation still running creates
169
- under the records \u2014 and --max-total, its default
170
- of 10000 too: raise it to take more. The reference
171
- data go whole. Small parents and the price catalog
172
- go whole while they fit a quarter of the room the
173
- target has, 80 % of what it has left once half a MB
174
- is off, whatever --fit-within and --max-total ask;
175
- a root that would bring in more than a tenth of that
176
- room by itself is set aside and named (heavy roots
177
- set aside:). Drawn before the gate, from ids,
178
- lookups and the few values that decide what it
179
- keeps \u2014 record types, creation dates \u2014, the plan
180
- is kept on disk, the ids of each object and no
181
- value: a dry run's in forge-samples/ under the
182
- journal directory for a day, a run's beside its
183
- journal. The gate counts the plan, and the run
184
- writes its records and no other: a lookup to a
185
- record outside it is written empty and said, a
186
- record gone from the source since is said apart,
187
- one whose parent changed since is held back and
188
- failed. The dry run says the sample
189
- (sample:), per object what it keeps and how, what
190
- goes whole (whole:), the roots set aside (heavy
191
- roots set aside:), what it leaves out and why (not
192
- in the sample:), the lookups left empty (left
193
- empty:) and its plan (sample plan: <folder>); with
194
- --json under wholeOrg.sample, a run's under sample,
195
- and what it wrote of the plan under result.sample.
196
- Not with --files or --list-objects.
197
- --fit-within <MB> take no more than this many MB of the target
198
- --fit-seed <n> the seed the roots are drawn by (default: 1)
199
- The same seed and setup draw the same records.
200
- --fit-draw uniform|recent
201
- uniform spreads the roots over each object, reading
202
- the id of every root; recent takes the newest by
203
- creation date, reading only those it keeps
204
- (default: uniform)
205
- --fit-parents all|required
206
- all copies a record outside the sample that an
207
- optional lookup names, without its children;
208
- required writes such a lookup empty (default: all)
209
- --fit-children <n>|all most children a record brings through each relation,
210
- the newest; a master record brings every detail
211
- (default: 100)
212
- --fit-whole <Object> copy this object whole (repeatable)
213
- --fit-floor <n> roots kept of each object whatever the share
214
- (default: 1)
215
- --fit-plan <folder> write the records of the plan a dry run drew, as its
216
- line sample plan: printed it, within a day: refused
217
- when drawn of another org or with other flags, or
218
- changed since (SAMPLE_PLAN_MISMATCH), or not there
219
- (SAMPLE_PLAN_GONE), exit 2. The run moves it beside
220
- its journal; one that writes nothing puts it back.
221
- Not with --resume, which writes the plan its journal
222
- names: gone, SAMPLE_PLAN_GONE, exit 2.
223
- Refused, exit 1: a target that would not say its
224
- storage, with neither --fit-within nor --max-total
225
- (SAMPLE_STORAGE_UNREAD); the objects copied whole
226
- and the floors alone past what it may take, the
227
- heaviest named (SAMPLE_CANNOT_FIT); more than a
228
- million records to hold (SAMPLE_TOO_LARGE); the
229
- roots' ids past a tenth of the source's requests
230
- left today (API_BUDGET_EXCEEDED); a target that has
231
- less room than the plan was fitted to: simulate
232
- again (STORAGE_EXCEEDED).
233
-
234
- Options:
235
- --depth <mode> direct | full | custom | all (default: custom)
236
- --custom-depth <n> traversal depth when --depth is custom (default: 5)
237
- --max <n> max records cloned per object (default: unlimited)
238
- --list-objects print the objects discovery reached, then stop
239
- Answers "why was my object not cloned?" \u2014 an object
240
- absent from this list was never in the graph. With
241
- --json, stdout carries them as JSON: each object's
242
- record count, depth and whether it is included, and
243
- whether the graph was truncated.
244
- --max-nodes <n> objects discovery may reach (default: 50)
245
- Raise it when the summary says TRUNCATED and an
246
- object you expected is missing, e.g. the lines of an
247
- Opportunity's quotes. The prices, products, price
248
- books and selling models the lines use come whatever
249
- the cap, as do the items of an activated order and
250
- the schedules of an opportunity's products. Each
251
- parent a record reached cannot be written without
252
- takes the cap one object further, up to twice it.
253
- An empty table takes no place under it, and nothing
254
- is reached through it; discovery reads four times
255
- the cap in objects at most.
256
- --anonymize anonymize PII fields (default: off)
257
- With --depth all, on unless --no-anonymize when the
258
- source's Organization record says a production org.
259
- --keep-contact-points write emails and phone numbers as read (default: off)
260
- Off, every record is written with its email addresses
261
- under .invalid and its phone numbers in a fictional
262
- range, anonymized or not, so what the target's flows
263
- and email alerts send to them reaches no one. On,
264
- they may reach the real people the records name.
265
- --dry-run skip writes, surface scoped queries (default: off)
266
- It reads the automation and counts the records as a
267
- real run does, and says what would stop that run,
268
- each under the code that run is refused with: a real
269
- run would be refused (CODE): ... With --json, under
270
- wouldBeRefused, and the codes under wouldBeRefusedCodes.
271
- --rehearse have the target judge the rows, keep none (default: off)
272
- Reads and prepares every row as a real run would,
273
- then creates a sample of them in the target \u2014 every
274
- row up to 200, one per object, record type and set of
275
- fields given a value past it, with the records they
276
- name \u2014 in composite calls that each fail on purpose,
277
- so that every write is rolled back. Prints each
278
- refusal (status code, field, rows) and what could not
279
- be judged (with --json, under rehearsal). The target's
280
- automation runs inside each call: emails, @future and
281
- Queueable jobs, platform events published after
282
- commit and the asynchronous paths of Flows never
283
- leave it; platform events published immediately and
284
- callouts do. Refused against a production org, and,
285
- like a real run, without --accept-automation when the
286
- target runs automation on insert. Not with --dry-run,
287
- --upsert, --files, --remap-csv or --list-objects.
288
- --accept-automation write although the target runs flows or Apex
289
- triggers as the clone inserts, or as it updates the
290
- records it inserted, or could not say what it runs
291
- (default: off)
292
- --accept-emails write although the target delivers every email of
293
- what still runs as the clone writes, or would not say
294
- whether it does; --accept-automation never stands for
295
- it. Asked only when what still runs sends one: flows,
296
- processes and workflow rules with an email action,
297
- those whose definition was not read, and the
298
- assignment rules --apply-assignment-rules applies,
299
- whatever --mute-automation leaves. Whether the org
300
- delivers them is read with one line of anonymous Apex
301
- that sends nothing,
302
- Messaging.reserveSingleEmailCapacity(1), as the user
303
- the run writes as, never in a production org; on
304
- System email only or No access, none of them goes
305
- out, the org still counts them against its daily
306
- limits, and nothing is asked. What an Apex trigger
307
- sends is read nowhere (default: off)
308
- --mute-automation mute the target's automation for the run through its
309
- own bypass: assign the user the run writes as, for the
310
- run alone, the permission sets holding the custom
311
- permissions its flows, processes and workflow rules
312
- test to stay quiet, and take them back as it ends.
313
- What no bypass keeps quiet (an Apex trigger, a managed
314
- package's flow) still runs, and still needs
315
- --accept-automation. Refused on a production org and
316
- for a user who cannot assign permission sets, exit 1;
317
- a dry run says what would be muted and assigns nothing
318
- (default: off)
319
- ${Fh({run:"the run",simulation:"--dry-run"})}
320
- --max-total <n> most records the run may write in all (default: 10000)
321
- Counted once every row is read: past it, nothing is
322
- written. --max caps each object, this the whole run.
323
- --max-records-per-object <n>
324
- most records one read of an object takes
325
- (default: 50000)
326
- An object with more is read to it and said
327
- TRUNCATED. A clone of a record holds what it reads,
328
- so a higher number takes more memory; 1000000 at most.
329
- --upsert use external Id upsert when available (default: insert)
330
- Skips DUPLICATE_VALUE on re-runs of the same source records.
331
- --expand-orphans single-hop expand orphan parent FKs (default: off)
332
- Clones missing parents (out-of-graph) so child FKs resolve.
333
- --apply-assignment-rules
334
- apply the target's assignment rules (default: off)
335
- Off, every write says Sforce-Auto-Assign: FALSE and
336
- keeps the owner the run sets. On, the target's active
337
- assignment rules may give the Cases, Leads and
338
- Accounts the run writes another owner, and mail them.
339
- --skip-preflight skip pre-execute target row count (default: off)
340
- The preflight queries each object on target so the user
341
- can see existing volume before pressing through.
342
- --json emit JSON summary on stdout (CI mode) (default: off)
343
- stdout then carries the JSON alone, and every other
344
- line goes to stderr. Saved to a file, the summary is
345
- what --remove takes the run back from. With
346
- --list-objects, the JSON is the objects of the graph.
347
- A run refused before its first write prints
348
- "refused": {"code", "message"} instead, the code its
349
- line names: refused (MAX_TOTAL_EXCEEDED): ..., each
350
- other reason under "alsoRefused", on a line of its own.
351
- How a run ended is under result.status: success,
352
- partial or failure, as its status: line says it.
353
- --fail-on-partial exit 3, not 0, when the run wrote some records and
354
- the target refused others (default: off)
355
- --summary <file> write the summary to <file> as the run goes
356
- The JSON --json prints, written after each object
357
- with what the run has created so far ("running":
358
- true), then whole once it ends. Ctrl-C stops the run
359
- between two calls to the org and writes what it had
360
- created by then ("interrupted": true), as --json then
361
- prints it: --remove takes the run back from either.
362
- A file already there is not overwritten. Not with
363
- --list-objects or --rehearse.
364
- --resume <journal|id> take up where it stopped a run that did not end \u2014 a
365
- Ctrl-C, a failure, a process killed \u2014 from its journal:
366
- its file, or its run id in the journal directory. Each
367
- record that run wrote is linked to and never written
368
- again, the lookups and statuses it still owed are
369
- given, and the rest is written. The same record, orgs,
370
- depth, choices and flags as the run it takes up, or it
371
- is refused; a run that ended is refused too. Every run
372
- that writes keeps its journal there (see
373
- SANDFORGE_JOURNAL_DIR), and says where as it starts.
374
- The calls the run had under way when it stopped are
375
- looked for in the target first: a row found there is
376
- kept as written by the run, never sent again; one the
377
- target may hold already stops the resume before it
378
- writes (see --write-uncertain).
379
- Not with --dry-run, --rehearse or --list-objects.
380
- --write-uncertain with --resume: write all the same the rows of a call
381
- under way when the run stopped that the target may
382
- already hold, records the resume cannot tell from
383
- them being there \u2014 each may then be there twice.
384
- --exclude <obj.field> skip a field on an object during clone (repeatable)
385
- e.g. --exclude Account.Description --exclude Account.NumberOfEmployees
386
- --exclude-object <obj> leave an object out of the clone (repeatable)
387
- e.g. --exclude-object PricebookEntry
388
- Out whether discovery reaches it or the run would
389
- add it past the cap. What it costs is said, not
390
- written: the records that cannot be written without
391
- one of its records, and the orders left drafts.
392
- --owner-map <src=tgt> remap OwnerId from source User Id to target User Id (repeatable)
393
- e.g. --owner-map 005AB...=005XY...
394
- Useful when source records were authored by users
395
- that don't exist on the target sandbox (ex-employees).
396
- A target user the target holds inactive is refused
397
- before anything is read (OWNER_MAP_INACTIVE), and
398
- one it holds no user of (OWNER_MAP_UNKNOWN).
399
- --filter <obj=where> per-object SOQL WHERE filter (repeatable)
400
- e.g. --filter "Case=Status = 'Open' AND CreatedDate > LAST_N_DAYS:30"
401
- Lets BAs narrow a clone to a subset without changing
402
- graph topology. Filter is appended via AND (...) to
403
- the scope-derived clause. Max 512 chars per filter,
404
- max 50 filters total.
405
- --map <obj.src=tgt> per-object source\u2192target field rename (repeatable)
406
- e.g. --map Account.Region__c=Region__pc
407
- Handles schema drift between source and target
408
- (managed-package re-key, namespace change). The
409
- source field is dropped and the value written to
410
- the target field name on insert.
411
- --config <file.json> the run's choices from a JSON file: the decisions
412
- taken in Review's Gaps row (picklistValueMappings,
413
- recordTypeMappings, defaultValues, truncateFields,
414
- skippedRows, ignoredGaps), the fields and objects
415
- left out (fieldExclusions, excludedObjects), the
416
- filters (objectSoqlFilters) and the mappings
417
- (ownerMappings, fieldMappings), as a Forge config
418
- names them. Checked as the panel checks a run's
419
- config; any other key is refused. The flags above
420
- win over the file: their exclusions are added, their
421
- filters and mappings replace the file's for the same
422
- object, user or field.
423
- --template <file.json> a template the Template tab exported: its decisions,
424
- exclusions, filters and mappings, as --config takes
425
- them, and its depth, caps, anonymization, contact
426
- points and orphan parents, each unless its flag is
427
- given. Its record is cloned when --record is not
428
- given; a template of a query needs --record, or
429
- --object. Not with --config.
430
- --remap-csv <file> write the source\u2192target ID remap table to a CSV
431
- file (header: sourceId,targetId). BA reconciliation:
432
- "where did source X go on the target sandbox?"
433
- --files copy the files of the cloned records (default: off)
434
- Salesforce Files (the latest version of each) and
435
- attachments, after the records they hang on. The
436
- total is checked against the target's file storage
437
- before anything is written: past it, refused
438
- (FILE_STORAGE_EXCEEDED), as when that storage could
439
- not be read (FILE_STORAGE_UNREAD) or the files not
440
- all looked up (FILES_UNREAD).
441
- --max-file-size <MB> largest file --files copies, 1 to 35 (default: 10)
442
- A larger file is left out and listed, never cut.
443
- --files-as-is accept that files are copied as they are: their
444
- content cannot be anonymized. Required with --files
445
- when --anonymize is on.
446
- --audit <file> record the run in an audit trail kept in <file>
447
- The entry the panel keeps in Reports -> Audit trail:
448
- per object the records created, updated and lost,
449
- the orgs, the outcome, the user as a hash of the
450
- username, and, for a run refused before it wrote,
451
- the code of what refused it. Counts only, never a
452
- value of a record. Each run adds its entry to the
453
- file; a dry run, --list-objects and --rehearse write
454
- nothing, and add none.
455
- -h, --help show this help and exit
456
-
457
- Remove what a run created:
458
- --remove <file> the summary a run printed with --json, saved to a file,
459
- or the journal of a run: every part of it, the run it
460
- took up and each time it was taken up
461
- Deletes from --target the records that run created,
462
- as the wizard removes a run from Recent runs: children
463
- first, never a record the target already held, and a
464
- record kept while records that stay depend on it. The
465
- target must be the org the run wrote to. A dry run's
466
- summary is refused: it created nothing.
467
- What a removal wrote to the records it left is kept
468
- beside the summary, clone-summary.removals.json for
469
- clone-summary.json, and the next --remove of that
470
- summary reads it: what a removal wrote is no change
471
- since the run. Keep that file with the summary.
472
- A summary of a run past 50 000 records keeps their ids
473
- in its journal, which the removal reads them from.
474
- Of a run stopped and taken up with --resume, one
475
- summary per part, it is kept beside the journal too:
476
- the removal of any part, or of the journal, reads what
477
- the others wrote, and once a part's own records are
478
- gone, takes what an earlier removal of another part
479
- left. What the run wrote to a record of another part
480
- is no change since the run. The journal's removal
481
- takes the parts the last first, each read against
482
- its own span: what someone changed, or made, between
483
- two parts stays.
484
- --include-changed remove also the records changed since the run, and
485
- what was added to them since (default: kept)
486
- --accept-automation delete although the target runs flows, Apex triggers,
487
- processes or workflow rules as the records go, those
488
- --sweep deletes included \u2014 before or after a delete,
489
- or as an activated order is set back to Draft for
490
- its delete \u2014 or could not say what it runs
491
- (default: off)
492
- --mute-automation mute the target's automation for the removal through
493
- its own bypass, as for a run: the permission sets
494
- holding the bypasses of what fires as the records go,
495
- those --sweep deletes included, assigned to the user
496
- it deletes as, for the removal alone, and taken back
497
- as it ends; what no bypass keeps quiet still needs
498
- --accept-automation (default: off)
499
- --leave-undeletable remove the rest when the user the removal runs as
500
- may not delete the records of some objects of the
501
- run, leaving those with what they hang from; without
502
- it the removal stops before its first delete and
503
- names them (default: off)
504
- --preview say what the removal would do, and do nothing: per
505
- object the records it would delete, those gone
506
- already, those changed since the run and who changed
507
- them, those it could not see, and what a removal run
508
- now would be refused for, each under the code it is
509
- refused with: a removal would be refused (CODE): ...,
510
- with --json the codes under "refusalCodes", in the
511
- order of "refusals". It reads the records, as
512
- the removal reads them before its first delete, and
513
- writes nothing: not to the org, not beside the
514
- summary. With --sweep, it lists what the sweep would
515
- take, and reads what fires on it with the run's own.
516
- Not with --sweep-list or --audit.
517
- A removal takes no --dry-run: one that did not read
518
- it would delete for real.
519
- --sweep before the run's records go, delete too what the
520
- target's automation made for the run, that the run's
521
- id map does not hold: what the run's user created
522
- under the run's records, what they point at, or what
523
- hangs from those, three links at most, at most a
524
- minute after the record it is tied to \u2014 in the
525
- objects the run wrote and their children, tasks,
526
- events, feed, email messages, notes, case comments,
527
- and the objects the target's flows create. What a
528
- record of the run points at by a lookup the org
529
- refuses the delete for (an asset its case names)
530
- goes once that record is gone. Listed and kept: what
531
- is tied to the run but came later, up to 15 minutes,
532
- or as the org's Automated Process user; and what the
533
- run's user created in the run's window, a second
534
- before its first write to a minute after its last,
535
- tied to nothing of it.
536
- What anyone changed more than 2 s after the run's
537
- last write, and after its own creation, stays \u2014 the
538
- run's user and its automation too \u2014 unless
539
- --include-changed, and the sweep then ends partial,
540
- exit 3; a change made before the run's last write
541
- reads as unchanged. Runs alone when an earlier
542
- --remove took every record of the run. Of a clone of
543
- the whole org, the removal says the sweep is off
544
- unless given: the run's window spans hours, and a
545
- sweep looks at 300 objects at most
546
- (default: off)
547
- --sweep-late with --sweep, take too what it lists as made late;
548
- with --sweep-list, say what it would take
549
- --sweep-untied with --sweep, take too what it lists as tied to
550
- nothing of the run; with --sweep-list, say what it
551
- would take; refused when another run of this
552
- machine wrote to the target in the run's window, or
553
- when that user created records there on objects
554
- neither the run nor the automation reaches (hand
555
- work, likely)
556
- --sweep-list list what --sweep would delete, per object with a few
557
- names and how many it ties to the run, and delete
558
- nothing, the run's records included; exit 3, as a
559
- refused --sweep, when it says the sweep is refused
560
- What a sweep leaves, and why: what another user
561
- created, a colleague's or an integration's; what is
562
- tied to nothing, unless --sweep-untied; what came
563
- more than 15 minutes after its record, or after the
564
- removal began, which cannot be told from work done
565
- by hand; what anyone changed after the run's last
566
- write, the run's own user included, unless
567
- --include-changed; what the
568
- automation changed or deleted rather than created,
569
- which a checkpoint taken before the run takes back;
570
- what left the org (emails, outbound messages); more
571
- than 10 000 records of one object; and what the
572
- panel, another machine or a CI wrote meanwhile, which
573
- a sweep does not see
574
- --json print what became of the records as JSON on stdout,
575
- every other line on stderr; refused before its first
576
- delete, "refused": {"code", "message"}, the code its
577
- line names: refused (CODE): ... \u2014 a production org
578
- (PRODUCTION_TARGET), what fires as it deletes
579
- (AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
580
- MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
581
- delete (UNDELETABLE_NOT_LEFT), an org that is not the
582
- one the run wrote to (OTHER_ORG, its --preview too)
583
- --audit <file> record the removal, and the sweep, in the audit trail
584
- kept in <file>
585
-
586
- Verify what a run created:
587
- --verify <file> the summary a run printed with --json, saved to a file,
588
- or the journal of a run, every part of it
589
- Reads back from --target every record the run created,
590
- after a pause and again until two readings agree (three
591
- at most, two seconds apart): those there, those in the
592
- recycle bin, those neither, out of the user's sight;
593
- checks on twenty records of each object that the
594
- lookups the run set point at the ids their parents got,
595
- reading the source records in --source; and lists the
596
- records changed since the run, which --remove keeps
597
- unless --include-changed. Only reads, from either org.
598
- Exits 0 when VERIFIED, 3 when PARTIAL (a record not
599
- there, a lookup that does not hold, or a part that could
600
- not be checked) and 4 when UNSTABLE (no two readings
601
- agreed: something still writes to the records).
602
- --source <alias> the org the run read from (default: the summary's)
603
- A lookup the clone left out with --exclude reads as
604
- one left empty.
605
- --json print the verification as JSON on stdout, every other
606
- line on stderr; refused for an org that is not the
607
- one the run wrote to, exit 1, "refused": {"code",
608
- "message"}, the code its line names: refused
609
- (OTHER_ORG): ...
610
- --audit <file> record the verification in the audit trail kept in
611
- <file>
612
-
613
- Environment:
614
- SANDFORGE_FORGE_PAGE_SIZE=<n>
615
- a diagnostic: read every statement through the org's
616
- cursor and hand it on in pages of <n> rows, as a run of
617
- whole tables reads, to see a clone's paged read against
618
- a real org. Not a setting: an org answers in pages of
619
- 200 to 2000 rows, and a page of <n> is cut from them.
620
- SANDFORGE_JOURNAL_DIR=<dir>
621
- where every run that writes keeps its journal, in
622
- <dir>/forge-runs/ (default: ~/.sandforge)
623
- What the run wrote, read and still owes, line by line
624
- as it goes, ids only: what --resume takes a run up
625
- from, and what --remove takes it back from however it
626
- ended.
627
-
628
- Exit codes:
629
- 0 the clone ran, a run the target refused some records of too unless
630
- --fail-on-partial; the rehearsal ran, whatever it found refused; the removal
631
- took every record it set out to take; the preview said what a removal
632
- would do, refusals included
633
- 1 the clone or the removal could not run; the clone produced only failures,
634
- or its files were refused; the target is a production org; the target
635
- runs automation on insert or on the updates the clone makes after its
636
- inserts, or the removal's deletes fire automation, and
637
- --accept-automation was not given; the target delivers the emails of
638
- what still runs, or would not say whether it does, and --accept-emails
639
- was not given (EMAILS_NOT_ACCEPTED); the checkpoint asked first was
640
- refused or could not be taken (CHECKPOINT_REFUSED); the run would write
641
- more than --max-total records, more than the target's data storage
642
- has left or more emails than it has left today, or would take more API
643
- requests than it has left today (nothing is written or deleted then);
644
- a clone of the whole org nobody answered the question of
645
- (CONFIRMATION_UNAVAILABLE) or that was declined (WRITE_DECLINED), or
646
- whose dry run says a real run would be refused; a sample of it that
647
- could not be drawn (SAMPLE_STORAGE_UNREAD, SAMPLE_CANNOT_FIT,
648
- SAMPLE_TOO_LARGE)
649
- 2 a bad command line, or a summary --remove cannot take a run back from, or
650
- a file beside it that is not what a removal kept there; the plan of a
651
- sample --fit-plan gives or --resume takes up gone, or drawn of another
652
- org or setup (SAMPLE_PLAN_GONE, SAMPLE_PLAN_MISMATCH)
653
- 3 the run was partial and --fail-on-partial was given, or was a clone of
654
- the whole org; the removal left
655
- records of the run in the org: kept, or refused, or found neither in the
656
- org nor in its recycle bin, as the user it ran as sees them; or the sweep
657
- was refused, or did not take all it was asked to (a --sweep-untied
658
- refused included)
659
- 130 Ctrl-C stopped the clone: the summary says what it created by then
660
- 143 a SIGTERM stopped it \u2014 a CI job cancelled or timed out \u2014, 129 a SIGHUP:
661
- as Ctrl-C does, the summary and the journal say what it created
662
- `,Ts=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,rt=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function qw(r,e){return r.verdict==="unread"?` API requests: about ${r.estimate}; what ${e} has left today could not be read (${r.unread})`:` API requests: about ${r.estimate}, of the ${r.remaining} ${e} has left of its ${r.max} a day`+(r.verdict==="exceeds"?": more than it has left":r.verdict==="near"?": it would leave less than a tenth of them":"")}var Uw={"validation-rule":"a validation rule refused it","restricted-picklist":"a restricted picklist refused its value","lookup-filter":"a lookup filter refused the record it names","inactive-owner":"the target holds the owner it names inactive"},Hw={inputMode:"--record",recordId:"--record",depth:"--depth",customDepth:"--custom-depth",maxRecordsPerObject:"--max",sourceOrgId:"--source",targetOrgId:"--target",fieldExclusions:"--exclude",ownerMappings:"--owner-map",objectSoqlFilters:"--filter",fieldMappings:"--map",soqlQuery:"--object",sample:"--fit"},hg=["fieldExclusions","excludedObjects","ownerMappings","objectSoqlFilters","fieldMappings","picklistValueMappings","recordTypeMappings","defaultValues","truncateFields","skippedRows","ignoredGaps"],Kw=W.strictObject(Vd.pick(Object.fromEntries(hg.map(r=>[r,!0]))).shape);function Vw(r){let e=r;for(let t="";t!==e;)t=e,e=e.replace(/\([^()]*\)/g," ");return/\bFROM\s+([A-Za-z][A-Za-z0-9_]*)/i.exec(e)?.[1]}function Jw(r){let e=[];function t(n){process.stderr.write(`${n}
663
- `),process.exit(2)}for(let n=0;n<r.length;n++){let o=r[n];if(o!=="--object"&&o!=="--where")continue;let s=r[n+1];if((s===void 0||s.startsWith("--"))&&t(o==="--object"?"--object takes the API name of a table to clone.":"--where takes a SOQL condition, written without WHERE."),n++,o==="--object"){rt.test(s)||t(`Invalid --object value "${s}" (must match SObject API name pattern)`),e.some(a=>a.objectApiName===s)&&t(`--object ${s} is named twice.`),e.push({objectApiName:s});continue}let i=e.at(-1);i?i.where!==void 0?t(`--object ${i.objectApiName} is given two --where: join them with AND.`):s.trim()===""?t(`--where for ${i.objectApiName} is empty.`):i.where=s.trim():t("--where filters the --object before it: name the table first.")}return e.length>0?e:void 0}function Ed(r){let[e]=r;return`SELECT Id FROM ${e.objectApiName}${e.where?` WHERE ${e.where}`:""}`}function Yw(r,e){let t=new Set(e.map(n=>n.objectApiName));return r.nodes.map(n=>n.objectApiName).filter(n=>!t.has(n))}function Qw(r,e){let t=new Set(r.nodes.map(n=>n.objectApiName));return e.map(n=>n.objectApiName).filter(n=>!t.has(n))}function Xw(r,e){let t=r.tables??[],n=[...new Set([...r.excludedObjects,...Yw(e,t)])];return{inputMode:"soql",soqlQuery:Ed(t),depth:r.depth,...r.depth==="custom"?{customDepth:r.customDepth}:{},sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...r.maxRecordsPerObject!==void 0?{maxRecordsPerObject:r.maxRecordsPerObject}:{},...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...n.length>0?{excludedObjects:n}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions}}function Zw(r,e,t,n,o){let s=dd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}},o)??{};return r.upsert?{...s,upsertMode:"auto"}:s}function Gh(r){return r.depth==="all"?{inputMode:"org"}:r.tables?{inputMode:"soql",soqlQuery:Ed(r.tables)}:{inputMode:"record",recordId:r.record}}function ey(r){return r.depth==="all"?"the whole org":r.tables?`tables=${r.tables.map(e=>e.where?`${e.objectApiName} (${e.where})`:e.objectApiName).join(", ")}`:`record=${r.record??""}`}var hd=12;function ty(r){if(r.record)return r.record;let e=(r.objects??[]).map(n=>n.objectApiName),t=e.length<=hd?e.join(", "):`${e.slice(0,hd).join(", ")} and ${e.length-hd} more object(s)`;return r.wholeOrg?e.length>0?`the whole org (${t})`:"the whole org":e.length>0?t:"the run"}function ny(r){return{inputMode:"org",depth:"all",sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...r.excludedObjects.length>0?{excludedObjects:r.excludedObjects}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions,...r.sample?{sample:gg(r.sample)}:{}}}function gg(r){let e={...r.options};return delete e.plan,e}function ry(r,e,t,n,o,s){return dd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{wholeReadBound:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{},...s?{sample:s}:{}}},o)??{}}function oy(r,e){return e.size===0?r:{...r,nodes:r.nodes.map(t=>e.has(t.objectApiName)?{...t,included:!1,leftOutByUser:!0}:t)}}var qh=1e6;function sy(r,e){if(e.length>qh)return{refusal:[`${r}: the file is larger than ${qh} bytes`]};let t;try{t=JSON.parse(e.replace(/^\uFEFF/,""))}catch{return{refusal:[`${r}: the file is not JSON`]}}let n=s=>s.issues.map(i=>{let a=i.path.map(String).join(".");return`${r}${a?` (${a})`:""}: ${i.message}`});if(r==="--template"){let s=Jd.safeParse(t);return s.success?{file:{kind:"template",template:s.data}}:{refusal:n(s.error)}}let o=Kw.safeParse(t);return o.success?{file:{kind:"config",config:o.data}}:{refusal:[...n(o.error),`${r} takes ${hg.join(", ")}; the other choices have flags of their own.`]}}var Pd=["--fit-within","--fit-seed","--fit-draw","--fit-parents","--fit-children","--fit-whole","--fit-floor","--fit-plan"],iy={switches:["--list-objects","--anonymize","--keep-contact-points","--dry-run","--rehearse","--accept-automation","--accept-emails","--mute-automation","--upsert","--expand-orphans","--apply-assignment-rules","--skip-preflight","--json","--fail-on-partial","--write-uncertain","--files","--files-as-is","--no-anonymize","--yes",...cd.switches,"--include-changed"],values:["--record","--source","--target","--object","--where","--depth","--custom-depth","--max","--max-nodes","--max-total","--max-records-per-object","--summary","--resume","--exclude","--exclude-object","--owner-map","--filter","--map","--config","--template","--remap-csv","--max-file-size","--audit","--fit",...Pd,...cd.values]},ay=[["--record","it starts from no record"],["--object","it starts from no table: --exclude-object leaves one out"],["--where","it starts from no table: --filter narrows an object"],["--template","a template holds the choices of a walk from its record or query: give them with --config"],["--custom-depth","it walks no depth"],["--max-nodes","it takes every object it can, and is refused past 1950 rather than cut"],["--max","it copies every row of what it takes: --filter narrows an object, and --fit share copies a sample of the org that fits the target, none of its records without those they name"],["--expand-orphans","every parent it reaches is in the org it copies"],["--rehearse","a rehearsal holds every row it prepares"],["--upsert","its writes go as Bulk API jobs that insert"]];function dy(r,e){if(!e){let n=["--yes","--no-anonymize"].filter(o=>r(o));if(n.length===0)return;process.stderr.write(`${n.join(" and ")} ${n.length===1?"goes":"go"} with --depth all: no other clone asks before it writes, and none anonymizes unless --anonymize is given.
664
- `),process.exit(2)}let t=ay.filter(([n])=>r(n));if(r("--anonymize")&&r("--no-anonymize")&&t.push(["--anonymize","it is given --no-anonymize too: give one of them"]),t.length!==0){for(let[n,o]of t)process.stderr.write(`--depth all clones the whole org, and does not go with ${n}: ${o}.
665
- `);process.exit(2)}}var cy=Pd.filter(r=>r!=="--fit-whole"),Uh=1e4,Hh=1e6,Kh=1e6,ly="sample.json";function uy(r,e){let t=b=>(process.stderr.write(`${b}
666
- `),process.exit(2)),n=b=>r.flatMap((S,R)=>S===b&&R+1<r.length?[r[R+1]]:[]),o=b=>r.includes(b),s=Pd.filter(b=>o(b));if(!o("--fit"))return s.length===0?void 0:t(`${s.join(", ")} ${s.length===1?"goes":"go"} with --depth all --fit share: ${s.length===1?"it sets":"they set"} how a sample of the whole org is drawn, and the line asks for none.`);let i=n("--fit");if(i.length!==1||i[0]!=="share")return t(`--fit takes share, once, not "${i.join(" ")}".`);if(!e.wholeOrg)return t("--fit share goes with --depth all: it copies a sample of the whole org that fits the target. A clone of a record or of tables reads what it reaches: --max caps each object.");if(o("--files"))return t("--fit share copies no files yet: leave out --files, or leave out --fit share to copy every record of the org with its files.");if(o("--list-objects"))return t("--list-objects lists the objects of the graph and draws no sample: leave out --fit share.");if(o("--fit-plan")&&o("--resume"))return t("--fit-plan does not go with --resume: a run taken up writes the plan its journal names, the one it began with.");for(let b of cy)n(b).length>1&&t(`${b} is given twice: give it once.`);let a=b=>n(b)[0],d={maxTotal:e.maxTotal},c=a("--fit-within");if(c!==void 0){let b=Number(c);(!/^\d+(?:\.\d+)?$/.test(c)||b<=0||b>Kh)&&t(`--fit-within takes a number of MB above 0, up to ${Kh}, not "${c}".`),d.withinMB=b}let l=a("--fit-seed");l!==void 0&&(/^\d{1,15}$/.test(l)||t(`--fit-seed takes a whole number, 0 or more, not "${l}".`),d.seed=Number(l));let u=a("--fit-draw");u!==void 0&&(u!=="uniform"&&u!=="recent"&&t(`--fit-draw takes uniform, the roots spread over each object by the seed, or recent, the newest by their creation date, not "${u}".`),d.draw=u);let p=a("--fit-parents");p!==void 0&&(p!=="all"&&p!=="required"&&t(`--fit-parents takes all, the records an optional lookup names copied without their children, or required, such a lookup left empty, not "${p}".`),d.parents=p);let f=a("--fit-children");if(f!==void 0){let b=Number(f);f==="all"?d.children="all":/^\d{1,7}$/.test(f)&&b>=1&&b<=Hh?d.children=b:t(`--fit-children takes a whole number of children from 1 to ${Hh}, or all, not "${f}".`)}let h=[];for(let b of n("--fit-whole"))rt.test(b)||t(`Invalid --fit-whole value "${b}" (must match SObject API name pattern)`),h.includes(b)||h.push(b);let g=h.filter(b=>e.excludedObjects.includes(b));g.length>0&&t(`--fit-whole and --exclude-object both name ${g.join(", ")}: the sample would copy whole an object the run leaves out. Give each to one of them.`),h.length>0&&(d.whole=h);let m=a("--fit-floor");if(m!==void 0){let b=Number(m);(!/^\d{1,5}$/.test(m)||b>Uh)&&t(`--fit-floor takes a whole number of records from 0 to ${Uh}, not "${m}".`),d.floor=b}let y=a("--fit-plan");if(y!==void 0){let b=Et(y);d.plan=_w(b)===ly?zw(b):b}return{options:d,maxTotalGiven:e.maxTotalGiven}}function py(r,e=process.env){let t=r.slice(2);(t.includes("-h")||t.includes("--help"))&&(process.stdout.write($d),process.exit(0)),ic(t,iy);let n=(F,Y)=>{let B=t.indexOf(F);return B>=0&&B+1<t.length?t[B+1]:Y},o=F=>t.includes(F);o("--config")&&o("--template")&&(process.stderr.write(`--config and --template: give one of them.
667
- `),process.exit(2));let s=o("--template")?"--template":o("--config")?"--config":void 0,i=s?n(s):void 0,a;if(s){(!i||i.startsWith("--"))&&(process.stderr.write(`${s} takes the path of a JSON file.
668
- `),process.exit(2));let F;try{F=yn(i,"utf8")}catch(B){process.stderr.write(`${s}: cannot read ${i}: ${X(B)}
669
- `),process.exit(2)}let Y=sy(s,F);if("refusal"in Y){for(let B of Y.refusal)process.stderr.write(`${B}
670
- `);process.exit(2)}a=Y.file}let d=a?.kind==="template"?a.template:void 0,c=n("--depth")==="all";dy(o,c);let l=a?.kind==="template"?{...a.template.config}:a?.config??{},u=d?.config.soqlQuery!==void 0?Vw(d.config.soqlQuery):void 0;if(u!==void 0&&l.objectSoqlFilters?.[u]!==void 0){let F={...l.objectSoqlFilters};delete F[u],l.objectSoqlFilters=F}let p=Jw(t);if(p){let F=["--record","--expand-orphans","--rehearse"].filter(Y=>o(Y));F.length>0&&(process.stderr.write(`--object clones whole tables, as the panel runs a query: it does not go with ${F.join(", ")}, which ${F.length===1?"goes":"go"} with a clone of one record (--record).
671
- `),process.exit(2)),d?.config.expandOrphanParents===!0&&(process.stderr.write(`--template: the template brings orphan parents (expandOrphanParents), which go with a clone of one record (--record), not with --object.
672
- `),process.exit(2))}let f=d?.config.inputMode==="record"?d.config.recordId:void 0;d&&!p&&!o("--record")&&!f&&(process.stderr.write(`--template: the template clones from a ${d.config.inputMode==="record"?"record it does not name":"query"}, and the command clones from a record: give --record.
673
- `),process.exit(2));let h=p||c?void 0:n("--record")??f,g=n("--source"),m=n("--target");(!h&&!p&&!c||!g||!m)&&(process.stderr.write(`Missing required flag. Run with --help for usage.
674
- `),process.exit(2)),o("--include-changed")&&(process.stderr.write(`--include-changed goes with --remove.
675
- `),process.exit(2));let y=["--dry-run","--upsert","--files","--remap-csv","--list-objects"].filter(F=>o(F));o("--rehearse")&&y.length>0&&(process.stderr.write(`--rehearse does not go with ${y.join(", ")}.
676
- `),process.exit(2));let b=by(t),S=Nh(t,[{flag:"--rehearse",why:"a rehearsal keeps nothing it creates in the target, and there is nothing to take back."},{flag:"--list-objects",why:"it lists the objects of the graph, and writes nothing."},{flag:"--resume",why:"a run taken up is the run its first part began, and a checkpoint taken now would hold what that part wrote: rewind to the one it took, if it took one."}]),R=n("--depth")??d?.config.depth??"custom",k=n("--custom-depth")??(d?.config.customDepth!==void 0?String(d.config.customDepth):"5"),A=n("--max")??(d?.config.maxRecordsPerObject!==void 0?String(d.config.maxRecordsPerObject):void 0),w=n("--max-nodes")??(d?.config.maxNodes!==void 0?String(d.config.maxNodes):void 0),I=n("--max-total"),P=n("--max-records-per-object"),v=F=>{let Y=[];for(let B=0;B<t.length;B++)t[B]===F&&B+1<t.length&&Y.push(t[B+1]);return Y},$=Object.fromEntries(Object.entries(l.fieldExclusions??{}).map(([F,Y])=>[F,[...Y]]));for(let F of v("--exclude")){let Y=F.indexOf(".");(Y<=0||Y===F.length-1)&&(process.stderr.write(`Invalid --exclude value "${F}" (expected Object.field)
677
- `),process.exit(2));let B=F.slice(0,Y),G=F.slice(Y+1);(!rt.test(B)||!rt.test(G))&&(process.stderr.write(`Invalid --exclude name in "${F}" (must match SObject API name pattern)
678
- `),process.exit(2));let be=$[B]??=[];be.includes(G)||be.push(G)}let E=[...l.excludedObjects??[]];for(let F of v("--exclude-object"))rt.test(F)||(process.stderr.write(`Invalid --exclude-object value "${F}" (must match SObject API name pattern)
679
- `),process.exit(2)),E.includes(F)||E.push(F);let M={...l.ownerMappings};for(let F of v("--owner-map")){let Y=F.indexOf("=");(Y<=0||Y===F.length-1)&&(process.stderr.write(`Invalid --owner-map value "${F}" (expected sourceId=targetId)
680
- `),process.exit(2));let B=F.slice(0,Y),G=F.slice(Y+1);(!Ts.test(B)||!Ts.test(G))&&(process.stderr.write(`Invalid --owner-map IDs in "${F}" (must be 15 or 18 char Salesforce IDs)
681
- `),process.exit(2)),M[B]=G}let Z={...l.objectSoqlFilters};for(let F of v("--filter")){let Y=F.indexOf("=");(Y<=0||Y===F.length-1)&&(process.stderr.write(`Invalid --filter value "${F}" (expected Object=where-clause)
682
- `),process.exit(2));let B=F.slice(0,Y),G=F.slice(Y+1);G.length>512&&(process.stderr.write(`--filter where-clause for "${B}" exceeds 512 chars
683
- `),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(G)&&(process.stderr.write(`--filter where-clause for "${B}" contains forbidden tokens (--, /*, */, trailing ;)
684
- `),process.exit(2)),Z[B]=G}let U=new Set(v("--filter").map(F=>F.slice(0,F.indexOf("="))));for(let F of p??[])F.where!==void 0&&(U.has(F.objectApiName)&&(process.stderr.write(`--where and --filter both filter ${F.objectApiName}: give one of them.
685
- `),process.exit(2)),F.where.length>512&&(process.stderr.write(`--where for "${F.objectApiName}" exceeds 512 chars
686
- `),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(F.where)&&(process.stderr.write(`--where for "${F.objectApiName}" contains forbidden tokens (--, /*, */, trailing ;)
687
- `),process.exit(2)),Z[F.objectApiName]=F.where);let H=Object.fromEntries(Object.entries(l.fieldMappings??{}).map(([F,Y])=>[F,{...Y}]));for(let F of v("--map")){let Y=F.indexOf("."),B=F.indexOf("=");(Y<=0||B<=Y+1||B===F.length-1)&&(process.stderr.write(`Invalid --map value "${F}" (expected Object.sourceField=targetField)
688
- `),process.exit(2));let G=F.slice(0,Y),be=F.slice(Y+1,B),Ae=F.slice(B+1);(!rt.test(be)||!rt.test(Ae))&&(process.stderr.write(`Invalid --map field name in "${F}" (must match SObject API name pattern)
689
- `),process.exit(2)),(H[G]??={})[be]=Ae}let K=k?Number(k):5,pe=A?Number(A):void 0,le=w?Number(w):void 0;le!==void 0&&(!Number.isInteger(le)||le<1)&&(process.stderr.write(`--max-nodes takes a whole number of objects, 1 or more.
690
- `),process.exit(2));let V=I===void 0?Hn:Number(I);(!Number.isInteger(V)||V<1)&&(process.stderr.write(`--max-total takes a whole number of records, 1 or more.
691
- `),process.exit(2));let fe=P===void 0?Xr:Number(P);(!Number.isInteger(fe)||fe<1||fe>Xs)&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${Xs}.
692
- `),process.exit(2));let se=e.SANDFORGE_FORGE_PAGE_SIZE,me=se===void 0||se===""?void 0:Number(se);me!==void 0&&(!Number.isInteger(me)||me<1)&&(process.stderr.write(`SANDFORGE_FORGE_PAGE_SIZE takes a whole number of rows, 1 or more.
693
- `),process.exit(2));let z=o("--anonymize")||d?.config.anonymizePII===!0,Oe=o("--keep-contact-points")||d?.config.keepContactPoints===!0,ne=Oy(t,z),q=Eo(l),ee=uy(t,{wholeOrg:c,maxTotal:V,maxTotalGiven:I!==void 0,excludedObjects:E}),te=(c?Ks:Ks.safeExtend({depth:Kd})).safeParse({...c?{inputMode:"org"}:p?{inputMode:"soql",soqlQuery:Ed(p)}:{inputMode:"record",recordId:h},depth:R,customDepth:R==="custom"?K:void 0,sourceOrgId:g,targetOrgId:m,anonymizePII:z,keepContactPoints:Oe,skipEmpty:!0,batchSize:"auto",maxRecordsPerObject:pe,fieldExclusions:$,excludedObjects:E,ownerMappings:M,objectSoqlFilters:Z,fieldMappings:H,...q,...ee?{sample:ee.options}:{}});if(!te.success){for(let F of te.error.issues){let[Y,...B]=F.path.map(String),G=Hw[Y??""]??(s&&Y?`${s} ${Y}`:Y??"arguments"),be=B.length>0?` (${B.join(".")})`:"";process.stderr.write(`Invalid ${G}${be}: ${F.message}
694
- `)}process.exit(2)}return{record:h,tables:p,source:g,target:m,depth:te.data.depth,customDepth:K,maxNodes:le,maxRecordsPerObject:pe,anonymize:z,anonymizeGiven:o("--anonymize")||o("--no-anonymize"),yes:o("--yes"),keepContactPoints:te.data.keepContactPoints===!0,dryRun:o("--dry-run"),listObjects:o("--list-objects"),upsert:o("--upsert"),expandOrphans:o("--expand-orphans")||d?.config.expandOrphanParents===!0,applyAssignmentRules:o("--apply-assignment-rules")||d?.config.applyAssignmentRules===!0,skipPreflight:o("--skip-preflight"),json:o("--json"),failOnPartial:o("--fail-on-partial"),summary:b,fieldExclusions:$,excludedObjects:E,ownerMappings:M,objectSoqlFilters:Z,fieldMappings:H,remapCsv:Ry(t),files:ne,acceptAutomation:o("--accept-automation"),acceptEmails:o("--accept-emails"),muteAutomation:o("--mute-automation"),...S!==void 0?{checkpointFirst:S}:{},maxTotal:V,readCeiling:fe,...me!==void 0?{pageSize:me}:{},rehearse:o("--rehearse"),decisions:q,anonymizationRules:{...d?.anonymization?.rules},anonymizeFields:d?.anonymization?.fields,choicesFrom:s&&i?{flag:s,path:i}:void 0,audit:xd(t),resume:gy(t),writeUncertain:fy(t),...ee?{sample:ee}:{}}}function fy(r){return r.includes("--write-uncertain")?(r.includes("--resume")||(process.stderr.write(`--write-uncertain goes with --resume: it writes the rows of a call under way when the run stopped that the target may already hold.
695
- `),process.exit(2)),!0):!1}function hy(r,e){let t=Ta(r),n=l=>(l??[]).reduce((u,p)=>u+p.rows,0),o=r.uncertain.map(({objectApiName:l,rows:u})=>`${u} ${l}`).join(", "),s=r.underway??[],i=n(r.untold),a=n(r.ofEndedJobs)-i,d=t-n(s)-i-a,c=[`${t} row(s) may already be in ${e} (${o}), sent by insert calls the run had under way when it stopped, their answer never kept.`];for(let l of s){let u=`${l.rows} of them went in Bulk API job ${l.jobId} (${l.objectApiName}), which ${e} holds ${l.state??"not ended"}`+(l.processed!==void 0?`, ${l.processed} row(s) processed`:"");c.push(l.state==="Open"?`${u}: the run stopped before it closed it, and closed, it would still write them.`:`${u}: ${e} writes it to its end whatever became of the run.`)}i>0&&c.push(`${i} of them went in a Bulk API job that wrote records the journal cannot tell apart, several rows under one fingerprint: none of those records is linked to a row, and each is kept as written by the run, for --remove to take back.`),a>0&&c.push(`${a} of them went in a Bulk API job that wrote records whose values are not what the run sent: none is taken for one of them, and each is kept as written by the run.`),d>0&&c.push(`${d} of them went in calls whose records ${e} holds and the resume cannot tell from them, or could not read.`),c.push("Nothing was written.");for(let l of s)c.push(l.state==="Open"?`Run the same --resume again ${l.openUntil!==void 0?`from ${l.openUntil}`+(l.graceLeftMs!==void 0?`, in about ${Math.max(1,Math.ceil(l.graceLeftMs/6e4))} minute(s)`:""):"an hour after the job was opened"}: it aborts job ${l.jobId} if it is open still, then writes its rows.`:`Run the same --resume again once job ${l.jobId} has ended: it reads what the job wrote, row by row.`);return i+a+d>0&&c.push(`Look at the records of those objects the run's user created in ${e} as the run stopped; run the same --resume with --write-uncertain to write those rows all the same (one already there is then there twice), or --remove the run.`),c.join(" ")}function gy(r){let e=r.indexOf("--resume");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--resume takes the journal of the run to take up, or its run id.
696
- `),process.exit(2));let n=["--dry-run","--rehearse","--list-objects"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--resume takes a run up and writes: it does not go with ${n.join(", ")}.
697
- `),process.exit(2)),t}function qt(r=process.env){let e=r.SANDFORGE_JOURNAL_DIR;return e!==void 0&&e.trim()!==""?Et(e):Ss(Dw(),".sandforge")}function Vh(r,e){return r.endsWith(".ndjson")||/[\\/]/.test(r)?Et(r):e.pathOf(r)}function Jh(r,e,t={}){return{...r.sample?{sample:qp(r.sample.options,t.planSha256),...t.sourceOrgId?{sourceOrgId:t.sourceOrgId.slice(0,15)}:{}}:{},source:r.source,targetOrgId:e.slice(0,15),record:r.record,...r.tables?{tables:r.tables}:{},depth:r.depth,customDepth:r.depth==="custom"?r.customDepth:null,maxNodes:r.maxNodes??null,maxRecordsPerObject:r.maxRecordsPerObject??null,anonymize:r.anonymize,keepContactPoints:r.keepContactPoints,upsert:r.upsert,expandOrphans:r.expandOrphans,applyAssignmentRules:r.applyAssignmentRules,fieldExclusions:r.fieldExclusions,excludedObjects:r.excludedObjects,ownerMappings:r.ownerMappings,objectSoqlFilters:r.objectSoqlFilters,fieldMappings:r.fieldMappings,decisions:r.decisions??null,anonymizationRules:r.anonymizationRules,anonymizeFields:r.anonymizeFields??null,files:r.files??null,readCeiling:r.depth==="all"?null:r.readCeiling}}async function my(r,e,t){let n=await r.headAt(e);if(!n)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: there is no journal of a run there.`};if(!n.resume)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the journal does not say how its run was set up, and the run cannot be taken up.`};if((await r.lastEndAt(e))?.status==="success")return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the run ended, and there is nothing of it to take up.`};if(n.targetOrgId.slice(0,15)!==t.targetOrgId.slice(0,15))return{code:"RESUME_TARGET_CHANGED",message:`${t.target} is not the org the run to take up wrote to (${n.targetOrgId}): it is taken up there only. Nothing was written.`};let s=t.setup,i=wy(r,e),a=t.sample?.asked===!0;if(i===void 0&&a)return{code:Tr,message:`--resume ${e}: the run to take up copied every record of the whole org, not a sample: take it up without --fit share and its --fit-* flags. Nothing was written.`};if(i!==void 0&&!a)return{code:Tr,message:`--resume ${e}: the run to take up copied a sample of the whole org: take it up with --fit share and the --fit-* flags it ran with. Nothing was written.`};if(i!==void 0&&t.sample){let d;try{d=await Jn.open(i.dir,{sha256:i.sha256})}catch(c){let l=Go(c,"resume");if(!l)throw c;return{code:l.code,message:l.message.replace(/ Nothing was written\.$/,` It was in ${i.dir}. Nothing was written.`)}}d.manifest.drawnBy==="dryRun"&&(s=t.sample.setupWith(d.sha256))}if(!Up(n.resume.fingerprint,t.graph,s))return{code:"RESUME_CHANGED",message:"The clone is set up otherwise than the run to take up: give the same record or tables, orgs, depth, choices and flags it ran with. Nothing was written."}}function wy(r,e){let t=r.openAt(e);try{return t.samplePlan}finally{t.close()}}function xd(r){let e=r.indexOf("--audit");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--audit takes the file the audit trail is kept in.
698
- `),process.exit(2));try{fa(t)}catch(n){process.stderr.write(`--audit ${t} is not an audit trail the command can add to (${X(n)}): give another file, or move it.
699
- `),process.exit(2)}return t}function yy(r,e){return{configStore:fa(r),orgManager:{getOrg:t=>e.get(t)},log:t=>process.stderr.write(`${t}
700
- `)}}function As(r,e,t){if(r)try{Sc(yy(r,e),t)}catch(n){process.stderr.write(`The run's entry could not be added to the audit trail in ${r} (${X(n)}).
701
- `)}}function by(r){let e=r.indexOf("--summary");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--summary takes the file to write the summary to.
702
- `),process.exit(2));let n=["--list-objects","--rehearse"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--summary does not go with ${n.join(", ")}.
703
- `),process.exit(2)),bn(t)&&(process.stderr.write(`--summary ${t} exists, and is not overwritten: it may be the summary of an earlier run, which --remove takes that run back from. Give another file, or move it.
704
- `),process.exit(2)),t}function Ry(r){let e=r.indexOf("--remap-csv");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--remap-csv takes the .csv file to write the id table to.
705
- `),process.exit(2));let n=Et(process.cwd(),t),o=Et(process.cwd());return n===o||n.startsWith(o+Gw)||(process.stderr.write(`--remap-csv must stay inside cwd: "${t}" resolves outside ${o}
706
- `),process.exit(2)),n.toLowerCase().endsWith(".csv")||(process.stderr.write(`--remap-csv must use a .csv extension: "${t}"
707
- `),process.exit(2)),bn(n)&&(process.stderr.write(`--remap-csv refuses to overwrite existing file: "${n}". Give another file, or move it.
708
- `),process.exit(2)),n}function Oy(r,e){let t=r.includes("--files"),n=r.includes("--files-as-is"),o=r.indexOf("--max-file-size"),s=o>=0?r[o+1]:void 0;if(!t){(n||o>=0)&&(process.stderr.write(`--files-as-is and --max-file-size go with --files.
709
- `),process.exit(2));return}let i=o>=0?Number(s):10;return(!Number.isInteger(i)||i<1||i>35)&&(process.stderr.write(`--max-file-size takes a whole number of MB from 1 to ${35}, the most one call to Salesforce carries.
710
- `),process.exit(2)),Kr(e,n)&&(process.stderr.write(`--anonymize anonymizes the records, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, or leave out --files.
711
- `),process.exit(2)),{maxFileSizeMB:i,acceptedAsIs:n}}function ky(r){let e=Cc(r.fields);return r.fields.map(t=>({name:t.name,type:t.type,queryable:!0,createable:t.createable??!1,isReference:t.type==="reference",referenceTo:(t.referenceTo??[]).filter(n=>typeof n=="string"),nillable:t.nillable??!0,picklistValues:(t.picklistValues??[]).filter(n=>n?.active!==!1&&typeof n?.value=="string").map(n=>n.value),restrictedPicklist:t.restrictedPicklist===!0,...t.controllerName?{controllerName:t.controllerName}:{},defaultedOnCreate:t.defaultedOnCreate===!0,externalId:t.externalId===!0,updateable:t.updateable!==!1,...t.length>0?{length:t.length}:{},...Fc(t,e),...typeof t.groupable=="boolean"?{groupable:t.groupable}:{},...typeof t.sortable=="boolean"?{sortable:t.sortable}:{},...typeof t.aggregatable=="boolean"?{aggregatable:t.aggregatable}:{}}))}function Sy(r){return{name:r.name,fields:r.fields.map(e=>({name:e.name,type:String(e.type),referenceTo:(e.referenceTo??[]).filter(t=>typeof t=="string"),relationshipName:e.relationshipName??null,isMasterDetail:e.cascadeDelete===!0,nillable:e.nillable!==!1,createable:e.createable!==!1,updateable:e.updateable!==!1})),childRelationships:r.childRelationships.map(e=>({childSObject:e.childSObject,field:e.field,relationshipName:e.relationshipName??"",isCascadeDelete:!!e.cascadeDelete}))}}async function Ty(r,e,t){let n="SELECT Id, Name, DeveloperName, NamespacePrefix, SobjectType FROM RecordType WHERE IsActive = true",o=async l=>(await yi({query:async u=>l.query(u),queryMore:async u=>l.queryMore(u)},n)).records,[s,i]=await Promise.all([o(r),o(e)]),a=l=>({id:l.Id,name:l.Name,developerName:l.DeveloperName,namespacePrefix:l.NamespacePrefix?l.NamespacePrefix:null,sobjectType:l.SobjectType}),[d,c]=[s.map(a),i.map(a)];for(let l of Du(d,c))t?.(_u(l));return new Ko().buildMapping(d,c)}function Ay(r){let e=new Map;return(t,n)=>{let o=`${t}::${n}`,s=e.get(o);if(s)return s;let i=r(t,n);return e.set(o,i),i.catch(()=>{e.get(o)===i&&e.delete(o)}),i}}async function gd(r,e,t=!1){let n=t?await r.sobject(e).describe():await r.describe$(e);return{keyPrefix:n.keyPrefix??null,recordTypes:_c(n.recordTypeInfos)}}function BT(r){return co(r)==="failure"}var md={masterInSource:"on Master in the source",notRead:"whose record type the run does not write",decidedDefault:"sent to the default by your decision",dropped:"whose record type the target lacks or keeps from the user"};function Sd({developerName:r,label:e}){return e!==""&&e!==r?`${r} (${e})`:r}function wd(r,e){let{predicted:t}=r;if(!t)return`${e} on Master, which the target gives a record sent without one for the user the run writes as`;let n=Sd(t);return t.basis==="userDefault"?`${e} as ${n}, the default record type of the user the run writes as`:`${e} as ${n}, the only other ${r.objectApiName} record type open to the user the run writes as, whose describe names Master the default`}function jy(r,e){let t=e.read<r.rows?`${e.read} of ${r.rows}`:`${e.read}`,n=r.predicted?.developerName??"Master",[o,...s]=e.types;if(o&&s.length===0&&o.developerName===n)return`went in as ${Sd(o)}, read back on ${t}`;if(!o)return`none of them found as they were read back (asked of ${t})`;let i=e.types.map(a=>`${a.rows} ${Sd(a)}`).join(", ");return`read back on ${t}: ${i}; the describe said ${n}: an automation of the target sets the record type`}function vy(r,e){if(r.length===0)return[];let t=[`record types the target ${e?"would give":"gave"} the records created without one (${r.length} object(s)):`];for(let n of r){let o=Object.keys(md).filter(d=>(n.why[d]??0)>0),s=o.length===1?` ${md[o[0]]}`:o.length>1?` (${o.map(d=>`${n.why[d]} ${md[d]}`).join(", ")})`:"",{readBack:i}=n,a=e?wd(n,"would go in"):i?i.unread!==void 0?`${wd(n,"went in, its describe says,")}; the record types they hold could not be read back: ${i.unread}`:jy(n,i):wd(n,"went in, its describe says,");t.push(` ${n.objectApiName} ${n.rows} record(s)${s}: ${a}`)}return t}function Iy(r,e){let t=Wn(r.maxFileBytes),n=[`files (up to ${t} each):`];r.lookupFailure&&n.push(` ${r.lookupFailure}`," A real run stops here, before writing anything.");for(let o of r.objects){let s=Wn(o.plannedBytes);n.push(e?` ${o.objectApiName} ${o.planned} would be copied (${s}, dry run, nothing written)`:` ${o.objectApiName} ${o.copied} of ${o.planned} copied (${s})`+(o.failed>0?`, ${o.failed} failed`:""))}if(r.objects.length===0&&!r.lookupFailure&&n.push(" none to copy"),e&&r.wouldCopy&&r.wouldCopy.length>0){n.push(` would copy (${r.wouldCopy.length}):`);for(let o of r.wouldCopy)n.push(` ${o.objectApiName} ${o.name} ${Wn(o.bytes)}`)}if(r.links>0&&n.push(` links to other cloned records: ${r.links}`),r.remainingStorageBytes!==void 0&&n.push(` target file storage left: ${Wn(r.remainingStorageBytes)}`),r.leftOut.length>0){n.push(` left out (${r.leftOut.length}):`);for(let o of r.leftOut){let s=o.reason==="too-large"?`larger than ${t}`:o.reason==="external"?"kept outside Salesforce":"its records were not created by this run";n.push(` ${o.objectApiName} ${o.name} ${Wn(o.bytes)} \u2014 ${s}`)}}return n}function mg(r,e){let t=r.truncatedObjects??[];if(t.length!==0)return{...e!==void 0?{perObject:e}:{},objects:[...t]}}function $y(r){let e=new Map;for(let{objectApiName:i,rows:a}of r.writtenByThePlatform??[]){let d=zn(i);e.set(d,(e.get(d)??0)+a)}let t=[...e.values()].reduce((i,a)=>i+a,0),n=r.linkedToCreatedCount??0;if(t===0&&n===0)return`linked: ${r.linkedCount} (already in the target, not created)`;let o=r.linkedCount-t-n,s=[...o>0?[`${o} already in the target, not created`]:[],...n>0?[`${n} to records the run created, the target refusing them as copies of those`]:[],...[...e].map(([i,a])=>`${a} written by the platform with ${i}`)];return`linked: ${r.linkedCount} (${s.join("; ")})`}function Yh(r,e=!1,t,n=!1){let o=[`success: ${r.successCount}`,...r.wouldInsertCount>0?[`would be inserted: ${r.wouldInsertCount} (dry run, nothing written)`]:[],...r.updatedCount>0?[`updated: ${r.updatedCount} (matched by their external id, not created)`]:[],$y(r),`failed: ${r.failedCount}`+(r.failedReads.length>0?` (read failed: ${r.failedReads.join(", ")})`:""),`skipped: ${r.skippedCount}`,`remaps: ${r.remapCount}`,...r.apiCalls!==void 0?[`calls: ${r.apiCalls} (requests the run sent to both orgs)`]:[]];if(r.existingRecords.length>0){o.push("",`already in the target (${r.existingRecords.length} object(s)):`);for(let f of r.existingRecords){let h=f.linkedToCreated??0,g=[...f.linked-h>0||h===0?[`${f.linked-h} linked`]:[],...h>0?[`${h} linked to records the run created (refused as copies of those)`]:[]];f.unidentified>0&&g.push(`${f.unidentified} not identified \u2014 their children lost the link`),o.push(` ${f.objectApiName} ${g.join(", ")}`)}}if(r.cappedObjects){let{perObject:f,objects:h}=r.cappedObjects;o.push("",`stopped at ${f} records per object (${vn("--max","maxRecordsPerObject")}), the source holding more, which were not cloned (${h.length} object(s)):`,...h.map(g=>` ${g}`))}let s=mg(r,t);if(s){let f=s.perObject!==void 0?`${s.perObject} `:"",h=Xn()?"":" (--max-records-per-object)";o.push("",`TRUNCATED at ${f}records per object${h}, the source holding more, which were not cloned (${s.objects.length} object(s)):`,...s.objects.map(g=>` ${g}`))}r.files&&o.push("",...Iy(r.files,e));let i=r.fileContentFieldsLeftOut??[];if(i.length>0){o.push("",`left empty, as they hold a file's content (${i.length} object(s)):`);for(let{objectApiName:f,fields:h}of i)o.push(` ${f} ${h.join(", ")}`)}let a=r.encryptedFieldsLeftOut??[];if(a.length>0){o.push("",`left out, encrypted and read masked: the user the source is read as lacks View Encrypted Data, and the masks are not copied (${a.length} object(s)):`);for(let{objectApiName:f,fields:h}of a)o.push(` ${f} ${h.join(", ")}`)}let d=r.picklistValuesChanged??[];if(d.length>0){let f=new Set(d.map(h=>h.objectApiName)).size;o.push("",`picklist values not written as read (${f} object(s)):`);for(let h of d)o.push(` ${h.objectApiName} ${vl(h)}`)}let c=r.currenciesReplaced??[];if(c.length>0){let f=new Set(c.map(h=>h.objectApiName)).size;o.push("",`written in another currency (${f} object(s)):`);for(let h of c)o.push(` ${h.objectApiName} ${Dc(h)}`)}let l=vy(r.recordTypesGiven??[],e);l.length>0&&(o.push("",...l),e&&n&&o.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"));let u=r.writtenWithoutFields??[];if(u.length>0){o.push("",`written again without a field the target refused (${u.length} object(s)):`);for(let{objectApiName:f,fields:h}of u)for(let{field:g,refusedBy:m="validation-rule",reason:y,rows:b}of h)o.push(` ${f}.${g} ${b} record(s) \u2014 ${Uw[m]} \u2014 ${y}`)}r.contactPoints&&o.push("",...Fy(r.contactPoints,e));let p=r.mayHaveBeenWritten??[];if(p.length>0){o.push("",`may be in the target, under ids the run never learned (${vn("--remove","destroy")} cannot reach them):`);for(let{objectApiName:f,sourceIds:h}of p)o.push(` ${f} ${h.length} record(s)`)}if(r.decisionsApplied&&r.decisionsApplied.length>0&&o.push("",...Cy(r.decisionsApplied)),r.gaps&&o.push("",...Py(r.gaps)),r.errors.length>0){o.push("",`errors (${r.errors.length} object(s)):`);for(let f of r.errors){o.push(` [${f.stage}] ${f.objectApiName} ${f.failedCount}/${f.attemptedCount}`);for(let h of f.samples){o.push(` ${h.recordSummary}`);for(let g of h.messages)o.push(` \u2514 ${g}`)}}}return o}function Ey(r){let e=r.detail??{},t=[];typeof e.longest=="number"&&typeof e.length=="number"&&t.push(`longest ${e.longest} of ${e.length} characters`),typeof e.precision=="number"&&t.push(`precision ${e.precision}, scale ${String(e.scale??0)}`),typeof e.replacement=="string"&&t.push(`written as "${e.replacement}"`);let n=e.amountsConverted;Array.isArray(n)&&n.length>0&&t.push(`amounts converted into it: ${n.join(", ")}`),e.amountsAsRead===!0&&t.push("amounts written as read, no rate converts them"),typeof e.colliding=="number"&&t.push(`${e.colliding} value(s) already in the target`),e.linkedToTheRecordItNames===!0&&t.push("a real run links each row to the record the target holds");let o=e.mapTo;return Array.isArray(o)&&o.length>0&&t.push(`may map to ${o.join(", ")}`),e.ignored===!0&&t.push("ignored"),t.length>0?` (${t.join("; ")})`:""}function Py(r){return r.length===0?["gaps: none found (dry run: nothing the target would refuse or change)"]:[`gaps the target holds against the rows (${r.length}, dry run):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.value!==void 0?` "${e.value}"`:"",o=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` [${e.severity}] ${t} ${e.kind}${n}${o}: ${e.rows} record(s)${Ey(e)}`})]}function xy(r){if(!r.choicesFrom)return[];let e=[Xn()?"choices from the resource in the file:":`choices from ${r.choicesFrom.flag} ${r.choicesFrom.path}, the flags over it:`],t=Object.entries(r.fieldExclusions).flatMap(([a,d])=>d.map(c=>`${a}.${c}`));t.length>0&&e.push(` fields left out: ${t.join(", ")}`),r.excludedObjects.length>0&&e.push(` objects left out: ${r.excludedObjects.join(", ")}`);for(let[a,d]of Object.entries(r.objectSoqlFilters))e.push(` filter ${a}: ${d}`);let n=Object.keys(r.ownerMappings).length;n>0&&e.push(` owners mapped: ${n}`);for(let[a,d]of Object.entries(r.fieldMappings))for(let[c,l]of Object.entries(d))e.push(` renamed: ${a}.${c} \u2192 ${l}`);let o=r.decisions,s=a=>a!==void 0?` (record type ${a})`:"",i=[...(o?.picklistValueMappings??[]).map(a=>` ${a.object}.${a.field} ${a.to===null?"leave_empty":"map_value"} "${a.from}"${a.to!==null?` \u2192 "${a.to}"`:""}${s(a.recordType)}`),...(o?.recordTypeMappings??[]).map(a=>` ${a.object} map_record_type "${a.from}" \u2192 ${a.to===null?"the default":`"${a.to}"`}`),...(o?.defaultValues??[]).map(a=>` ${a.object}.${a.field} set_default "${String(a.value)}"`),...(o?.truncateFields??[]).map(a=>` ${a.object}.${a.field} truncate`),...(o?.skippedRows??[]).map(a=>{let d=Ud(a.gapId),c=Il(a);return` ${a.object}.${d?.field??"?"} skip_rows "${d?.value??""}"${s(d?.recordType)}`+(c!==void 0?`: ignored, ${c}`:"")}),...(o?.ignoredGaps??[]).map(a=>` ignore ${a}`)];return i.length>0&&e.push(` decisions (${i.length}):`,...i),e}function Cy(r){return[`decisions applied (${r.length}):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.from!==void 0?` "${e.from}"`:"",o=e.to!==void 0?` \u2192 "${e.to}"`:"",s=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` ${t} ${e.kind}${n}${o}${s}: ${e.rows} record(s)`})]}function Fy(r,e){if(!r.neutralized)return[`contact points: written as read (${vn("--keep-contact-points","keepContactPoints")}): the target's flows and email alerts may reach the people the records name`];let t=e?"would be neutralized (dry run, nothing written)":"neutralized";return[`contact points: ${r.values} value(s) in ${r.fields.length} field(s) ${t} \u2014 emails under .invalid, phone numbers in a fictional range`,...r.fields.map(({objectApiName:n,field:o,values:s})=>` ${n}.${o} ${s}`),...r.numbersExhausted?[` ${r.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]}function Ny(r){return r.flatMap(({objectApiName:e,fields:t})=>t.flatMap(n=>{if(n.externalId!==!0||n.createable===!1)return[];let o=Ao(n.name,String(n.type).toLowerCase());return o?[{objectApiName:e,field:n.name,kind:o}]:[]}))}function My(r,e){return r.length===0?[]:[`upsert keys: --upsert matches the records of ${e} by these external ids, which the run writes neutralized (emails under .invalid, phone numbers in a fictional range): a record of ${e} holding the real address or number is not matched, and the run creates another beside it; one an earlier run wrote neutralized is. --keep-contact-points matches the real ones`,...r.map(({objectApiName:t,field:n,kind:o})=>` ${t}.${n} (${o})`)]}function By(r,e,t,n){if(!r)return{};let o=rc(Hd(e.gaps,t??[]).filter(s=>!Vr(s,n)));return o.length>0?{adminChanges:o}:{}}function Ly(r,e){let t=mg(r,e);return{successCount:r.successCount,updatedCount:r.updatedCount,linkedCount:r.linkedCount,...r.linkedToCreatedCount?{linkedToCreatedCount:r.linkedToCreatedCount}:{},...r.writtenByThePlatform?{writtenByThePlatform:r.writtenByThePlatform}:{},wouldInsertCount:r.wouldInsertCount,failedCount:r.failedCount,skippedCount:r.skippedCount,remapCount:r.remapCount,existingRecords:r.existingRecords,errors:r.errors.map(n=>({objectApiName:n.objectApiName,stage:n.stage,failedCount:n.failedCount,attemptedCount:n.attemptedCount,samples:n.samples,...n.referenceData===!0?{referenceData:!0}:{},...n.skipped===!0?{skipped:!0}:{}})),remapTable:r.remapTable,existingSourceIds:r.existingSourceIds,updatedSourceIds:r.updatedSourceIds,createdByObject:r.createdByObject,...r.withTheirRecordSourceIds?{withTheirRecordSourceIds:r.withTheirRecordSourceIds}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},readByObject:r.readByObject,failedReads:r.failedReads,...r.cappedObjects?{cappedObjects:r.cappedObjects}:{},...t?{truncatedObjects:t}:{},...r.files?{files:r.files}:{},...r.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:r.fileContentFieldsLeftOut}:{},...r.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:r.encryptedFieldsLeftOut}:{},...r.picklistValuesChanged?{picklistValuesChanged:r.picklistValuesChanged}:{},...r.currenciesReplaced?{currenciesReplaced:r.currenciesReplaced}:{},...r.recordTypesGiven?{recordTypesGiven:r.recordTypesGiven}:{},...r.writtenWithoutFields?{writtenWithoutFields:r.writtenWithoutFields}:{},...r.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:r.lookupsLeftEmptyByFilter}:{},...r.contactPoints?{contactPoints:r.contactPoints}:{},...r.apiCalls!==void 0?{apiCalls:r.apiCalls}:{},...r.gaps?{gaps:r.gaps}:{},...r.decisionsApplied?{decisionsApplied:r.decisionsApplied}:{},...r.mayHaveBeenWritten?{mayHaveBeenWritten:r.mayHaveBeenWritten}:{},...r.remapInJournal?{remapInJournal:!0}:{},...r.sample?{sample:ob(r.sample)}:{}}}function Wy(r){if(r.status==="running"&&r.message.startsWith("[dry-run] "))return` ${r.message}`;if(r.status==="scanning")return r.progress>0&&r.message?` ${r.message}`:void 0;if(!(r.status!=="done"&&r.status!=="error"&&r.status!=="skipped"&&r.status!=="stopped"))return r.message?` ${r.message}`:void 0}function Dy(r){let e=new Set(r.nodes.filter(Js).map(n=>n.objectApiName)),t=!1;return n=>{if(n.status==="skipped"&&e.size>1&&e.has(n.objectName)){if(t)return;t=!0;let o=ft("--list-objects")?"; --list-objects names them":"";return` Skipped ${e.size} objects (excluded: empty tables${o})`}return Wy(n)}}function _y(r,e,t){let n=new Set(r.nodes.map(u=>u.objectApiName)),o=r.nodes.filter(u=>u.included).length,s=r.edges.filter(u=>n.has(u.sourceObject)&&n.has(u.targetObject)).length,i=r.nodes.length-r.nodes.filter(Nu).length,a=i>0?` (${i} empty, taking no place under it)`:"",d=r.nodes.length-i>t?" (raised for the parents their records cannot be written without)":"",{notCounted:c}=bg(r),l=c>0?`, ${c} not counted`:"";return`graph: ${r.nodes.length} objects at a cap of ${t}${a}${d}, ${o} included${l}; ${r.edges.length} lookups, ${s} between these objects; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`+(r.truncated?" (TRUNCATED)":"")}var wg={missingInTarget:"missing in the target",notQueryable:"not queryable",empty:"empty",unreadable:"unreadable",notWritable:"not writable in the target",createOnly:"creatable but not editable or deletable in the target",setup:"setup",platformCreated:"written by the platform alone",metadata:"metadata",chatter:"Chatter",history:"history",sharing:"sharing",changeEvent:"change events",unsupportedKind:"of a kind no clone writes",customSetting:"custom settings",files:"files, copied with --files",excludedByUser:"left out by --exclude-object",notDescribed:"not described"};function zy(r,e,t){let n=r.nodes.filter(a=>a.included).length,{objects:o,counts:s}=zo(r),i=s.map(({reason:a,count:d})=>`${d} ${wg[a]}`).join(", ");return`graph: the whole of ${t}, ${n} object(s) to copy, ${o.length} left out${i?` (${i})`:""}; ${r.edges.length} lookups; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`}var Gy={listing:()=>"discovery: listing the objects of both orgs\u2026",counting:r=>`discovery: counting the records of ${r??"each"} object(s)\u2026`,describing:r=>`discovery: describing the ${r??""} object(s) that hold records\u2026`};async function qy(r,e,t){let n;try{return await r.discover(e,{onProgress:o=>{if(o.phase===n)return;n=o.phase;let s=Gy[o.phase];s&&t(s(o.total))}})}catch(o){process.stderr.write(`The whole org could not be discovered: ${X(o)}
712
- `),process.exit(1)}}function yd(r,e,t){let{estimate:n,remaining:o,max:s}=e;return o===void 0||s===void 0?` ${r} of ${t}: about ${n}; what it has left today could not be read`+(e.unread?` (${e.unread})`:""):` ${r} of ${t}: about ${n}, of the ${o} it has left of its ${s} a day`+(e.near?": it would leave less than a tenth of them":"")}var Qh=10;function Lr(r){let e=r.length-Qh;return e>0?`${r.slice(0,Qh).join(", ")} and ${e} more`:r.join(", ")}function Uy(r,e,t,n=[]){let{source:o,bulk:s}=r,i=n.filter(({jobs:m})=>m>0),a=i.length>0?` (${Lr(i.map(m=>`${m.objectApiName}: ${m.jobs} of ${m.jobRows}`))}; rows of a job carrying the same values go by REST instead)`:"",d=[` writes: ${s?.jobs??0} Bulk API job(s) of ${s?.jobRows??0} record(s) at most${a}, ${s?.restRows??0} record(s) by REST, ${r.restObjects.length} object(s) by REST alone; about ${Math.max(1,Math.round(r.durationSeconds/60))} minute(s) one after another`,yd("API requests",r.targetApi,t),...s?.batches?[yd("Bulk API batches",s.batches,t)]:[],yd("API requests",r.sourceApi,o),...r.discovery?[` of them, sent already by discovery: ${r.discovery.target} of ${t}'s and ${r.discovery.source} of ${o}'s`]:[]],c=r.fileStorage;c&&d.push(` files: ${c.files} file(s), about ${Xt(c.estimateMB)} MB of file storage, of the ${c.remainingMB} MB ${t} has left of ${c.maxMB} MB`+(c.overCeiling>0?`; ${c.overCeiling} past the largest file copied, left out`:""));let l=e.map(({reason:m,count:y})=>`${y} ${wg[m]}`).join(", ");d.push(` left out of ${o}: ${r.leftOut} object(s)${l?`: ${l}`:""}`);let{carried:u}=r,p=u?[["read through a filter",u.filters],["left out by name",u.excluded],["with rows held back by a decision",u.heldBack],["copied without some of their fields",u.fieldsLeftOut]]:[];for(let[m,y]of p)y.length>0&&d.push(` ${m}: ${Lr(y)}`);let f=r.personalAsIs??[],h=f.reduce((m,{fields:y})=>m+y.length,0);d.push(h>0?` personal data: ${h} field(s) of ${f.length} object(s) copied as ${o} holds them: `+Lr(f.map(({objectApiName:m,fields:y})=>`${m} (${y.join(", ")})`)):" personal data: no personal field copied as it is");let g=r.managedPackages??[];return g.length>0&&d.push(` managed packages: ${g.length} object(s) written, whose triggers and flows no mute reaches: ${Lr(g)}`),r.contactPointsBlanked!==void 0&&d.push(` phone numbers: up to ${r.contactPointsBlanked} past the fictional range go in empty`),d}function Hy(r,e,t){return`discovery: ${r.source} API request(s) sent to ${e} and ${r.target} to ${t}, before any row is read`}function ws(r,e,t){let n=(o,s)=>{if(!o)return{sent:s};let{parts:i,...a}=o;return{...a,...i?{parts:i}:{},sent:s}};return{target:n(e.target,r.target),source:n(e.source,r.source),...t?{discovery:t}:{}}}function Ky(r,e,t,n){let{source:o,bulk:s}=r,i=e.objects.filter(({rows:f})=>f>0).length,a=r.managedPackages??[],d=r.personalAsIs??[],c=d.reduce((f,{fields:h})=>f+h.length,0),l=r.sample;return[(l&&n?`a sample of ${o}: ${e.totalRows} record(s) of ${i} object(s) (of ${l.sourceRows} in ${o}) into ${t}, about ${Xt(l.storageMB)} MB`+(Cd(n.budget)?` of the ${Xt(l.budgetMB)} MB it may take`:"")+(l.automationMB!==void 0?`, ${Xt(l.automationMB)} MB of it for what the target's automation creates`:"")+`; ${Fd(l)}, ${Ps(l.share)} % of the roots; drawn at ${l.drawnAt} by ${l.drawnBy==="dryRun"?"a dry run":"this run"}; ${s?.jobs??0} Bulk API job(s) among them`:void 0)??`${e.totalRows} record(s) of ${i} object(s) of ${o} into ${t}, ${s?.jobs??0} Bulk API job(s) among them`,`about ${r.targetApi.estimate} of ${t}'s API requests`+(s?.batches?` and ${s.batches.estimate} of its Bulk API batches`:"")+` and ${r.sourceApi.estimate} of ${o}'s`,...a.length>0?[`${a.length} object(s) of managed packages, whose triggers and flows no mute reaches (${Lr(a)})`]:[],...r.contactPointsBlanked!==void 0?[`up to ${r.contactPointsBlanked} phone number(s) written empty`]:[],c>0?`${c} personal field(s) of ${d.length} object(s) copied as they are`:"no personal field copied as it is"].join("; ")}function Xh(r){return r.replaceAll("turn the copy of files off on Review","leave out --files").replaceAll("leave the object out on Review","leave it out with --exclude-object").replaceAll("the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting","--max-records-per-object lets a run hold at once: raise it")}function Vy(r,e){return`The clone of the whole org would write ${r} records, more than the ${e} --max-total holds it to: give --max-total the count its dry run says, or leave objects out (--exclude-object) or narrow them (--filter).`}function Jy(r,e){if(r.verdict==="exceeds")return`The records to write take ${Ru(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB: copy a sample of the org that fits it (--fit share, its dry run first), leave objects out (--exclude-object) or narrow them (--filter), or free data storage in ${e}.`}var Yy=2*1024;function Qy(r){let{storage:e,sample:t,target:n}=r,{withinMB:o}=t.options,s=t.options.maxTotal??Hn,i=Su({storage:e,bounds:{...o!==void 0?{withinMB:o}:{},...t.maxTotalGiven?{maxTotal:s}:{}},target:n});if(i)throw bt.of(i);let a=r.automation?{automation:r.automation}:{},d=Ia({storage:e,...o!==void 0?{withinMB:o}:{},...a});if(d)return{...d,budget:{...d.budget,maxTotal:s}};let c=Ia({storage:{maxMB:0,remainingMB:0},...a});return{budget:{bytes:Number.MAX_SAFE_INTEGER,maxTotal:s,limitedBy:"maxTotal"},bytesLimit:"within",roomBytes:s*Yy,...c?.automationBytes?{automationBytes:c.automationBytes}:{}}}function Cd(r){return r.remainingMB!==void 0||r.withinMB!==void 0}function Ps(r){return String(Number((r*100).toPrecision(2)))}function Fd(r){return r.draw==="recent"?"the newest by creation date":`seed ${r.seed}, spread over the org`}function Xy(r,e,t){let{budget:n}=r;switch(n.limitedBy){case"heavyRoots":return`every root fits but ${r.heavyRoots.length} heavy root(s) set aside below, each past a tenth of the room ${t} has: they alone keep the sample from every root`;case"storage":return`limited by the data storage ${t} has left`;case"within":return`limited by --fit-within ${n.withinMB??""}`.trimEnd();case"maxTotal":return`limited by --max-total ${n.maxTotal??Hn}`;case"targetRequests":return`limited by the daily API requests ${t} has left`;case"bulkBatches":return`limited by the daily Bulk API batches ${t} has left`;case"sourceRequests":return`limited by the daily API requests ${e} has left`;case"whole":return"every record of the org fits: leave out --fit share to copy the whole org"}}function Zy(r){let e=`${r.details} records (${r.details}.${r.field})`;return r.asParents!==void 0?`the ${r.asParents} brought in as parents keep only the ${e} drawn on their own: if they total them (an amount, a roll-up summary), the total counts only those`:`keeps ${r.kept??0} of its ${r.sourceRows??0} ${e} in the sample: if it totals them (an amount, a roll-up summary), the total counts only those`}function eb(r,e){let{budget:t}=r,n=`about ${Xt(r.storageBytes/1048576)} MB`;if(!Cd(t))return`${n}, held to ${t.maxTotal??Hn} records (--max-total): ${e} would not say its data storage`;let o=`${n} of the ${Xt(t.bytes/1048576)} MB the sample may take`;if(t.remainingMB===void 0)return`${o} (--fit-within ${t.withinMB}; ${e} would not say its data storage)`;let s=[`${Ps(t.share??0)} % of the ${t.remainingMB} MB ${e} has left`+(t.maxMB!==void 0?` of ${t.maxMB} MB`:""),...t.roundingMB!==void 0?[`${t.roundingMB} MB off for rounding`]:[],...t.automationMB!==void 0&&t.automationMB>0?[`${Xt(t.automationMB)} MB for what its automation creates`]:[],...t.withinMB!==void 0?[`--fit-within ${t.withinMB}`]:[]];return`${o} (${s.join(", ")})`}var yg={referenceData:"reference data, matched by name",catalog:"the price catalog",smallParent:"a small parent",asked:"--fit-whole"};function tb(r,e,t){switch(r){case"noParentInSource":return`a lookup they may not leave empty names a record ${e} does not hold`;case"outsideFilter":return"a lookup they may not leave empty names a record outside its object's filter";case"excludedObject":return"a lookup they may not leave empty names a record of an object left out";case"withoutParent":return"a record they cannot be written without is left out itself";case"heldBack":return"their record type is closed to the user the run writes as";case"recordTypeNotInTarget":return`their record type is one ${t} has none of`}}function nb(r,e){if(r.whole){let t=e.find(n=>n.objectApiName===r.objectApiName)?.why;return`copied whole${t?` (${yg[t]})`:""}`}return`${r.roots} drawn, ${r.below} under a parent, ${r.asParents} as parents`}function rb(r,e){let{source:t,target:n}=e,o=r.objects.reduce((d,c)=>d+c.sourceRows,0)+r.noRecordDrawn.reduce((d,c)=>d+c.sourceRows,0),s=[`sample: ${r.rows} of ${o} record(s) of ${t}, of ${r.objects.length} object(s): ${Ps(r.share)} % of the roots of each object (${Fd(r)}), with the records they reach and name; ${eb(r,n)}; ${Xy(r,t,n)}`];for(let d of r.objects){let c=(d.childrenCut??[]).map(({field:u,rows:p})=>`${u} ${p}`),l=(r.partialMasters??[]).filter(u=>u.objectApiName===d.objectApiName);s.push(` ${d.objectApiName}: ${d.kept} of ${d.sourceRows} (${nb(d,r.whole)})`+(c.length>0?`; left by the cap of ${r.children} children a record, by the lookup naming their parent: ${c.join(", ")}`:"")+l.map(u=>`; ${Zy(u)}`).join(""))}if(r.whole.length>0&&s.push(`whole: ${r.whole.map(({objectApiName:d,why:c})=>`${d} (${yg[c]})`).join(", ")}`),r.newestByIds&&r.newestByIds.length>0&&s.push(`newest by the order of their ids, the org sorting none of their creation dates \u2014 ids follow it within a load only: ${r.newestByIds.join(", ")}`),r.heavyRoots.length>0){s.push(`heavy roots set aside, each bringing in more than a tenth of the room ${n} has:`);for(let{objectApiName:d,id:c,rows:l,relation:u}of r.heavyRoots)s.push(` ${d} ${c}: ${l} record(s) through ${u.objectApiName}.${u.field}`)}if(r.dropped.length>0){s.push("not in the sample, never sent:");for(let{objectApiName:d,rows:c,reason:l}of r.dropped)s.push(` ${d}: ${c}, ${tb(l,t,n)}`)}if(r.leftEmpty.length>0){s.push("left empty, their record outside the sample:");for(let{objectApiName:d,field:c,rows:l}of r.leftEmpty)s.push(` ${d}.${c}: ${l} record(s)`)}if(r.noRecordDrawn.length>0){s.push(`no record drawn, ${t} holding some:`);for(let{objectApiName:d,sourceRows:c}of r.noRecordDrawn)s.push(` ${d}: ${c} in ${t}`)}let{plan:i}=r,a=i.drawnBy==="run"?"by this run":e.dryRun?e.replayed===!0?"by a dry run, said again by this one (--fit-plan)":"by this dry run":"by a dry run, written by this run (--fit-plan)";return s.push(`sample plan: ${i.path} (sha256 ${i.sha256}, drawn ${i.drawnAt} ${a})`,` drawing it sent ${r.planRequests.source} request(s) to ${t}`+(e.dryRun&&i.drawnBy==="dryRun"?`; --fit-plan ${i.path} writes these records, within a day`:"")),s}function Zh(r){let{budget:e,plan:t}=r;return{seed:r.seed,draw:r.draw,share:r.share,floor:r.floor,parents:r.parents,children:r.children,budget:{bytes:Cd(e)?e.bytes:null,...e.remainingMB!==void 0?{remainingMB:e.remainingMB}:{},...e.maxMB!==void 0?{maxMB:e.maxMB}:{},...e.share!==void 0?{share:e.share}:{},...e.roundingMB!==void 0?{roundingMB:e.roundingMB}:{},...e.automationMB!==void 0?{automationMB:e.automationMB}:{},...e.withinMB!==void 0?{withinMB:e.withinMB}:{},...e.maxTotal!==void 0?{maxTotal:e.maxTotal}:{},limitedBy:e.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(n=>({objectApiName:n.objectApiName,sourceRows:n.sourceRows,kept:n.kept,roots:n.roots,below:n.below,asParents:n.asParents,...n.whole?{whole:!0}:{},...n.childrenCut&&n.childrenCut.length>0?{childrenCut:n.childrenCut.map(({field:o,rows:s})=>({field:o,rows:s}))}:{}})),whole:r.whole.map(({objectApiName:n,why:o})=>({objectApiName:n,why:o})),heavyRoots:r.heavyRoots.map(({objectApiName:n,id:o,rows:s,relation:i})=>({objectApiName:n,id:o,rows:s,relation:{objectApiName:i.objectApiName,field:i.field}})),dropped:r.dropped.map(({objectApiName:n,rows:o,reason:s})=>({objectApiName:n,rows:o,reason:s})),leftEmpty:r.leftEmpty.map(({objectApiName:n,field:o,rows:s})=>({objectApiName:n,field:o,rows:s})),noRecordDrawn:r.noRecordDrawn.map(({objectApiName:n,sourceRows:o})=>({objectApiName:n,sourceRows:o})),partialMasters:(r.partialMasters??[]).map(n=>({...n})),...r.newestByIds&&r.newestByIds.length>0?{newestByIds:[...r.newestByIds]}:{},planRequests:{source:r.planRequests.source},plan:{path:t.path,sha256:t.sha256,drawnAt:t.drawnAt,drawnBy:t.drawnBy,...t.drawnAgain?{drawnAgain:t.drawnAgain}:{}}}}function ob(r){return{seed:r.seed,draw:r.draw,share:r.share,sha256:r.sha256,drawnAt:r.drawnAt,objects:r.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:!0}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...r.leftEmpty&&r.leftEmpty.length>0?{leftEmpty:r.leftEmpty.map(({objectApiName:e,field:t,rows:n})=>({objectApiName:e,field:t,rows:n}))}:{}}}function sb(r,e){let t=[`sample (${Fd(r)}, ${Ps(r.share)} % of the roots of each object; plan sha256 ${r.sha256}, drawn ${r.drawnAt}):`];for(let n of r.objects){let o=n.whole?"copied whole":`${n.roots} drawn, ${n.below} under a parent, ${n.asParents} as parents`;t.push(` ${n.objectApiName}: ${n.written} written of ${n.kept} in the sample (${o}) of ${n.sourceRows} in ${e}`+(n.goneSinceTheSample>0?`; ${n.goneSinceTheSample} gone from ${e} since the sample, not written`:"")+(n.changedSinceTheSample>0?`; ${n.changedSinceTheSample} changed since the sample: a record they cannot be written without is no longer the one the plan named, held back (failed)`:""))}for(let{objectApiName:n,field:o,rows:s}of r.leftEmpty??[])t.push(` left empty, their record outside the sample: ${n}.${o} ${s}`);return t}function ib(r,e,t){let n=e.draw??dn.draw,o=e.maxTotal??Hn,s=0;for(let i of r.nodes){if(!i.included||i.recordCount<=0)continue;let a=n==="uniform"?i.recordCount:Math.min(i.recordCount,o),d=Math.ceil(a/ab);s+=1+d+(n==="uniform"?0:Math.max(0,d-1))}return`sample: drawing it reads at most about ${s} request(s) of ${t} for the roots, by discovery's counts (${n==="uniform"?"every root's id, spread over the org":"the newest by creation date, those it may keep"}); the records they reach and name are read on top, and said once drawn`}var ab=2e3,db={counting:"counting the roots of each object",drawing:"reading the ids of the roots",closing:"closing the sample over the records they reach and name",fitting:"cutting it to what the target may take",saving:"keeping its plan"};function cb(r){let e;return t=>{t.step!==e&&(e=t.step,r(`sampling: ${db[t.step]}\u2026 (${t.requests} request(s) so far)`))}}function eg(r){return r===Hi||r===Tr?2:1}function bg(r){let e=0,t=0,n=0,o=0;for(let s of r.nodes)s.included?e++:Js(s)?t++:s.status==="error"||s.errors.length>0?n++:o++;return{included:e,emptyTables:t,notCounted:n,leftOut:o}}function ys(r,e){return{nodes:r.nodes.length,...bg(r),edges:r.edges.length,waves:e.waves.length,cycles:e.cycleResolutions.length,truncated:r.truncated??!1}}function lb(r){return[...r.nodes].sort((e,t)=>e.objectApiName.localeCompare(t.objectApiName)).map(e=>({objectApiName:e.objectApiName,recordCount:e.recordCount,depth:e.level,included:e.included}))}function tg(r,e,t,n){return{rootRecordId:r.record,rootObjectApiName:e.nodes[0]?.objectApiName??"",dryRun:r.dryRun,recordTypeMappings:t,maxRecordsPerObject:r.maxRecordsPerObject,referenceFallback:"nullify",upsertMode:r.upsert?"auto":void 0,expandOrphanParents:r.expandOrphans,fieldExclusions:Object.keys(r.fieldExclusions).length>0?r.fieldExclusions:void 0,excludedObjects:r.excludedObjects.length>0?r.excludedObjects:void 0,ownerMappings:Object.keys(r.ownerMappings).length>0?r.ownerMappings:void 0,objectSoqlFilters:Object.keys(r.objectSoqlFilters).length>0?r.objectSoqlFilters:void 0,fieldMappings:Object.keys(r.fieldMappings).length>0?r.fieldMappings:void 0,anonymization:ns(r.anonymize,e,r.anonymizationRules,n),keepContactPoints:r.keepContactPoints,decisions:r.decisions,files:r.files?{maxFileBytes:r.files.maxFileSizeMB*1048576,acceptedAsIs:r.files.acceptedAsIs}:void 0,stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}}}function ub(r,e){return e?{...r,stream:{...r.stream,store:e,summaryBound:zp}}:r}function pb(r,e){if(!e)return r;let t=new Map(e.map(n=>[n.objectApiName,n.fieldNames]));return{...r,nodes:r.nodes.map(n=>{let o=t.get(n.objectApiName);if(!o)return n;let s=new Set(n.piiFields);return{...n,anonymizeFields:o.filter(i=>s.has(i))}})}}function xs(r){return new ou({query:async(e,t)=>jn({query:async n=>r.query(n),queryMore:async n=>r.queryMore(n)},t),toolingQuery:async(e,t)=>jn({query:async n=>r.tooling.query(n),queryMore:async n=>r.tooling.queryMore(n)},t),toolingQueries:async(e,t)=>ru(await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(nu(`/services/data/v${r.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length),toolingRetrieves:(e,t)=>_i(r)(t)})}function fb(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return new eu({query:async(o,s)=>jn({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s),toolingQuery:async(o,s)=>jn({query:async i=>n(o).tooling.query(i),queryMore:async i=>n(o).tooling.queryMore(i)},s),describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`),a=await e(o,s);return{sent:i,createable:a.createable!==!1,fields:a.fields.map(Wi)}},readDuplicateRules:async(o,s)=>{let i=await n(o).metadata.read("DuplicateRule",s);return Array.isArray(i)?i:[i]},readLimits:async o=>n(o).request({method:"GET",url:"/limits"}),toolingQueries:async(o,s)=>Zl(n(o))(s),toolingRetrieves:(o,s)=>_i(n(o))(s)})}async function on(r){let t=(await r.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof t?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(t.IsSandbox===!0)return{id:t.Id,sandbox:!0};try{let o=(await r.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof o=="string"&&o!==""?{id:t.Id,sandbox:!1,edition:o}:{id:t.Id,sandbox:!1}}catch{return{id:t.Id,sandbox:!1}}}function Dr(r,e,t){if(e.sandbox||Xd(e.edition))return;let n=t==="clone"?"sandforge clone writes to sandboxes and Developer Edition orgs only. Nothing was written; --dry-run, which only reads, runs against it.":"sandforge clone removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.",o=e.edition?`IsSandbox false, edition ${e.edition}`:"IsSandbox false, and no edition";return`${r} is a production org (its Organization record says ${o}): ${n}`}var hb={parent_refused:"a record it names was refused",beyond_a_call:"the records it needs are more, or deeper, than one call holds",call_budget:"the calls ran out before its turn"};function gb(r,e){let t=r.updates.reduce((n,o)=>n+o.updates,0);return[`rehearsal: ${r.sampled} of the ${r.rows} record(s) the run would create, created in ${e} and rolled back with each call`,...t>0?[` and ${t} update(s) the run makes after its inserts, each in the call that creates its record: ${r.updates.map(n=>`${n.objectApiName} ${n.updates}`).join(", ")}`]:[],` ${r.calls} composite call(s), ${r.maxCalls} at most if a call stops at a refused record`,...r.objects.map(({objectApiName:n,rows:o})=>` ${n.padEnd(40)} ${o}`)]}function mb(r,e,t={}){let n=r.updatesJudged>0?`; ${r.updatesJudged} update(s) judged, ${r.updatesPassed} would save, ${r.updatesJudged-r.updatesPassed} refused`:"",o=r.linked??0,s=o>0?`${o} linked to a record the target holds, `:"",i=[`rehearsed in ${e}: ${r.judged} judged, ${r.passed} would save, ${s}${r.judged-r.passed-o} refused, ${r.notJudged} not judged${n} (${r.calls} call(s), every write rolled back)`];for(let a of r.gaps){let d=typeof a.detail?.statusCode=="string"?a.detail.statusCode:a.value,c=a.field?`.${a.field}`:"",l=a.kind==="picklist_value_refused"&&a.value?` "${a.value}"`:"",u=a.recordType?` (record type ${a.recordType})`:"",p=a.detail?.rowsOfTheRun,f=typeof p=="number"&&p>a.rows?`, ${p} in the run`:"";if(a.kind==="rehearsal_update_refusal"){i.push(` refused on update ${a.objectApiName}${c}: ${d}, ${a.rows} update(s)${f} (the record goes in without what the update gives it)`);continue}let h=Vr(a,t.lifted);if(h){i.push(` refused ${a.objectApiName}${c}: ${d}, ${a.rows} row(s)${f}, validation rule "${String(a.detail?.rule)}": the mute lifts it (${h.permission}, in ${h.permissionSet}), which the rehearsal ran without; a real run under it writes the row whole`);continue}i.push(` ${a.severity==="blocking"?"REFUSED":"refused"} ${a.objectApiName}${c}${l}${u}: ${d}, ${a.rows} row(s)${f}`+(a.detail?.writtenWithoutTheField===!0?" (a real run writes it again without the field)":"")+(a.detail?.linkedToTheRecordItNames===!0?" (a real run links it to the record the target holds)":""))}for(let{objectApiName:a,rows:d,reason:c}of r.notJudgedWhy)i.push(` not judged ${a}: ${d} row(s), ${hb[c]}`);return r.updatesNotRehearsed>0&&i.push(` not rehearsed: ${r.updatesNotRehearsed} of the ${r.updates} update(s) the run makes after its inserts`),i}function wb(r,e){return{...r,gaps:r.gaps.map(t=>{let n=Vr(t,e);return n?{...t,detail:{...t.detail,liftedByPermission:n.permission,liftedByPermissionSet:n.permissionSet}}:t})}}var yb=new Set(["--remove","--target","--preview","--include-changed","--json","--accept-automation","--leave-undeletable","--sweep","--sweep-list","--sweep-late","--sweep-untied","--audit","--mute-automation"]),bb=new Set(["--remove","--target","--audit"]);function Rb(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write($d),process.exit(0));let t=d=>{let c=e.indexOf(d),l=c>=0?e[c+1]:void 0;return l!==void 0&&!l.startsWith("--")?l:void 0},n=d=>e.includes(d);for(let d=0;d<e.length;d++){let c=e[d];if(bb.has(c)){e[d+1]!==void 0&&!e[d+1].startsWith("--")&&d++;continue}c==="--dry-run"&&(process.stderr.write(`--remove does not take --dry-run: a removal that did not read it would delete for real. --preview says what the removal would do, and writes nothing. Run with --help for usage.
713
- `),process.exit(2)),yb.has(c)||(process.stderr.write(`--remove takes --target, --preview, --include-changed, --accept-automation, --mute-automation, --leave-undeletable, --sweep, --sweep-late, --sweep-untied, --sweep-list, --json and --audit, not "${c}". Run with --help for usage.
714
- `),process.exit(2))}let o=t("--remove"),s=t("--target");(!o||!s)&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, and --target the org the run wrote to. Run with --help for usage.
715
- `),process.exit(2)),n("--sweep")&&n("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help for usage.
716
- `),process.exit(2));let i=["--sweep-list",...n("--sweep")?[]:Ig,"--audit"].filter(d=>n(d));n("--preview")&&i.length>0&&(process.stderr.write(`--preview writes nothing: give it without ${i.join(", ")}. Run with --help for usage.
717
- `),process.exit(2));let a=_b(e);return"refusal"in a&&(process.stderr.write(`${a.refusal} Run with --help for usage.
718
- `),process.exit(2)),{summaryPath:o,target:s,includeChanged:n("--include-changed"),json:n("--json"),acceptAutomation:n("--accept-automation"),muteAutomation:n("--mute-automation"),leaveUndeletable:n("--leave-undeletable"),sweep:n("--sweep"),sweepList:n("--sweep-list"),...a,audit:xd(e),...n("--preview")?{preview:!0}:{}}}var nt=W.string().regex(Ts,"not a Salesforce id"),bs=W.iso.datetime(),ng=W.object({objectApiName:W.string().regex(rt,"not an API name"),kind:W.enum(["flow","trigger","process","workflowRule"]),name:W.string().max(255)}),Ob=W.object({silenced:W.array(ng.extend({permission:W.string().max(255)})),stillRan:W.array(ng.extend({why:W.enum(["noBypass","managedPackage","notRead","noPermissionSet"])}))});function LT(...r){for(let e of r)if(typeof e=="string"&&Ts.test(e))return e}var Rg=W.object({tool:W.literal("sandforge-clone"),version:W.literal(1),source:W.string(),target:W.string().min(1),targetOrgId:nt.optional(),record:W.string().optional(),objects:W.array(W.object({objectApiName:W.string().regex(rt,"not an API name"),where:W.string().max(512).optional()})).max(2e3).optional(),wholeOrg:W.literal(!0).optional(),dryRun:W.literal(!1),elapsedMs:W.number().transform(r=>Math.max(0,r)),finishedAt:bs.optional(),journal:W.string().min(1).max(4096).optional(),part:W.number().int().nonnegative().optional(),result:W.object({remapInJournal:W.literal(!0).optional(),remapTable:W.record(nt,nt),existingSourceIds:W.array(nt),updatedSourceIds:W.array(nt),createdByObject:W.array(W.object({objectApiName:W.string().regex(rt,"not an API name"),sourceIds:W.array(nt)})),withTheirRecordSourceIds:W.array(nt).optional(),unattributed:W.array(W.object({objectApiName:W.string().regex(rt,"not an API name"),ids:W.array(nt)})).optional(),writtenBetween:W.object({first:bs,last:bs}).optional(),mayHaveBeenWritten:W.array(W.object({objectApiName:W.string().regex(rt,"not an API name"),sourceIds:W.array(nt)})).optional(),runUserId:nt.optional()}),mutedAutomation:Ob.optional().catch(void 0)});async function Td(r,e,t,n=Dt(qt())){let o=e.indexOf(`
719
- `),s=o>=0?e.slice(0,o):e;if(/^\{"run":/.test(s))return kb(r,t,n);let i=Sb(e);if("refusal"in i)return i;let{journal:a,part:d}=i.summary,c=a!==void 0&&d!==void 0?await n.readAt(a,d):void 0;return c?{summary:{...i.summary,result:{...i.summary.result,remapTable:c.remap.table,existingSourceIds:c.remap.linked,updatedSourceIds:[],createdByObject:c.remap.createdByObject,...c.remap.withTheirRecord?{withTheirRecordSourceIds:c.remap.withTheirRecord}:{},...c.unattributed?{unattributed:c.unattributed}:{}}}}:i.summary.result.remapInJournal?a===void 0||d===void 0?{refusal:"keeps the ids of its records in a journal it does not name."}:{refusal:`keeps the ids of its records in ${a}, which cannot be read.`}:i}async function kb(r,e,t){let n=await t.readAt(r,"all");if(!n)return{refusal:"is not the journal of a run."};let s=(await t.lastEndAt(r))?.at??pg(r).mtime.toISOString(),i=Date.parse(s)-Date.parse(n.startedAt),a=n.resume?.startedWith,d=n.resume?.recordId??a?.config.recordId,c=!d&&a?.config.inputMode==="org",l=!d&&a&&(a.config.inputMode==="soql"||c)?a.graph.nodes.filter(p=>p.included).map(({objectApiName:p})=>{let f=a.config.objectSoqlFilters?.[p];return f!==void 0?{objectApiName:p,where:f}:{objectApiName:p}}):void 0,u=Rg.safeParse({tool:"sandforge-clone",version:1,source:n.resume?.sourceOrgId??"",target:e,targetOrgId:n.targetOrgId,record:d??(l?void 0:""),...l?{objects:l}:{},...c?{wholeOrg:!0}:{},dryRun:!1,elapsedMs:Number.isFinite(i)&&i>0?i:0,finishedAt:s,journal:r,result:{remapTable:n.remap.table,existingSourceIds:n.remap.linked,updatedSourceIds:[],createdByObject:n.remap.createdByObject,...n.remap.withTheirRecord?{withTheirRecordSourceIds:n.remap.withTheirRecord}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.unattributed?{unattributed:n.unattributed}:{}}});return u.success?{summary:u.data}:{refusal:`is a journal the command cannot take a run back from: ${u.error.issues.slice(0,5).map(f=>`${f.path.map(String).join(".")||"the journal"}: ${f.message}`).join("; ")}.`}}function Sb(r){let e;try{e=JSON.parse(r)}catch(a){return{refusal:`is not JSON (${a instanceof Error?a.message:String(a)}).`}}let n=W.object({tool:W.literal("sandforge-clone"),dryRun:W.boolean()}).safeParse(e);if(!n.success)return{refusal:"is not a summary sandforge clone printed with --json."};if(n.data.dryRun)return{refusal:"is the summary of a dry run, which wrote nothing to the target: there is nothing of it to remove."};let o=ei(e,"sandforge-clone");if(o)return{refusal:ti(o)};if(!W.object({result:W.object({createdByObject:W.array(W.unknown())})}).safeParse(e).success)return{refusal:"does not say which records the run created (createdByObject): it was printed before the summary said so, and the records the run created cannot be told from those the target already held. sandforge cleanup remains for such a run."};let i=Rg.safeParse(e);return i.success?{summary:i.data}:{refusal:`is not a summary a removal can read: ${i.error.issues.slice(0,5).map(d=>`${d.path.map(String).join(".")||"the summary"}: ${d.message}`).join("; ")}.`}}function Nd(r){let{result:e}=r,t=ec({idRemapTable:e.remapTable,idRemapExisting:[...e.existingSourceIds,...e.updatedSourceIds],idRemapCreated:e.createdByObject});return Gp(t,e.unattributed)}function Og(r){return`${tc({idRemapTable:r.result.remapTable,idRemapExisting:r.result.existingSourceIds,idRemapCreated:r.result.createdByObject,idRemapWithTheirRecord:r.result.withTheirRecordSourceIds}).length+r.result.updatedSourceIds.length} record(s) the target already held, which the run linked to or wrote over, stay`}function Tb(r,e,t){let n=e.reduce((s,i)=>s+i.ids.length,0),o=r.result.writtenBetween?.last??r.finishedAt;return[`the clone of ${ty(r)} wrote to ${t.target}${o?` until ${o}`:""}; a removal deletes the ${n} record(s) it created, children first:`,...e.map(s=>` ${s.objectApiName}: ${s.ids.length}`),...jb(e),Og(r),t.includeChanged?"records changed since the run go too, and what was added to them since":`records changed since the run stay, as do those records added since depend on (${gn("--include-changed","removal")} takes them)`]}function Ab(r){return r.flatMap(({part:e,plan:t})=>[`then the ${$n(t).length} record(s) of the run's part ${e.part} (its summary's "part") an earlier --remove of that part left, once these are gone:`,...t.map(n=>` ${n.objectApiName}: ${n.ids.length}`)])}function jb(r){let e=new Set(r.filter(n=>n.ids.length>0).map(n=>n.objectApiName)),t=e.has("QuoteLineItem")||e.has("OpportunityLineItem");return!e.has("Quote")||!t?[]:[" and the lines the platform copied between a quote the run synced and its opportunity, read as the removal begins and counted apart (--preview counts them)"]}function kg(r){let e=r.platformCopies??0;if(e<=0)return"";let t=r.planned-e;return r.objectApiName===ko?` (${t>0?`${t} the run wrote, and `:""}${e} the target's duplicate rules made of the run's records)`:` (${t} the run wrote, and ${e} the platform copied between the quote the run synced and its opportunity)`}function vb(r,e="run"){let t=r.tookAlong,n=r.cameAlong;return[...t&&t.count>0?[` took along ${t.count} record(s) that were not the ${e}'s, added or changed since it: ${t.objects.join(", ")}`]:[],...n&&n.count>0?[` took along ${n.count} record(s) the ${e} did not write that came with its records, made as it wrote: ${n.objects.join(", ")}`]:[]]}function Ib(r){return[r.deleted>0?`${r.deleted} deleted`:"",r.alreadyGone>0?`${r.alreadyGone} already gone`:"",(r.notVisible??0)>0?`${r.notVisible} not visible to this user (neither found nor in the recycle bin)`:"",r.keptChanged>0?`${r.keptChanged} kept, changed since the run`:"",r.keptDependents>0?`${r.keptDependents} kept for records that stay`+(r.heldBy.length>0?` (${r.heldBy.join(", ")})`:""):"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean).join(", ")}function $b(r){let e=r.count>r.names.length?", \u2026":"";return`${r.count} file(s) attached to them stay in the org, as the run did not create them: ${r.names.join(", ")}${e}`}function Eb(r,e,t=0){let n=[...new Set(e.flatMap(o=>o.unchecked))];return[`removal: ${r.toUpperCase()}`,...e.flatMap(o=>[` ${o.objectApiName}: ${Ib(o)||"nothing"} of ${o.planned}${kg(o)}`,...vb(o),...o.reasons.map(s=>` ${s}`),...o.filesLeft&&o.filesLeft.count>0?[` ${$b(o.filesLeft)}`]:[]]),...n.length>0?[`not checked, deleted with their parent: ${n.join(", ")}`]:[],...t>0?[`not reachable: ${t} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned`]:[]]}function Sg(r){let e=r.automationGaps;return e?[...e.error?[` the target's automation could not all be read (${e.error}): what it creates may be missed`]:[],...e.flowsNotRead>0?[` ${e.flowsNotRead} flow(s) on the run's objects not read: what they create is not looked at`]:[],...e.triggers>0?[` ${e.triggers} Apex trigger(s) on the run's objects: what they create no metadata says`]:[]]:[]}function Tg(r){return[...r.unread.map(e=>` not looked at: ${e.objectApiName}: ${e.reason}`),...r.handWork.map(e=>` created by the run's user in the window, where neither the run nor its automation writes: ${e.objectApiName}: ${e.count} (left)`)]}var rg=10;function Pb(r,e,t=!1){return ft("--max-total")?`The run would write ${r} records, more than --max-total ${e}: narrow the clone (--max, --exclude-object, --filter), or raise --max-total.`:Qn()?.startsWith("sandforge env")===!0?t?`The run would write ${r} records, more than the ${e} the resource's maxTotal holds it to: narrow the resource in the file, or raise its maxTotal.`:`The run would write ${r} records, more than the ${e} its plan counted: the source holds more records than when it was planned. Plan again.`:`The run would write ${r} records, more than the ${e} ${gn("--max-total")} holds it to: narrow the clone with this script's own --max, --exclude-object or --filter, or raise its --max-total.`}function sn(r){return ft(r)?r:`this script's own removal with ${r==="--sweep-list"||r==="--sweep"?"":"--sweep "}${r}`}function Ad(r){let e=Qn();return e===void 0?`${r} takes them`:`${e} keeps them; ${sn(r)} takes them`}function js(r){let e=r.length-rg;return`${r.slice(0,rg).join(", ")}${e>0?` and ${e} more`:""}`}function Cn(r){return r.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}function xb(r,e){let t=r.changed??0;return[r.made>0?`${r.made} made for the run`+((r.sameSave??0)>0?` (${r.sameSave} in the same save)`:""):"",r.madeOver>0?`${r.madeOver} under records the run wrote over`:"",r.late>0?`${r.late} late`:"",r.untied>0?`${r.untied} tied to nothing of the run`:"",t>0?`${t} of them changed since the run${e.includeChanged===!0?"":", kept"}`:""].filter(Boolean).join(", ")}function Wr(r,e,t){return r[e]-(t.includeChanged===!0?0:r.changedIn?.[e]??0)}function Cb(r,e){let t=e.sweepUntied===!0&&r.untied?.refusal===void 0;return r.found.reduce((n,o)=>{let s=o.classes;return s?n+Wr(s,"made",e)+Wr(s,"madeOver",e)+(e.sweepLate===!0?Wr(s,"late",e):0)+(t?Wr(s,"untied",e):0):n},0)}function og(r,e,t,n){return t.flatMap(o=>{let s=r.found.find(a=>a.objectApiName===o.objectApiName)?.classes,i=s?Math.min(o.count,Wr(s,e,n)):o.count;return i>0?[{objectApiName:o.objectApiName,count:i}]:[]})}function Fb(r,e,t){let n=[],o=r.late??[];if(o.length>0&&e.sweepLate!==!0)n.push(`kept, made late \u2014 tied to the run but created more than a minute after the record it hangs from, or by the org's Automated Process user: ${Cn(o)} (${Ad("--sweep-late")})`);else if(t&&e.sweepLate===!0){let i=og(r,"late",o,e);n.push("with --sweep-late, it would delete too what was made late: "+(i.length>0?Cn(i):o.length>0?"none":"none found"))}let s=r.untied;if(s&&s.objects.length>0){if(s.refusal!==void 0)n.push(`kept, tied to nothing of the run: ${Cn(s.objects)} \u2014 --sweep-untied is refused: ${s.refusal}`);else if(e.sweepUntied!==!0)n.push(`kept, created as the run's user in its window but tied to nothing of it: ${Cn(s.objects)} (${Ad("--sweep-untied")})`);else if(t){let i=og(r,"untied",s.objects,e);n.push("with --sweep-untied, it would delete too what is tied to nothing of the run: "+(i.length>0?Cn(i):"none"))}}else t&&e.sweepUntied===!0&&n.push(s?.refusal!==void 0?`with --sweep-untied, it would delete nothing tied to nothing of the run: --sweep-untied is refused: ${s.refusal}`:"with --sweep-untied, it would delete too what is tied to nothing of the run: none found");if(r.notLooked&&r.notLooked.length>0&&n.push(`not looked at, past the ${$a} objects a sweep counts: `+js(r.notLooked)),r.muted){let{silenced:i,stillRan:a}=r.muted;n.push(`the run's mute kept ${i.length} automation(s) quiet; `+(a.length>0?`what still ran may have made what is listed: ${js(a.map(d=>`${d.name} (${d.objectApiName})`))}`:"nothing of what the run fired still ran"))}return t&&n.push(...Nb(r,e)),n}function Nb(r,e){let t=s=>r.found.some(i=>!i.overBound&&(i.classes?.[s]??0)>0),n=t("made")||t("madeOver"),o=[n?Ag:"",e.sweepLate===!0&&t("late")?`under ${n?"them":"the run's records"} within a quarter of an hour with --sweep-late`:"",e.sweepUntied===!0&&r.untied?.refusal===void 0&&t("untied")?"anywhere in the run's window with --sweep-untied":""].filter(Boolean);return o.length===0?[]:[`${jg(`${o.join(", or ")}${o.length>1?",":""}`)}: check the names before a --sweep`]}var Ag="under the run's records within a minute of them";function jg(r){return`a record made by hand as the run's user ${r} reads as the automation's, and one changed by hand before the run's last write as unchanged`}function Rs(r,e,t,n=t===void 0){let o=Cb(r,t??{}),s=r.found.reduce((a,d)=>a+d.count,0),i=r.found.some(a=>a.overBound)?" or more":"";return[r.window?`a sweep looks in ${e} for what the run's user created from ${r.window.from} to ${r.window.to} that the run's id map does not hold, in: ${js(r.looked)}`:`a sweep of ${e} cannot tell the window the run wrote in`,...r.found.length>0?[`it found ${s}${i} record(s) and would delete `+(o>0?`${o} of them, children first`:"none of them")+"; per object, all it found:",...r.found.map(a=>` ${a.objectApiName}: ${a.count}`+(a.overBound?" or more (over the bound: none would be deleted)":"")+(a.classes?` \u2014 ${xb(a.classes,t??{})}`:"")+(a.names.length>0?` (${a.names.join(", ")}${a.count>a.names.length?", \u2026":""})`:""))]:r.window?["it finds nothing to delete"]:[],...Fb(r,t??{},n),...Sg(r),...Tg(r),...r.refusal?[`sweep refused: ${r.refusal}`]:[]]}function Mb(r,e){let t=r?.listing;return e===void 0&&t?.refusal===void 0?t:void 0}function bd(r,e){let t=r.reduce((g,m)=>g+(m.heldByAutomation??0),0);if(t===0)return[];let n=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAfterRun??0),0)),o=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAlong??0),0)),s=Bb(t,o),i=[...new Set(r.flatMap(g=>g.automationHolders??[]))],a=i.length>0?` (${js(i)})`:"",d=`likely by the target's automation${a}`,c=`delete them by hand, then remove the run again; ${gn("--preview","removal")} says what of it their delete leaves changed since, which ${gn("--include-changed","removal")} takes`;if(e.part===void 0&&e.sweep!==!0&&e.windowUntold===!0)return[`${t} record(s) of the run kept for records created under them as its user, within a minute of them, ${d}: a sweep cannot take them, as it cannot tell the window the run wrote in now \u2014 ${c}`];let l=e.part!==void 0?"that part's last write":e.inParts===!0?"the last write of the run's part that wrote them":"the run's last write",u=n===0?"during the run, as its user":n===t?`as its user after ${l}, within a minute of them`:`as its user during the run or, under ${n} of them, after ${l}, within a minute of them`,p=e.part===void 0?"of the run":`of the run's part ${e.part} (its summary's "part")`,f=`${t} record(s) ${p} kept for records created under them ${u}, `+(n===0?d:`by the target's automation or by hand${a}`),h=jg(Ag);if(e.part!==void 0){let g=m=>`${Qn()===void 0?"--remove":"this script's own removal"} of part ${e.part}'s summary with ${m}`;return[`${f}: `+(e.sweep===!0?"this removal's sweep looked in its own part's window alone, and did not see them; ":"a sweep of this summary looks in its own part's window alone, and leaves them; ")+`${g("--sweep")} ${s} (${g("--sweep-list")} shows them; ${h}: check the names before it), or ${c}`]}return[e.sweep===!0?`${f}: the sweep left them \u2014 ${sn("--sweep-list")} says why; ${sn("--sweep-late")} takes those it lists as late, ${gn("--include-changed","removal")} those changed after the run's last write`:`${f}: ${sn("--sweep")} ${s} (${sn("--sweep-list")} shows them); ${h}: check the names before `+(ft("--sweep")?"a --sweep":sn("--sweep"))]}function Bb(r,e){let t="the removal deletes those, and the org takes them along";return e<=0?"takes them first":e>=r?`takes them with the run's records they hang from: ${t}`:`takes them first, but for those under ${e} of the run's records, which go with them: ${t}`}var vg={late:"made late",untied:"tied to nothing of the run"};function Lb(r){return r.map(({class:e,objects:t,option:n,refusal:o})=>{let s=` left, ${vg[e]}: ${Cn(t)}`;return o!==void 0?`${s} \u2014 ${n} is refused: ${o}`:`${s} (${Ad(n)})`})}function Wb(r){return[`sweep: ${r.status.toUpperCase()}`,...r.objects.flatMap(e=>{let t=e.afterRemoval??0,n=Math.min(e.afterRemovalUnder??0,t),o=e.withRemoval??0,s=[t-n>0?`${t-n} once the records of the run that point at them were gone`:"",n>0?`${n} once the removal was through: the org had not taken them along with the records of the run they hung from`:""].filter(Boolean),i=[e.deleted>0?`${e.deleted} deleted`+(s.length>0?` (${s.join("; ")})`:""):"",e.alreadyGone>0?`${e.alreadyGone} already gone`+(o>0?` (${o} with the records of the run they hung from, as the removal deleted those: the org took them along)`:""):"",e.keptChanged>0?`${e.keptChanged} kept, changed since the run`:"",(e.keptDependents??0)>0?`${e.keptDependents} kept for records that stay`+((e.heldBy??[]).length>0?` (${(e.heldBy??[]).join(", ")})`:""):"",e.refused>0?`${e.refused} refused`:""].filter(Boolean).join(", ");return[` ${e.objectApiName}: ${i||"nothing"} of ${e.found}`,...e.reasons.map(a=>` ${a}`)]}),...Lb(r.left??[]),...(r.goneAlong??[]).map(({class:e,objects:t})=>` ${vg[e]}, no longer in the org once the records of the run were gone: ${Cn(t)}`),...Sg(r),...Tg(r),...r.refusal?[` ${r.refusal}`]:[]]}function Db(r){return Cs(r).flatMap(e=>[...$n(e.created),...e.linked])}function Cs(r){let e=r?.part;return e===void 0?[]:(r?.parts??[]).filter(t=>t.part!==e)}function Os(r,e){let t=new Set(r?.earlier?.partsRemoved??[]);return Cs(r).flatMap(n=>{let o=(e?.otherParts??[]).filter(({part:i})=>i===n.part).flatMap(({objects:i})=>i).reduce((i,a)=>i+a.count,0),s=$n(Zt(n.created,r?.earlier?.removalLeft)).length+o;return s===0?[]:[`a sweep of this summary leaves the ${s} record(s) of the run's part ${n.part} (its summary's "part"), the run's own, never the target's automation's: `+(t.has(n.part)?"an earlier --remove of that part left them, which the removal of this summary takes up once its own records are gone":"--remove of that part's summary takes them")]})}async function jd(r,e,t,n,o,{signal:s,ofTheRun:i}={}){let a;try{a=await xs(r).read(e,n.map(l=>l.objectApiName))}catch(l){a={error:X(l)}}let d=t.result.runUserId,c=Cs(i).map(({part:l,created:u})=>({part:l,created:u}));return{writtenBetween:t.result.writtenBetween,created:n,remap:new Set([...Object.values(t.result.remapTable),...Db(i)].map(l=>l.slice(0,15))),...c.length>0?{otherParts:c}:{},automation:sf(a),...d?{runUserId:d}:{},ties:o,...s?{signal:s}:{}}}var Ig=["--sweep-late","--sweep-untied"];function _b(r){let e=Ig.filter(t=>r.includes(t));return e.length>0&&!r.includes("--sweep")&&!r.includes("--sweep-list")?{refusal:`${e.join(" and ")} ${e.length===1?"takes":"take"} more of what --sweep lists: give ${e.length===1?"it":"them"} with --sweep, or with --sweep-list to see what ${e.length===1?"it":"they"} would take.`}:{...r.includes("--sweep-late")?{sweepLate:!0}:{},...r.includes("--sweep-untied")?{sweepUntied:!0}:{}}}function zb(r){return{...r.sweepLate?{sweepLate:!0}:{},...r.sweepUntied?{sweepUntied:!0}:{}}}function Gb(r){return r?{sweep:e=>r.first(e),automationMade:r.automationMade,afterRemoval:e=>r.afterRemoval(e)}:{}}function vd(r,e,t){let n=Gn(r,e),o=Object.create(n);return o.counts=af(au(iu(r),t)),o}function WT(r){let e=Date.parse(r.firstWrittenAt??r.startedAt),t=Date.parse(r.end?.at??r.lastWriteAt??r.lastWrittenAt??"");return Number.isFinite(e)&&Number.isFinite(t)?{from:e,to:Math.max(e,t)}:void 0}function Rd(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}async function qb(r){let e=r.journalDir??qt(),t=new Set(r.own.ids.map(c=>c.slice(0,15))),n=(c,l)=>!r.span||!Number.isFinite(c)||!Number.isFinite(l)||c<=r.span.to+of&&l>=r.span.from-rf,o=[],s=c=>{c.length===0||c.some(l=>t.has(l.slice(0,15)))||o.push({ids:[...c]})},i=Ss(e,"forge-runs"),a=[];try{a=Ww(i).filter(c=>c.endsWith(".ndjson"))}catch{}let d=Dt(e);for(let c of a){let l=Ss(i,c);if(!(r.own.journal!==void 0&&Et(r.own.journal)===Et(l)))try{let u=await d.headAt(l);if(!u||!Rd(u.targetOrgId,r.organizationId))continue;let p=await d.lastEndAt(l),f=Date.parse(p?.at??"")||pg(l).mtimeMs;if(!n(Date.parse(u.startedAt),f))continue;let h=await d.readAt(l,"all");s(h?.created.flatMap(g=>g.ids)??[])}catch{}}for(let c of r.own.otherParts??[])n(c.from,c.to)&&s(c.ids);for(let c of[vi(e),vi(e,ff)]){let l=[];try{l=await c.list()}catch{continue}for(let u of l){if(r.own.runId!==void 0&&u.runId===r.own.runId||!(Rd(u.targetOrganizationId,r.organizationId)||u.targetOrganizationId===void 0&&(Rd(u.targetOrgId,r.organizationId)||r.alias!==void 0&&u.targetOrgId===r.alias)))continue;let f=Date.parse(u.firstWrittenAt??u.startedAt),h=u.end?Date.parse(u.end.at):Date.parse(u.lastWriteAt??u.lastWrittenAt??"")||Date.now();n(f,h)&&s([...u.created,...u.overwritten??[]].flatMap(g=>g.ids))}}return o}function Ub(r){let e=r.removalSpans?.map(t=>t.first).filter(t=>Number.isFinite(Date.parse(t))).sort((t,n)=>Date.parse(t)-Date.parse(n))[0];return{otherRuns:r.otherRuns,...r.muted?{muted:{silenced:r.muted.silenced,stillRan:r.muted.stillRan}}:{},...e!==void 0?{removalBegan:e}:{},...r.made&&r.made.length>0?{madeEarlier:r.made}:{},...r.late&&r.late.length>0?{lateEarlier:r.late}:{}}}async function $g(r,e,t,n,o,s){let i=Date.parse(t.finishedAt??""),a=Cs(s).map(d=>({ids:$n(d.created),from:Date.parse(d.startedAt??""),to:Date.parse(d.endedAt??"")}));return Ub({otherRuns:await qb({organizationId:r,alias:e,span:Number.isFinite(i)?{from:i-t.elapsedMs,to:i}:void 0,own:{...t.journal!==void 0?{journal:t.journal}:{},ids:n.flatMap(d=>d.ids),...a.length>0?{otherParts:a}:{}}}),...t.mutedAutomation?{muted:t.mutedAutomation}:{},...o?{removalSpans:o.removalSpans}:{},...o?.made?{made:o.made}:{},...o?.late?{late:o.late}:{}})}var sg=3;function Fs(r){return/\.json$/i.test(r)?r.replace(/\.json$/i,".removals.json"):`${r}.removals.json`}function Ns(r){let e=r.flatMap(t=>t.ids.map(n=>n.slice(0,15))).sort();return Lw("sha256").update(e.join(",")).digest("hex")}var Od=W.string().refine(r=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/.test(r)&&Number.isFinite(Date.parse(r)),"not a date"),Hb=W.object({tool:W.literal("sandforge-clone"),version:W.literal(1),run:W.string(),removalStamps:W.record(nt,Od),removalSpans:W.array(W.object({first:Od,last:Od,userId:nt})),removalLeft:W.array(nt).optional(),sweep:W.object({sweptAt:bs,deleted:W.number().int().nonnegative(),keptChanged:W.number().int().nonnegative(),refused:W.number().int().nonnegative()}).optional(),made:W.array(nt).max(1e4*100).optional(),late:W.array(nt).max(1e4*100).optional(),partsRemoved:W.array(W.number().int().nonnegative()).max(1e4).optional()});function Ms(r,e){if(r===void 0)return{};let t;try{t=JSON.parse(r)}catch{}let n=W.object({tool:W.literal("sandforge-clone"),run:W.string()}).safeParse(t);if(!n.success)return{refusal:"is not the record of removals sandforge clone keeps there, and is not overwritten: move it, as the removal keeps there what it leaves on the records of the run."};if(n.data.run!==e)return{otherRun:!0};let o=Hb.safeParse(t);if(!o.success)return{refusal:`is not a record of removals a removal can read: ${o.error.issues.slice(0,5).map(f=>`${f.path.map(String).join(".")||"the file"}: ${f.message}`).join("; ")}.`};let{removalStamps:s,removalSpans:i,removalLeft:a,sweep:d,made:c,late:l,partsRemoved:u}=o.data;return{earlier:{removalStamps:s,removalSpans:i,...a?{removalLeft:a}:{},...d?{sweep:d}:{},...c?{made:c}:{},...l?{late:l}:{},...u?{partsRemoved:u}:{}}}}function Kb(r,e,t,n=[],o,s=[],i=[],a=[]){let d=new Set(t.gone??[]),c=[...a],l=Ti(e?.made,s,c),u=Ti(e?.late,i,c),p=l.join()!==(e?.made??[]).join()||u.join()!==(e?.late??[]).join();if(Object.keys(t.stamps).length===0&&!t.span&&d.size===0&&!o&&!p)return;let f=o??e?.sweep,h=d.size>0?n.flatMap(({ids:g})=>g.filter(m=>!d.has(m))):e?.removalLeft;return{tool:"sandforge-clone",version:1,run:r,removalStamps:{...e?.removalStamps,...t.stamps},removalSpans:[...e?.removalSpans??[],...t.span?[t.span]:[]],...h?{removalLeft:h}:{},...f?{sweep:f}:{},...l.length>0?{made:l}:{},...u.length>0?{late:u}:{},...e?.partsRemoved?{partsRemoved:e.partsRemoved}:{}}}async function Eg(r,e=Dt(qt())){let t=r.journal;if(t===void 0||!bn(t))return;let n=await Sf(t,e),o=n.length>1?await e.readAt(t,"all"):void 0;if(!o)return;let s=Fs(t),i;try{i=yn(s,"utf8")}catch(c){if(c?.code!=="ENOENT")return{refusal:`${s} cannot be read: ${c instanceof Error?c.message:String(c)}`}}let a=Ns(o.created),d=Ms(i,a);return"refusal"in d?{refusal:`${s} ${d.refusal}`}:{parts:n,...r.part!==void 0?{part:r.part}:{},file:s,key:a,created:o.created,...d.earlier?{earlier:d.earlier}:{}}}function Pg(r){let e=new Set(r.earlier?.partsRemoved??[]);return r.parts.flatMap(t=>{if(t.part===r.part||!e.has(t.part))return[];let n=Zt(t.created,r.earlier?.removalLeft);return n.length>0?[{part:t,plan:n}]:[]})}function xg(r,e){if(!(r.parts.length<2))return[...r.parts].sort((t,n)=>n.part-t.part).flatMap(t=>{let n=Zt(e,$n(t.created));return n.length>0?[{part:t,plan:n}]:[]})}function Vb(r,e){let t=[...new Set(e.flatMap(s=>s.keptDependents>0?s.heldBy:[]))],n=new Set(r.earlier?.partsRemoved??[]),o=s=>Zt(s.created,r.earlier?.removalLeft).map(i=>i.objectApiName);return r.parts.flatMap(s=>{if(s.part===r.part||n.has(s.part))return[];let i=new Set(So(o(s),r.parts.flatMap(d=>d.part===s.part?[]:o(d)))),a=t.filter(d=>i.has(d));return a.length>0?[{part:s.part,objects:a}]:[]})}function ig(r){return r.map(({part:e,objects:t})=>`of what this removal kept for records that stay, what the run's part ${e} (its summary's "part") holds \u2014 its ${t.join(", ")} records \u2014 goes with --remove of that part's summary, once that part's own records are gone, without --include-changed`)}function Cg(r,e,t){return r.parts.flatMap(n=>{if(n.part===e)return[];let o=Zt(n.created,r.earlier?.removalLeft),s=In(n);if(o.length===0||!s)return[];let i=Zn(r.parts,n.part);return[{part:n.part,alongside:{plan:o,span:s,...Object.keys(t).length>0?{removalStamps:t}:{},...i.length>0?{laterParts:i}:{}}}]})}function Fg(r){return r?.part===void 0?[]:[...new Set(r.parts.flatMap(e=>e.part===r.part?[]:Zt(e.created,r.earlier?.removalLeft).map(t=>t.objectApiName)))]}function Jb(r,e){let t=r.earlier,n=[...new Set([...t?.partsRemoved??[],...e.parts])].sort((i,a)=>i-a);if(Object.keys(e.stamps).length===0&&e.spans.length===0&&e.gone.length===0&&n.length===(t?.partsRemoved?.length??0))return;let o=new Set(e.gone.map(i=>i.slice(0,15))),s=(t?.removalLeft??$n(r.created)).filter(i=>!o.has(i.slice(0,15)));return{tool:"sandforge-clone",version:1,run:r.key,removalStamps:{...t?.removalStamps,...e.stamps},removalSpans:br(t?.removalSpans,e.spans),removalLeft:s,...t?.sweep?{sweep:t.sweep}:{},...t?.made?{made:t.made}:{},...t?.late?{late:t.late}:{},partsRemoved:n}}function Yb(r){let e={};for(let o of r)for(let s of[...o.otherPartStamps??[],o.stamps])Object.assign(e,s);let n=r.flatMap(o=>o.span?[o.span]:[]).reduce((o,s)=>o?{...o,first:Date.parse(s.first)<Date.parse(o.first)?s.first:o.first,last:Date.parse(s.last)>Date.parse(o.last)?s.last:o.last}:s,void 0);return{stamps:e,...n?{span:n}:{},gone:r.flatMap(o=>o.gone)}}function Ng(r,e){return e?{...r,removalStamps:{...r?.removalStamps,...e.removalStamps},removalSpans:br(r?.removalSpans,e.removalSpans)}:r}function Id(r,e){let t=`${r}.${process.pid}.tmp`;try{fg(t,JSON.stringify(e,null,2)+`
720
- `,"utf8"),ug(t,r);return}catch(n){try{kd(t,{force:!0})}catch{}return n instanceof Error?n.message:String(n)}}async function Qb(r=process.argv){let e=Date.now(),t=Rb(r),n=D=>t.json?console.error(D):console.log(D),o;try{o=yn(t.summaryPath,"utf8")}catch(D){process.stderr.write(`--remove ${t.summaryPath} cannot be read: ${D instanceof Error?D.message:String(D)}
721
- `),process.exit(2)}let s=await Td(t.summaryPath,o,t.target);if("refusal"in s&&(process.stderr.write(`--remove ${t.summaryPath} ${s.refusal}
722
- `),process.exit(2)),t.preview)return tR(t,s.summary,n,e);let i,a=async()=>{if(!i){let D=await Sn(t.target),J=cn(D);i={session:D,conn:J,org:await on(J)}}return i},d=s.summary.journal;if(d!==void 0&&bn(d)&&Dt(qt()).callsInFlightAt(d)>0){let{conn:D,org:J}=await a();s.summary.targetOrgId!==void 0&&!Is(s.summary.targetOrgId,J.id)&&Ut(Pt(s.summary.targetOrgId));let re=await Dt(qt()).reconcileAt(d,ka(D));for(let ie of Sa(re,t.target,"removal"))n(ie);let we=(re.underway??[]).reduce((ie,{rows:_e})=>ie+_e,0),Q=_p(re)-we;Q>0&&n(` the journal names none of the ${Q} row(s) that may be in ${t.target}: they stay, and ${sn("--sweep-list")} shows what the run's user created in the run's window`),s=await Td(t.summaryPath,yn(t.summaryPath,"utf8"),t.target),"refusal"in s&&(process.stderr.write(`--remove ${t.summaryPath} ${s.refusal}
723
- `),process.exit(2))}let{summary:c}=s;c.targetOrgId===void 0&&c.target!==t.target&&(process.stderr.write(`The run wrote to ${c.target}, and its records are removed from that org only: give --target ${c.target}.
724
- `),process.exit(2));let l=(c.result.mayHaveBeenWritten??[]).reduce((D,{sourceIds:J})=>D+J.length,0),u=0,p,f,h,g=[],m=!1,y=!1,b,S=D=>{let J={sweep:t.sweep,windowUntold:m,inParts:y};return b?[...bd(b.own,J),...b.others.flatMap(({part:re,objects:we})=>bd(we,{...J,part:re}))]:bd(D,J)},R=(D,J,re,we,Q)=>{if(t.json){process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"remove",summary:t.summaryPath,target:t.target,...re?{targetOrgId:re}:{},includeChanged:t.includeChanged,result:{status:D,planned:J.reduce((ie,_e)=>ie+_e.planned,0),objects:J,...l>0?{mayHaveBeenWritten:l}:{},...u>0?{removedEarlier:u}:{},...Q?{sweep:Q}:{},...p?{sweepListing:p}:{},...ag(c,t)!==void 0?{wholeOrgNotSwept:!0}:{},...f?{mutedAutomation:f}:{},...g.length>0?{heldByOtherParts:g}:{}},...we?{removalsFile:we}:{},elapsedMs:We(e)},null,2)+`
725
- `);for(let ie of S(J))console.error(ie);for(let ie of ig(g))console.error(ie);return}if(J.length>0||!Q)for(let ie of Eb(D,J,l))console.log(ie);if(Q)for(let ie of Wb(Q))console.log(ie);for(let ie of S(J))console.log(ie);for(let ie of ig(g))console.log(ie);we&&console.log(`what this removal left on the run's records is kept in ${we}, which the next --remove of this summary reads`),console.log(`
726
- done in ${We(e)}ms`)},k=Nd(c);if(k.length===0){n("The run created no record: there is nothing of it to remove."),R("success",[]);return}let A=Ns(k),w=Fs(t.summaryPath),I;try{I=yn(w,"utf8")}catch(D){D?.code!=="ENOENT"&&(process.stderr.write(`${w} cannot be read: ${D instanceof Error?D.message:String(D)}
727
- `),process.exit(2))}let P=Ms(I,A);"refusal"in P&&(process.stderr.write(`${w} ${P.refusal}
728
- `),process.exit(2));let{otherRun:v,earlier:$}=P,E=await Eg(c);E&&"refusal"in E&&(process.stderr.write(`${E.refusal}
729
- `),process.exit(2)),y=E!==void 0;let M=E&&Et(w)!==Et(E.file)?E:void 0,Z=Ng($,M?.earlier);n(`sandforge clone --remove ${t.summaryPath} from ${t.target}`);let U=ag(c,t);U!==void 0&&n(U);let H=Yr({objects:k,removalLeft:$?.removalLeft}),K=Zt(H,M?.earlier?.removalLeft),pe=D=>D.reduce((J,re)=>J+re.ids.length,0);u=pe(k)-pe(K),pe(k)>pe(H)&&n(`${pe(k)-pe(H)} record(s) removed by an earlier --remove of this summary`),pe(H)>pe(K)&&n(`${pe(H)-pe(K)} record(s) removed by an earlier --remove of the run's other part or of its journal`);let le=M?Pg(M):[],V=E&&!("refusal"in E)&&!M?E:void 0,fe=V?xg(V,K):void 0,se=t.includeChanged&&c.result.runUserId!==void 0;if(K.length===0&&le.length===0&&!t.sweep&&!t.sweepList&&!se){n("nothing left of the run to remove"),R("success",[]);return}let{session:me,conn:z,org:Oe}=await a(),ne=new Map([[Oe.id,{alias:t.target,username:me.username}]]),q=`sandforge-clone-${ks()}`,ee,ke=D=>As(t.audit,ne,{action:"cleanup_delete",module:"forge",operationId:q,orgId:Oe.id,...D,...f?{muted:Qr(f)}:{}}),te=t.sweepList?void 0:Dr(t.target,Oe,"remove");te&&he({code:"PRODUCTION_TARGET",message:te}),c.targetOrgId!==void 0&&!Is(c.targetOrgId,Oe.id)&&Ut(Pt(c.targetOrgId));let F=c.result.writtenBetween===void 0?c:void 0;c=await vs(z,c);let Y=()=>$g(Oe.id,t.target,c,k,Z,M);if(t.sweepList){let D=await Ea(vd(z,"sandforge clone --sweep-list"),await jd(z,t.target,c,k,await Y(),{ofTheRun:M}),Z?.removalSpans??[]);for(let J of Rs(D,t.target,t,!0))n(J);for(let J of Os(M,D))n(J);t.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"sweep-list",summary:t.summaryPath,target:t.target,targetOrgId:Oe.id,listing:D,elapsedMs:We(e)},null,2)+`
730
- `):console.log(`
731
- done in ${We(e)}ms`),D.refusal!==void 0&&process.exit(sg);return}let B=c.result.runUserId,G=new AbortController,be=()=>G.abort(),Ae=K.length>0||le.length>0||se;K.length>0||le.length>0?Ie():n(se?"nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run":"nothing left of the run to remove");let ve=t.sweep?df(vd(z,"sandforge clone --sweep",G.signal),await jd(z,t.target,c,k,await Y(),{signal:G.signal,ofTheRun:M}),{includeChanged:t.includeChanged,removalSpans:Z?.removalSpans??[],...zb(t),approve:async D=>{p=D,n("");for(let J of Rs(D,t.target,t))n(J);for(let J of Os(M,D))n(J)}}):void 0;if(ve){let D=Dn(be);try{await ve.ask()}finally{D()}let J=Mb(ve,p);if(J){p=J,n("");for(let re of Rs(J,t.target,t))n(re);for(let re of Os(M,J))n(re)}}let ot=ve?.takes??[];(Ae||ot.length>0)&&!G.signal.aborted&&await an(ot);let L,Te=[];if(Ae)L=await Ot(),L.stoppedForUndeletable&&(h&&he(h),process.exit(1));else if(ve){let D=await ct(),J=Dn(be);try{await ve.first(),await ve.afterRemoval()}finally{if(J(),D){f=await D.release();for(let re of qn(f,t.target))n(re)}}}let De=ve?.result();De&&As(t.audit,ne,{action:"cleanup_delete",module:"forge",operationId:`${q}-sweep`,orgId:Oe.id,outcome:De.status==="refused"?"stopped":De.status,...De.status==="refused"?{code:"SWEEP_REFUSED"}:{},objects:lf(De),details:uf(De,A),...!Ae&&f?{muted:Qr(f)}:{}});function Ie(){for(let D of Tb(c,K,t))n(D);for(let D of Ab(le))n(D);$?n(`what earlier removals of this summary left on the run's records, read from ${w}, is not a change since the run`):v&&n(`${w} is of another run: it is not read, and what this removal leaves on the records, if anything, takes its place`),M?.earlier&&n(`what the removals of the run's other part or of its journal left on its records, read from ${M.file}, is no change since the run`)}function he(D){return ke({outcome:"stopped",code:D.code}),Ut(D)}function Ut(D){return process.stderr.write(`${Qt(D)}
732
- `),t.json&&process.stdout.write(to({tool:"sandforge-clone",summary:t.summaryPath,target:t.target,elapsedMs:We(e)},D)),process.exit(1)}function Pt(D){return{code:eo,message:`${t.target} is not the org the run wrote to (${D}), and its records are removed from that org only. Nothing was deleted.`}}async function an(D){let J=[...new Set([...K,...le.flatMap(Pe=>Pe.plan)].map(Pe=>Pe.objectApiName))],re=[...new Set([...So(J,Fg(M),{userKept:B!==void 0}),...J.length===0&&se?[ko]:[],...D])],we=Si(J),Q=await xs(z).read(t.target,re);n("");for(let Pe of ra(Q,t.target,re.length,we))n(Pe);if(t.muteAutomation){let Pe=new Set(we);try{ee=await Ei(async()=>Ii(z),Q,{writes:(ut,pt)=>pt==="delete"||pt==="update"&&Pe.has(ut)}),f=ee.muted;for(let ut of qn(ee.muted,t.target))n(` ${ut}`)}catch(ut){if(!Rr(ut))throw ut;he(ut.refusal)}}let ie=ee?.automation??Q,_e=na(ie,t.target,{drafted:we,assign:qo(ie,Qs(ie,we)),mayMute:ee===void 0&&ft("--mute-automation")});_e&&!t.acceptAutomation&&he({code:"AUTOMATION_NOT_ACCEPTED",message:_e})}async function ct(){let D=ee?.prepared&&!G.signal.aborted?await ee.prepared.acquire(`sandforge clone --remove ${q}`).catch(J=>{if(!Rr(J))throw J;return he(J.refusal)}):void 0;return D&&(f=D.outcome),D}async function Ot(){let D,J=Dn(be),re=c.result.writtenBetween,we=re?{runStartedAt:new Date(re.first),runEndedAt:new Date(re.last)}:{runDurationMs:c.elapsedMs,...c.finishedAt?{runRecordedAt:new Date(c.finishedAt)}:{}},Q=il,ie=[],_e=Wh(t.leaveUndeletable,t.target,Ye=>{h=Ye}),[Pe,...ut]=fe??[],pt=M??(Pe?V:void 0),st=M?.part??Pe?.part.part,Fn=pt&&st!==void 0?Cg(pt,st,Z?.removalStamps??{}):[],jt=pt&&st!==void 0?Zn(pt.parts,st):[];try{if(K.length>0||se){let Ue=Pe?Pe.plan:K;Q=await yr(Gn(z,"sandforge clone --remove"),Ue,{...(Pe&&In(Pe.part))??we,...Z?{removalStamps:Z.removalStamps,removalSpans:Z.removalSpans}:{},...Gb(ve),...B?{runUserId:B}:{},...jt.length>0?{laterParts:jt}:{},...Fn.length>0?{otherParts:Fn.map(Ne=>Ne.alongside)}:{},includeChanged:t.includeChanged,onUndeletable:_e,beforeFirstWrite:async()=>{D=await ct()},signal:G.signal})}else D=await ct();let Ye={...Z?.removalStamps,...Q.stamps};for(let Ue of Q.otherPartStamps??[])Object.assign(Ye,Ue);let gt=[...st!==void 0?[{part:st,plan:Pe?Pe.plan:K}]:[],...[...ut,...le].map(Ue=>({part:Ue.part.part,plan:Ue.plan}))];for(let{part:Ue,plan:Ne}of[...ut,...le]){if(Q.stoppedForUndeletable||Q.cancelled||G.signal.aborted)break;let Kt=In(Ue)??(Pe?we:void 0);if(!Kt)continue;let xt=br(Z?.removalSpans,[Q,...Te].flatMap(Ct=>Ct.span?[Ct.span]:[])),Rn=Zn(pt?.parts??[],Ue.part),Vt=await yr(Gn(z,"sandforge clone --remove"),Ne,{...Kt,removalStamps:Ye,removalSpans:xt,...B?{runUserId:B}:{},...Rn.length>0?{laterParts:Rn}:{},otherPartRecords:gt.flatMap(Ct=>Ct.part===Ue.part?[]:Ct.plan),includeChanged:t.includeChanged,onUndeletable:_e,signal:G.signal});Object.assign(Ye,Vt.stamps),Te.push(Vt),M&&ie.push({part:Ue.part,objects:Vt.objects})}}finally{if(J(),D){f=await D.release();for(let Ye of qn(f,t.target))n(Ye)}}if(ie.length>0&&(b={own:Q.objects,others:ie}),Q.stoppedForUndeletable)return Q;let Ht=Z?.removalSpans.at(-1)?.last,kt=To(Q.objects,...Te.map(Ye=>Ye.objects)),Nn=Q.cancelled||Te.some(Ye=>Ye.cancelled);return ke({outcome:dl({status:Ai(kt,Nn)}),objects:cl(kt),...Ht?{leftBy:Ht}:{}}),Q}let lt=De&&cf(De,new Date().toISOString(),Z?.sweep),Je=Kb(A,Z,L&&fe?Yb([L,...Te]):L??{stamps:{}},K,lt,ve?.made??[],ve?.late??[],ve?.gone??[]);Je&&E&&!M&&(Je.partsRemoved=E.parts.map(D=>D.part));let et=Je?Id(w,Je):void 0;if(et&&process.stderr.write(`What this removal left on the run's records could not be kept in ${w} (${et}): a later --remove of this summary may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
733
- `),M?.part!==void 0&&L&&!L.stoppedForUndeletable){let D=[L,...Te],J={};for(let Q of D)for(let ie of[Q.stamps,...Q.otherPartStamps??[]])Object.assign(J,ie);let re=Jb(M,{stamps:J,spans:D.flatMap(Q=>Q.span?[Q.span]:[]),gone:D.flatMap(Q=>Q.gone),parts:[M.part,...le.map(Q=>Q.part.part)]}),we=re?Id(M.file,re):void 0;we&&process.stderr.write(`What this removal left on the run's records could not be kept in ${M.file} (${we}): a later --remove of the run's other part or of its journal may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
734
- `)}let Be=To(L?.objects??[],...Te.map(D=>D.objects)),$e=L?.cancelled===!0||Te.some(D=>D.cancelled),ht=al(L?Ai(Be,$e):"success",De);M?.part!==void 0&&(g=Vb(M,Be)),F&&!t.sweep&&Be.some(D=>(D.heldByAutomation??0)>0)&&(m=(await vs(z,F)).result.writtenBetween===void 0),R(ht,Be,Oe.id,Je&&!et?w:void 0,De),ht!=="success"&&process.exit(sg)}var Xb="not read by a preview: what the target's automation does as the records go \u2014 a trigger or a flow that deletes, keeps or creates other records \u2014 and what hangs from them, which a removal reads at each object\u2019s turn: a record kept for records that stay is counted with those to delete";function Zb(r){return`${JSON.stringify({tool:"sandforge-clone",version:1,action:"remove-preview",summary:r.summary,target:r.target,...r.targetOrgId!==void 0?{targetOrgId:r.targetOrgId}:{},includeChanged:r.includeChanged,preview:r.preview,...r.sweepListing?{sweepListing:r.sweepListing}:{},refusals:r.refusals.map(({message:e})=>e),refusalCodes:r.refusals.map(({code:e})=>e),notes:r.notes,elapsedMs:r.elapsedMs},null,2)}
735
- `}function eR(r,e,t,n){let o=i=>r.userNames[i]??i,s=["preview: what a removal would do; nothing was written"];for(let i of r.objects){let a=[i.toDelete>0?`${i.toDelete} to delete`:"",n&&i.changedSince>0?`${i.changedSince} of them changed since the run`:"",i.alreadyGone>0?`${i.alreadyGone} gone already`:"",i.notVisible>0?`${i.notVisible} not visible`:"",i.keptChanged>0?`${i.keptChanged} kept, changed since the run`:"",i.undeletable>0?`${i.undeletable} left, the user may not delete them`:"",i.unread>0?`${i.unread} left, not read`:""].filter(Boolean);s.push(` ${i.objectApiName}: ${a.join(", ")||"nothing"} of ${i.planned}${kg(i)}`);let d=Object.entries(i.changedBy).sort((c,l)=>l[1]-c[1]);d.length>0&&s.push(` last changed by: ${d.map(([c,l])=>`${o(c)} ${l}`).join(" \xB7 ")}`);for(let c of i.reasons)s.push(` ${c}`)}for(let i of e)s.push(_n(i,"a removal"));return[...s,...t]}async function tR(r,e,t,n){let o=e,s=[],i,a=(B,G,be)=>{if(s.push(Xb),r.json){process.stdout.write(Zb({summary:r.summaryPath,target:r.target,...be!==void 0?{targetOrgId:be}:{},includeChanged:r.includeChanged,preview:B,refusals:G,notes:s,elapsedMs:We(n),...i?{sweepListing:i}:{}}));return}t("");for(let Ae of eR(B,G,s,r.includeChanged))t(Ae);t(`
736
- done in ${We(n)}ms`)};t(`sandforge clone --remove ${r.summaryPath} --preview of ${r.target}`),o.targetOrgId===void 0&&o.target!==r.target&&(process.stderr.write(`The run wrote to ${o.target}, and its records are read in that org only: give --target ${o.target}.
737
- `),process.exit(2));let d=o.journal;d!==void 0&&bn(d)&&Dt(qt()).callsInFlightAt(d)>0&&s.push("the run's journal names calls under way when it stopped: a removal looks for their rows in the target first and removes those it finds with the rest; this preview counts only what the summary names");let c=(o.result.mayHaveBeenWritten??[]).reduce((B,{sourceIds:G})=>B+G.length,0);c>0&&s.push(`${c} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned: no removal reaches them`);let l=Nd(o);if(l.length===0){s.push("The run created no record: there is nothing of it to remove."),a({planned:0,objects:[],userNames:{}},[]);return}let u=Fs(r.summaryPath),p;try{p=yn(u,"utf8")}catch(B){B?.code!=="ENOENT"&&(process.stderr.write(`${u} cannot be read: ${B instanceof Error?B.message:String(B)}
738
- `),process.exit(2))}let f=Ms(p,Ns(l));"refusal"in f&&(process.stderr.write(`${u} ${f.refusal}
739
- `),process.exit(2));let h=await Eg(o);h&&"refusal"in h&&(process.stderr.write(`${h.refusal}
740
- `),process.exit(2));let g=h&&Et(u)!==Et(h.file)?h:void 0,m=Ng(f.earlier,g?.earlier),y=Yr({objects:l,removalLeft:f.earlier?.removalLeft}),b=Zt(y,g?.earlier?.removalLeft),S=g?Pg(g):[],R=B=>B.reduce((G,be)=>G+be.ids.length,0);R(l)>R(y)&&s.push(`${R(l)-R(y)} record(s) removed by an earlier --remove of this summary`),R(y)>R(b)&&s.push(`${R(y)-R(b)} record(s) removed by an earlier --remove of the run's other part or of its journal`);for(let{part:B,plan:G}of S)s.push(`with them, ${R(G)} record(s) of the run's part ${B.part} an earlier --remove of that part left, read against that part, once these are gone`);let k=r.includeChanged&&o.result.runUserId!==void 0;if(b.length===0&&S.length===0&&!r.sweep&&!k){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},[]);return}let A=await Sn(r.target),w=cn(A),I=await on(w);if(o.targetOrgId!==void 0&&!Is(o.targetOrgId,I.id)){let B={code:eo,message:`${r.target} is not the org the run wrote to (${o.targetOrgId}): its records are read in that org only. Nothing of the run was read.`};process.stderr.write(`${Qt(B)}
741
- `),r.json&&process.stdout.write(to({tool:"sandforge-clone",action:"remove-preview",summary:r.summaryPath,target:r.target,elapsedMs:We(n)},B)),process.exit(1)}let P=[],v=Dr(r.target,I,"remove");if(v&&P.push({code:"PRODUCTION_TARGET",message:v}),o=await vs(w,o),r.sweep){i=await Ea(vd(w,"sandforge clone --remove --preview --sweep"),await jd(w,r.target,o,l,await $g(I.id,r.target,o,l,m,g),{ofTheRun:g}),m?.removalSpans??[]),t("");for(let B of Rs(i,r.target,r,!0))t(B);for(let B of Os(g,i))t(B)}let $=[...new Set([...b,...S.flatMap(B=>B.plan)].map(B=>B.objectApiName))],E=i?oc(i,r):[],M=[...new Set([...So($,Fg(g),{userKept:o.result.runUserId!==void 0}),...$.length===0&&k?[ko]:[],...E])],Z=Si($),U=await xs(w).read(r.target,M);t("");for(let B of ra(U,r.target,M.length,Z))t(B);let H=na(U,r.target,{drafted:Z,assign:qo(U,Qs(U,Z)),mayMute:!r.muteAutomation&&ft("--mute-automation")});if(H&&!r.acceptAutomation&&P.push({code:"AUTOMATION_NOT_ACCEPTED",message:H}),b.length===0&&S.length===0&&!k){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},P,I.id);return}b.length===0&&S.length===0&&s.push("nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run");let K=new AbortController,pe,le=Dn(B=>{pe=B,K.abort()}),V=o.result.writtenBetween,fe=V?{runStartedAt:new Date(V.first),runEndedAt:new Date(V.last)}:{runDurationMs:o.elapsedMs,...o.finishedAt?{runRecordedAt:new Date(o.finishedAt)}:{}},se,me=[],[z,...Oe]=(h&&!g?xg(h,b):[])??[],ne=g??(z?h:void 0),q=g?.part??z?.part.part,ee=ne&&q!==void 0?Zn(ne.parts,q):[],ke=ne&&q!==void 0?Cg(ne,q,m?.removalStamps??{}):[],te=[...q!==void 0?[{part:q,plan:z?z.plan:b}]:[],...[...Oe,...S].map(B=>({part:B.part.part,plan:B.plan}))];try{se=await yr(Gn(w,"sandforge clone --remove --preview"),z?z.plan:b,{...(z&&In(z.part))??fe,...m?{removalStamps:m.removalStamps,removalSpans:m.removalSpans}:{},...ee.length>0?{laterParts:ee}:{},...ke.length>0?{otherParts:ke.map(B=>B.alongside)}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},includeChanged:r.includeChanged,previewOnly:!0,signal:K.signal});for(let{part:B,plan:G}of[...Oe,...S]){let be=In(B)??(z?fe:void 0);if(!be||!se.preview||K.signal.aborted)continue;let Ae=Zn(ne?.parts??[],B.part);me.push(await yr(Gn(w,"sandforge clone --remove --preview"),G,{...be,...m?{removalStamps:m.removalStamps,removalSpans:m.removalSpans}:{},...Ae.length>0?{laterParts:Ae}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},otherPartRecords:te.flatMap(ve=>ve.part===B.part?[]:ve.plan),includeChanged:r.includeChanged,previewOnly:!0,signal:K.signal}))}}finally{le()}let F=se.preview&&me.every(B=>B.preview)?{objects:ji(se.preview.objects,...me.map(B=>B.preview?.objects??[])),userNames:Object.assign({},se.preview.userNames,...me.map(B=>B.preview?.userNames??{}))}:void 0;F||(process.stderr.write(`interrupted: the preview stopped before it was through, and wrote nothing
742
- `),process.exit(fr(pe??"SIGINT")));let Y=[se,...me].flatMap(B=>B.undeletable??[]);if(Y.length>0&&!r.leaveUndeletable){let B=Y.map(G=>`${G.objectApiName} (${G.records} records)`).join(", ");P.push({code:fd,message:`The user SandForge connects as may not delete the records of ${B} in ${r.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}(b.length>0||S.length>0)&&s.push(Og(o)),a({planned:R(b)+S.reduce((B,G)=>B+R(G.plan),0),objects:F.objects,...Y.length>0?{undeletable:Y}:{},userNames:F.userNames},P,I.id)}async function vs(r,e,t=Dt(qt())){if(e.result.writtenBetween||e.journal===void 0||!bn(e.journal))return e;let n={query:(s=>r.query(s,{scanAll:!0}))},o=await t.writtenBetweenAt(e.journal,r)??await t.writtenBetweenAt(e.journal,n);return o?{...e,result:{...e.result,writtenBetween:o}}:e}function Is(r,e){return r.slice(0,15)===e.slice(0,15)}var nR=new Set(["--verify","--target","--source","--json","--audit"]),rR=new Set(["--verify","--target","--source","--audit"]);function oR(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write($d),process.exit(0));let t=s=>{let i=e.indexOf(s),a=i>=0?e[i+1]:void 0;return a!==void 0&&!a.startsWith("--")?a:void 0};for(let s=0;s<e.length;s++){let i=e[s];if(rR.has(i)){e[s+1]!==void 0&&!e[s+1].startsWith("--")&&s++;continue}nR.has(i)||(process.stderr.write(`--verify takes --target, --source, --json and --audit, not "${i}". Run with --help for usage.
743
- `),process.exit(2))}let n=t("--verify"),o=t("--target");return(!n||!o||e.includes("--source")&&!t("--source"))&&(process.stderr.write(`--verify takes the file a run printed its --json summary to, --target the org the run wrote to, and --source, when given, the org it read from. Run with --help for usage.
744
- `),process.exit(2)),{summaryPath:n,target:o,source:t("--source"),json:e.includes("--json"),audit:xd(e)}}var sR=W.object({result:W.object({writtenWithoutFields:W.array(W.object({objectApiName:W.string().regex(rt),fields:W.array(W.object({field:W.string().regex(rt)}))}))})}),iR=W.object({result:W.object({lookupsLeftEmptyByFilter:W.array(W.object({objectApiName:W.string().regex(rt),field:W.string().regex(rt),records:W.number().int().nonnegative(),recordIds:W.array(nt)}))})}),aR={verified:0,partial:3,unstable:4};function dR(r,e){let t=[r.verdict==="unstable"?`verification: UNSTABLE \u2014 no two of ${r.attempts} readings of ${e} agreed: something still writes to the run's records; verify again once it is done`:`verification: ${r.verdict.toUpperCase()} (${r.attempts} readings of ${e})`],n=[];for(let s of r.objects){if(s.error!==void 0){t.push(` ${s.objectApiName}: not read (${s.error})`);continue}let i=[s.deleted>0?`${s.deleted} in the recycle bin`:"",s.notVisible>0?`${s.notVisible} neither there nor in the recycle bin, out of sight`:""].filter(Boolean),a=s.linksLeftEmptyByFilter??0,d=s.linksSetByAutomation??0,c=s.linksLeftEmptyByTheRun??0,l=[c>0?`${c} left empty by the run, as it said`:"",a>0?`${a} left empty by the target's lookup filter, as the run said`:"",d>0?`${d} set by the target's automation during the run`:""].filter(Boolean),u=s.linksChecked-s.linksBroken-a-d-c,p=s.withTheirRecord??0,f=s.linksUnchecked!==void 0?`lookups not checked (${s.linksUnchecked})`:s.linksChecked===0?"no lookup the run set to check":s.linksBroken===0&&l.length===0?`lookups: ${s.linksChecked} checked, all hold`:`lookups: ${s.linksChecked} checked, `+[...s.linksBroken>0?[`${s.linksBroken} do not hold`]:[`${u} hold`],...l].join(", ");t.push(` ${s.objectApiName}: ${s.present} of ${s.expected} there`+(i.length>0?`, ${i.join(", ")}`:"")+(p>0?`, and ${p} written by the platform with their record`:"")+`; ${f}`);for(let h of s.brokenLinks)t.push(h.found===null?` ${h.recordId}: ${h.field} is empty, the run set it to ${h.expected}`:` ${h.recordId}: ${h.field} points at ${h.found}, the run set it to ${h.expected}`);for(let h of s.explainedLinks??[])t.push(h.cause==="automation"?` ${h.recordId}: ${h.field} points at ${h.found??""}, which the target's automation created during the run; the run set it to ${h.expected}`:h.cause==="run"?` ${h.recordId}: ${h.field} is empty: left empty by the run, as it said, rather than set to ${h.expected}`:` ${h.recordId}: ${h.field} is empty: the target's lookup filter refused ${h.expected}, and the run left it empty`);s.recycleBinUnread!==void 0&&t.push(` the recycle bin could not be read (${s.recycleBinUnread})`),(s.moreInTheWindow??0)>0&&t.push(` ${s.moreInTheWindow} more ${s.objectApiName} record(s) were created in ${e} during the run by the run's user than the run wrote`+(p>0?" and the platform wrote with its records":"")+": the target's automation, another session writing as that user, or a call written twice");for(let h of s.changedRecords)n.push(` ${s.objectApiName} ${h.recordId}: modified ${h.modifiedAt}`+(h.modifiedById?` by ${h.modifiedById}`:""))}let o=r.objects.reduce((s,i)=>s+i.changed,0);return o>0&&t.push(`changed since the run: ${o} record(s), which --remove keeps unless --include-changed`,...n),r.linksUnchecked!==void 0&&t.push(`lookups not checked: ${r.linksUnchecked}`),t}async function cR(r=process.argv){let e=Date.now(),t=oR(r),n=$=>t.json?console.error($):console.log($),o;try{o=yn(t.summaryPath,"utf8")}catch($){process.stderr.write(`--verify ${t.summaryPath} cannot be read: ${$ instanceof Error?$.message:String($)}
745
- `),process.exit(2)}let s;try{s=JSON.parse(o)}catch{}W.object({tool:W.literal("sandforge-clone"),dryRun:W.literal(!0)}).safeParse(s).success&&(process.stderr.write(`--verify ${t.summaryPath} is the summary of a dry run, which wrote nothing to the target: there is nothing of it to verify.
746
- `),process.exit(2));let a=ei(s,"sandforge-clone");a&&(process.stderr.write(`--verify ${t.summaryPath} ${ti(a,"verify")}
747
- `),process.exit(2));let d=await Td(t.summaryPath,o,t.target);"refusal"in d&&(process.stderr.write(`--verify ${t.summaryPath} ${d.refusal}
748
- `),process.exit(2));let{summary:c}=d;c.targetOrgId===void 0&&c.target!==t.target&&(process.stderr.write(`The run wrote to ${c.target}, and its records are verified in that org only: give --target ${c.target}.
749
- `),process.exit(2));let l=Nd(c);if(l.length===0){n("The run created no record: there is nothing of it to verify.");return}let u,p=Fs(t.summaryPath),f;try{f=yn(p,"utf8")}catch{}let h=Ms(f,Ns(l)),g=l;if("refusal"in h)n(`${p} ${h.refusal}`);else if(u=h.earlier?.removalStamps,g=Yr({objects:l,removalLeft:h.earlier?.removalLeft}),g.length===0){n("An earlier --remove of this summary took every record the run created: there is nothing of it to verify.");return}let m=sR.safeParse(s),y=iR.safeParse(s);n(`sandforge clone --verify ${t.summaryPath} in ${t.target}`);let b=await Sn(t.target),S=cn(b),R=await on(S);if(c.targetOrgId!==void 0&&!Is(c.targetOrgId,R.id)){let $={code:eo,message:`${t.target} is not the org the run wrote to (${c.targetOrgId}), and its records are verified in that org only. Nothing of the run was read.`};process.stderr.write(`${Qt($)}
750
- `),t.json&&process.stdout.write(to({tool:"sandforge-clone",action:"verify",summary:t.summaryPath,target:t.target,elapsedMs:We(e)},$)),process.exit(1)}c=await vs(S,c);let k=t.source??c.source,A;try{A=Ca(cn(await Sn(k)),"sandforge clone --verify source")}catch($){A={unavailable:`the org the run read from, ${k}, could not be reached: ${X($)}`}}let w=new Map([[R.id,{alias:t.target,username:b.username}]]),I=$=>As(t.audit,w,{action:"forge_verify",module:"forge",operationId:`sandforge-clone-${ks()}`,orgId:R.id,...$}),P;try{P=await new wf({target:Ca(S,"sandforge clone --verify"),source:A}).verify({records:g,remapTable:c.result.remapTable,...c.result.writtenBetween?{runStartedAt:new Date(c.result.writtenBetween.first),runEndedAt:new Date(c.result.writtenBetween.last)}:c.finishedAt?{runRecordedAt:new Date(c.finishedAt)}:{},...u?{removalStamps:u}:{},...m.success?{writtenWithout:Rf(m.data.result.writtenWithoutFields)}:{},...y.success?{leftEmptyByFilter:y.data.result.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:bf(c.wholeOrg===!0),...c.result.withTheirRecordSourceIds?{withTheirRecord:c.result.withTheirRecordSourceIds}:{}})}catch($){throw I({outcome:"failure"}),$}if(I({outcome:P.verdict==="verified"?"success":"partial",verdict:P.verdict,details:yf(P)}),t.json)process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"verify",summary:t.summaryPath,target:t.target,targetOrgId:R.id,source:k,result:P,elapsedMs:We(e)},null,2)+`
751
- `);else{for(let $ of dR(P,t.target))console.log($);console.log(`
752
- done in ${We(e)}ms`)}let v=aR[P.verdict];v!==0&&process.exit(v)}var lR=new Set(["done","error","stopped"]);function uR(r){return r?`interrupted: the clone stopped before it was through; ${r} says what it created, and --remove ${r} takes it back`:"interrupted: the clone stopped before it was through; the summary above says what it created, and --remove takes it back from that summary saved to a file (--json)"}function ag(r,e){if(!(r.wholeOrg!==!0||e.sweep||e.sweepList))return`the sweep is off for a clone of the whole org: its window spans the hours the run wrote in, and a sweep looks at ${$a} objects at most; ${sn("--sweep-list")} lists what the target's automation made for it, and ${sn("--sweep")} takes it`}var dg="ROOT_NEVER_CREATED",cg="No record was read or written.";async function pR(r,e,t){let n=[];for(let i of r)try{await t.createable(i.objectApiName)===!1&&n.push(i)}catch{}if(n.length===0)return;let o=n.find(i=>ao(i.objectApiName));if(o){let i=o.objectApiName;return{code:dg,message:`${o.named}: SandForge never copies ${i} records, setup or the platform's own, and ${e}'s user may not create them: a clone has nothing to write of what it starts from. ${cg}`}}let s;try{s=await t.whyNot(n.map(i=>i.objectApiName))}catch{return}for(let i of n){let a=s.get(i.objectApiName);if(a===void 0||!Ql(a))continue;let d=i.objectApiName,c=a==="platform"?"the platform writes them itself":"not even one with Modify All Data: they are setup the org keeps as records, or the platform's own";return{code:dg,message:`${i.named}: no user can create ${d} records in ${e}, ${c}, and a clone has nothing to write of what it starts from. ${cg}`}}}async function fR(r,e){if(r.tables)return r.tables.map(({objectApiName:i})=>({objectApiName:i,named:`--object ${i}`}));let t=r.record??"";if(t==="")return[];let n=t.slice(0,3),o;try{o=await e(r.source)}catch{return[]}let s=o.find(i=>i.keyPrefix===n)?.name;return s?[{objectApiName:s,named:`--record ${t} (a ${s})`}]:[]}function lg(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return{describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`);return{fields:(await e(o,s)).fields.map(Wi),sent:i}},query:async(o,s)=>jn({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s)}}function nr(r,e){let t=r.get(e);if(!t)throw new Error(`No connection for ${e}`);return t}var hR=new Set(["Lead","Case"]);function gR(r,e,t,n){return{bulkWriteRecords:async(o,s,i,a,d)=>{if(e.dryRun)throw new Error("A dry run sends no Bulk API job.");if(e.applyAssignmentRules&&hR.has(s))return{answers:[],rows:[],unmatchedIds:[],untouched:{reason:"the run applies the target's assignment rules, which a job cannot",unsupported:!0},requests:0};try{let c=await ql(ki(nr(r,o)),d.bulkManager,s,i,a,{...d.externalIdField?{externalIdField:d.externalIdField}:{},...d.signal?{signal:d.signal}:{},...d.onOpened?{onOpened:d.onOpened}:{}});return(c.unmatchedIds.length>0||c.answers.some(l=>l.success))&&n(),c}catch(c){throw c instanceof Gl&&(n(),t?.note({orgId:o,objectApiName:s,...c.jobId?{jobId:c.jobId}:{}})),c}},duplicateRuleObjects:async o=>Qp(nr(r,o))}}async function mR(r,e,t){let n=r?.since(0,e)??[];if(!r||n.length===0)return[];t(`waiting for ${n.length} Bulk API job(s) the run could not read back to end, before the mute is given back\u2026`);let o=await r.stillRunning(n);if(o.length>0){let s=o.map(i=>`${i.objectApiName}${i.jobId?` (${i.jobId})`:""}`).join(", ");t(`warning: ${o.length} Bulk API job(s) were still running as the mute was given back: ${s}; their records may have gone in with the target's automation on`)}return o}async function wR(r,e,t){let n=r.get(e);if(!n)throw new Error(`No connection for ${e}`);return jn({query:async o=>n.tooling.query(o),queryMore:async o=>n.tooling.queryMore(o)},t)}async function yR(r=process.argv){if(r.slice(2).includes("--verify"))return cR(r);if(r.slice(2).includes("--remove"))return Qb(r);let e={};try{await bR(r,e)}finally{e.release?.()}}var $s=class extends Error{constructor(e){super(e),this.name="CheckpointTakeInterrupted"}},Es=class extends Error{constructor(e){super(e),this.name="QuestionInterrupted"}};async function bR(r,e){let t=Date.now(),n=py(r),o=n.depth==="all",s=O=>n.json?console.error(O):console.log(O);s(`sandforge clone ${n.source} -> ${n.target} ${ey(n)}`);for(let O of xy(n))s(O);if(n.resume&&n.files===void 0){let O=Dt(qt()),T=await O.headAt(Vh(n.resume,O));T?.resume?.files&&(n={...n,files:T.resume.files},s("files: copied as the run taken up was begun, with --files"))}let i=await Sn(n.source),a=await Sn(n.target),d,c=()=>d??=new hf({...Gh(n),depth:n.depth,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,keepContactPoints:n.keepContactPoints,skipEmpty:!0,batchSize:"auto",excludedObjects:n.excludedObjects,...n.decisions},{reviewSkipped:!0}),l=new Map;l.set(n.source,cn(i)),l.set(n.target,cn(a));let u=new Map([...l].map(([O,T])=>[O,[Zr(T)]])),p=O=>(u.get(O)??[]).reduce((T,C)=>T+C(),0),f,h=new Map,g,m=`sandforge-clone-${ks()}`,y,b=O=>{if(f===void 0||n.dryRun||n.listObjects||n.rehearse)return;let T=d?.fit();As(n.audit,h,{action:"forge_execute",module:"forge",operationId:m,orgId:f,...O,...y?{muted:Qr(y)}:{},...T?{fit:T}:{}})},S;if(!n.dryRun&&!n.listObjects){let O=await on(l.get(n.target));S=O,f=O.id,h.set(O.id,{alias:n.target,username:a.username}),n.audit&&!n.rehearse&&(g=(await on(l.get(n.source))).id,h.set(g,{alias:n.source,username:i.username}));let T=Dr(n.target,O,"clone");T&&(b({outcome:"stopped",code:"PRODUCTION_TARGET",context:c().context()}),process.stderr.write(`${T}
753
- `),process.exit(1))}let R;if(o){let O=await on(l.get(n.source));R=O.id;let T=Dr(n.source,O,"clone")!==void 0;T&&!n.anonymizeGiven&&(n={...n,anonymize:!0},n.files&&!n.files.acceptedAsIs&&(process.stderr.write(`--files: ${n.source} is a production org, whose personal data a clone of the whole org anonymizes unless --no-anonymize is given, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, give --no-anonymize, or leave out --files.
754
- `),process.exit(2))),s(n.anonymize?`anonymize: on${T&&!n.anonymizeGiven?`, ${n.source} being a production org (--no-anonymize copies its personal data as it is)`:""}`:`anonymize: off, the personal data copied as ${n.source} holds it`)}if(!n.listObjects){let O=await Yo(n.ownerMappings,async T=>(await l.get(n.target).query(T)).records);if(O){b({outcome:"stopped",code:O.code,context:c().context()});let T={code:O.code,message:O.message};process.stderr.write(`${Qt(T)}
755
- `),n.json&&process.stdout.write(hr({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:We(t),apiRequests:ws({target:p(n.target),source:p(n.source)},{})},T)),process.exit(1)}}let k=n.checkpointFirst?Bh({module:"forge",operationId:m,request:n.checkpointFirst,session:a,org:Mh(a,S??await on(l.get(n.target))),connect:O=>{let T=cn(O);return u.get(n.target)?.push(Zr(T)),T},journalDir:qt(),say:s}):void 0,A=[...l.values()].map(Zr),w=()=>A.reduce((O,T)=>O+T(),0),I={...Gh(n),depth:n.depth,customDepth:n.depth==="custom"?n.customDepth:void 0,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,skipEmpty:!0,batchSize:"auto",...(n.tables||o)&&Object.keys(n.objectSoqlFilters).length>0?{objectSoqlFilters:n.objectSoqlFilters}:{}},P=new wl,v=new Set,$=Ay(async(O,T)=>{v.add(`${O}::${T}`);let C=l.get(O);if(!C)throw new Error(`No connection for ${O}`);return C.sobject(T).describe()}),E=new Map,M={describeObject:async(O,T)=>Sy(await $(O,T)),queryCount:async(O,T,C,N)=>{let x=l.get(O);if(!x)throw new Error(`No connection for ${O}`);return(await x.query(T,N?.all?{scanAll:!0}:void 0)).totalSize},detectPII:O=>ml(P,O),describeGlobal:O=>{let T=E.get(O);if(!T){let C=l.get(O);if(!C)throw new Error(`No connection for ${O}`);T=C.describeGlobal().then(N=>N.sobjects.map(x=>o?{name:x.name,keyPrefix:x.keyPrefix??null,queryable:x.queryable,createable:x.createable,updateable:x.updateable,deletable:x.deletable,customSetting:x.customSetting,layoutable:x.layoutable}:{name:x.name,keyPrefix:x.keyPrefix??null})),E.set(O,T)}return T},...o?{toolingObjects:async O=>{let T=l.get(O);if(!T)throw new Error(`No connection for ${O}`);return(await T.tooling.describeGlobal()).sobjects.map(C=>C.name)},recordCounts:async O=>{let T=l.get(O);if(!T)throw new Error(`No connection for ${O}`);return T.request(`/services/data/v${T.version}/limits/recordCount`)},createFacts:async O=>(await Li(lg(l,$,v),O)).facts}:{}},Z=await fR(n,M.describeGlobal),U=await pR(Z,n.target,{createable:async O=>(await $(n.target,O)).createable!==!1,whyNot:O=>Xl((T,C)=>wR(l,T,C),async T=>(await Li(lg(l,$,v),T)).facts)(n.target,O)});U&&(b({outcome:"stopped",code:U.code,context:c().context()}),process.stderr.write(`${Qt(U)}
756
- `),n.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,refused:U,elapsedMs:We(t)},null,2)}
757
- `),process.exit(1)),s("discovery\u2026");let H=new Bu(M),K={source:p(n.source),target:p(n.target)},pe=o?await qy(H,I,s):await H.discover(I,n.maxNodes===void 0?void 0:{maxNodes:n.maxNodes}),le={source:p(n.source)-K.source,target:p(n.target)-K.target};o&&s(Hy(le,n.source,n.target));let V=o?void 0:pe.nodes[0]?.objectApiName;V!==void 0&&n.excludedObjects.includes(V)&&(process.stderr.write(`${vn(`--exclude-object ${V}`,`the resource's template leaves out ${V}`)}: the ${n.tables?"first table":"record"} to clone is of this object, and nothing would be left to clone.
758
- `),process.exit(2));let fe=n.tables?Qw(pe,n.tables):[];if(fe.length>0){let O=Xn(),T=O?`the table${fe.length===1?"":"s"} ${fe.join(", ")}`:`--object ${fe.join(", ")}`;process.stderr.write(`${T}: discovery from ${V??n.tables?.[0]?.objectApiName} did not reach ${fe.length===1?"it":"them"} (${pe.nodes.length} object(s), depth ${n.depth==="custom"?n.customDepth:n.depth}): name first a table it hangs from or points at, or raise ${O?"the resource's depth or maxNodes":"--depth or --max-nodes"}.
759
- `),process.exit(2)}let se=n.tables?Xw(n,pe):o?ny(n):I,me=se.excludedObjects??n.excludedObjects,z=o?oy(pe,new Set(me)):pb(xo(pe,new Set(me)),n.anonymizeFields),Oe=new Yl().generate(z);if(s(o?zy(z,Oe,n.source):_y(z,Oe,n.maxNodes??Fu)),n.listObjects){let O=lb(z),T=O.map(C=>` ${C.objectApiName.padEnd(42)}${String(C.recordCount).padStart(8)} depth ${C.depth}${C.included?"":" (excluded)"}`);s(`
760
- objects in the graph (${z.nodes.length}):`),s(T.join(`
761
- `)),z.truncated&&s(`
762
- The graph was truncated: discovery stopped before it had walked everything. Raise --max-nodes if an object you need is missing.`),n.json&&process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"list-objects",source:n.source,target:n.target,...n.tables?{tables:n.tables}:o?{wholeOrg:!0}:{record:n.record},graph:ys(z,Oe),objects:O,...o?{leftOut:zo(z)}:{},elapsedMs:We(t)},null,2)+`
763
- `);return}let ne=o?Kp(z):void 0;ne&&(b({outcome:"stopped",code:ne.code,context:c().context()}),process.stderr.write(`${Qt(ne)}
764
- `),n.json&&process.stdout.write(hr({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:We(t),apiRequests:ws({target:p(n.target),source:p(n.source)},{},le)},ne)),process.exit(1));let q=O=>(b({outcome:"stopped",code:O.code,context:c().context()}),process.stderr.write(`${Qt(O)}
765
- `),n.json&&process.stdout.write(hr({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:We(t),apiRequests:ws({target:p(n.target),source:p(n.source)},{},le)},O)),process.exit(eg(O.code))),ee=qt(),ke="",te;if(n.sample){let O=f??(await on(l.get(n.target))).id,T={...R?{sourceOrgId:R}:{}};ke=ja(z,Jh(n,O,T)),await Ep(ee,new Date).catch(()=>0);let C=n.sample.options.plan;if(C!==void 0)try{if(te=await Jn.open(C,{sourceOrgId:n.source,fingerprint:ke}),te.ageMs(new Date)>=Tp)throw new Qo("gone","The plan of this sample is a day old or more.")}catch(N){let x=Go(N,"replay");if(!x)throw N;q({code:x.code,message:x.message.replace(/ Nothing was written\.$/,` Given: ${C}. Nothing was written.`)})}}let F=!n.dryRun&&!n.rehearse?Dt(ee):void 0,Y=(O,T)=>Jh(n,O,{...R?{sourceOrgId:R}:{},...T?{planSha256:T}:{}}),B=f!==void 0?ja(z,Y(f,te?.sha256)):"",G,be,Ae=n.muteAutomation;if(F&&f!==void 0&&n.resume){G=Vh(n.resume,F);let O=f,T=await my(F,G,{target:n.target,targetOrgId:f,graph:z,setup:Y(f),sample:{asked:n.sample!==void 0,setupWith:N=>Y(O,N)}});T&&((T.code===Hi||T.code===Tr)&&q(T),b({outcome:"stopped",code:T.code,context:c().context()}),process.stderr.write(`${T.message}
766
- `),process.exit(2)),be=await F.lastEndAt(G),(await F.headAt(G))?.resume?.muteAutomation===!0&&(Ae=!0),s(`taking up the run of ${G}`);let C=await F.reconcileAt(G,ka(l.get(n.target)));for(let N of Sa(C,n.target))s(N);Ta(C)>0&&!n.writeUncertain&&(b({outcome:"stopped",code:"RESUME_UNCERTAIN",context:c().context()}),process.stderr.write(`${hy(C,n.target)}
767
- `),process.exit(2))}let ve=new Xp,ot=new AbortController,L={},Te,De=O=>{Te=O,process.stderr.write(`
768
- interrupted: the clone stops after the call under way, and says what it created (Ctrl-C again ends it at once)
769
- `),ve.stop(void 0,{discovery:()=>{},run:()=>{ot.abort(),L.executor?.abort()}})};if(!n.dryRun&&!n.rehearse&&!n.listObjects){ve.beginRun(m,ot);let O=Dn(De);e.release=()=>{O(),ve.endRun(m)}}let Ie=async O=>{ot.signal.aborted&&(b({outcome:"stopped",code:pi,context:c().context()}),await O?.(),s("interrupted: the clone stopped before it wrote anything"),process.exit(fr(Te??"SIGINT")))},he=await xs(l.get(n.target)).readForGraph(n.target,z,new Set(me));s("");for(let O of su(he,n.target,{applyAssignmentRules:n.applyAssignmentRules,mayMute:ft("--mute-automation"),mayApplyAssignmentRules:ft("--apply-assignment-rules")}))s(O);let Ut=sc(he,new Set(me));for(let O of Eu(Ut,n.target,he.unread,vn("--remove","destroy, or a replace")))s(O);s(n.keepContactPoints?`contact points: written as read (${vn("--keep-contact-points","keepContactPoints")})`:"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range)");let Pt=await fb(l,$,v).read(n.source,n.target,z,{inputMode:I.inputMode,recordId:I.recordId,maxRecordsPerObject:n.maxRecordsPerObject,fieldExclusions:n.fieldExclusions,fieldMappings:n.fieldMappings,excludedObjects:me}),an={...n.decisions,fieldExclusions:n.fieldExclusions,excludedObjects:me},ct=Iu(z,{leftOut:new Set(me),upsert:n.upsert}),Ot=new Set(ct.map(O=>O.objectApiName)),lt=(O,T)=>T==="insert"||T==="update"&&Ot.has(O),Je=Ae?Sl(he,lt).plan.alsoLifts:void 0;s("");for(let O of tu(Pt,n.target,{decisions:an,...Je?{lifted:Je}:{}}))s(O);let et=n.upsert&&!n.keepContactPoints?Ny(await Promise.all(z.nodes.filter(O=>O.included).map(async({objectApiName:O})=>({objectApiName:O,fields:await $(n.source,O).then(T=>T.fields).catch(()=>[])})))):[];for(let O of My(et,n.target))s(O);let Be,$e,ht={},D=()=>({apiRequests:ws({target:p(n.target),source:p(n.source)},ht,o?le:void 0)}),J=(O,T=[],C=1)=>{for(let N of[O,...T])process.stderr.write(`${Qt(N)}
770
- `);return n.json&&process.stdout.write(hr({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:We(t),...D()},O,T)),process.exit(C)};if(Ae){n.muteAutomation||s(" mute: the run taken up was muted, and so is this part of it");try{Be=await Ei(async()=>Ii(l.get(n.target)),he,{writes:lt});for(let O of qn(Be.muted,n.target))s(` ${O}`)}catch(O){if(!Rr(O))throw O;n.dryRun||(b({outcome:"stopped",code:O.code,context:c().context()}),J(O.refusal)),$e=O.refusal,s(` ${_n(O.refusal)}`)}}let re=Be?.automation??he,we=Pu(re,n.target,{updated:ct,assign:qo(re,$u(re,ct.map(O=>O.objectApiName))),mayMute:!Ae&&ft("--mute-automation")});c().automationRead({automation:re},ct),we&&n.acceptAutomation&&c().confirm("automation");let Q=n.rehearse?void 0:await kl({read:he,...Be?.plan?{plan:Be.plan}:{},writes:lt,applyAssignmentRules:n.applyAssignmentRules,readDeliverability:async()=>{let O=l.get(n.target),T=S??await on(O);return Dr(n.target,T,"clone")!==void 0?Rl:Ol(O)},accepted:n.acceptEmails,target:n.target,run:"clone",keepsAddresses:n.keepContactPoints,mayMute:!Ae&&ft("--mute-automation")});Q?.gate.line!==void 0&&s(` ${Q.gate.line}`),c().emailsRead(Q?.gate.audit),Q?.gate.verdict==="asks"&&n.acceptEmails&&c().confirm("emails");let ie=Q?.gate.stop,_e=$e!==void 0?[$e]:[],Pe=we!==void 0&&!n.acceptAutomation;(Pe||ie)&&!n.dryRun&&(b({outcome:"stopped",code:Pe?"AUTOMATION_NOT_ACCEPTED":Au,context:c().context()}),Pe&&J({code:"AUTOMATION_NOT_ACCEPTED",message:we},ie?[ie]:[]),ie&&J(ie)),Pe&&(_e.push({code:"AUTOMATION_NOT_ACCEPTED",message:we}),s(" a real run would be refused (AUTOMATION_NOT_ACCEPTED): it writes nothing without --accept-automation: see what fires as it inserts and updates, or could not be read, above")),ie&&(_e.push(ie),s(` ${_n(ie)}`)),await Ie(),s("record-type mapping\u2026");let ut=w(),pt=[],st=await Ty(l.get(n.source),l.get(n.target),O=>pt.push(O)),Fn=w()-ut;s(`record-types: ${st.length} mappings`);for(let O of pt)s(` warning: ${O}`);await Ie();let jt={statements:0,pages:0},Ht=!1,kt=O=>(O.some(T=>T.success)&&(Ht=!0),O),Nn=o?new Yp(async(O,T)=>(await ki(nr(l,O)).bulk2.job("ingest",{id:T}).check()).state):void 0,Ye={...o?gR(l,n,Nn,()=>Ht=!0):{},queryRecords:async(O,T,C)=>{let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);let{records:x,truncated:oe}=await yi({query:async Ee=>N.query(Ee),queryMore:async Ee=>N.queryMore(Ee)},T,n.readCeiling);return oe&&C?.(),x},queryPages:(O,T,C)=>{let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);return jt.statements++,xc({query:async x=>(jt.pages++,N.query(x)),queryAll:async x=>(jt.pages++,N.query(x,{scanAll:!0})),queryMore:async x=>(jt.pages++,N.queryMore(x))},T,C)},countRecords:async(O,T,C)=>{let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);return(await N.query(T,C?.all?{scanAll:!0}:void 0)).totalSize},queryTooling:async(O,T)=>{let C=l.get(O);if(!C)throw new Error(`No connection for ${O}`);return(await C.tooling.query(T)).records},insertRecords:async(O,T,C)=>{if(n.dryRun)return C.map(()=>({id:"",success:!0,errors:[]}));let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);let x=await N.sobject(T).create(C,{headers:ar({applyAssignmentRules:n.applyAssignmentRules})});return kt(Oi(x,T))},updateRecords:async(O,T,C)=>{if(n.dryRun)return[];let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);let x=await N.sobject(T).update(C,{headers:ar({applyAssignmentRules:n.applyAssignmentRules})}),oe=Array.isArray(x)?x:[x];return kt(oe.map((Ee,Mt)=>({id:Ee.id??C[Mt].Id??"",success:Ee.success,errors:(Ee.errors??[]).map(ol),errorDetails:(Ee.errors??[]).map(rl)})))},describeFields:async(O,T)=>ky(await $(O,T)),isObjectCreatable:async(O,T)=>(await $(O,T)).createable!==!1,describeObject:async(O,T)=>{let C=l.get(O);if(!C)throw new Error(`No connection for ${O}`);return gd(C,T)},describeObjectAgain:async(O,T)=>{let C=l.get(O);if(!C)throw new Error(`No connection for ${O}`);return gd(C,T,!0)},recordTypePicklists:async(O,T,C)=>{let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);return Zp(N,T,C)},upsertRecords:async(O,T,C,N)=>{if(n.dryRun)return N.map(()=>({id:"",success:!0,errors:[]}));let x=l.get(O);if(!x)throw new Error(`No connection for ${O}`);let oe=await x.sobject(T).upsert(N,C,{headers:ar({applyAssignmentRules:n.applyAssignmentRules})});return kt(Oi(oe,T))},readFileBody:async(O,T,C)=>{let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);return ef(N,T,C)},insertFile:async(O,T,C)=>{if(n.dryRun)return{id:"",success:!0,errors:[]};let N=l.get(O);if(!N)throw new Error(`No connection for ${O}`);let[x]=kt([await tf(N,T,C)]);return x},remainingFileStorageMB:async O=>{let T=l.get(O);if(!T)throw new Error(`No connection for ${O}`);return nf(T)},requestsSent:w,runningUser:async O=>{let T=l.get(O);if(!T)throw new Error(`No connection for ${O}`);return(await T.identity()).user_id}};if(n.rehearse){let O=l.get(n.target),T=ar({applyAssignmentRules:n.applyAssignmentRules});s(`
771
- rehearsing\u2026 (the rows are read and prepared as the run would; nothing stays in the target)`);let C;try{C=await xa({prepare:async x=>{await new tr(Pa(Ye,x)).execute(z,n.source,n.target,()=>{},{...tg(n,z,st,oe=>H.personalFields(oe)),dryRun:!1,files:void 0})},keyPrefixOf:async x=>(await gd(O,x)).keyPrefix,runningUser:async()=>(await O.identity()).user_id,composite:x=>O.request({method:"POST",url:"/composite",body:JSON.stringify(x),headers:{"Content-Type":"application/json",...T}}),apiPath:`/services/data/v${O.version}`,writeHeaders:T,recordTypeNames:new Map(st.map(x=>[x.targetId.slice(0,15),x.developerName])),targetRecordTypes:Dh(Ye,n.target),targetFields:x=>Ye.describeFields(n.target,x),validationRules:async()=>gf(Pt.gaps),confirm:async x=>{s("");for(let oe of gb(x,n.target))s(oe)},onProgress:x=>{x.phase==="rehearsing"&&s(` call ${x.call} of ${x.calls}\u2026`)}})}catch(x){throw x instanceof mf&&(process.stderr.write(`${x.message}
772
- `),process.exit(1)),x}let N=We(t);s("");for(let x of mb(C,n.target,Je?{lifted:Je}:{}))s(x);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"rehearse",source:n.source,target:n.target,...f?{targetOrgId:f}:{},record:n.record,graph:ys(z,Oe),targetAutomation:he,rehearsal:wb(C,Je),elapsedMs:N},null,2)+`
773
- `):console.log(`
774
- done in ${N}ms`);return}if(!n.skipPreflight){s(`
775
- preflight (target row counts)\u2026`);let O=l.get(n.target),T=z.nodes.slice(0,30),C=[];for(let x of T)try{let oe=await O.query(`SELECT COUNT() FROM ${x.objectApiName}`);C.push({name:x.objectApiName,existing:oe.totalSize})}catch{C.push({name:x.objectApiName,existing:-1})}let N=C.filter(x=>x.existing>0);if(N.length===0)s(" target is empty for all sampled objects.");else{let x=N.sort((oe,Ee)=>Ee.existing-oe.existing).slice(0,10);s(` ${N.length}/${C.length} sampled objects have existing rows. Top 10:`);for(let oe of x){let Ee=oe.existing>1e3?" \u26A0":"";s(` ${oe.name.padEnd(40)} ${String(oe.existing).padStart(8)}${Ee}`)}z.nodes.length>T.length&&s(` (sampled first ${T.length}/${z.nodes.length} nodes; --skip-preflight to bypass)`)}}await Ie();let gt=l.get(n.target),Ue,Ne,Kt=[],xt={},Rn,Vt,Ct=async(O,T)=>{if(!k||T.totalRows===0)return;let C=new Set(T.objects.map(({objectApiName:x})=>x)),N={written:O.objects.map(({objectApiName:x})=>x).filter(x=>C.has(x)),running:{firing:pr(re,void 0,lt).firing}};try{Ne={ask:N,estimate:await k.scope(N)};return}catch(x){return Gi(x).replace(/ Nothing was written\.$/,"")}},Ft=O=>({unread:X(O)}),On=()=>({target:Math.max(0,p(n.target)-(Q?.ofRun.read?.requests??0)),source:p(n.source)}),_r=async O=>{let T=O.wholeOrg;if(!T)throw new Error("A clone of the whole org reached its write gate without what it measured of both orgs, which its gate weighs it on. Nothing was written.");let C=wu(T.readWholeOver);if(C&&!O.dryRun)throw bt.of({...C,message:Xh(C.message)});let N=Ou(O.objects,T),x=oa({firing:pr(re,void 0,lt).firing},(ce,At)=>lt(ce,At)).perRecord,oe=T.sample?.report;oe&&(Vt=oe,c().sampled(oe));let Ee=await Ct(O,N),Mt=[...Ot],it,St,He,Tt,Jt;if(O.dryRun)it=await ku({objects:O.objects,measures:T,graph:z,anonymizePII:n.anonymize,updatedAfterInsert:Mt,...Ne?{checkpoint:Ne.estimate}:{},...O.readBack!==void 0?{readBack:O.readBack}:{},mute:jo(Be?.plan),deliverability:Q?.ofRun.read?.requests??0,sentBefore:On,...oe?{sample:oe}:{},automation:x,target:{org:n.target,limits:gt},source:{org:n.source,limits:nr(l,n.source)}}),St=Vp(it),He=it.storage,Tt=it.files,Jt=it.wouldBeRefused;else{let ce=await Do(gt).catch(Ft),At="unread"in ce?await Sr(gt).catch(Ft):ce.dailyApiRequests;He=Ui(N,ce,bu(N,x));let Hr=ea(He,n.target),Us=oe?Tu({sample:oe,storage:ce,target:n.target}):void 0,Hs=yu(T.files,ce,n.target);Tt=Hs.files;let Gg=await Sr(nr(l,n.source)).catch(Ft),qd=On(),ir=qi({plan:N,updatedAfterInsert:Mt,...O.readBack!==void 0?{readBack:O.readBack}:{},...Ne?{checkpoint:Ne.estimate}:{},mute:jo(Be?.plan),...Zi(Q?.ofRun),sentBefore:qd.target,budget:At,target:n.target,wholeOrg:{measures:T,bulkBatches:"unread"in ce?ce:ce.dailyBulkApiBatches,sourceBudget:Gg,source:n.source,sourceSentBefore:qd.source}});St={api:ir.api,wholeOrg:ir.wholeOrg},Jt=[...Us?[Us]:[],...Us===void 0&&Hr!==void 0&&He.verdict==="exceeds"?[{code:"STORAGE_EXCEEDED",message:`${Hr} Nothing was written.`,storage:{estimateMB:Number(Xt(He.estimateMB)),remainingMB:He.remainingMB}}]:[],...Hs.stop?[Hs.stop]:[],...ir.stop?[ir.stop]:[],...ir.alsoRefused??[]]}let Ur=oe?void 0:Jy(He,n.target);Ur!==void 0&&(Jt=Jt.map(ce=>ce.code==="STORAGE_EXCEEDED"?{...ce,message:`${Ur} Nothing was written.`}:ce));let sr={...Jp({run:{source:n.source,graph:z,anonymizePII:n.anonymize,...rr()},measures:T,plan:N,budget:St,...Tt?{files:Tt}:{},...oe?{sample:oe,now:Date.now()}:{}}),discovery:le};if(ht={target:St.api,source:St.wholeOrg.source},Rn={...it?{dry:it}:{},question:sr},s(""),oe)for(let ce of rb(oe,{source:n.source,target:n.target,dryRun:O.dryRun===!0,replayed:n.sample?.options.plan!==void 0}))s(ce);for(let ce of ta(N,He,n.target))s(ce);for(let ce of Uy(sr,zo(z).counts,n.target,T.writes))s(ce);if(Ne)for(let ce of ld(Ne.estimate))s(ce);let Yt=Ys(re),xe;if(Yt.length>0){let ce=await Ki(gt).catch(Ft),At=Vi(N,Yt,ce);for(let Hr of Xi(At,n.target))s(Hr);xe=Qi(At,n.target)}let Ke=Yi(re,Ji(N));Ke!==void 0&&s(` emails: not counted, ${Ke} could not be read`);let qe=ce=>Xh(ce).replace(/ Nothing was written\.$/,""),Gs=[...N.totalRows>n.maxTotal?[{code:"MAX_TOTAL_EXCEEDED",message:Vy(N.totalRows,n.maxTotal)}]:[],...Ee!==void 0?[{code:fn,message:Ee}]:[],...Jt.map(ce=>({code:ce.code,message:ce.code===fn&&ce.refusal!==void 0?gs(ce.refusal):qe(ce.message),stop:ce})),...xe!==void 0?[{code:"EMAILS_EXCEEDED",message:xe}]:[]];if(it){for(let{code:ce,message:At}of Gs)s(` ${_n({code:ce,message:At})}`);throw _e.push(...Gs.map(({code:ce,message:At})=>({code:ce,message:At}))),new va(it)}let qs=ce=>`${ce} Nothing was written.`,[Ln,...zg]=Gs;if(Ln)throw Kt=zg.map(({code:ce,message:At})=>({code:ce,message:qs(At)})),Ln.stop?bt.of({...Ln.stop,message:qs(Ln.message)}):new bt(Ln.code,qs(Ln.message));xt=Ri(St.api),await Bs(sr,N,oe)},rr=()=>{let O=Hp(se);return O?{carried:O}:{}},Bs=async(O,T,C)=>{let N=Ky(O,T,n.target,C);if(n.yes){s(` --yes: written without the question: ${N}`),c().confirm("volume");return}if(process.stdin.isTTY!==!0)throw new bt("CONFIRMATION_UNAVAILABLE",`A clone of the whole org asks before it writes ${N}, and no terminal is there to answer: give --yes to write it. Nothing was written.`);let x=await Yu(`Write ${N}?`,void 0,ot.signal);if(ot.signal.aborted)throw new Es("interrupted at its question: the clone stopped before it wrote anything");if(!x)throw new bt("WRITE_DECLINED","The clone of the whole org was declined at its question. Nothing was written.");c().confirm("volume")},Ls=async O=>{if(o)return _r(O);let T=pu(O.objects),C;try{C=await Do(gt)}catch(xe){C={unread:X(xe)}}let N=Ui(T,C);s("");for(let xe of ta(T,N,n.target))s(xe);let x="unread"in C?await Sr(gt).catch(xe=>({unread:X(xe)})):C.dailyApiRequests,oe;if(k&&T.totalRows>0){let xe=new Set(T.objects.map(({objectApiName:qe})=>qe)),Ke={written:O.objects.map(({objectApiName:qe})=>qe).filter(qe=>xe.has(qe)),running:{firing:pr(re,void 0,lt).firing}};try{Ne={ask:Ke,estimate:await k.scope(Ke)}}catch(qe){oe=Gi(qe).replace(/ Nothing was written\.$/,"")}}let Ee=qi({plan:T,updatedAfterInsert:[...Ot],...O.readBack!==void 0?{readBack:O.readBack}:{},...Ne?{checkpoint:Ne.estimate}:{},mute:jo(Be?.plan),...Zi(Q?.ofRun),sentBefore:On().target,budget:x,target:n.target});if(xt=Ri(Ee.api),ht={target:Ee.api},s(qw(Ee.api,n.target)),Ne)for(let xe of ld(Ne.estimate))s(xe);let Mt=Ys(re),it,St;if(Mt.length>0){let xe=await Ki(gt).catch(qe=>({unread:X(qe)})),Ke=Vi(T,Mt,xe);for(let qe of Xi(Ke,n.target))s(qe);it=Qi(Ke,n.target),St=Ke.map(qe=>({limit:qe.limit,emails:qe.emails}))}let He=Yi(re,Ji(T));He!==void 0&&s(` emails: not counted, ${He} could not be read`);let Tt=T.totalRows>n.maxTotal?Pb(T.totalRows,n.maxTotal,n.dryRun):void 0,Jt=ea(N,n.target),Ur=oe??(Ee.stop?.refusal!==void 0?gs(Ee.stop.refusal):void 0),sr=hu(Ee.api,n.target)?.replace(/ Nothing was written\.$/,""),Yt=[[fn,Ur],["MAX_TOTAL_EXCEEDED",Tt],["STORAGE_EXCEEDED",Jt],["EMAILS_EXCEEDED",it],[_o,sr]].flatMap(([xe,Ke])=>Ke!==void 0?[{code:xe,message:Ke}]:[]);if(O.dryRun){for(let qe of Yt)s(` ${_n(qe)}`);_e.push(...Yt);let xe=ie&&Q?ju(Q.ofRun.senders,T):[],Ke=vu(xe);Ke!==void 0&&s(Ke),Ue={totalRows:T.totalRows,storageBytes:T.storageBytes,objects:T.objects,...T.leftOut?{leftOut:T.leftOut}:{},...St!==void 0?{emails:St}:{},...He!==void 0?{emailsUncounted:He}:{},...xe.length>0?{emailSendersOfNothingWritten:xe}:{}};return}if(Yt.length>0){let xe=Ke=>`${Ke} Nothing was written.`;throw Kt=Yt.slice(1).map(({code:Ke,message:qe})=>({code:Ke,message:xe(qe)})),new bt(Yt[0].code,xe(Yt[0].message))}},Mn=n.dryRun||n.rehearse?void 0:await pf(()=>gt.identity(),"sandforge clone");s(`
776
- executing\u2026 (${n.dryRun?"DRY-RUN":"REAL"}${n.tables?", WHOLE TABLES":""}${o?", WHOLE ORG":""}${n.upsert?", UPSERT":""}${n.expandOrphans?", EXPAND-ORPHANS":""}${n.applyAssignmentRules?", ASSIGNMENT-RULES":""}${n.files?", FILES":""}${n.pageSize!==void 0?`, READ IN PAGES OF ${n.pageSize}`:""})`);let Bn=O=>O.apiCalls===void 0?O:{...O,apiCalls:O.apiCalls+Fn},j=(O,T,C={},N)=>({tool:"sandforge-clone",version:1,source:n.source,target:n.target,...f?{targetOrgId:f}:{},...n.tables?{objects:n.tables}:o?{wholeOrg:!0}:{record:n.record},dryRun:n.dryRun,upsert:n.upsert,expandOrphans:n.expandOrphans,applyAssignmentRules:n.applyAssignmentRules,files:n.files!==void 0,...n.choicesFrom?{choices:{from:n.choicesFrom.flag,file:n.choicesFrom.path,...n.decisions?{decisions:n.decisions}:{}}}:{},graph:ys(z,Oe),...Vt?{sample:Zh(Vt)}:{},targetAutomation:Q?.ofRun.read?{...he,deliverability:Q.ofRun.read.reading}:he,...y?{mutedAutomation:y}:n.dryRun?$i(Be):{},...D(),removalRisks:Ut,targetGaps:Di(Pt,an),...By(n.dryRun,Pt,O.gaps,Je),...et.length>0?{neutralizedUpsertKeys:et}:{},result:{...N?{status:N}:{},...Ly(O,n.readCeiling),...Mn?{runUserId:Mn}:{}},...n.dryRun&&Ue!==void 0?{writePlan:Ue}:{},...je(),...n.dryRun?Zs(_e):{},elapsedMs:We(t,T.getTime()),finishedAt:T.toISOString(),...G&&Nt?{journal:G}:{},...Ws()!==void 0?{part:Ws()}:{},..._s.length>0?{bulkJobsPastMute:_s}:{},...C}),_=O=>{let T=Rn?.question;return{tool:"sandforge-clone",version:1,source:n.source,target:n.target,dryRun:!0,anonymize:n.anonymize,files:n.files!==void 0,graph:ys(z,Oe),targetAutomation:Q?.ofRun.read?{...he,deliverability:Q.ofRun.read.reading}:he,...$i(Be),removalRisks:Ut,targetGaps:Di(Pt,an),wholeOrg:{...O.sample?{sample:Zh(O.sample)}:{},wouldInsert:O.wouldInsert,totalRows:O.totalRows,requests:{target:O.targetRequests,source:O.sourceRequests},...O.bulkBatches?{bulkBatches:O.bulkBatches}:{},storage:O.storage,...O.files?{files:O.files}:{},durationSeconds:O.durationSeconds,leftOut:O.leftOut,personalAsIs:O.personalAsIs,managedPackages:T?.managedPackages??[],...T?.contactPointsBlanked!==void 0?{contactPointsBlanked:T.contactPointsBlanked}:{},...T?.carried?{carried:T.carried}:{}},...je(),...D(),...Zs(_e),elapsedMs:We(t)}},ae,de,je=()=>{let O=n.dryRun?Ne?.estimate:de??ae;return O!==void 0?{checkpoint:O}:{}},Xe=async()=>{if(!(!k||!ae||de)){try{de=await k.settle(ae,Ht)}catch(O){de=ae,s(`warning: the checkpoint '${ae.name}' taken before the run, which wrote nothing, could not be deleted (${X(O)}): delete it with ${jr("checkpoint")} delete --org ${n.target} --checkpoint ${ae.checkpointId}`)}for(let O of pd(de))s(O)}},Nt,vt;F&&f!==void 0&&(G&&n.resume?(await F.resumingAt(G),vt=(await F.headAt(G))?.journalId):(vt=`sandforge-clone-${new Date(t).toISOString().replace(/[:.]/g,"-")}-${ks().slice(0,8)}`,G=F.pathOf(vt),await F.begin(vt,f,new Date,{sourceOrgId:n.source,fingerprint:B,targetSalesforceOrgId:f,...n.record?{recordId:n.record}:{},...n.muteAutomation?{muteAutomation:!0}:{},...n.files?{files:n.files}:{},startedWith:{graph:z,config:se}},Mn)),Nt=F.openAt(G),s(Xn()?`journal: ${G}`:`journal: ${G} (--resume ${G} takes the run up if it stops)`));let Ws=()=>Nt&&Nt.partCount>0?Nt.partCount-1:void 0,Mg=async()=>{if(!n.sample||n.dryRun||n.resume||vt===void 0)return;let O=Ra(ee,vt);if(te&&bn(O)&&!bn(te.dir))try{ug(O,te.dir);return}catch{}await $p(O)},or=async(O,T)=>{if(!F||!G||!Nt)return;Nt.close();let C=G;try{!T&&be?await F.stopAt(C,be.status,be.forgeId):!T&&!n.resume?(kd(C,{force:!0}),kd(C.replace(/\.ndjson$/,".end.json"),{force:!0}),await Mg()):await F.stopAt(C,O,`${vt??"run"}#${Ws()??0}`)}catch(N){process.stderr.write(`The journal ${C} could not be ended (${X(N)}).
777
- `)}},Md;if(n.sample){let O=n.sample,T=te;if(te&&!n.dryRun&&vt!==void 0)try{T=await Ip(te,ee,vt)}catch(x){await or("failure",!1),process.stderr.write(`The plan of --fit-plan ${te.dir} could not be moved beside the run's journal (${X(x)}): keep it in ${Ss(ee,"forge-samples")}, where its dry run put it. Nothing was written.
778
- `),process.exit(1)}if(T)s(`sample: takes up the plan ${T.dir}, drawn ${T.manifest.drawnAt}: no root is drawn again`);else if(n.resume)s("sample: the run taken up goes on with the plan its journal names");else{s(ib(z,O.options,n.source));let x=n.dryRun?void 0:await vp(ee,ke,new Date).catch(()=>{});x instanceof Jn&&s(` a dry run drew a plan of this setup at ${x.manifest.drawnAt}: this run draws its own; --fit-plan ${x.dir} writes that one's records instead`)}let C=oa({firing:pr(re,void 0,lt).firing},(x,oe)=>lt(x,oe)).perRecord,N=T||n.resume?void 0:await Sr(nr(l,n.source)).catch(Ft);Md={options:gg(O),budget:async()=>Qy({storage:await Do(gt).catch(Ft),sample:O,target:n.target,automation:C}),keepAt:n.dryRun||vt===void 0?Ap(ee,ke):Ra(ee,vt),fingerprint:ke,...T?{plan:T}:{},...N&&"remaining"in N?{sourceRequestsLeft:N.remaining}:{},onProgress:cb(s)}}let It,Bg=Dy(z),Ds=new tr(Ye),Bd=!1,zr=O=>{if(!n.summary)return;let T=Id(n.summary,O);T&&!Bd&&(Bd=!0,process.stderr.write(`The summary could not be written to ${n.summary} (${T}).
779
- `))},Ld=-1,Lg=()=>{let O=Ds.summarySoFar();if(!O)return;let T=O.successCount+O.linkedCount+O.updatedCount+O.failedCount;T!==Ld&&(Ld=T,zr(j(Bn(O),new Date,{running:!0})))};L.executor=Ds,await Ie(()=>or("cancelled",!1));let Gr,_s=[],Wg,Wd=()=>Wg??=mR(Nn,n.target,s).then(O=>{_s=O.map(({objectApiName:T,jobId:C})=>({objectApiName:T,...C?{jobId:C}:{}}))}),Dg=async O=>{if(await Ls(O),O.dryRun||n.dryRun)return;if(k&&Ne&&!ae){let N=Ne,x=await mu(()=>k.take(N.ask,N.estimate,{signal:ot.signal}));if("stop"in x)throw x.stop.code!==fn?new $s(ud(x.stop)):new bt(fn,ud(x.stop));ae=x.checkpoint;for(let oe of Lh(x.checkpoint,n.target,Ae))s(oe)}if(!Be?.prepared||Gr)return xt;let T=await Be.prepared.acquire(`sandforge clone ${t}`).catch(async N=>{if(!Rr(N))throw N;return b({outcome:"stopped",code:N.code,context:c().context()}),await Xe(),J(N.refusal)});Gr=T,y=T.outcome;let C=Q?.afterLease(T.outcome,n.acceptEmails);if(C)throw new bt(C.code,C.message);return{...xt,lease:{assigned:T.outcome.assigned.length,giveBack:async()=>(await Wd(),T.release())}}};try{let O=await Ds.execute(z,n.source,n.target,T=>{let C=Bg(T);C&&s(C),n.summary&&lR.has(T.status)&&Lg()},ub({...o?ry(n,se,z,st,T=>H.personalFields(T),Md):n.tables?Zw(n,se,z,st,T=>H.personalFields(T)):tg(n,z,st,T=>H.personalFields(T)),beforeWrite:Dg},Nt)).finally(async()=>{if(Gr){await Wd(),y=await Gr.release();for(let T of qn(y,n.target))s(T)}});It=Bn(O),await Xe(),n.pageSize!==void 0&&s(`read in pages of ${n.pageSize}: ${jt.statements} statement(s) through the org's cursor, ${jt.pages} page(s) answered`)}catch(O){if(O instanceof va){let Tt=_(O.dryRun);n.json?process.stdout.write(`${JSON.stringify(Tt,null,2)}
780
- `):console.log(`
781
- done in ${Tt.elapsedMs}ms`),_e.length>0&&process.exit(1);return}(O instanceof $s||O instanceof Es)&&(b({outcome:"stopped",code:pi,context:c().context()}),await or("cancelled",!1),s(O.message),process.exit(fr(Te??"SIGINT"))),await Xe();let T=O instanceof bt?O:n.sample?Go(O,n.resume?"resume":"draw"):void 0,C=O instanceof hn?O:void 0,N=T??C,x=N?void 0:yp(O),oe=x?fi(x):void 0,Ee=oe?hi(oe):[],Mt=Te!==void 0||O instanceof Re,it=N?"stopped":Mt?Ac(x,Ee):"failure";b({outcome:it,...N?{code:N.code}:it==="stopped"?{code:Tc}:{},...oe?{objects:Ee,...g?{source:{origin:"org",orgId:g}}:{},carried:mi(oe)}:{},...gi(x?.contactPoints),context:c().context(x?.decisionsApplied)});let St=x!==void 0&&x.successCount+x.updatedCount+x.linkedCount>0;await or(Mt?"cancelled":"failure",St),N&&J({code:N.code,message:N.message},T?Kt:[],eg(N.code));let He=x;if(He&&(Te!==void 0||O instanceof Re)){let Tt=j(Bn(He),new Date,{interrupted:!0});if(zr(Tt),n.json)process.stdout.write(JSON.stringify(Tt,null,2)+`
782
- `);else{console.log("");for(let Jt of Yh(He,n.dryRun,n.readCeiling))console.log(Jt)}s(uR(n.summary)),process.exit(fr(Te??"SIGINT"))}throw He&&zr(j(Bn(He),new Date,{error:X(O)})),O}finally{e.release?.()}await or("success",!0);let Dd=fi(It),qr=co(It);b({outcome:qr,objects:hi(Dd),...g?{source:{origin:"org",orgId:g}}:{},carried:mi(Dd),...gi(It.contactPoints),context:c().context(It.decisionsApplied)});let _d=new Date,_g=We(t,_d.getTime()),zd=j(It,_d,{},qr);zr(zd);let zs;if(n.remapCsv){let O=["sourceId,targetId"];for(let[T,C]of Object.entries(It.remapTable))O.push(`"${T.replace(/"/g,'""')}","${C.replace(/"/g,'""')}"`);try{fg(n.remapCsv,O.join(`
783
- `)+`
784
- `,{encoding:"utf8",flag:"wx"}),s(`remap-csv: wrote ${Object.keys(It.remapTable).length} mappings to ${n.remapCsv}`)}catch(T){zs=T?.code==="EEXIST"?`--remap-csv refuses to overwrite existing file: "${n.remapCsv}"`:`--remap-csv ${n.remapCsv} could not be written: ${X(T)}`}}if(n.json)process.stdout.write(JSON.stringify(zd,null,2)+`
785
- `);else{console.log(""),console.log(`status: ${qr}`);let O=(Be?.plan?.assign.length??0)>0;for(let T of Yh(It,n.dryRun,n.readCeiling,O))console.log(T);if(It.sample){console.log("");for(let T of sb(It.sample,n.source))console.log(T)}console.log(`
786
- done in ${_g}ms`)}zs!==void 0&&(process.stderr.write(`${zs}: the summary names what the run created.
787
- `),process.exit(1));let Gd=dc(qr,n.failOnPartial||o);Gd!==0&&process.exit(Gd)}/sandforge-clone\.[cm]?[jt]s$/.test(process.argv[1]??"")&&(Of(),yR().catch(r=>{console.error("FATAL:",r instanceof Error?r.stack:r),process.exit(1)}));export{Fa as a,Qn as b,ft as c,gn as d,We as e,Br as f,cd as g,Fh as h,Nh as i,Mh as j,Bh as k,ld as l,gs as m,ud as n,Lh as o,pd as p,Jk as q,fd as r,Wh as s,qw as t,Vw as u,Ed as v,Yw as w,Qw as x,Xw as y,Zw as z,Gh as A,ey as B,ty as C,ny as D,ry as E,oy as F,sy as G,uy as H,py as I,hy as J,qt as K,Vh as L,Jh as M,my as N,yy as O,ky as P,Sy as Q,Ty as R,Ay as S,gd as T,BT as U,vy as V,Iy as W,Yh as X,Py as Y,xy as Z,Cy as _,Fy as $,Ny as aa,My as ba,By as ca,Ly as da,Wy as ea,Dy as fa,_y as ga,zy as ha,Uy as ia,Hy as ja,ws as ka,Ky as la,Xh as ma,Vy as na,Qy as oa,rb as pa,Zh as qa,ob as ra,sb as sa,ib as ta,cb as ua,eg as va,bg as wa,lb as xa,tg as ya,ub as za,pb as Aa,xs as Ba,fb as Ca,on as Da,Dr as Ea,gb as Fa,mb as Ga,Rb as Ha,Ob as Ia,LT as Ja,Td as Ka,Sb as La,Nd as Ma,Tb as Na,Ab as Oa,jb as Pa,kg as Qa,vb as Ra,Eb as Sa,Pb as Ta,sn as Ua,Rs as Va,Mb as Wa,bd as Xa,Wb as Ya,Db as Za,Os as _a,jd as $a,Ig as ab,_b as bb,zb as cb,Gb as db,vd as eb,WT as fb,qb as gb,Ub as hb,Fs as ib,Ns as jb,Ms as kb,Kb as lb,Eg as mb,Pg as nb,xg as ob,Cg as pb,Jb as qb,Yb as rb,Ng as sb,Id as tb,Qb as ub,Xb as vb,Zb as wb,eR as xb,vs as yb,oR as zb,dR as Ab,cR as Bb,uR as Cb,ag as Db,dg as Eb,pR as Fb,gR as Gb,mR as Hb,yR as Ib};