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