sandforge 1.79.0 → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
  2. package/lib/chunk-2CNCDM56.mjs +7 -0
  3. package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
  4. package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
  5. package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
  6. package/lib/chunk-3F6Q5E7I.mjs +14 -0
  7. package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
  8. package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
  9. package/lib/chunk-4VS2V6WU.mjs +25 -0
  10. package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
  11. package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
  12. package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
  13. package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
  14. package/lib/chunk-7ABODJ4G.mjs +7 -0
  15. package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
  16. package/lib/chunk-7FFGJWHN.mjs +7 -0
  17. package/lib/chunk-7YDNUBO5.mjs +7 -0
  18. package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
  19. package/lib/chunk-ADOAS63R.mjs +7 -0
  20. package/lib/chunk-AEKONPF4.mjs +7 -0
  21. package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
  22. package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
  23. package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
  24. package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
  25. package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
  26. package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
  27. package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
  28. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
  29. package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
  30. package/lib/chunk-CION3VMZ.mjs +7 -0
  31. package/lib/chunk-COFG7Q6R.mjs +7 -0
  32. package/lib/chunk-CSBS5U5I.mjs +7 -0
  33. package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
  34. package/lib/chunk-DB7RBE5D.mjs +7 -0
  35. package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
  36. package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
  37. package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
  38. package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
  39. package/lib/chunk-EFR2Y7E4.mjs +7 -0
  40. package/lib/chunk-EHQ3FX6X.mjs +7 -0
  41. package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
  42. package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
  43. package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
  44. package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
  45. package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
  46. package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
  47. package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
  48. package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
  49. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
  50. package/lib/chunk-G35N4P7D.mjs +7 -0
  51. package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
  52. package/lib/chunk-GSG7WZHM.mjs +7 -0
  53. package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
  54. package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
  55. package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
  56. package/lib/chunk-HOJYWTP7.mjs +20 -0
  57. package/lib/chunk-HS4YRX4J.mjs +7 -0
  58. package/lib/chunk-IFETCRWE.mjs +10 -0
  59. package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
  60. package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
  61. package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
  62. package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
  63. package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
  64. package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
  65. package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
  66. package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
  67. package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
  68. package/lib/chunk-JWTSEDIQ.mjs +7 -0
  69. package/lib/chunk-K327QKMD.mjs +7 -0
  70. package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
  71. package/lib/chunk-KDGMAGQR.mjs +7 -0
  72. package/lib/chunk-KRCA6IPH.mjs +8 -0
  73. package/lib/chunk-KYEDBS54.mjs +7 -0
  74. package/lib/chunk-L5FGY6YA.mjs +7 -0
  75. package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
  76. package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
  77. package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
  78. package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
  79. package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
  80. package/lib/chunk-MFG4MUIO.mjs +9 -0
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
  82. package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
  83. package/lib/chunk-MJU2PGZQ.mjs +15 -0
  84. package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
  85. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  86. package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
  87. package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
  88. package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
  89. package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
  90. package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
  91. package/lib/chunk-OAZRPP4I.mjs +7 -0
  92. package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
  93. package/lib/chunk-OLSGVAIL.mjs +341 -0
  94. package/lib/chunk-OO6CLPEH.mjs +7 -0
  95. package/lib/chunk-OPXCV2KL.mjs +7 -0
  96. package/lib/chunk-P33PSCXK.mjs +7 -0
  97. package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
  98. package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
  99. package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
  100. package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
  101. package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
  102. package/lib/chunk-RMBPOTD7.mjs +7 -0
  103. package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
  104. package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
  105. package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
  106. package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
  107. package/lib/chunk-SOU4FRYN.mjs +7 -0
  108. package/lib/chunk-SU65Z2BA.mjs +7 -0
  109. package/lib/chunk-T62WNR54.mjs +7 -0
  110. package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
  111. package/lib/chunk-TTFDUKUS.mjs +47 -0
  112. package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
  113. package/lib/chunk-UCD54V2M.mjs +7 -0
  114. package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
  115. package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
  116. package/lib/chunk-VS7ZXUII.mjs +824 -0
  117. package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
  118. package/lib/chunk-VYXMVJL5.mjs +7 -0
  119. package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
  120. package/lib/chunk-W7U5E5ZL.mjs +9 -0
  121. package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
  122. package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
  123. package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
  124. package/lib/chunk-WXAQ7FK3.mjs +115 -0
  125. package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
  126. package/lib/chunk-XAMBCQPU.mjs +7 -0
  127. package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
  128. package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
  129. package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
  130. package/lib/chunk-YRQGKDHM.mjs +7 -0
  131. package/lib/chunk-ZM6OJGIG.mjs +7 -0
  132. package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
  133. package/lib/sandforge-autopilot.mjs +29 -24
  134. package/lib/sandforge-backup.mjs +25 -21
  135. package/lib/sandforge-checkpoint.mjs +15 -14
  136. package/lib/sandforge-cleanup.mjs +14 -10
  137. package/lib/sandforge-clone.mjs +1 -1
  138. package/lib/sandforge-compare.mjs +9 -8
  139. package/lib/sandforge-dataops.mjs +1 -1
  140. package/lib/sandforge-empty.mjs +15 -15
  141. package/lib/sandforge-env.mjs +88 -88
  142. package/lib/sandforge-frozen.mjs +43 -34
  143. package/lib/sandforge-mcp.mjs +12 -12
  144. package/lib/sandforge-monitor.mjs +7 -7
  145. package/lib/sandforge-seed.mjs +1 -1
  146. package/lib/sandforge-sync.mjs +1 -1
  147. package/lib/sandforge.mjs +4 -4
  148. package/package.json +1 -1
  149. package/lib/chunk-2S5OMIIA.mjs +0 -7
  150. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  151. package/lib/chunk-3F5YMM2F.mjs +0 -7
  152. package/lib/chunk-3RYLICRX.mjs +0 -7
  153. package/lib/chunk-4GL773D5.mjs +0 -7
  154. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  155. package/lib/chunk-5AJRHRXA.mjs +0 -20
  156. package/lib/chunk-5HMAPZBV.mjs +0 -7
  157. package/lib/chunk-6LAXTAVN.mjs +0 -7
  158. package/lib/chunk-6MUEPV7M.mjs +0 -9
  159. package/lib/chunk-75ADZS6B.mjs +0 -7
  160. package/lib/chunk-B45CNPUX.mjs +0 -47
  161. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  162. package/lib/chunk-D3QRXG63.mjs +0 -787
  163. package/lib/chunk-EEVVGGM6.mjs +0 -7
  164. package/lib/chunk-ENLBYECD.mjs +0 -7
  165. package/lib/chunk-EQOQASDQ.mjs +0 -7
  166. package/lib/chunk-FQBRBBY4.mjs +0 -7
  167. package/lib/chunk-GAM726CK.mjs +0 -7
  168. package/lib/chunk-HUMEKZT5.mjs +0 -8
  169. package/lib/chunk-I3JKJTLO.mjs +0 -110
  170. package/lib/chunk-KLX67VPL.mjs +0 -7
  171. package/lib/chunk-L776PUMV.mjs +0 -7
  172. package/lib/chunk-NEVXIGR6.mjs +0 -10
  173. package/lib/chunk-NHWE66K5.mjs +0 -7
  174. package/lib/chunk-OQOZAPCI.mjs +0 -7
  175. package/lib/chunk-PA3MKJVH.mjs +0 -7
  176. package/lib/chunk-RH3N2H7P.mjs +0 -7
  177. package/lib/chunk-SRQDABQ2.mjs +0 -15
  178. package/lib/chunk-SVS6UMDU.mjs +0 -323
  179. package/lib/chunk-TNXUU6W7.mjs +0 -14
  180. package/lib/chunk-VXHDBYMI.mjs +0 -7
  181. package/lib/chunk-WRU5FJFC.mjs +0 -7
  182. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  183. package/lib/chunk-XEFDB2R4.mjs +0 -7
  184. package/lib/chunk-XETCPL7E.mjs +0 -7
  185. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  186. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  187. package/lib/chunk-YMJVMFPY.mjs +0 -7
  188. package/lib/chunk-YPSRZRIT.mjs +0 -7
  189. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  190. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  191. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  192. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as je,b as Ne,c as Pe,d as Fe,k as We,l as xe,o as Le,q as _e}from"./chunk-TBZMC2VV.mjs";import{e as Me}from"./chunk-LQ4DRFUH.mjs";import{b as De,f as Te}from"./chunk-57VHUYNG.mjs";import{m as Be}from"./chunk-5O6JOMHS.mjs";import{b as Se}from"./chunk-KLX67VPL.mjs";import{i as he,j as we,k as ke,l as ye,m as be,p as Re,q as Ae}from"./chunk-342FN7AO.mjs";import{A as Ie,B as $e,C as ve,z as Ue}from"./chunk-Z7X534S4.mjs";import{$ as Ce,C as ge,_ as Oe}from"./chunk-6QSM2WIH.mjs";import{a as le,b as fe}from"./chunk-SAR5622P.mjs";import{s as pe}from"./chunk-6MUEPV7M.mjs";import{b as ue,d as ce}from"./chunk-OTWRDD6L.mjs";import{Ba as Ee,s as me}from"./chunk-VXHDBYMI.mjs";import{g as L,h as _,q as de}from"./chunk-PA3MKJVH.mjs";import{b as x}from"./chunk-CA5NAXSU.mjs";import{Kc as se,Sc as W}from"./chunk-B45CNPUX.mjs";var C=class extends Error{constructor(){super("The undo was stopped before it wrote anything to the org."),this.name="UndoStopped"}},z="No record was written.",Je="accept that it runs to undo the rewind all the same";function ze(e){return e.slice(0,15)}function Ke(e){return{query:n=>e.query(n),queryMore:n=>e.queryMore(n)}}function Ye(e,n,t){if(e.kind==="org")return;let a=e.userKey;if(n.users.some(i=>i.slice(0,15)!==a))return{code:"PERMISSIONS",message:`This rewind was made as another user than ${t}: what it deleted is that user's deletion in the recycle bin, which Salesforce brings back only for a user with View All Data and Modify All Data. Undo it as the user it was made as, or as a user with View All Data and Modify All Data. ${z}`};let r=n.objects.flatMap(i=>{let l=e.notHeld.get(i);return l===void 0?[]:[`${i}: ${l}`]});if(r.length!==0)return{code:"PERMISSIONS",message:`Undo takes back what the rewind did to objects ${t} no longer holds whole (${r.join("; ")}), and does not stop part way: an undo left part way could not be offered again. Undo it once the user has View All and Modify All on them again, or as a user with View All Data and Modify All Data. ${z}`}}function Qe(e,n){return{undone:!1,refusal:{code:e,message:n}}}function Xe(e,n){return{code:"RUN_WRITING",message:`${n.operation==="take"?`A checkpoint of ${e} is being taken`:n.operation==="rewind"?`A rewind is writing to ${e}`:n.operation==="undo"?`An undo is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${n.pid} on ${n.host}): undo the rewind once it has ended. No record was read or written.`}}function Ze(e,n,t,a){let r=W(n,t),i=[...new Set(r.map(b=>b.objectApiName))],l=(t.setToDraft??[]).length>0?", sets an order back to Draft":"",h=r.length>0?`${Me(r)} flow(s), trigger(s) or rule(s) of ${i.join(", ")} run as the undo brings records back, gives them their values back${l} or sends them back to the recycle bin`:"what runs as the undo writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${e}: ${h}. ${ke("undo",a)}Undo refused; ${Je}. ${z}`}}async function et(e,n){let t=0,a=0;for await(let r of n.bringBack.pages(L)){t+=r.length;for(let i of ce(r,ue)){let l=await e.queryDeleted(`SELECT Id, ContentSize FROM ${L} WHERE Id IN (${i}) AND IsDeleted = true`);for(let h of l.records)typeof h.ContentSize=="number"&&(a+=h.ContentSize)}}return{files:t,bytes:a}}function tt(e,n){return e.status==="cancelled"||e.status==="failure"?e.status:n.some(t=>t.reason==="changedDuringRewind")?"unstable":e.status}function nt(e,n){return e.map(t=>{let a=Object.keys(t.by).filter(i=>!n.has(ze(i)));if(a.length===0)return{objectApiName:t.objectApiName,reason:"automation",count:t.count,ids:[...t.ids]};let r=a.length===1&&a[0]!=="unknown"?a[0]:void 0;return{objectApiName:t.objectApiName,reason:"changedDuringRewind",...r!==void 0?{by:r}:{},count:t.count,ids:[...t.ids]}})}async function Ot(e,n){let{checkpoint:t,folder:a,orgName:r,rewindId:i}=n,l=e.signal,h=()=>l?.aborted===!0,b=(U,k)=>e.onProgress?.({percentage:U,step:k}),c=_e(e.org,e.undelete),T,S=await Se(Ke(c.org),{act:"undo",orgName:r,registered:n.registered,username:n.username,organizationId:t.org.organizationId,customSettings:de(t)},{userId:async()=>T=await c.org.userId()});if(!S.allowed)return{undone:!1,refusal:S.refusal};let R=e.store.lock(t.org.organizationId,"undo",t.checkpointId);if("busy"in R)return{undone:!1,refusal:Xe(r,R.busy)};try{let U=await e.runWriting?.(S.org.id);if(U!==void 0)return Qe("RUN_WRITING",U);let k=await Ie(c.org,r);if(h())throw new C;b(5,"Reading what the rewind did");let g=await Ne(a,i,t.objects),G=Pe(g),M=g.goesWithParent.objects,Ge=g.remade.keys.size>0?"Sending back to the recycle bin what the rewind brought back, and deleting again what it made again":"Sending back to the recycle bin what the rewind brought back",A=o=>o.filter(u=>u.count>0).map(u=>u.objectApiName),j=g.links,q=o=>o>0?[_]:[],N=g.remade.objects.filter(({objectApiName:o,count:u})=>u>0&&ge([o]).length>0),m={bringBack:A(g.bringBack.objects),giveBack:[...A(g.giveBack.objects),...q(j?.share.count??0)],...N.length>0?{setToDraft:A(N)}:{},delete:[...new Set([...A(M),...A(g.remove.objects),...q(j?.remove.count??0)])],...(j?.reinsert.count??0)>0?{recreate:[_]}:{}},H;try{H=await et(c.org,g)}finally{await g.dispose()}let V=ve("undo",H,k.fileStorage?.remaining,r);if(V)return{undone:!1,refusal:V};let w=[...new Set([...m.bringBack??[],...m.giveBack??[],...m.setToDraft??[],...m.delete??[],...m.recreate??[]])],P;try{P=await De({grants:S.grants,...T!==void 0?{userId:T}:{},username:n.username,checkpoint:t,reader:Ce(c.org,l)})}catch(o){throw o instanceof Oe||h()?new C:o}if(P.kind==="perObject"){let o=await je(a,i),u=Ye(P,{users:o.passes.map(f=>f.userId),objects:w},n.username);if(u)return{undone:!1,refusal:u}}let d;if(w.length>0&&e.readAutomation){try{d=await e.readAutomation(w)}catch(o){d=Le(w,x(o))}c.add(d.requests)}let I=d,y=w.length>0?await We(e.mute,d,m):{},$="refusal"in y?y:void 0,J="refusal"in y?void 0:y.mute;y.automation&&(d=y.automation);let v=$?$.plan:J?.plan,K=n.acceptEmails===!0,p=w.length>0&&I?await Re({act:"undo",orgName:r,automation:I,steps:m,...v?{plan:v}:{},accepted:K,mayMute:e.mute===void 0&&n.canMute===!0,read:()=>me(c.org)}):void 0,Y=he(G,M,N),Q=d?we(Y,d):void 0,O=$?[$.refusal]:[];d&&!n.acceptAutomation&&(W(d,m).length>0||se(d.unread)||Q!==void 0)&&O.push(Ze(r,d,m,Q));let X=Ue({objects:t.objects,rewound:G,along:M,automationRequests:0}),Z=Ee(p?.ofRun),ee=$e("undo",{run:c.used()-(Z.deliverability??0)+X.apiRequests,...Z},k,r);w.length>0&&ee&&O.push(ee);let te=d?be("undo",ye(Y,d,k.emails),r):void 0;w.length>0&&te&&O.push(te),p?.refusal&&O.push(p.refusal);let[ne,...oe]=O;if(ne)return{undone:!1,refusal:ne,...oe.length>0?{alsoRefused:oe}:{}};if(h())throw new C;let qe=await c.org.userId(),He=new Set(Te(t.takenBy,qe).map(ze));b(20,"Bringing back what the rewind deleted and giving back what it wrote over");let B,E;try{E=await xe(J,`undo ${t.checkpointId} ${i}`,o=>{let u=o&&v&&I&&p?Ae({act:"undo",orgName:r,automation:I,steps:m,plan:v,held:o.outcome,planned:p.ofRun.senders,...p.ofRun.read?{reading:p.ofRun.read.reading}:{},accepted:K}):void 0;return u?Promise.resolve({relit:u}):Fe({folder:a,rewindId:i,lock:R.lock,objects:t.objects,org:c.org,undelete:c.undelete,splitting:le(fe(k.remaining,c.used()+X.apiRequests)),...l?{signal:l}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},onProgress:(f,ae,Ve)=>b(20+Math.round(70*f/Math.max(ae,1)),`${Ge}: ${Ve} ${f} / ${ae}`)})},o=>{B=o})}catch(o){if(!pe(o))throw o;return{undone:!1,refusal:{code:"MUTE",message:`${o.message} No record was written.`}}}if("relit"in E)return{undone:!1,refusal:E.relit};let s=E,re=nt(s.residual,He),D=tt(s,re),F=[...s.notes];if(D!=="cancelled"&&D!=="failure"){let o=(e.now??(()=>new Date))().toISOString();try{await e.store.update(t.checkpointId,f=>f.lastRewind?.rewindId===i?{...f,lastRewind:{...f.lastRewind,undoneAt:o}}:f)}catch(f){F.push(`The checkpoint could not be told the rewind was undone (${x(f)}): its list may still offer to undo it.`)}let u=await Be({folder:a,lock:R.lock,checkpoint:t,rewindId:i,status:D,undoneAt:o});u!==void 0&&F.push(u)}let ie=c.used();return{undone:!0,result:{checkpointId:t.checkpointId,rewindId:i,status:D,deleted:s.deleted,...s.remade?{remade:s.remade}:{},...s.carriedAlone?{carriedAlone:s.carriedAlone}:{},...s.wentAlong?{wentAlong:s.wentAlong}:{},restored:s.restored,undeleted:s.undeleted,...s.files?{files:s.files}:{},residual:re,passes:1,apiRequests:{used:ie,leftToday:Math.max(0,k.remaining-ie)},finishedAt:s.finishedAt,...B?{mutedAutomation:B}:{}},notes:F,...p?.gate.audit!==void 0?{deliverability:p.gate.audit}:{}}}finally{R.lock.release()}}export{C as a,Je as b,Ot as c};
7
+ import{a as je,b as Ne,c as Pe,d as Fe,k as We,l as xe,o as Le,q as _e}from"./chunk-UNJA4J37.mjs";import{e as Me}from"./chunk-XLXIPIEW.mjs";import{b as De,f as Te}from"./chunk-TTKXMDBN.mjs";import{m as Be}from"./chunk-TSLJUSLW.mjs";import{b as Se}from"./chunk-OAZRPP4I.mjs";import{i as he,j as we,k as ke,l as ye,m as be,p as Re,q as Ae}from"./chunk-NZC67CGR.mjs";import{A as Ie,B as $e,C as ve,z as Ue}from"./chunk-F43REJDZ.mjs";import{$ as Ce,C as ge,_ as Oe}from"./chunk-JPUR2CFX.mjs";import{a as le,b as fe}from"./chunk-SAR5622P.mjs";import{t as pe}from"./chunk-MFG4MUIO.mjs";import{b as ue,d as ce}from"./chunk-GSKCGQIP.mjs";import{Ba as Ee,s as me}from"./chunk-VYXMVJL5.mjs";import{g as L,h as _,q as de}from"./chunk-JWTSEDIQ.mjs";import{b as x}from"./chunk-CA5NAXSU.mjs";import{Nc as se,Vc as W}from"./chunk-TTFDUKUS.mjs";var C=class extends Error{constructor(){super("The undo was stopped before it wrote anything to the org."),this.name="UndoStopped"}},z="No record was written.",Je="accept that it runs to undo the rewind all the same";function ze(e){return e.slice(0,15)}function Ke(e){return{query:n=>e.query(n),queryMore:n=>e.queryMore(n)}}function Ye(e,n,t){if(e.kind==="org")return;let a=e.userKey;if(n.users.some(i=>i.slice(0,15)!==a))return{code:"PERMISSIONS",message:`This rewind was made as another user than ${t}: what it deleted is that user's deletion in the recycle bin, which Salesforce brings back only for a user with View All Data and Modify All Data. Undo it as the user it was made as, or as a user with View All Data and Modify All Data. ${z}`};let r=n.objects.flatMap(i=>{let l=e.notHeld.get(i);return l===void 0?[]:[`${i}: ${l}`]});if(r.length!==0)return{code:"PERMISSIONS",message:`Undo takes back what the rewind did to objects ${t} no longer holds whole (${r.join("; ")}), and does not stop part way: an undo left part way could not be offered again. Undo it once the user has View All and Modify All on them again, or as a user with View All Data and Modify All Data. ${z}`}}function Qe(e,n){return{undone:!1,refusal:{code:e,message:n}}}function Xe(e,n){return{code:"RUN_WRITING",message:`${n.operation==="take"?`A checkpoint of ${e} is being taken`:n.operation==="rewind"?`A rewind is writing to ${e}`:n.operation==="undo"?`An undo is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${n.pid} on ${n.host}): undo the rewind once it has ended. No record was read or written.`}}function Ze(e,n,t,a){let r=W(n,t),i=[...new Set(r.map(b=>b.objectApiName))],l=(t.setToDraft??[]).length>0?", sets an order back to Draft":"",h=r.length>0?`${Me(r)} flow(s), trigger(s) or rule(s) of ${i.join(", ")} run as the undo brings records back, gives them their values back${l} or sends them back to the recycle bin`:"what runs as the undo writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${e}: ${h}. ${ke("undo",a)}Undo refused; ${Je}. ${z}`}}async function et(e,n){let t=0,a=0;for await(let r of n.bringBack.pages(L)){t+=r.length;for(let i of ce(r,ue)){let l=await e.queryDeleted(`SELECT Id, ContentSize FROM ${L} WHERE Id IN (${i}) AND IsDeleted = true`);for(let h of l.records)typeof h.ContentSize=="number"&&(a+=h.ContentSize)}}return{files:t,bytes:a}}function tt(e,n){return e.status==="cancelled"||e.status==="failure"?e.status:n.some(t=>t.reason==="changedDuringRewind")?"unstable":e.status}function nt(e,n){return e.map(t=>{let a=Object.keys(t.by).filter(i=>!n.has(ze(i)));if(a.length===0)return{objectApiName:t.objectApiName,reason:"automation",count:t.count,ids:[...t.ids]};let r=a.length===1&&a[0]!=="unknown"?a[0]:void 0;return{objectApiName:t.objectApiName,reason:"changedDuringRewind",...r!==void 0?{by:r}:{},count:t.count,ids:[...t.ids]}})}async function Ot(e,n){let{checkpoint:t,folder:a,orgName:r,rewindId:i}=n,l=e.signal,h=()=>l?.aborted===!0,b=(U,k)=>e.onProgress?.({percentage:U,step:k}),c=_e(e.org,e.undelete),T,S=await Se(Ke(c.org),{act:"undo",orgName:r,registered:n.registered,username:n.username,organizationId:t.org.organizationId,customSettings:de(t)},{userId:async()=>T=await c.org.userId()});if(!S.allowed)return{undone:!1,refusal:S.refusal};let R=e.store.lock(t.org.organizationId,"undo",t.checkpointId);if("busy"in R)return{undone:!1,refusal:Xe(r,R.busy)};try{let U=await e.runWriting?.(S.org.id);if(U!==void 0)return Qe("RUN_WRITING",U);let k=await Ie(c.org,r);if(h())throw new C;b(5,"Reading what the rewind did");let g=await Ne(a,i,t.objects),G=Pe(g),M=g.goesWithParent.objects,Ge=g.remade.keys.size>0?"Sending back to the recycle bin what the rewind brought back, and deleting again what it made again":"Sending back to the recycle bin what the rewind brought back",A=o=>o.filter(u=>u.count>0).map(u=>u.objectApiName),j=g.links,q=o=>o>0?[_]:[],N=g.remade.objects.filter(({objectApiName:o,count:u})=>u>0&&ge([o]).length>0),m={bringBack:A(g.bringBack.objects),giveBack:[...A(g.giveBack.objects),...q(j?.share.count??0)],...N.length>0?{setToDraft:A(N)}:{},delete:[...new Set([...A(M),...A(g.remove.objects),...q(j?.remove.count??0)])],...(j?.reinsert.count??0)>0?{recreate:[_]}:{}},H;try{H=await et(c.org,g)}finally{await g.dispose()}let V=ve("undo",H,k.fileStorage?.remaining,r);if(V)return{undone:!1,refusal:V};let w=[...new Set([...m.bringBack??[],...m.giveBack??[],...m.setToDraft??[],...m.delete??[],...m.recreate??[]])],P;try{P=await De({grants:S.grants,...T!==void 0?{userId:T}:{},username:n.username,checkpoint:t,reader:Ce(c.org,l)})}catch(o){throw o instanceof Oe||h()?new C:o}if(P.kind==="perObject"){let o=await je(a,i),u=Ye(P,{users:o.passes.map(f=>f.userId),objects:w},n.username);if(u)return{undone:!1,refusal:u}}let d;if(w.length>0&&e.readAutomation){try{d=await e.readAutomation(w)}catch(o){d=Le(w,x(o))}c.add(d.requests)}let I=d,y=w.length>0?await We(e.mute,d,m):{},$="refusal"in y?y:void 0,J="refusal"in y?void 0:y.mute;y.automation&&(d=y.automation);let v=$?$.plan:J?.plan,K=n.acceptEmails===!0,p=w.length>0&&I?await Re({act:"undo",orgName:r,automation:I,steps:m,...v?{plan:v}:{},accepted:K,mayMute:e.mute===void 0&&n.canMute===!0,read:()=>me(c.org)}):void 0,Y=he(G,M,N),Q=d?we(Y,d):void 0,O=$?[$.refusal]:[];d&&!n.acceptAutomation&&(W(d,m).length>0||se(d.unread)||Q!==void 0)&&O.push(Ze(r,d,m,Q));let X=Ue({objects:t.objects,rewound:G,along:M,automationRequests:0}),Z=Ee(p?.ofRun),ee=$e("undo",{run:c.used()-(Z.deliverability??0)+X.apiRequests,...Z},k,r);w.length>0&&ee&&O.push(ee);let te=d?be("undo",ye(Y,d,k.emails),r):void 0;w.length>0&&te&&O.push(te),p?.refusal&&O.push(p.refusal);let[ne,...oe]=O;if(ne)return{undone:!1,refusal:ne,...oe.length>0?{alsoRefused:oe}:{}};if(h())throw new C;let qe=await c.org.userId(),He=new Set(Te(t.takenBy,qe).map(ze));b(20,"Bringing back what the rewind deleted and giving back what it wrote over");let B,E;try{E=await xe(J,`undo ${t.checkpointId} ${i}`,o=>{let u=o&&v&&I&&p?Ae({act:"undo",orgName:r,automation:I,steps:m,plan:v,held:o.outcome,planned:p.ofRun.senders,...p.ofRun.read?{reading:p.ofRun.read.reading}:{},accepted:K}):void 0;return u?Promise.resolve({relit:u}):Fe({folder:a,rewindId:i,lock:R.lock,objects:t.objects,org:c.org,undelete:c.undelete,splitting:le(fe(k.remaining,c.used()+X.apiRequests)),...l?{signal:l}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},onProgress:(f,ae,Ve)=>b(20+Math.round(70*f/Math.max(ae,1)),`${Ge}: ${Ve} ${f} / ${ae}`)})},o=>{B=o})}catch(o){if(!pe(o))throw o;return{undone:!1,refusal:{code:"MUTE",message:`${o.message} No record was written.`}}}if("relit"in E)return{undone:!1,refusal:E.relit};let s=E,re=nt(s.residual,He),D=tt(s,re),F=[...s.notes];if(D!=="cancelled"&&D!=="failure"){let o=(e.now??(()=>new Date))().toISOString();try{await e.store.update(t.checkpointId,f=>f.lastRewind?.rewindId===i?{...f,lastRewind:{...f.lastRewind,undoneAt:o}}:f)}catch(f){F.push(`The checkpoint could not be told the rewind was undone (${x(f)}): its list may still offer to undo it.`)}let u=await Be({folder:a,lock:R.lock,checkpoint:t,rewindId:i,status:D,undoneAt:o});u!==void 0&&F.push(u)}let ie=c.used();return{undone:!0,result:{checkpointId:t.checkpointId,rewindId:i,status:D,deleted:s.deleted,...s.remade?{remade:s.remade}:{},...s.carriedAlone?{carriedAlone:s.carriedAlone}:{},...s.wentAlong?{wentAlong:s.wentAlong}:{},restored:s.restored,undeleted:s.undeleted,...s.files?{files:s.files}:{},residual:re,passes:1,apiRequests:{used:ie,leftToday:Math.max(0,k.remaining-ie)},finishedAt:s.finishedAt,...B?{mutedAutomation:B}:{}},notes:F,...p?.gate.audit!==void 0?{deliverability:p.gate.audit}:{}}}finally{R.lock.release()}}export{C as a,Je as b,Ot as c};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{p as re,q as De}from"./chunk-AEKONPF4.mjs";import{A as Fe,T as Ne,va as Ie}from"./chunk-CION3VMZ.mjs";import{a as _e,b as Me}from"./chunk-HF6LAK3G.mjs";import{j as xe,k as ve,l as Ce,m as $e,n as je}from"./chunk-L77FJZEP.mjs";import{D as $,Z as Te,b as C,ca as Pe,p as W,q as G,s as ne}from"./chunk-A527W53V.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{$c as Ee,Kc as be,Mc as ye,Oc as ee,Pc as we,Rc as x,Sc as Re,Tc as te,Vc as L,_c as Ae,bd as Se,ec as Z,ed as v,kd as Be,l as pe,md as Oe,nd as ke,r as he}from"./chunk-TTFDUKUS.mjs";import{b as Q,e as w,f as D,k as fe,l as b}from"./chunk-7EANH5PY.mjs";import{createHash as vt}from"node:crypto";var Le="lineage:runs",Tt="lineage";function We(e){let t=e.objects.filter(i=>i.records>0);if(t.length===0)return null;let n="source",r="target",o=[{id:n,type:"source",label:e.source.label,origin:e.source.origin,...e.source.orgId?{orgId:e.source.orgId}:{}}],s=[];for(let i of t){let u=`object:${i.objectApiName}`;o.push({id:u,type:"object",label:i.objectApiName,objectApiName:i.objectApiName,recordCount:i.records}),s.push({sourceId:n,targetId:u}),s.push({sourceId:u,targetId:r,recordCount:i.records})}return o.push({id:r,type:"destination",label:e.target.label,orgId:e.target.orgId,origin:"org"}),{nodes:o,edges:s,operationId:e.operationId,generatedAt:e.generatedAt,module:e.module,action:e.action}}var U=class{constructor(t,n=100){this.configStore=t;this.limit=n}configStore;limit;save(t){let n=this.read().filter(r=>r.operationId!==t.operationId);n.push(t),this.configStore.set(Le,n.slice(-this.limit),Tt)}get(t){let n=this.read();return t===void 0?n[n.length-1]??null:n.find(r=>r.operationId===t)??null}runs(){return this.read().reverse().map(t=>({operationId:t.operationId,generatedAt:t.generatedAt,...t.module?{module:t.module}:{},...t.action?{action:t.action}:{},...Pt(t)}))}read(){let t=this.configStore.get(Le);return Array.isArray(t)?t.filter(xt):[]}};function Pt(e){let t=e.nodes.find(n=>n.type==="destination");return t?{targetLabel:t.label}:{}}function xt(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.operationId=="string"&&typeof t.generatedAt=="string"&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}var Ct=100,Ge="audit:trail",$t="audit",oe=class{constructor(t,n=he){this.configStore=t;this.limit=n}configStore;limit;append(t){let n=this.read();n.push(t),this.configStore.set(Ge,n.slice(-this.limit),$t)}list(t={}){let n=this.read().reverse(),r=n.filter(i=>(t.module===void 0||i.module===t.module)&&(t.orgId===void 0||i.orgId===t.orgId)),o=t.offset??0,s=t.limit??Ct;return{entries:r.slice(o,o+s),total:r.length,offset:o,facets:jt(n)}}read(){let t=this.configStore.get(Ge);return Array.isArray(t)?t.filter(Ft):[]}};function jt(e){let t=new Set,n=new Map;for(let r of e)t.add(r.module),r.orgId!==void 0&&!n.has(r.orgId)&&n.set(r.orgId,r.orgAlias);return{modules:[...t].sort(),orgs:[...n].map(([r,o])=>o?{orgId:r,orgAlias:o}:{orgId:r})}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.action=="string"&&typeof t.module=="string"&&typeof t.timestamp=="string"}var Lr="ABORTED_BEFORE_START";function _t(e){let t=e?.trim().toLowerCase();if(t)return`sha256:${vt("sha256").update(t).digest("hex").slice(0,12)}`}function Wr(e,t,n=new Date){try{let r=e.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1;if(!r&&t.outcome==="stopped"&&t.code===void 0)return;let o=n.toISOString(),s=e.orgManager.getOrg(t.orgId),i=s?Z(s):void 0,u=_t(s?.username),a=t.source?.origin==="org"?t.source.orgId:void 0,d=a!==void 0?e.orgManager.getOrg(a):void 0,l=d?Z(d):void 0,c=t.objects??[];if(new oe(e.configStore).append({id:crypto.randomUUID(),action:t.action,module:t.module,orgId:t.orgId,...i?{orgAlias:i}:{},...a!==void 0?{sourceOrgId:a}:{},...l?{sourceOrgAlias:l}:{},operationId:t.operationId,outcome:t.outcome,...r&&t.guard?{guard:t.guard}:{},objects:[...c],...t.leftBy?{leftBy:t.leftBy}:{},...u?{userId:u}:{},...t.context?{context:t.context}:{},...t.verdict?{verdict:t.verdict}:{},...t.muted?{muted:t.muted}:{},...t.checkpointId?{checkpointId:t.checkpointId}:{},...t.beforeRun?{beforeRun:{...t.beforeRun}}:{},...t.fit?{fit:{...t.fit}}:{},details:{...t.details,...t.code?{code:t.code}:{}},timestamp:o}),!t.source)return;let g=We({operationId:t.operationId,module:t.module,action:t.action,source:t.source.origin==="org"?{origin:"org",orgId:t.source.orgId,label:l??t.source.orgId}:{origin:t.source.origin,label:t.source.label??""},target:{label:i??t.orgId,orgId:t.orgId},objects:Mt(c,t.carried),generatedAt:o});g&&new U(e.configStore).save(g)}catch(r){e.log(`[WARN] audit trail: run ${t.operationId} was not recorded \u2014 ${R(r)}`)}}function Mt(e,t){return t?Object.entries(t).map(([n,r])=>({objectApiName:n,records:r})):e.map(n=>({objectApiName:n.objectApiName,records:n.created+n.updated+(n.upserted??0)}))}function Ue(e){return{objectApiName:e,created:0,updated:0,deleted:0,failed:0}}var Nt="__pass2__";function qe(e){let t=e.errors??[],n=t.some(s=>s.skipped===!0),r=t.some(s=>s.objectApiName===Nt&&s.failedCount>0);return e.failedCount===0&&e.failedReads.length===0&&!n&&!r?"success":e.successCount+e.updatedCount+e.linkedCount+(e.wouldInsertCount??0)>0?"partial":"failure"}function Ur(e,t,n){return{forgeId:`forge-${Date.now()}`,status:n.status,graph:t,duration:Date.now()-n.startedAt,timestamp:new Date().toISOString(),idRemapCount:e.remapCount,idRemapTable:e.remapTable,idRemapExisting:e.existingSourceIds,...e.withTheirRecordSourceIds?{idRemapWithTheirRecord:e.withTheirRecordSourceIds}:{},...e.withTheirRecordCount!==void 0&&e.withTheirRecordCount>0?{withTheirRecordCount:e.withTheirRecordCount}:{},...e.linkedToCreatedCount!==void 0&&e.linkedToCreatedCount>0?{linkedToCreatedCount:e.linkedToCreatedCount}:{},createdCount:e.successCount,...e.updatedCount>0?{updatedCount:e.updatedCount}:{},linkedExistingCount:e.linkedCount,existingRecords:e.existingRecords,idRemapByObject:e.remapByObject,idRemapCreated:e.createdByObject,readByObject:e.readByObject,failedReads:e.failedReads,errors:e.errors,truncatedObjects:e.truncatedObjects,...e.cappedObjects?{cappedObjects:e.cappedObjects}:{},...e.fieldExclusionsUnmatched?{fieldExclusionsUnmatched:e.fieldExclusionsUnmatched}:{},...e.orphanParentsCapped?{orphanParentsCapped:e.orphanParentsCapped}:{},...e.files?{files:e.files}:{},...e.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:e.fileContentFieldsLeftOut}:{},...e.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:e.encryptedFieldsLeftOut}:{},...e.picklistValuesChanged?{picklistValuesChanged:e.picklistValuesChanged}:{},...e.currenciesReplaced?{currenciesReplaced:e.currenciesReplaced}:{},...e.recordTypesGiven?{recordTypesGiven:e.recordTypesGiven}:{},...e.writtenWithoutFields?{writtenWithoutFields:e.writtenWithoutFields}:{},...e.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:e.lookupsLeftEmptyByFilter}:{},...e.contactPoints?{contactPoints:e.contactPoints}:{},...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.apiCalls!==void 0?{apiCalls:e.apiCalls}:{},...e.dryRun?{dryRun:!0,wouldInsertCount:e.wouldInsertCount}:{},...e.gaps?{gaps:e.gaps}:{},...e.decisionsApplied?{decisionsApplied:e.decisionsApplied}:{},...e.mayHaveBeenWritten?{mayHaveBeenWritten:e.mayHaveBeenWritten}:{},...e.remapInJournal?{remapInJournal:!0}:{},...e.sample?{sample:e.sample}:{}}}var ze="RUN_CANCELLED";function Vr(e){return{idRemapByObject:e.remapByObject,errors:e.errors,notSentByObject:e.notSentByObject,writtenWithoutFields:e.writtenWithoutFields,mayHaveBeenWritten:e.mayHaveBeenWritten}}function Kr(e){let t=new Map,n=r=>{let o=t.get(r)??Ue(r);return t.set(r,o),o};for(let r of e.idRemapByObject??[]){let o=n(r.objectApiName);o.created+=r.created,o.updated+=r.updated??0}for(let r of e.errors??[]){if(r.objectApiName.startsWith("__")||r.referenceData===!0||r.stage==="scope"&&r.failedCount===0&&r.skipped!==!0)continue;let o=n(r.objectApiName);o.failed+=r.failedCount,r.skipped===!0&&(o.skipped=r.failedCount>0?"counted":"uncounted")}for(let r of e.notSentByObject??[]){let o=n(r.objectApiName);o.notSent=(o.notSent??0)+r.notSent}for(let r of e.writtenWithoutFields??[]){let o=n(r.objectApiName);o.writtenWithoutFields=(o.writtenWithoutFields??0)+r.rows}for(let{objectApiName:r,sourceIds:o}of e.mayHaveBeenWritten??[]){let s=n(r);s.mayHaveBeenWritten=(s.mayHaveBeenWritten??0)+o.length}return[...t.values()]}function Xr(e,t){return t.some(r=>r.created+r.updated>0)?"cancelled":(e?qe(e):"success")==="success"?"stopped":"cancelled"}function Yr(e){return e?{details:{contactPoints:e.neutralized?"neutralized":"kept",contactPointFields:e.fields.length,contactPointValues:e.values}}:{}}function Jr(e){return Object.fromEntries((e.idRemapByObject??[]).map(t=>[t.objectApiName,t.created+t.linked+(t.updated??0)]))}var j=class extends Error{operation;timeoutMs;constructor(t,n){super(`Operation "${t}" timed out after ${n}ms`),this.name="TimeoutError",this.operation=t,this.timeoutMs=n}},q=class{defaultTimeoutMs;constructor(t=3e4){this.defaultTimeoutMs=t}async withTimeout(t,n,r){let o=r??this.defaultTimeoutMs,s=new AbortController;return new Promise((i,u)=>{let a=setTimeout(()=>{s.abort(),u(new j(t,o))},o);n(s.signal).then(d=>{clearTimeout(a),i(d)},d=>{clearTimeout(a),u(d)})})}getDefaultTimeout(){return this.defaultTimeoutMs}};var lo=2e3,co=1e4,Dt=Be;function mo(e,t,n=Dt){let r=t!==void 0&&t>0?Math.floor(t):void 0;return r!==void 0&&r<=n?[]:e.nodes.filter(o=>o.included&&o.recordCountUnknown!==!0).map(o=>({objectApiName:o.objectApiName,rows:r===void 0?o.recordCount:Math.min(o.recordCount,r)})).filter(o=>o.rows>n).sort((o,s)=>s.rows-o.rows)}var tt=.8,N=1024,H=2*N,nt=4*N,Lt=8*N,Wt=1*N,Gt=4*N,Ut=255,qt=/__kav$/i,zt=new Map([C,W,G,"Campaign","CampaignMember"].map(e=>[e.toLowerCase(),e]));function V(e){return zt.get(e.toLowerCase())??e}function He(e,t=0){let n=0;for(let r of Object.values(e))typeof r=="string"&&r.length>t&&(n+=Buffer.byteLength(r,"utf8"));return n}function ie(e,t){let n=V(e);return n===C?He(t):n===W?ne(t)?nt:H:n===G&&ne(t)?0:n==="Campaign"?Lt:n==="CampaignMember"?Wt:qt.test(e)?Gt+He(t,Ut):H}function Ht(e,t){let n=Math.min(t.personAccounts??0,t.rows),r=t.rows-n,o=V(e);return o===W?r*H+n*nt:o===G?r*H:r*ie(e,{})}function Vt(e){let t=e.map(({objectApiName:m,rows:f,counted:p,mayAdd:h=0,mayBeByThePlatform:O})=>{let E={rows:h,storageBytes:h*ie(m,{}),...h>0?{mayAdd:h}:{},...O&&O.rows>0?{mayBeByThePlatform:O}:{}};return p?{objectApiName:m,...E,rows:p.rows+E.rows,storageBytes:Ht(m,p)+E.storageBytes}:{objectApiName:m,...E,rows:f.length+E.rows,storageBytes:f.reduce((J,kt)=>J+ie(m,kt),0)+E.storageBytes}}).filter(({rows:m})=>m>0).sort((m,f)=>f.rows-m.rows||m.objectApiName.localeCompare(f.objectApiName)),n=e.reduce((m,f)=>m+(f.leftOut?.writtenBefore??0),0),r=e.filter(m=>(m.leftOut?.heldBack??0)>0).map(({objectApiName:m,leftOut:f})=>({objectApiName:m,rows:f?.heldBack??0})),o=e.filter(m=>(m.leftOut?.byThePlatform??0)>0).map(({objectApiName:m,leftOut:f})=>({objectApiName:m,rows:f?.byThePlatform??0})),s=e.flatMap(({objectApiName:m,leftOut:f})=>f?.linkedByValue&&f.linkedByValue.rows>0?[{objectApiName:m,...f.linkedByValue}]:[]),i=m=>e.filter(f=>(f.leftOut?.[m]??0)>0).map(({objectApiName:f,leftOut:p})=>({objectApiName:f,rows:p?.[m]??0})),u=i("recordTypeNotInTarget"),a=i("withoutParent"),d=i("noParentInSource"),l=i("outsideFilter"),c=i("linkedToTarget"),g=i("currencyReplaced");return{objects:t,totalRows:t.reduce((m,f)=>m+f.rows,0),storageBytes:t.reduce((m,f)=>m+f.storageBytes,0),...n>0||r.length>0||u.length>0||o.length>0||s.length>0||a.length>0||d.length>0||l.length>0||c.length>0||g.length>0?{leftOut:{writtenBefore:n,heldBack:r,...u.length>0?{recordTypeNotInTarget:u}:{},...o.length>0?{byThePlatform:o}:{},...s.length>0?{linkedByValue:s}:{},...a.length>0?{withoutParent:a}:{},...d.length>0?{noParentInSource:d}:{},...l.length>0?{outsideFilter:l}:{},...c.length>0?{linkedToTarget:c}:{},...g.length>0?{currencyReplaced:g}:{}}}:{}}}function go(e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null])}var Kt=16,Ve=class{kept=new Map;note(t,n,r=Date.now()){this.kept.delete(t),this.kept.set(t,{at:r,total:n.totalRows,objects:n.objects.map(({objectApiName:o,rows:s})=>({objectApiName:o,rows:s}))});for(let o of this.kept.keys()){if(this.kept.size<=Kt)break;this.kept.delete(o)}}of(t){return this.kept.get(t)}},Xt=500;function Yt(e,t){return e>2*t||e-t>Xt}function fo(e,t,n=Date.now()){return{minutesBefore:Math.max(1,Math.ceil((n-e.at)/6e4)),total:e.total,objects:e.objects.map(({objectApiName:r,rows:o})=>({objectApiName:r,rows:o})),...Yt(t,e.total)?{farAbove:!0}:{}}}function po(e){let t=e.objects.reduce((n,r)=>n+(r.mayAdd??0),0);return t>0?{pricesForLines:t}:{}}function ho(e){let t=e.objects.find(n=>n.mayBeByThePlatform)?.mayBeByThePlatform;return!t||t.rows<=0?{}:{rolesMayBeByThePlatform:{rows:t.rows,...t.before===!0?{before:!0}:{}}}}var z=b({Max:w(),Remaining:w()}).loose(),Jt=b({DataStorageMB:z,DailyApiRequests:z.optional(),DailyBulkApiBatches:z.optional(),FileStorageMB:z.optional()}).loose(),Qt=b({DailyApiRequests:b({Max:w(),Remaining:w()}).loose()}).loose(),Zt="the org does not tell this user its daily API requests";function rt(e,t,n){if(e!==null&&typeof e=="object"&&!(t in e))throw new Error(n)}async function en(e){let t=await e.request({method:"GET",url:"/limits"});rt(t,"DataStorageMB",pe);let n=Jt.parse(t);return{maxMB:n.DataStorageMB.Max,remainingMB:n.DataStorageMB.Remaining,...n.DailyApiRequests?{dailyApiRequests:{max:n.DailyApiRequests.Max,remaining:n.DailyApiRequests.Remaining}}:{},...n.DailyBulkApiBatches?{dailyBulkApiBatches:{max:n.DailyBulkApiBatches.Max,remaining:n.DailyBulkApiBatches.Remaining}}:{},...n.FileStorageMB?{fileStorage:{maxMB:n.FileStorageMB.Max,remainingMB:n.FileStorageMB.Remaining}}:{}}}async function Ke(e){let t=await e.request({method:"GET",url:"/limits"});rt(t,"DailyApiRequests",Zt);let n=Qt.parse(t);return{max:n.DailyApiRequests.Max,remaining:n.DailyApiRequests.Remaining}}var ae=200,ot=2e3,tn=.1;function nn(e){return e.reduce((t,{rows:n,bulk:r,readRows:o,perCall:s})=>{let i=Math.min(ae,Math.max(1,s??ae)),u=n<=0?0:r?je(n):Math.ceil(n/i),a=o&&o>0?Math.ceil(o/ot):0;return t+u+a},0)}var le=["checkpoint","mute","readBack","deliverability","fit"],rn={checkpoint:"for the checkpoint taken first",mute:"to assign and take back the permission sets that mute the target's automation",readBack:"to read back the record types the target gave",deliverability:"to read whether the target delivers its emails",fit:"to fit the run to the storage"};function on(e){return le.reduce((t,n)=>t+Math.max(0,e[n]??0),e.run)}function sn(e){return le.some(t=>(e[t]??0)>0)?{...e}:void 0}function se(e,t){let n=typeof e=="number"?void 0:sn(e),r=typeof e=="number"?e:on(e),o=n?{parts:n}:{};if(!t)return{verdict:"unread",estimate:r,unread:"the limits the org answered list no DailyApiRequests",...o};if("unread"in t)return{verdict:"unread",estimate:r,unread:t.unread,...o};let{max:s,remaining:i}=t;return{verdict:r>i?"exceeds":i-r<tn*s?"near":"fits",estimate:r,max:s,remaining:i,...o}}function an(e){if(!e)return"";let t=le.filter(n=>(e[n]??0)>0).map((n,r)=>`${e[n]}${r===0?" of them":""} ${rn[n]}`);return t.length>0?` (${t.join(", ")})`:""}var F="API_BUDGET_EXCEEDED";function un(e,t,n){if(e.verdict==="exceeds")return`The run takes about ${e.estimate} API requests${an(e.parts)}, and ${t} has ${e.remaining} of its ${e.max} daily requests left: it would stop part way through, its records refused with REQUEST_LIMIT_EXCEEDED. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records. `+(n?`${n} `:"")+"Nothing was written."}function dn(e){return e.verdict==="near"?{apiRequests:{estimate:e.estimate,remaining:e.remaining,max:e.max,...e.parts?{parts:{...e.parts}}:{}}}:{}}var K="CHECKPOINT_REFUSED";function ln(e){return e?{checkpoint:e.estimate.apiRequests}:{}}function cn(e){let t=e?.refusal;if(t!==void 0)return{code:K,message:re(t),refusal:t}}var mn="The run was stopped while it took the checkpoint first: nothing of it was kept, and nothing was written.";async function bo(e){let t;try{t=await e()}catch(n){return{stop:{code:K,message:De(n)}}}return t.taken?{checkpoint:t.checkpoint}:"stopped"in t?{stop:{code:ze,message:mn}}:{stop:{code:K,message:re(t.refusal),refusal:t.refusal}}}var Xe=1e4,gn=1e4,fn=.01;function pn(e,t,n){return t<2e3||_e.has(e)||(n??Me).has(e)}function X(e,t,n){if(t<=0)return{jobs:[],rest:0};if(pn(e,t,n.restOnly))return{jobs:[],rest:t};let r=[];for(let o=t;o>0;o-=Xe){let s=Math.min(o,Xe);if(s<2e3)return{jobs:r,rest:s};r.push(s)}return{jobs:r,rest:0}}function hn(e){return ve({stateReads:$e(e,xe,"save")})}function bn(e,t,n){let{jobs:r,rest:o}=X(e,t,n);return r.reduce((s,i)=>s+hn(i),0)+Math.ceil(o/ae)}var yn=4,wn=3;function Rn(e){let t=new Set(e.updatedAfterInsert??[]),n=new Map((e.plan.leftOut?.linkedByValue??[]).map(({objectApiName:a,rows:d})=>[a,d])),r=[...e.plan.objects.map(({objectApiName:a,rows:d})=>({objectApiName:a,rows:d+(n.get(a)??0)})),...[...n].filter(([a])=>!e.plan.objects.some(d=>d.objectApiName===a)).map(([a,d])=>({objectApiName:a,rows:d}))],o=e.plan.objects.filter(({objectApiName:a})=>t.has(a)).map(({objectApiName:a,rows:d})=>({objectApiName:a,rows:d})),{bulk:s}=e,i=e.files!==void 0&&e.files>0?e.files:0,u=s?yn*r.filter(({rows:a})=>a>0).length:0;return{run:(s?[...r,...o].reduce((a,{objectApiName:d,rows:l})=>a+bn(d,l,s),0):nn([...r,...o]))+i+u+Math.max(0,e.sentBefore??0),...ln(e.checkpoint),...e.mute!==void 0&&e.mute>0?{mute:e.mute}:{},...e.readBack!==void 0&&e.readBack>0?{readBack:e.readBack}:{},...e.deliverability!==void 0&&e.deliverability>0?{deliverability:e.deliverability}:{}}}var An=200;function En(e){let t={...e.measures.restOnly?{restOnly:e.measures.restOnly}:{}},n=new Set(e.updatedAfterInsert??[]),r=e.plan.objects.map(({objectApiName:u,rows:a})=>({objectApiName:u,rows:a,writes:X(u,a,t),updates:n.has(u)?X(u,a,t):void 0})),o=r.flatMap(({writes:u,updates:a})=>a?[u,a]:[u]),s=e.measures.files,i=s&&"count"in s&&s.count>0?s.count:0;return{objects:r.map(({objectApiName:u,rows:a,writes:d})=>({objectApiName:u,rows:a,jobs:d.jobs.length})),sourceRequests:(e.measures.sourceReads??r.reduce((u,{rows:a})=>u+Math.ceil(Math.max(0,a)/ot),0)+i+Math.ceil(i/An))+wn*r.filter(({rows:u})=>u>0).length+(e.sourceSentBefore===void 0?Math.max(0,e.measures.heldReads??0):Math.max(0,e.sourceSentBefore)),bulkBatches:o.reduce((u,{jobs:a})=>u+a.reduce((d,l)=>d+Math.ceil(l/gn),0),0),durationSeconds:o.reduce((u,{jobs:a,rest:d})=>u+a.reduce((l,c)=>l+Ce(c,"save"),0)+d*fn,0),restObjects:r.filter(({rows:u,writes:a})=>u>0&&a.jobs.length===0).map(({objectApiName:u})=>u)}}var Sn="the limits the org answered list no DailyBulkApiBatches";function Bn(e,t){if(e.verdict==="exceeds")return`The run writes through Bulk API jobs that take about ${e.estimate} of the daily Bulk API batches, and ${t} has ${e.remaining} of its ${e.max} left: its jobs would be refused part way through. Run it once the org has batches to spare \u2014 the limit is counted over the last 24 hours, and Bulk API 1.0 shares it \u2014 or leave objects out. Nothing was written.`}function On(e,t){if(e.verdict==="exceeds")return`The run reads the source records in about ${e.estimate} API requests, and ${t} has ${e.remaining} of its ${e.max} daily requests left: the reads would stop part way through, and the org's own integrations with them. Run it once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or leave objects out. Nothing was written.`}function kn(e,t){if(e.verdict==="exceeds")return`The files to copy take about ${P(e.estimateMB)} MB of file storage, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB: leave out the objects whose files take it, turn the copy of files off on Review, or free file storage in ${t}. Nothing was written.`}function Tn(e,t){return`A clone of the whole org reads a few objects whole, and ${e.map(({objectApiName:r,rows:o})=>`${r} (${o} rows)`).join(", ")} ${e.length===1?"holds":"hold"} more than the ${t} rows of one object the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting or leave the object out on Review. Nothing was written.`}var Pn=200;function xn(e){if(!e||e.length===0)return;let t=Math.min(...e.map(r=>r.bound)),n=e.map(({objectApiName:r,rows:o})=>({objectApiName:r,rows:o}));return{code:"READ_BOUND_EXCEEDED",message:Tn(n,t),readBound:{bound:t,objects:n.slice(0,Pn)}}}var st="FILES_UNREAD",it="FILE_STORAGE_UNREAD";function vn(e,t,n){if(!e)return{};if("unmeasured"in e)return{files:{unmeasured:!0},stop:{code:st,message:`The source would neither sum nor list its files, so what they take of the file storage ${n} has left is not known: turn the copy of files off on Review, or run it again once the source answers. Nothing was written.`}};if(e.count<=0)return{};let r=at({storageBytes:e.bytes},"unread"in t?t:t.fileStorage??{unread:"the limits the org answered list no FileStorageMB"});if(r.verdict==="unread")return{files:{count:e.count,check:r},stop:{code:it,message:`The file storage ${n} has left could not be read (${r.unread}), so the ${e.count} files to copy could not be checked against it: turn the copy of files off on Review, or run it again once the org answers. Nothing was written.`}};let o=kn(r,n);return{files:{count:e.count,check:r},...o!==void 0&&r.verdict==="exceeds"?{stop:{code:"STORAGE_EXCEEDED",message:o,storage:{estimateMB:Number(P(r.estimateMB)),remainingMB:r.remainingMB,kind:"files"}}}:{}}}function Cn(e){let t=e.wholeOrg,n=t?.measures.files,r=se(Rn({...e,...t?{bulk:t.measures.restOnly?{restOnly:t.measures.restOnly}:{},...n&&"count"in n?{files:n.count}:{}}:{}}),e.budget),o=un(r,e.target),s=[],i=cn(e.checkpoint);i&&s.push(i),o!==void 0&&s.push({code:F,message:o,...t&&r.verdict==="exceeds"?{api:{kind:"requests",org:"target",estimate:r.estimate,remaining:r.remaining}}:{}});let u;if(t){let c=En({...e,measures:t.measures,...t.sourceSentBefore!==void 0?{sourceSentBefore:t.sourceSentBefore}:{}}),g=c.bulkBatches>0?se(c.bulkBatches,t.bulkBatches??{unread:Sn}):void 0,m=g&&Bn(g,e.target);m!==void 0&&g?.verdict==="exceeds"&&s.push({code:F,message:m,api:{kind:"bulkBatches",org:"target",estimate:g.estimate,remaining:g.remaining}});let f=se(c.sourceRequests,t.sourceBudget),p=On(f,t.source);p!==void 0&&f.verdict==="exceeds"&&s.push({code:F,message:p,api:{kind:"requests",org:"source",estimate:f.estimate,remaining:f.remaining}}),u={source:f,...g?{bulkBatches:g}:{},cost:c}}let[a,...d]=s,l=d.filter(c=>c.code===F);return{api:r,...a?{stop:a}:{},...t&&l.length>0?{alsoRefused:l}:{},...u?{wholeOrg:u}:{},asks:e.checkpoint!==void 0||t!==void 0,confirmation:{...dn(r),...e.checkpoint?{checkpoint:e.checkpoint}:{}}}}function at(e,t,n=0){let r=Math.max(0,n),o=e.storageBytes+r,s=o/1048576,i=r>0?{automationMB:r/1048576}:{};if("unread"in t)return{verdict:"unread",estimateMB:s,unread:t.unread,...i};let{maxMB:u,remainingMB:a}=t;return{verdict:o>a*1048576?"exceeds":o>tt*a*1048576?"near":"fits",estimateMB:s,maxMB:u,remainingMB:a,...i}}function $n(e,t){if(!t||t.length===0)return 0;let n=new Map;for(let{objectApiName:r,bytes:o}of t)n.set(r,(n.get(r)??0)+Math.max(0,o));return e.objects.reduce((r,{objectApiName:o,rows:s})=>r+s*(n.get(o)??0),0)}function ut(e){return`about ${P(e.estimateMB)} MB of data storage`+(e.automationMB!==void 0&&e.automationMB>0?`, about ${P(e.automationMB)} MB of it for what the target's automation creates under them`:"")}function jn(e,t){let n=Vt(e),r=t.emailTextBytes,o=e.some(i=>V(i.objectApiName)===C&&i.counted);if(r===void 0||!Number.isFinite(r)||!o)return n;let s=n.objects.map(i=>V(i.objectApiName)===C?{...i,storageBytes:i.storageBytes+Math.max(0,r)}:i);return{...n,objects:s,storageBytes:s.reduce((i,u)=>i+u.storageBytes,0)}}function Fn(e,t,n){return e.flatMap(({objectApiName:r,included:o,piiFields:s,anonymizeFields:i})=>{if(!o||!t.has(r))return[];let u=new Set(n?i:[]),a=s.filter(d=>!u.has(d));return a.length>0?[{objectApiName:r,fields:a}]:[]})}function _n(e){let t=e.leftOut??[],n=new Set(t.map(({objectApiName:s})=>s)),r=[...t,...e.nodes.filter(s=>s.leftOutByUser===!0&&!n.has(s.objectApiName)).map(({objectApiName:s})=>({objectApiName:s,reason:"excludedByUser"}))],o=new Map;for(let{reason:s}of r)o.set(s,(o.get(s)??0)+1);return{objects:r,counts:[...o].map(([s,i])=>({reason:s,count:i})).sort((s,i)=>i.count-s.count||s.reason.localeCompare(i.reason))}}var Mn=2;async function yo(e){let t=h=>({unread:R(h)}),n=jn(e.objects,e.measures),r=await en(e.target.limits).catch(t),o="unread"in r?await Ke(e.target.limits).catch(t):r.dailyApiRequests,s=await Ke(e.source.limits).catch(t),i=at(n,r,$n(n,e.automation)),u=pr(i,e.target.org),a=e.sample?Gn({sample:e.sample,storage:r,target:e.target.org}):void 0,d=vn(e.measures.files,r,e.target.org),l=e.sentBefore?.(),c=Cn({plan:n,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...e.readBack!==void 0?{readBack:e.readBack}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{},...e.mute!==void 0?{mute:e.mute}:{},deliverability:e.deliverability??Mn,...l?{sentBefore:l.target}:{},budget:o,target:e.target.org,wholeOrg:{measures:e.measures,bulkBatches:"unread"in r?r:r.dailyBulkApiBatches,sourceBudget:s,source:e.source.org,...l?.source!==void 0?{sourceSentBefore:l.source}:{}}}),g=[xn(e.measures.readWholeOver),a,a===void 0&&u!==void 0&&i.verdict==="exceeds"?{code:"STORAGE_EXCEEDED",message:`${u} Nothing was written.`,storage:{estimateMB:Number(P(i.estimateMB)),remainingMB:i.remainingMB}}:void 0,d.stop,c.stop,...c.alsoRefused??[]].filter(h=>h!==void 0),m=e.measures.restOnly?{restOnly:e.measures.restOnly}:{},f=new Set(n.objects.map(({objectApiName:h})=>h)),{wholeOrg:p}=c;return{wouldInsert:n.objects.map(({objectApiName:h,rows:O})=>{let{jobs:E,rest:J}=X(h,O,m);return{objectApiName:h,rows:O,jobs:E.length,byRest:J}}),totalRows:n.totalRows,targetRequests:c.api,sourceRequests:p.source,...p.bulkBatches?{bulkBatches:p.bulkBatches}:{},storage:i,...d.files?{files:d.files}:{},durationSeconds:p.cost.durationSeconds,leftOut:{..._n(e.graph),...n.leftOut?{rows:n.leftOut}:{}},personalAsIs:Fn(e.graph.nodes,f,e.anonymizePII),wouldBeRefused:g,...e.sample?{sample:e.sample}:{}}}var Nn="SAMPLE_STORAGE_UNREAD",dt="SAMPLE_CANNOT_FIT",In="SAMPLE_TOO_LARGE",lt="SAMPLE_PLAN_MISMATCH",ue="SAMPLE_PLAN_GONE";function Dn(e){let{storage:t,bounds:n,target:r}=e;if("unread"in t&&!(n.withinMB!==void 0||n.maxTotal!==void 0))return{code:Nn,message:`The data storage ${r} has left could not be read (${t.unread}), and a sample is fitted to it: there is nothing to hold it to. Give the most it may take (--fit-within <MB>) or the most records (--max-total <n>), or run it again once the org answers. Nothing was written.`}}function Ln(e,t){if(e.remainingMB===void 0||e.share===void 0)return;let n=Math.max(0,t.remainingMB-(e.roundingMB??0));return Math.floor(e.share*n*1048576)}function Wn(e){let{sample:t,storage:n,target:r}=e,o=Ln(t.budget,n);if(o===void 0||t.storageBytes<=o)return;let s=Et(t.storageBytes/1048576,o/1048576),i=P(t.budget.bytes/1048576);return{code:"STORAGE_EXCEEDED",message:`The sample was fitted to ${i} MB of the data storage ${r} had left (${t.budget.remainingMB} MB), and ${r} now says ${n.remainingMB} MB left, which holds ${s.bound} MB of a sample: the sample takes about ${s.over} MB. Simulate again \u2014 run the dry run again \u2014 to draw a sample that fits: a run never cuts its sample short. Nothing was written.`,storage:{estimateMB:Number(s.over),remainingMB:n.remainingMB},sample:{fittedMB:Number(i),holdsMB:Number(s.bound)}}}function Gn(e){let{sample:t,storage:n,target:r}=e;return"unread"in n?Dn({storage:n,bounds:t.budget,target:r}):Wn({sample:t,storage:n,target:r})}var Un=new Set(["gone","changed","otherOrg","otherSetup","otherSha"]),qn={changed:"is no longer as its dry run wrote it: its ids changed since",otherOrg:"was drawn of another org than the source",otherSetup:"was drawn for another setup of the run \u2014 other flags, filters, objects or options of the sample",otherSha:"is not the plan its dry run printed"};function zn(e,t){return t==="resume"?{code:ue,message:`The plan of the sample this run resumes ${e==="gone"?"is no longer on this machine":"is no longer as it was written"}: the records it was to write cannot be taken up after where it stopped (--resume). Remove what it wrote (--remove), or run the clone again without --resume to draw a new sample. Nothing was written.`,sample:{plan:e}}:e==="gone"?{code:ue,message:'No plan of a sample is at the path given to --fit-plan: give the folder its dry run printed ("sample plan: \u2026"), within a day of it, or leave --fit-plan out to draw a new sample. Nothing was written.',sample:{plan:e}}:{code:lt,message:`The plan given to --fit-plan ${qn[e]}: run the dry run again with the flags of this run, and replay the plan it prints. Nothing was written.`,sample:{plan:e}}}var Hn=new Set([In,dt,ue,lt]),Vn=20;function wo(e,t){if(e instanceof Error){if(e.name==="SampleRefusedError"){let{code:n,heaviest:r,sample:o}=e;if(typeof n!="string"||!Hn.has(n))return;let s=Array.isArray(r)?r.flatMap(a=>{let d=a?.objectApiName;return typeof d=="string"?[d]:[]}):[],i=ke({code:n,sample:o})?.sample??{},u={...i,...n===dt&&i.heaviest===void 0&&s.length>0?{heaviest:s.slice(0,Vn)}:{}};return B.of({code:n,message:e.message,...Object.keys(u).length>0?{sample:u}:{}})}if(e.name==="SamplePlanError"&&t!=="draw"){let{refusal:n}=e;return typeof n!="string"||!Un.has(n)?void 0:B.of(zn(n,t))}}}var Kn=b({SingleEmail:b({Max:w(),Remaining:w()}).loose().optional(),DailyWorkflowEmails:b({Max:w(),Remaining:w()}).loose().optional()}).loose();async function Ro(e){let t=Kn.parse(await e.request({method:"GET",url:"/limits"})),n={};for(let r of["SingleEmail","DailyWorkflowEmails"]){let o=t[r];o&&(n[r]={max:o.Max,remaining:o.Remaining})}return n}var Xn=15;function ct(e){let t=e.SingleEmail;return t!==void 0&&t.max<=Xn}function Yn(e){return ct(e)&&e.DailyWorkflowEmails!==void 0}function Jn(e,t,n=!1){let r=e.map(u=>({...u,sentBy:[...u.sentBy]})),o=(u,a)=>{let d=r.find(l=>l.objectApiName===u.objectApiName&&l.limit===a);if(!d){let l={...u,limit:a,sentBy:[...u.sentBy]};return r.push(l),l}d.perRecord+=u.perRecord;for(let l of u.sentBy)d.sentBy.includes(l)||d.sentBy.push(l);return d},s=e.filter(u=>u.limit==="SingleEmail"),i=e.filter(u=>u.limit==="DailyWorkflowEmails");if(n)for(let u of s)o(u,"DailyWorkflowEmails");if(t)for(let u of i)o(u,"SingleEmail").alertsAmong=!0;return r}function mt(e){let t=new Map(e.objects.map(n=>[n.objectApiName,{rows:n.rows,byThePlatform:0}]));for(let{objectApiName:n,rows:r}of e.leftOut?.byThePlatform??[]){let o=t.get(n)??{rows:0,byThePlatform:0};t.set(n,{rows:o.rows+r,byThePlatform:o.byThePlatform+r})}return t}function ce(e){return new Set([...mt(e)].flatMap(([t,{rows:n}])=>n>0?[t]:[]))}function Qn(e,t,n){let r=mt(e),o=new Map;for(let i of t){let{rows:u,byThePlatform:a}=r.get(i.objectApiName)??{rows:0,byThePlatform:0};if(u===0)continue;let d=o.get(i.limit)??{limit:i.limit,objects:[],emails:0,verdict:"fits"};d.objects.push({objectApiName:i.objectApiName,rows:u,perRecord:i.perRecord,sentBy:i.sentBy,...a>0?{byThePlatform:a}:{}}),d.emails+=u*i.perRecord,o.set(i.limit,d)}let s=Y(n)?n.unread:void 0;return[...o.values()].map(i=>{if(s!==void 0||Y(n))return{...i,verdict:"unread",unread:s};let u=n[i.limit];return u?{...i,verdict:i.emails>u.remaining?"exceeds":"fits",remaining:u.remaining,max:u.max}:{...i,verdict:"unread",unread:`the org's limits list no ${i.limit}`}})}function Y(e){return typeof e.unread=="string"}function Zn(e,t,n){let r=!Y(n)&&ct(n),o=!Y(n)&&Yn(n),s=Qn(e,Jn(t,r,o),n);if(!r)return s;let i=ce(e);return t.some(a=>a.limit==="DailyWorkflowEmails"&&i.has(a.objectApiName))?s.map(a=>a.limit==="SingleEmail"?{...a,alertsCounted:!0}:a):s}async function Ao(e){if(e.plan.totalRows===0||e.objects.length===0)return{checks:[]};let t;try{t=await e.readAutomation(e.objects)}catch(i){return{checks:[],unread:`the target's automation: ${R(i)}`}}let n=tr(t,er(e.plan)),r=n!==void 0?{unread:n}:{},o=we(t);if(o.length===0)return{checks:[],...r};let s=await e.readLimits().catch(i=>({unread:R(i)}));return{checks:Zn(e.plan,o,s),...r}}function er(e){let t=ce(e);return(n,r)=>r==="insert"&&t.has(n)}function tr(e,t,n="the target's"){let r=[gt(e.unread,n),or(e,t)].filter(o=>o!==void 0).join("; ");return r!==""?r:void 0}var nr={flows:"flows",processes:"processes",workflowRules:"workflow rules"};function gt(e,t){let n=e.flatMap(({part:r,reason:o})=>{let s=nr[r];return s!==void 0?[`${t} ${s}: ${o}`]:[]});return n.length>0?n.join("; "):void 0}var k=10;function rr(e){if(e.condition!=="unreadable")return;let t=e.apiName.indexOf("__");return t>0?e.apiName.slice(0,t):void 0}function or(e,t){let n=e.objects.flatMap(o=>{let i=[...new Set(be(o).filter(a=>t(o.objectApiName,a.write)).flatMap(a=>a.fired).flatMap(({flow:a,keptQuiet:d})=>a!==void 0&&d!==!0&&a.condition!=="read"&&a.timing!=="beforeSave"?[a]:[]))].map(a=>{let d=rr(a);return d!==void 0?`${a.label} (package ${d}, whose flows the org lets no one read)`:a.label});if(i.length===0)return[];let u=i.length>k?` and ${i.length-k} more`:"";return[{count:i.length,words:`${i.slice(0,k).join(", ")}${u} on ${o.objectApiName}`}]});return n.length===0?void 0:`the definition${n.reduce((o,{count:s})=>o+s,0)===1?"":"s"} of ${n.map(({words:o})=>o).join("; ")}`}function Eo(e){return{limit:e.limit,emails:e.emails,remaining:e.remaining??0,max:e.max??0,objects:e.objects.map(({objectApiName:t,perRecord:n})=>({objectApiName:t,perRecord:n})),...e.alertsCounted?{alertsCounted:!0}:{}}}function So(e){return{limit:e.limit,emails:e.emails,unread:e.unread??""}}var sr={SingleEmail:{one:"single email",more:"single emails"},DailyWorkflowEmails:{one:"workflow email",more:"workflow emails"}};function ft(e,t){let n=sr[t];return`${e} ${e===1?n.one:n.more}`}function ir(e,t){return e.alertsCounted?`, its email alerts among them: ${t} counts them against its single emails, as a Developer Edition does`:""}function Bo(e,t){let n=e.filter(o=>o.verdict==="exceeds");if(n.length===0)return;let r=n.map(o=>`about ${ft(o.emails,o.limit)}`+(o.alertsCounted?" (its email alerts among them, as a Developer Edition counts them)":"")+`, ${o.remaining??0} of ${o.max??0} left today`).join("; ");return`The target's automation would make ${t} send ${r}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. Assign the user a bypass that keeps what sends quiet \u2014 muting the target's automation for the run (--mute-automation on the command line, the Mute box on a page) assigns, for the run alone, those the target's flows test \u2014 or write fewer records.`}function Oo(e,t){return e.map(n=>{let r=n.objects.map(s=>`${s.perRecord} per ${s.objectApiName}, by ${s.sentBy.join(", ")}`+(s.byThePlatform?`; ${s.byThePlatform} ${s.objectApiName} written by the platform with ${$(s.objectApiName)}, whose flows run all the same`:"")).join("; "),o=` emails: these records make ${t} send about ${ft(n.emails,n.limit)} (${r})`+ir(n,t);return n.verdict==="unread"?`${o}; what it has left today could not be read (${n.unread??""})`:n.verdict==="fits"?`${o}; it has ${n.remaining??"?"} of ${n.max??"?"} left today`:`${o}, more than the ${n.remaining??"?"} of ${n.max??"?"} it has left today: past them the action fails, and a record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER). A bypass that keeps the flow quiet, or a smaller run, avoids it`})}var pt="EMAILS_NOT_ACCEPTED";function ht(e,t={}){let n=[gt(e,"the target's"),...t.applyAssignmentRules===!0?e.filter(({part:r})=>r==="assignmentRules").map(({reason:r})=>`the target's assignment rules: ${r}`):[]].filter(r=>r!==void 0);return n.length>0?n.join("; "):void 0}function ko(e){return"requests"in e&&typeof e.requests=="number"?Math.max(0,e.requests):Ne}function To(e){let t=e?.read?.requests??0;return t>0?{deliverability:t}:{}}var bt={clone:{run:"this clone",allTheSame:"to clone all the same"},sync:{run:"this sync",allTheSame:"to sync all the same"},seed:{run:"this seed",allTheSame:"to seed all the same"},autopilot:{run:"this Autopilot run",allTheSame:"to run it all the same"},rewind:{run:"this rewind",allTheSame:"to rewind all the same"},undo:{run:"this undo",allTheSame:"to undo all the same"},masking:{run:"this masking",allTheSame:"to mask all the same"},restore:{run:"this restore",allTheSame:"to restore all the same"},cleanup:{run:"this cleanup",allTheSame:"to delete all the same"},empty:{run:"this emptying",allTheSame:"to empty all the same"},load:{run:"this load",allTheSame:"to load all the same"}},ar={flow:"flow",process:"process",workflowRule:"workflow rule",assignmentRule:"assignment rule"},ur={email:"",notRead:" (its definition was not read)",assignment:" (applied: it can mail the owner it assigns)"};function yt(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function _(e){let t=new Map;for(let n of e){let r=t.get(n.objectApiName)??[];r.push(`${ar[n.kind]} "${n.name}"${ur[n.why]}`),t.set(n.objectApiName,r)}return[...t].map(([n,r])=>{let o=r.length>k?[...r.slice(0,k),`${r.length-k} more`]:r;return`${yt(o)} on ${n}`}).join("; ")}var Ye="read with one line of anonymous Apex that sends nothing";function wt(e){return"level"in e&&e.level==="withheld"}function dr(e){return"unread"in e?`deliverability: not read (${e.unread}) \u2014 the run is refused without --accept-emails, as on All email`:e.level==="all"?`deliverability: All email \u2014 the emails of what still runs go out (${Ye})`:`deliverability: System email only or No access \u2014 none of the emails its flows, processes, workflow rules and Apex send goes out, and the org still counts them against its daily email limits (${Ye})`}function lr(e,t){let{run:n,allTheSame:r}=bt[e.run],{target:o}=e,s=_(e.senders),i=e.sendersUnread,u=s!==""?`what still runs as ${n} writes its records sends some: ${s}`+(i!==void 0?`; what could not be read may send more (${i})`:""):`what runs as ${n} writes its records could not all be read (${i??""}), so it may send some`,a=[];"unread"in t?a.push(`Whether ${o} delivers the emails its automation sends could not be read (${t.unread}), and ${u}.`,`Nothing was written. Add --accept-emails ${r}, or check Setup > Deliverability: on System email only or No access, none of them goes out.`):a.push(`${o} delivers every email its automation sends (Setup > Deliverability: All email), and ${u}.`,e.keepsAddresses===!0?`They go to the addresses the records and the alerts name: those of the records ${n} writes, as they hold them, the records' owners, the records already in ${o}, and an address an alert names.`:`They go to the addresses the records and the alerts name: those ${n} writes are under .invalid, but not the records' owners, the records already in ${o}, nor an address an alert names.`,`Nothing was written. Add --accept-emails ${r}, set the org's deliverability to System email only, or turn off what sends them.`);let d=e.muteQuiets??[];if(d.length>0){let l=new Set(d.map(g=>`${g.objectApiName}\0${g.kind}\0${g.name}`)),c=e.senders.filter(g=>!l.has(`${g.objectApiName}\0${g.kind}\0${g.name}`));a.push(`--mute-automation keeps quiet ${_(d)}, which ${d.length===1?"tests":"test"} a bypass a permission set of ${o} holds`+(c.length>0?`; it cannot quiet ${_(c)}.`:"."))}return a.join(" ")}function Rt(e){if(e.senders.length===0&&e.sendersUnread===void 0)return{verdict:"nothingSends",confirmation:{}};let t=e.reading??{unread:"the run did not read it"},n={reading:t,senders:[...e.senders],...e.sendersUnread!==void 0?{sendersUnread:e.sendersUnread}:{}},r=dr(t);return wt(t)?{verdict:"withheld",deliverability:n,confirmation:{},line:r,audit:"withheld"}:{verdict:"asks",deliverability:n,confirmation:{deliverability:e.keepsAddresses===!0?{...n,keepsAddresses:!0}:n},...e.accepted?{}:{stop:{code:pt,message:lr(e,t)}},line:r,audit:"unread"in t?"unread":"all"}}function Po(e,t){let n=ce(t);return e.filter(r=>!n.has(r.objectApiName))}function xo(e){if(e.length===0)return;let t=[...new Set(e.map(n=>n.objectApiName))];return` emails: ${_(e)} send nothing: the run writes no ${yt(t)} record. A real run is refused all the same, and names them: it asks before it reads which records it writes`}function At(e){let t=a=>`${a.objectApiName}\0${a.kind}\0${a.name}`,n=new Set(e.planned.map(t)),r=e.held.filter(a=>!n.has(t(a)));if(r.length===0||e.accepted)return;let o=e.reading;if(o!==void 0&&wt(o))return;let{run:s,allTheSame:i}=bt[e.run],u=o===void 0?`whether ${e.target} delivers them was not read, as nothing that sends one was to run`:"unread"in o?`whether ${e.target} delivers them could not be read (${o.unread})`:`${e.target} delivers every one of them (All email)`;return{code:pt,relit:r,message:`The mute's lease does not hold every permission set it was to assign, and what they were to keep quiet still runs for ${s}: ${_(r)} may send emails, and ${u}. The run's question did not ask about them. Nothing was written. Add --accept-emails ${i}, or run it again once the lease can assign them.`}}function vo(e){return e.verdict==="unread"?{estimateMB:e.estimateMB,unread:e.unread}:{estimateMB:e.estimateMB,maxMB:e.maxMB,remainingMB:e.remainingMB,near:e.verdict==="near"}}function P(e){return de(e,e<10?2:1)}function de(e,t){if(e<=0)return"0";let n=10**t;return(Math.ceil(e*n-1e-9)/n).toString()}function Et(e,t){let n={over:e<10?2:1,bound:t<10?2:1};for(;;){let r={over:de(e,n.over),bound:de(t,n.bound)},o=Math.max(n.over,n.bound);if(Number(r.over)>Number(r.bound)||o>=6)return r;n={over:o+1,bound:o+1}}}function St(e){return e.map(({objectApiName:t,kind:n,name:r})=>({objectApiName:t,kind:n,name:r}))}function cr(e){return St(ee(e,"insert"))}function mr(e,t){let n=new Set(t);return St(ee(e,"update",r=>n.has(r)))}var Bt=["lookups","statuses","invitees","retry","upsert"];function Co(e,t={}){let n=Ie(e,t.leftOut),r=new Set(n),o=new Map,s=(l,c)=>{if(!r.has(l))return;let g=o.get(l)??new Set;g.add(c),o.set(l,g)},i=e.edges.filter(l=>Fe(l)&&r.has(l.sourceObject)&&r.has(l.targetObject)),u=new Map;for(let{sourceObject:l,targetObject:c}of i)l!==c&&u.set(l,[...u.get(l)??[],c]);let a=(l,c)=>{let g=new Set([l]),m=[l];for(let f=m.shift();f!==void 0;f=m.shift())for(let p of u.get(f)??[]){if(p===c)return!0;g.has(p)||(g.add(p),m.push(p))}return!1},d=i.filter(l=>l.required!==!0&&l.insertOnly!==!0);for(let{sourceObject:l,targetObject:c}of d)(l===c||a(c,l))&&s(c,"lookups");for(let l of Object.keys(Pe))s(l,"statuses");for(let l of Object.keys(Te))s(l,"invitees");if(t.retry===!0)for(let{sourceObject:l,targetObject:c}of d)l!==c&&s(c,"retry");if(t.upsert===!0)for(let l of n)s(l,"upsert");return n.flatMap(l=>{let c=o.get(l);return c?[{objectApiName:l,steps:Bt.filter(g=>c.has(g))}]:[]})}function gr(e){let t=new Set(e.flatMap(n=>n.steps));return Bt.filter(n=>t.has(n))}function $o(e,t=[]){let n=new Set(t);return Re(e,(r,o)=>o==="insert"||o==="update"&&n.has(r))}function jo(e,t,n){let r=new Set(ye(e).map(i=>i.toLowerCase())),o=t.filter(i=>!r.has(i.toLowerCase())),s=Ae(e,o);return o.map(i=>{let u=s.find(d=>d.permission.toLowerCase()===i.toLowerCase()),a=u?.permissionSet?.name;return{permission:i,...a?{permissionSet:a}:{},others:u?.others.map(d=>d.name)??[],...u&&!a?{noneHolds:!0}:{},...a&&n?.alias&&n.username?{command:Ee(a,n.alias,n.username)}:{}}})}function fr(e){return e==="flows"||e==="triggers"||e==="processes"||e==="workflowRules"||e==="automation"}function I(e){return e.unread.flatMap(({part:t,reason:n})=>fr(t)?[{part:t,reason:n}]:[])}var Fo="OWNER_MAP_INACTIVE",_o="OWNER_MAP_UNKNOWN",B=class e extends Error{code;storage;ceiling;reason;api;readBound;sample;constructor(t,n,r,o,s,i){super(n),this.name="ForgeRunGateError",this.code=t,r&&(this.storage=r),o!==void 0&&(this.ceiling=o),s!==void 0&&(this.reason=s),i?.api&&(this.api=i.api),i?.readBound&&(this.readBound=i.readBound),i?.sample&&(this.sample=i.sample)}static of(t){return new e(t.code,t.message,t.storage,void 0,t.refusal?.code,{...t.api?{api:t.api}:{},...t.readBound?{readBound:t.readBound}:{},...t.sample?{sample:t.sample}:{}})}get stop(){if(Oe(this.code))return{code:this.code,...this.storage?{storage:this.storage}:{},...this.ceiling!==void 0?{ceiling:this.ceiling}:{},...this.reason!==void 0&&this.code===K?{reason:this.reason}:{},...this.api&&this.code===F?{api:this.api}:{},...this.readBound&&this.code==="READ_BOUND_EXCEEDED"?{readBound:this.readBound}:{},...this.sample?{sample:this.sample}:{}}}};function Mo(e){return e instanceof B||e instanceof Error&&e.name==="ForgeRunGateError"&&typeof e.code=="string"}var Je="FILE_STORAGE_EXCEEDED";function No(e){if(!(e instanceof Error)||e.name!=="ForgeFilesRefusedError")return;let{code:t,storage:n}=e;if(t===st||t===it)return new B(t,e.message);let r=n?.neededBytes,o=n?.remainingBytes;if(t!==Je||typeof r!="number"||typeof o!="number"||!Number.isFinite(r)||!Number.isFinite(o))return;let s=o/1048576;return new B(Je,e.message,{estimateMB:Number(Et(r/1048576,s).over),remainingMB:s,kind:"files"})}function pr(e,t){if(e.verdict==="exceeds")return`The records to write take ${ut(e)}, and ${t} has ${e.remainingMB} MB left of ${e.maxMB} MB: leave objects out, lower the records per object, or free data storage in ${t}.`}var Qe=10;function Io(e,t,n){let r=[`write gate: ${e.totalRows} record(s) to write to ${n}, ${ut(t)}`];for(let s of e.objects.slice(0,Qe))r.push(` ${s.objectApiName.padEnd(42)}${String(s.rows).padStart(8)}`);let o=e.objects.slice(Qe);if(o.length>0){let s=o.reduce((i,u)=>i+u.rows,0);r.push(` and ${o.length} more object(s), ${s} record(s)`)}for(let{objectApiName:s,mayAdd:i}of e.objects)i!==void 0&&r.push(` counted in: up to ${i} ${s} record(s) the run may read as it writes them, a price in the currency of the record its lines belong to, the source's own beside the one read`);for(let{objectApiName:s,mayBeByThePlatform:i}of e.objects)i!==void 0&&r.push(` counted in: up to ${i.rows} ${s} record(s) the platform `+(i.before===!0?`may have written with ${$(s)}, in the run this one takes up`:`may write itself with ${$(s)}`)+", which the run then links to and does not send");return r.push(...hr(e.leftOut)),t.verdict==="unread"?(r.push(` the data storage ${n} has left could not be read (${t.unread}): whether the records fit is not known`),r):(r.push(` data storage of ${n}: ${t.remainingMB} MB left of ${t.maxMB} MB`),t.verdict==="near"&&r.push(` that is more than ${Math.round(tt*100)} % of what ${n} has left: Salesforce counts storage a while after a load, so less may be left than it says`),r)}function hr(e){if(!e)return[];let t=[];e.writtenBefore>0&&t.push(` not counted: ${e.writtenBefore} record(s) the run it retries or resumes wrote, which it links to and does not write again`);for(let{objectApiName:n,rows:r}of e.heldBack)t.push(` not counted: ${n}, ${r} record(s), held back for a record type closed to the user the run writes as`);for(let{objectApiName:n,rows:r}of e.recordTypeNotInTarget??[])t.push(` not counted: ${n}, ${r} record(s), held back for a record type the target has none of, which it would refuse`);for(let{objectApiName:n,rows:r}of e.withoutParent??[])t.push(` not counted: ${n}, ${r} record(s) held back with a record they cannot be written without, held back itself`);for(let{objectApiName:n,rows:r}of e.noParentInSource??[])t.push(` not counted: ${n}, ${r} record(s) left aside: a lookup they may not leave empty names a record the source does not hold, which no copy can write`);for(let{objectApiName:n,rows:r}of e.outsideFilter??[])t.push(` not counted: ${n}, ${r} record(s) left aside: a lookup they may not leave empty names a record outside its object's filter, which the run does not copy`);for(let{objectApiName:n,rows:r}of e.byThePlatform??[])t.push(` not counted: ${n}, ${r} record(s) written by the platform with ${$(n)}, which the run links to and does not send`);for(let{objectApiName:n,rows:r,fields:o}of e.linkedByValue??[])t.push(` not counted: ${n}, ${r} record(s) the target holds under the same ${o.join(", ")}, which the run links to and does not create`);for(let{objectApiName:n,rows:r}of e.linkedToTarget??[])t.push(` not counted: ${n}, ${r} record(s), the standard price book: linked to the target's own, never written`);for(let{objectApiName:n,rows:r}of e.currencyReplaced??[])t.push(` not counted: ${n}, ${r} record(s) in a currency the target lacks, replaced by the source's own price in the currency written, for the same product and price book`);return t}var br={flow:e=>`flow "${e}" runs before a record is deleted, and can refuse the delete`,trigger:e=>`Apex trigger ${e} runs on a delete, and can refuse it`,packageTrigger:e=>`Apex trigger ${e}, installed by a managed package, runs on a delete and can refuse it; no one in the org can change it`,lock:()=>"once activated, a record locks the records under it, which a removal then takes only with it, or once it is back in Draft"},yr=["flows","triggers"];function Do(e,t,n=[],r="--remove"){let o=yr.filter(i=>n.some(u=>u.part===i)),s=o.length===0?[]:[` ${o.map(i=>A[i]).join(" and ")} could not be read: whether one refuses the removal is not known`];if(e.length===0&&o.length===0)return[`reversibility: nothing found in ${t} that refuses a removal of this run's records (no flow before a delete, no Apex trigger on one, no record that locks past Draft)`];if(e.length===0){let i=[...o.includes("flows")?[]:["no flow before a delete"],...o.includes("triggers")?[]:["no Apex trigger on a delete"],"no record that locks past Draft"];return[`reversibility: nothing found in ${t} that refuses a removal of this run's records in what could be read (${i.join(", ")})`,...s]}return[`reversibility: a removal of this run's records (${r}) may be refused in ${t}:`,...e.map(({objectApiName:i,kind:u,name:a})=>` ${i}: ${br[u](a??"")}`),...s]}var A={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function S({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}var wr={lookups:"a lookup filled in once its record exists",statuses:"an order or a contract given back its status after it went in as a draft",invitees:"an event's invitee given its answer",retry:"a lookup the run it retries left empty filled in",upsert:"a record the target holds written over by --upsert"};function T(e){return e.map(t=>`${t.objectApiName}: ${S(t)}`).join("; ")}function me(e,t,n){return e.flatMap(r=>{if(r.command){let o=r.others.length>0?`; ${r.others.join(", ")} hold${r.others.length===1?"s":""} it too`:"";return[`${r.permissionSet} is the smallest permission set of ${t} that holds ${r.permission}${o}. Assigned to the user ${n} writes as, it keeps quiet what ${r.permission} excludes: ${r.command}`]}return r.noneHolds?[`No permission set of ${t} holds ${r.permission}: an admin creates one that includes it, and assigns it to the user ${n} writes as.`]:[]})}function ge(e,t,n){let r=[...new Set(e.flatMap(o=>o.permissionSet??[]))];return!n||r.length===0?[]:[`With --mute-automation, the ${t} assigns ${r.join(", ")} to the user it writes as for the ${t} alone, under a lease, and what ${r.length===1?"it keeps":"they keep"} quiet does not fire.`]}function Lo(e,t,n={}){let r=n.updated??[],o=cr(e),s=mr(e,r.map(d=>d.objectApiName)),i=I(e);if(o.length===0&&s.length===0&&i.length===0)return;let u=[];if(o.length>0&&u.push(`${t} runs automation on the records this clone inserts: ${T(o)}.`),s.length>0){let d=gr(r.filter(l=>s.some(c=>c.objectApiName===l.objectApiName))).map(l=>wr[l]);u.push(`${t} runs automation as this clone updates records it inserted (${d.join("; ")}): ${T(s)}.`)}let a=r.length>0?"inserts and updates":"inserts";for(let{part:d,reason:l}of i)u.push(`${A[d][0].toUpperCase()}${A[d].slice(1)} of ${t} could not be read (${l}), so what fires as the clone ${a} is not known.`);return u.push(...me(n.assign??[],t,"the clone")),u.push(...ge(n.assign??[],"clone",n.mayMute===!0)),u.push(`Nothing was written. Add --accept-automation to clone all the same, or turn that automation off in ${t} first.`),u.join(" ")}function Wo(e,t,n={}){let r=te(e,n.drafted??[]),o=I(e);if(r.length===0&&o.length===0)return;let s=[],i=r.filter(a=>a.write==="update"),u=r.filter(a=>a.write==="delete");if(u.length>0){let a=u.map(d=>`${d.objectApiName}: ${S(d)} (${M[d.when]})`);s.push(`${t} runs automation on the records this removal deletes: ${a.join("; ")}.`)}i.length>0&&s.push(`${t} runs automation as this removal sets activated records back to Draft, the only way the platform deletes them: ${T(i)}.`);for(let{part:a,reason:d}of o)s.push(`${A[a][0].toUpperCase()}${A[a].slice(1)} of ${t} could not be read (${d}), so what fires as the removal deletes is not known.`);return s.push(...me(n.assign??[],t,"the removal")),s.push(...ge(n.assign??[],"removal",n.mayMute===!0)),s.push(`Nothing was deleted. Add --accept-automation to remove all the same, or turn that automation off in ${t} first.`),s.join(" ")}var M={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"};function Go(e,t,n,r){let o=[`removal automation: what ${t} runs as the removal takes the records back`];for(let i of te(e,r))o.push(i.write==="delete"?` ${i.objectApiName}: ${M[i.when]}: ${S(i)}`:` ${i.objectApiName}: set back to Draft before its delete: ${S(i)}`);let s=I(e);o.length===1&&s.length===0&&o.push(` nothing fires on the ${n} object(s) it deletes records of`);for(let{part:i,reason:u}of s)o.push(` ${A[i]} could not be read: ${u}`);return o}var Rr={bringBack:"brought back from the recycle bin",recreate:"made again with a new Id",giveBack:"given back its values from before the run",setToDraft:"set back to Draft before its delete"};function Uo(e,t,n,r="removal",o){let s=I(e),i=(u,a)=>{let d=[Ar[a](t)];for(let l of L(e,u))d.push(l.step==="delete"?` ${l.objectApiName}: ${M[l.when]}: ${S(l)}`:` ${l.objectApiName}: ${Rr[l.step]}: ${S(l)}`);if(d.length===1&&s.length===0){let l=new Set(Object.values(u).flat()).size,c=a==="reloadSweep"?"deletes":"writes";d.push(` nothing fires on the ${l} object(s) it ${c} records of`)}return d};return[...i(n,r),...o?i(o,"reloadSweep"):[],...s.map(({part:u,reason:a})=>` ${A[u]} could not be read: ${a}`)]}var Ar={removal:e=>`removal automation: what ${e} runs as the removal takes the run back`,reload:e=>`reload automation: what ${e} runs as the reload purges what earlier loads created`,reloadSweep:e=>`reload automation: what ${e} runs as the reload's sweep deletes what the target's automation made for the loads it replaces`};function qo(e,t,n){let r=L(e,n.steps),o=n.sweep?L(e,n.sweep):[],s=I(e);if(r.length===0&&o.length===0&&s.length===0)return;let i=d=>r.filter(l=>l.step===d),u=Ze[n.subject??"removal"],a=[];if(i("bringBack").length>0&&a.push(`${t} runs automation as ${u.this} brings back from the recycle bin what the run deleted: ${T(i("bringBack"))}.`),i("giveBack").length>0&&a.push(`${t} runs automation as ${u.this} gives the records the run wrote over their values from before it: ${T(i("giveBack"))}.`),i("setToDraft").length>0&&a.push(`${t} runs automation as ${u.this} sets activated records back to Draft, the only way the platform deletes them: ${T(i("setToDraft"))}.`),i("delete").length>0){let d=i("delete").map(l=>`${l.objectApiName}: ${S(l)} (${M[l.when]})`);a.push(`${t} runs automation on the records ${u.this} deletes: ${d.join("; ")}.`)}if(o.length>0){let d=o.map(l=>`${l.objectApiName}: ${S(l)} (${M[l.when]})`);a.push(`${t} runs automation on the records ${Ze.reloadSweep.this} deletes: ${d.join("; ")}.`)}for(let{part:d,reason:l}of s)a.push(`${A[d][0].toUpperCase()}${A[d].slice(1)} of ${t} could not be read (${l}), so what fires as ${u.the} writes is not known.`);return a.push(...me(n.assign??[],t,u.who)),a.push(...ge(n.assign??[],u.run,n.mayMute===!0)),a.push(`Nothing was written or deleted. Add --accept-automation to ${u.verb} all the same, or turn that automation off in ${t} first.`),a.join(" ")}var Ze={removal:{this:"this removal",the:"the removal",who:"the removal",run:"removal",verb:"remove"},reload:{this:"this reload's purge",the:"the reload's purge",who:"the reload",run:"reload",verb:"reload"},reloadSweep:{this:"this reload's sweep",the:"the reload's sweep",who:"the reload",run:"reload",verb:"reload"}};var Er="Messaging.reserveSingleEmailCapacity(1);",Sr="System.NoAccessException: The organization is not permitted to send email",Br=`/tooling/executeAnonymous?anonymousBody=${encodeURIComponent(Er)}`,Or=`/query?q=${encodeURIComponent("SELECT PermissionsEmailSingle FROM UserPermissionAccess")}`,kr=3e4,Tr=b({compiled:D(),success:D(),compileProblem:Q().nullish(),exceptionMessage:Q().nullish()}).loose(),Pr=b({records:fe(b({PermissionsEmailSingle:D().optional()}).loose())}).loose(),Yo={reading:{unread:"SandForge runs no Apex in a production org"},requests:0};function xr(e){return e%1e3===0?`${e/1e3} s`:`${e} ms`}function Ot(e,t){return e instanceof j?`the org did not answer within ${xr(t)}`:`the org refused it: ${R(e)}`}function vr(e){let t=Tr.safeParse(e);if(!t.success)return{unread:"its answer is not one anonymous Apex gives"};let{compiled:n,success:r,compileProblem:o,exceptionMessage:s}=t.data;if(!n)return{unread:`it did not compile${o?`: ${o}`:""}`};if(r)return{level:"all"};let i=s?.trim();return i===Sr?{refused:!0}:{unread:i?`the org answered: ${i}`:"it failed, and the org did not say why"}}async function Jo(e,t={}){let n=t.timeoutMs??kr,r=l=>new q(n).withTimeout("forge:deliverability",()=>e.request({method:"GET",url:l})),o;try{o=await r(Br)}catch(l){return{reading:{unread:Ot(l,n)},requests:1}}let s=vr(o);if(!("refused"in s))return{reading:s,requests:1};let i="so the org's refusal does not say how it is set",u;try{u=await r(Or)}catch(l){return{reading:{unread:`whether the user the run writes as may send email could not be read (${Ot(l,n)}), ${i}`},requests:2}}let a=Pr.safeParse(u),d=a.success?a.data.records[0]?.PermissionsEmailSingle:void 0;return d===!0?{reading:{level:"withheld"},requests:2}:{reading:{unread:d===!1?`the user the run writes as may not send email (Send Email), ${i}`:`the org did not say whether the user the run writes as may send email, ${i}`},requests:2}}async function Cr(e){let t=x(e.running,{applyAssignmentRules:e.applyAssignmentRules,writes:e.writes}),n=ht(e.running.automation.unread??[],{applyAssignmentRules:e.applyAssignmentRules===!0}),r=n!==void 0?{sendersUnread:n}:{};if(t.length===0&&n===void 0)return{senders:t};let o;try{o=await e.read()}catch(s){o={reading:{unread:R(s)},requests:1}}return{senders:t,...r,read:o}}function $r(e,t={}){let n=s=>`${s.objectApiName}\0${s.kind}\0${s.name}`,r=x(v(e,void 0,t.writes),t),o=new Set(x(v(e,Se(e,t.writes),t.writes),t).map(n));return r.filter(s=>!o.has(n(s)))}function jr(e,t){let n=new Set([...t.assigned,...t.held]);return{assign:e.assign.filter(r=>n.has(r.permissionSet))}}var Fr=["flows","processes","workflowRules"];async function Qo(e){let{plan:t,writes:n,applyAssignmentRules:r,read:o,target:s,run:i}=e,u=typeof o.unread=="string"?void 0:o,a=r===!0?{applyAssignmentRules:r}:{},d=await Cr({running:u?v(u,t,n):{automation:{objects:[],unread:Fr.map(g=>({part:g,reason:String(o.unread)}))},firing:[]},...a,writes:n,read:e.readDeliverability}),l=e.mayMute===!0&&t===void 0&&u!==void 0&&d.senders.length>0?$r(u,{...a,writes:n}):[],c=d.read?.reading;return{ofRun:d,gate:Rt({senders:d.senders,...d.sendersUnread!==void 0?{sendersUnread:d.sendersUnread}:{},...c!==void 0?{reading:c}:{},accepted:e.accepted,target:s,run:i,muteQuiets:l,keepsAddresses:e.keepsAddresses===!0}),afterLease:(g,m)=>{if(!(t===void 0||u===void 0))return At({planned:d.senders,held:x(v(u,jr(t,g),n),{...a,writes:n}),...c!==void 0?{reading:c}:{},accepted:m,target:s,run:i})}}}export{U as a,oe as b,Lr as c,_t as d,Wr as e,Ue as f,qe as g,Ur as h,ze as i,Vr as j,Kr as k,Xr as l,Yr as m,Jr as n,j as o,q as p,kr as q,Yo as r,Jo as s,Cr as t,$r as u,jr as v,Qo as w,lo as x,co as y,Dt as z,mo as A,tt as B,ie as C,Ht as D,Vt as E,go as F,Ve as G,fo as H,po as I,ho as J,en as K,Ke as L,tn as M,nn as N,se as O,F as P,un as Q,dn as R,K as S,ln as T,cn as U,mn as V,bo as W,xn as X,vn as Y,Cn as Z,at as _,$n as $,ut as aa,jn as ba,Fn as ca,_n as da,yo as ea,lt as fa,ue as ga,Dn as ha,Gn as ia,wo as ja,Ro as ka,ct as la,Yn as ma,Jn as na,Qn as oa,Zn as pa,Ao as qa,er as ra,tr as sa,Eo as ta,So as ua,ft as va,Bo as wa,Oo as xa,pt as ya,ht as za,ko as Aa,To as Ba,dr as Ca,Rt as Da,Po as Ea,xo as Fa,At as Ga,vo as Ha,P as Ia,Et as Ja,cr as Ka,mr as La,Co as Ma,gr as Na,$o as Oa,jo as Pa,I as Qa,Fo as Ra,_o as Sa,B as Ta,Mo as Ua,No as Va,pr as Wa,Io as Xa,Do as Ya,me as Za,Lo as _a,Wo as $a,Go as ab,Uo as bb,qo as cb};
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{c as u}from"./chunk-PUOX4NBJ.mjs";import{cb as f,ka as d}from"./chunk-B45CNPUX.mjs";import{mkdir as h,readdir as g,readFile as m,rename as w,writeFile as S}from"node:fs/promises";import*as c from"node:path";var k=".sandforge-scenario.json",P={depth:3,files:50},y=new Set(["node_modules","dist","out","coverage"]),E=10;function O(){return{list:async r=>{try{return(await g(r,{withFileTypes:!0})).map(e=>({name:e.name,folder:e.isDirectory()}))}catch(t){let e=t.code;if(e==="ENOENT"||e==="ENOTDIR"||e==="EACCES")return[];throw t}},readFile:r=>m(r,"utf8"),writeNew:async(r,t)=>{await h(c.dirname(r),{recursive:!0});try{return await S(r,t,{encoding:"utf8",flag:"wx"}),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}},replace:async(r,t)=>{let e=`${r}.${process.pid}.tmp`;await S(e,t,"utf8"),await w(e,r)}}}function x(r){let t;try{t=JSON.parse(r)}catch{return{issues:["The file is not JSON"]}}let e=d.safeParse(t);return e.success?{pack:e.data}:{issues:e.error.issues.slice(0,E).map(n=>`${n.path.join(".")||"the file"}: ${n.message}`)}}async function F(r,t){let e=[],n=async(a,o,i)=>{let p=[...await r.list(o)].sort((s,l)=>s.name.localeCompare(l.name));for(let s of p){if(e.length>=P.files)return;let l=c.join(o,s.name);s.folder?i<P.depth&&!v(s.name)&&await n(a,l,i+1):s.name.endsWith(k)&&e.push({path:l,relativePath:c.relative(a,l).split(c.sep).join("/")})}};for(let a of t)await n(a,a,0);return e}function v(r){return r.startsWith(".")||y.has(r)}async function N(r,t){let e=f.map(n=>({source:"built-in",pack:n}));for(let n of await F(r,t)){let a;try{a=await r.readFile(n.path)}catch{e.push({source:"workspace",...n,issues:["The file could not be read"]});continue}let o=x(a);e.push({source:"workspace",...n,...o})}return e}function A(r){return`${JSON.stringify(r,null,2)}
7
+ import{c as u}from"./chunk-IG2MTQRP.mjs";import{fb as f,ma as d}from"./chunk-TTFDUKUS.mjs";import{mkdir as h,readdir as g,readFile as m,rename as w,writeFile as S}from"node:fs/promises";import*as c from"node:path";var k=".sandforge-scenario.json",P={depth:3,files:50},y=new Set(["node_modules","dist","out","coverage"]),E=10;function O(){return{list:async r=>{try{return(await g(r,{withFileTypes:!0})).map(e=>({name:e.name,folder:e.isDirectory()}))}catch(t){let e=t.code;if(e==="ENOENT"||e==="ENOTDIR"||e==="EACCES")return[];throw t}},readFile:r=>m(r,"utf8"),writeNew:async(r,t)=>{await h(c.dirname(r),{recursive:!0});try{return await S(r,t,{encoding:"utf8",flag:"wx"}),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}},replace:async(r,t)=>{let e=`${r}.${process.pid}.tmp`;await S(e,t,"utf8"),await w(e,r)}}}function x(r){let t;try{t=JSON.parse(r)}catch{return{issues:["The file is not JSON"]}}let e=d.safeParse(t);return e.success?{pack:e.data}:{issues:e.error.issues.slice(0,E).map(n=>`${n.path.join(".")||"the file"}: ${n.message}`)}}async function F(r,t){let e=[],n=async(a,o,i)=>{let p=[...await r.list(o)].sort((s,l)=>s.name.localeCompare(l.name));for(let s of p){if(e.length>=P.files)return;let l=c.join(o,s.name);s.folder?i<P.depth&&!v(s.name)&&await n(a,l,i+1):s.name.endsWith(k)&&e.push({path:l,relativePath:c.relative(a,l).split(c.sep).join("/")})}};for(let a of t)await n(a,a,0);return e}function v(r){return r.startsWith(".")||y.has(r)}async function N(r,t){let e=f.map(n=>({source:"built-in",pack:n}));for(let n of await F(r,t)){let a;try{a=await r.readFile(n.path)}catch{e.push({source:"workspace",...n,issues:["The file could not be read"]});continue}let o=x(a);e.push({source:"workspace",...n,...o})}return e}function A(r){return`${JSON.stringify(r,null,2)}
8
8
  `}async function T(r,t,e,n=!1){let a=t[0];if(a===void 0)return{kind:"no-workspace"};let o=d.parse(e),i=`${o.id}${k}`,p=c.join(a,i),s=A(o);if(n)await r.replace(p,s);else if(!await r.writeNew(p,s))return{kind:"exists",path:p,relativePath:i};return{kind:"saved",path:p,relativePath:i}}async function b(r,t,e,n){let a=i=>i.id===e&&u(i)===n,o=f.find(a);if(o)return o;for(let i of await N(r,t))if(i.source==="workspace"&&"pack"in i&&a(i.pack))return i.pack}export{k as a,P as b,O as c,x as d,F as e,N as f,A as g,T as h,b as i};
@@ -0,0 +1,9 @@
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 s,b as d,c as g,d as f}from"./chunk-HS4YRX4J.mjs";import{a}from"./chunk-SU65Z2BA.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
8
+ `),process.exit(u)}let r=c(t,o,e);return r!==void 0&&(process.stderr.write(`${r}
9
+ `),process.exit(u)),o}export{p as a,y as b};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{i as d}from"./chunk-3OHPD72J.mjs";import{i as s,j as c}from"./chunk-PUOX4NBJ.mjs";import{access as p}from"node:fs/promises";import*as l from"node:path";var u="sfdx-project.json";async function w(n,e=g){for(let t of n)if(await e(l.join(t,u)))return{kind:"dx",dir:t};let r=n[0];return r===void 0?{kind:"none"}:{kind:"folder",dir:r}}async function g(n){try{return await p(n),!0}catch{return!1}}async function S(n,e){if(e.project.kind==="none")return{kind:"unavailable",reason:"no-workspace",message:"Open a folder in VS Code: the test file is written into it."};let r=await c(n.sidecar,e.storagePath,e.runId);if(r.kind==="absent")return{kind:"unavailable",reason:"no-companion",message:"This run kept no companion file: it was not seeded from a scenario, or it wrote no open case for a test to be about."};if(r.kind==="invalid")return{kind:"unavailable",reason:"companion-invalid",message:r.message};let{sidecar:t}=r,o=await e.findPack(t.packId,t.packFingerprint);if(!o)return{kind:"unavailable",reason:"pack-not-found",message:`The scenario ${t.packId} this run was seeded from is no longer in the workspace as it was: its tests would be about subjects and addresses no record of the run holds.`};let i=await e.readCatalog();if(i.kind==="no-agent")return{kind:"no-agent",reason:i.reason,message:i.message};if(i.kind==="unreadable")return{kind:"unavailable",reason:"catalog-unreadable",message:i.message};let a=await d(n.spec,{sidecar:t,pack:o,catalog:i.catalog,choice:e.choice,projectDir:e.project.dir,alias:e.alias,...e.overwrite!==void 0?{overwrite:e.overwrite}:{}});if(a.kind==="refused")return a;if(a.kind==="exists")return{kind:"exists",path:a.path,specPath:a.specPath};await s(n.sidecar,e.storagePath,a.sidecar).catch(()=>{});let f=e.project.kind==="dx";return{kind:"written",path:a.path,specPath:a.specPath,apiName:a.apiName,...f?{commands:{create:a.commands.create.line,run:a.commands.run.line}}:{notDxProject:!0},leftOut:a.leftOut}}export{u as a,w as b,S as c};
7
+ import{i as d}from"./chunk-LKQ5RKIV.mjs";import{i as s,j as c}from"./chunk-IG2MTQRP.mjs";import{access as p}from"node:fs/promises";import*as l from"node:path";var u="sfdx-project.json";async function w(n,e=g){for(let t of n)if(await e(l.join(t,u)))return{kind:"dx",dir:t};let r=n[0];return r===void 0?{kind:"none"}:{kind:"folder",dir:r}}async function g(n){try{return await p(n),!0}catch{return!1}}async function S(n,e){if(e.project.kind==="none")return{kind:"unavailable",reason:"no-workspace",message:"Open a folder in VS Code: the test file is written into it."};let r=await c(n.sidecar,e.storagePath,e.runId);if(r.kind==="absent")return{kind:"unavailable",reason:"no-companion",message:"This run kept no companion file: it was not seeded from a scenario, or it wrote no open case for a test to be about."};if(r.kind==="invalid")return{kind:"unavailable",reason:"companion-invalid",message:r.message};let{sidecar:t}=r,o=await e.findPack(t.packId,t.packFingerprint);if(!o)return{kind:"unavailable",reason:"pack-not-found",message:`The scenario ${t.packId} this run was seeded from is no longer in the workspace as it was: its tests would be about subjects and addresses no record of the run holds.`};let i=await e.readCatalog();if(i.kind==="no-agent")return{kind:"no-agent",reason:i.reason,message:i.message};if(i.kind==="unreadable")return{kind:"unavailable",reason:"catalog-unreadable",message:i.message};let a=await d(n.spec,{sidecar:t,pack:o,catalog:i.catalog,choice:e.choice,projectDir:e.project.dir,alias:e.alias,...e.overwrite!==void 0?{overwrite:e.overwrite}:{}});if(a.kind==="refused")return a;if(a.kind==="exists")return{kind:"exists",path:a.path,specPath:a.specPath};await s(n.sidecar,e.storagePath,a.sidecar).catch(()=>{});let f=e.project.kind==="dx";return{kind:"written",path:a.path,specPath:a.specPath,apiName:a.apiName,...f?{commands:{create:a.commands.create.line,run:a.commands.run.line}}:{notDxProject:!0},leftOut:a.leftOut}}export{u as a,w as b,S as c};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{b as X,e as Y}from"./chunk-RSYICMZG.mjs";import{a as G,b as q,e as J,f as Q,j as L}from"./chunk-FQGHL7GR.mjs";import{ha as A,ja as N,ka as Z,la as W}from"./chunk-B45CNPUX.mjs";var O=class extends Error{constructor(t){super(`The scenario cannot be compiled: ${t.join("; ")}`);this.issues=t;this.name="ScenarioCompileError"}issues},ee="2026-10-28T00:00:00.000Z",x={subject:255,description:32e3,commentBody:4e3,articleTitle:255,articleSummary:1e3},ie=new Set(["Phone"]);function $e(e,n={}){let t=Z.safeParse(e),a=W.safeParse(n);if(!t.success||!a.success)throw new O([...t.error?.issues.map(i=>te(["pack",...i.path],i))??[],...a.error?.issues.map(i=>te(["options",...i.path],i))??[]]);let r=n.customers??e.customers.count;if(r<e.topics.length)throw new O([`options.customers: ${r} customer(s) for ${e.topics.length} topics: each topic's utterances are said about a customer's open case on it`]);let s=n.seed??A.seed,u=n.historyPerCustomer??A.historyPerCustomer,l=n.caseStatus??A.caseStatus,c=ge(e.language),o=ce(),p=e.id,m=e.topics,f=fe(p,r,c,s),S=f.map((i,d)=>({key:i.key,values:o.row({Name:i.company,Industry:e.customers.industry,Type:"Customer - Direct",Phone:L(c,2*d),Website:`https://www.${se(i.company)}`})})),$=f.map((i,d)=>({key:i.key,parentKey:i.key,values:o.row({FirstName:i.firstName,LastName:i.lastName,Email:i.email,Phone:L(c,2*d+1)})})),T=m.map(()=>0),k=[],M=[],D=[],z=[],F=i=>`${p}-article-${m[i].key}`;for(let[i,d]of f.entries()){let I=[...Array.from({length:u},(g,h)=>({topicIndex:(i+1+h)%m.length,key:`${d.key}-h${h+1}`,open:!1})),{topicIndex:i%m.length,key:`${d.key}-open`,open:!0}];for(let{topicIndex:g,key:h,open:j}of I){let U=m[g].caseTemplates,w=U[T[g]++%U.length],v=o.text(P(w.subject,d),x.subject),V={...d,caseSubject:v};k.push({key:h,parentKey:d.key,values:o.row({Subject:v,Description:o.text(P(w.description,V),x.description),Status:j?l.open:l.closed,Priority:w.priority,Origin:w.origin})}),M.push(...le(h,w,j,V,o)),j?D.push({key:h,subject:v,topicIndex:g,customer:d}):z.push({caseKey:h,articleKey:F(g)})}}let y=ue(n),_=[],oe=m.map((i,d)=>{if(!y)return;let I=i.article.facts.map(h=>o.text(h)),g=me(o.text(i.article.body),I,y);if(typeof g=="string")return g;_.push(`pack.topics[${d}].article.facts[${g.unfit}]: the fact "${i.article.facts[g.unfit]}" does not fit, with the facts before it, in the ${y.max} characters of ${y.name}, the field the article's body goes to in this org: shorten the facts, or give Knowledge a longer field for the body`)});if(_.length>0)throw new O(_);let H=[...m.map((i,d)=>({key:F(d),values:ne(i.article,`${p}-${i.key}-${s}`,e,o,y&&{name:y.name,text:oe[d]??""})})),{key:`${p}-decoy-article`,values:ne(e.decoy,`${p}-${s}-decoy`,e,o,y&&{name:y.name,text:de(o.text(e.decoy.body),o.text(e.decoy.summary),y)})}],ae={id:`scenario-${p}`,name:o.text(e.name),description:o.text(e.businessContext),version:1,strategy:"template",objects:[R("Account",0,S),R("Contact",1,$),R("Case",2,k),R("CaseComment",3,M),{...R("Knowledge__kav",4,H),optional:!0}],relations:[B("Contact","AccountId","Account"),B("Case","ContactId","Contact"),B("CaseComment","ParentId","Case")],tags:["scenario",p],createdAt:ee,updatedAt:ee};return{packId:p,seed:s,template:ae,tests:pe(e,D,F,H,o),closedCaseArticles:z}}function te(e,n){return`${e.reduce((a,r)=>typeof r=="number"?`${a}[${r}]`:`${a}.${String(r)}`,"").replace(/^\./,"")}: ${n.message}`}function ce(){let e=X(),n=new Map,t=r=>{let s=n.get(r);if(s!==void 0)return s;let u=e(r);return n.set(r,u),u},a=(r,s)=>Y(r,s,t);return{text(r,s){let u=a({text:r},new Set).text;return E(typeof u=="string"?u:r,s)},row(r){return a(r,ie)}}}function E(e,n){if(n===void 0||e.length<=n)return e;let t=e.slice(0,n);if(/\s/.test(e.charAt(n)))return t.trimEnd();let a=t.search(/\s\S*$/);return a>0?t.slice(0,a).trimEnd():t}function P(e,n){return e.replace(/\{([A-Za-z][A-Za-z0-9_]*)\}/g,(t,a)=>n[a]??t)}function le(e,n,t,a,r){return(t?[n.followUp]:n.resolution).map((u,l)=>({key:`${e}-${l+1}`,parentKey:e,values:{CommentBody:r.text(P(u,a),x.commentBody),IsPublished:!1}}))}function ne(e,n,t,a,r){let s={Title:a.text(e.title,x.articleTitle),UrlName:n,Summary:a.text(e.summary,x.articleSummary),Language:t.language,IsVisibleInPkb:!1,IsVisibleInCsp:!1,IsVisibleInPrm:!1};return r&&(s[r.name]=r.text),s}function ue(e){let n=e.articleBodyField;if(n===void 0)return;let t=e.articleBodyLength??(n==="Summary"?x.articleSummary:void 0);return{name:n,...t!==void 0?{max:t}:{},html:e.articleBodyHtml===!0}}function K(e){return e.split(/\n\s*\n/).map(n=>n.trim()).filter(Boolean)}function C(e,n){return n.html?e.map(t=>`<p>${re(t)}</p>`).join(""):e.join(`
7
+ import{b as X,e as Y}from"./chunk-O2HDYYUV.mjs";import{a as G,b as q,e as J,f as Q,j as L}from"./chunk-FQGHL7GR.mjs";import{ja as A,la as N,ma as Z,na as W}from"./chunk-TTFDUKUS.mjs";var O=class extends Error{constructor(t){super(`The scenario cannot be compiled: ${t.join("; ")}`);this.issues=t;this.name="ScenarioCompileError"}issues},ee="2026-10-28T00:00:00.000Z",x={subject:255,description:32e3,commentBody:4e3,articleTitle:255,articleSummary:1e3},ie=new Set(["Phone"]);function $e(e,n={}){let t=Z.safeParse(e),a=W.safeParse(n);if(!t.success||!a.success)throw new O([...t.error?.issues.map(i=>te(["pack",...i.path],i))??[],...a.error?.issues.map(i=>te(["options",...i.path],i))??[]]);let r=n.customers??e.customers.count;if(r<e.topics.length)throw new O([`options.customers: ${r} customer(s) for ${e.topics.length} topics: each topic's utterances are said about a customer's open case on it`]);let s=n.seed??A.seed,u=n.historyPerCustomer??A.historyPerCustomer,l=n.caseStatus??A.caseStatus,c=ge(e.language),o=ce(),p=e.id,m=e.topics,f=fe(p,r,c,s),S=f.map((i,d)=>({key:i.key,values:o.row({Name:i.company,Industry:e.customers.industry,Type:"Customer - Direct",Phone:L(c,2*d),Website:`https://www.${se(i.company)}`})})),$=f.map((i,d)=>({key:i.key,parentKey:i.key,values:o.row({FirstName:i.firstName,LastName:i.lastName,Email:i.email,Phone:L(c,2*d+1)})})),T=m.map(()=>0),k=[],M=[],D=[],z=[],F=i=>`${p}-article-${m[i].key}`;for(let[i,d]of f.entries()){let I=[...Array.from({length:u},(g,h)=>({topicIndex:(i+1+h)%m.length,key:`${d.key}-h${h+1}`,open:!1})),{topicIndex:i%m.length,key:`${d.key}-open`,open:!0}];for(let{topicIndex:g,key:h,open:j}of I){let U=m[g].caseTemplates,w=U[T[g]++%U.length],v=o.text(P(w.subject,d),x.subject),V={...d,caseSubject:v};k.push({key:h,parentKey:d.key,values:o.row({Subject:v,Description:o.text(P(w.description,V),x.description),Status:j?l.open:l.closed,Priority:w.priority,Origin:w.origin})}),M.push(...le(h,w,j,V,o)),j?D.push({key:h,subject:v,topicIndex:g,customer:d}):z.push({caseKey:h,articleKey:F(g)})}}let y=ue(n),_=[],oe=m.map((i,d)=>{if(!y)return;let I=i.article.facts.map(h=>o.text(h)),g=me(o.text(i.article.body),I,y);if(typeof g=="string")return g;_.push(`pack.topics[${d}].article.facts[${g.unfit}]: the fact "${i.article.facts[g.unfit]}" does not fit, with the facts before it, in the ${y.max} characters of ${y.name}, the field the article's body goes to in this org: shorten the facts, or give Knowledge a longer field for the body`)});if(_.length>0)throw new O(_);let H=[...m.map((i,d)=>({key:F(d),values:ne(i.article,`${p}-${i.key}-${s}`,e,o,y&&{name:y.name,text:oe[d]??""})})),{key:`${p}-decoy-article`,values:ne(e.decoy,`${p}-${s}-decoy`,e,o,y&&{name:y.name,text:de(o.text(e.decoy.body),o.text(e.decoy.summary),y)})}],ae={id:`scenario-${p}`,name:o.text(e.name),description:o.text(e.businessContext),version:1,strategy:"template",objects:[R("Account",0,S),R("Contact",1,$),R("Case",2,k),R("CaseComment",3,M),{...R("Knowledge__kav",4,H),optional:!0}],relations:[B("Contact","AccountId","Account"),B("Case","ContactId","Contact"),B("CaseComment","ParentId","Case")],tags:["scenario",p],createdAt:ee,updatedAt:ee};return{packId:p,seed:s,template:ae,tests:pe(e,D,F,H,o),closedCaseArticles:z}}function te(e,n){return`${e.reduce((a,r)=>typeof r=="number"?`${a}[${r}]`:`${a}.${String(r)}`,"").replace(/^\./,"")}: ${n.message}`}function ce(){let e=X(),n=new Map,t=r=>{let s=n.get(r);if(s!==void 0)return s;let u=e(r);return n.set(r,u),u},a=(r,s)=>Y(r,s,t);return{text(r,s){let u=a({text:r},new Set).text;return E(typeof u=="string"?u:r,s)},row(r){return a(r,ie)}}}function E(e,n){if(n===void 0||e.length<=n)return e;let t=e.slice(0,n);if(/\s/.test(e.charAt(n)))return t.trimEnd();let a=t.search(/\s\S*$/);return a>0?t.slice(0,a).trimEnd():t}function P(e,n){return e.replace(/\{([A-Za-z][A-Za-z0-9_]*)\}/g,(t,a)=>n[a]??t)}function le(e,n,t,a,r){return(t?[n.followUp]:n.resolution).map((u,l)=>({key:`${e}-${l+1}`,parentKey:e,values:{CommentBody:r.text(P(u,a),x.commentBody),IsPublished:!1}}))}function ne(e,n,t,a,r){let s={Title:a.text(e.title,x.articleTitle),UrlName:n,Summary:a.text(e.summary,x.articleSummary),Language:t.language,IsVisibleInPkb:!1,IsVisibleInCsp:!1,IsVisibleInPrm:!1};return r&&(s[r.name]=r.text),s}function ue(e){let n=e.articleBodyField;if(n===void 0)return;let t=e.articleBodyLength??(n==="Summary"?x.articleSummary:void 0);return{name:n,...t!==void 0?{max:t}:{},html:e.articleBodyHtml===!0}}function K(e){return e.split(/\n\s*\n/).map(n=>n.trim()).filter(Boolean)}function C(e,n){return n.html?e.map(t=>`<p>${re(t)}</p>`).join(""):e.join(`
8
8
 
9
9
  `)}function re(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function b(e,n){return n.max===void 0||e.length<=n.max}function me(e,n,t){let a=K(e),r=t.html?C(a,t):e;if(b(r,t))return r;let s=a.filter(c=>n.some(o=>N(c,o)));if(n.every(c=>N(s.join(`
10
10
 
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{M as f,j as k,k as s}from"./chunk-NEVXIGR6.mjs";import{a as d,b as u}from"./chunk-TYYOBZMU.mjs";import{Ia as i}from"./chunk-B45CNPUX.mjs";import{b as c,l as a,u as p}from"./chunk-7EANH5PY.mjs";import{homedir as E}from"node:os";import{join as O}from"node:path";var $=a({...d,operation:p(["apply","destroy","reset","recover"]),env:i,alias:c().min(1).max(255).optional()}),l=u(n=>{let e=$.safeParse(n);return e.success?e.data:void 0});function j(n=E()){return k(n)}function v(n,e){return O(n,`${s(e)}.env.lock`)}function K(n,e,o,r={}){let m=v(n,e),y=i.parse(o.env),t=l.acquire(m,h=>({...h,operation:o.operation,env:y,...o.alias!==void 0?{alias:o.alias}:{}}),r);return"busy"in t?{busy:L(t.busy)}:{lock:{organizationId:s(e),release:t.lock.release}}}function N(n,e,o={}){let r=l.holder(v(n,e),o);return r!==void 0?L(r):void 0}function L({version:n,token:e,...o}){return o}function g(n){return`process ${n.pid} on ${n.host}, since ${n.acquiredAt}`}function R(n){return`${w(n)}. Nothing was written: run this again once it ends. Two jobs applying to one org from two machines are not kept apart: give them one concurrency group.`}function w(n){let e=n.alias!==void 0?` to ${n.alias}`:"";return`${n.operation==="apply"?"an apply":n.operation==="recover"?"a state recover":`a ${n.operation}`} of ${n.env}${e} is under way on this machine (${g(n)})`}function _(n,e,o={}){let r=f(n,e,o);if(r!==void 0)return`a checkpoint ${r.operation} of this org is under way on this machine (${g(r)}): its records would be read or written as the step writes. Run this again once it ends.`}export{j as a,v as b,K as c,N as d,R as e,w as f,_ as g};
7
+ import{O as f,j as k,k as s}from"./chunk-IFETCRWE.mjs";import{a as d,b as u}from"./chunk-TYYOBZMU.mjs";import{Ka as i}from"./chunk-TTFDUKUS.mjs";import{b as c,l as a,u as p}from"./chunk-7EANH5PY.mjs";import{homedir as E}from"node:os";import{join as O}from"node:path";var $=a({...d,operation:p(["apply","destroy","reset","recover"]),env:i,alias:c().min(1).max(255).optional()}),l=u(n=>{let e=$.safeParse(n);return e.success?e.data:void 0});function j(n=E()){return k(n)}function v(n,e){return O(n,`${s(e)}.env.lock`)}function K(n,e,o,r={}){let m=v(n,e),y=i.parse(o.env),t=l.acquire(m,h=>({...h,operation:o.operation,env:y,...o.alias!==void 0?{alias:o.alias}:{}}),r);return"busy"in t?{busy:L(t.busy)}:{lock:{organizationId:s(e),release:t.lock.release}}}function N(n,e,o={}){let r=l.holder(v(n,e),o);return r!==void 0?L(r):void 0}function L({version:n,token:e,...o}){return o}function g(n){return`process ${n.pid} on ${n.host}, since ${n.acquiredAt}`}function R(n){return`${w(n)}. Nothing was written: run this again once it ends. Two jobs applying to one org from two machines are not kept apart: give them one concurrency group.`}function w(n){let e=n.alias!==void 0?` to ${n.alias}`:"";return`${n.operation==="apply"?"an apply":n.operation==="recover"?"a state recover":`a ${n.operation}`} of ${n.env}${e} is under way on this machine (${g(n)})`}function _(n,e,o={}){let r=f(n,e,o);if(r!==void 0)return`a checkpoint ${r.operation} of this org is under way on this machine (${g(r)}): its records would be read or written as the step writes. Run this again once it ends.`}export{j as a,v as b,K as c,N as d,R as e,w as f,_ as g};
@@ -0,0 +1,115 @@
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 Re}from"./chunk-TW3N6W5Z.mjs";import{a as ue,b as ce}from"./chunk-5P4PHJRL.mjs";import{a as ke,b as $e,c as Ae,d as je}from"./chunk-RSWDYIHY.mjs";import{O as he,c as le}from"./chunk-VS7ZXUII.mjs";import{a as T}from"./chunk-QROPNEGY.mjs";import{b as B,e as G}from"./chunk-BZ24IAP5.mjs";import{a as U}from"./chunk-SCKUIE3R.mjs";import{c as H}from"./chunk-AV5SWEHP.mjs";import{a as fe,c as ge,d as we,e as ye,f as be}from"./chunk-I7O6C2B5.mjs";import{a as ve}from"./chunk-YRQGKDHM.mjs";import{f as ne,j as E,k as N,l as ie,m as de}from"./chunk-MJU2PGZQ.mjs";import{za as se}from"./chunk-2CNCDM56.mjs";import{y as pe}from"./chunk-4VS2V6WU.mjs";import{l as ae}from"./chunk-F43REJDZ.mjs";import{h as oe}from"./chunk-PZPJKATS.mjs";import{b as Z}from"./chunk-KDGMAGQR.mjs";import{p as re}from"./chunk-A527W53V.mjs";import{e as ee,g as te}from"./chunk-TZE3Y7IQ.mjs";import{a as X,b as K,d as V,e as Y,g as me}from"./chunk-MTMH6H2A.mjs";import{Yb as Q}from"./chunk-TTFDUKUS.mjs";import{readFileSync as De}from"node:fs";import{basename as Pe,join as Ee}from"node:path";var Te=`sandforge dataops \u2014 mask an org's records, and put them back, without the editor.
8
+
9
+ Usage:
10
+ npx sandforge dataops anonymize \\
11
+ --org <alias> [--object <ApiName>] (--template <id> | --rules <file>) [options]
12
+ npx sandforge dataops anonymize \\
13
+ --org <alias> --restore <snapshot> [--rewrite-all] [--include-changed] [--store <dir>] [--yes]
14
+ Either takes [--accept-automation] [--accept-emails] [--mute-automation].
15
+
16
+ Required:
17
+ anonymize the command
18
+ --org <alias> sf CLI alias of the org
19
+ --template <id> a template that ships (tpl-gdpr-standard, tpl-ccpa-california,
20
+ tpl-hipaa-health, tpl-sandbox-scrub) or one saved in the store
21
+ --rules <file> or a JSON file of rules, saved in the store as a template:
22
+ {"name": "...", "rules": [{"fieldPattern": "Contact.Email",
23
+ "ruleType": "hash"}]} \u2014 a rule as the panel's editor saves it
24
+
25
+ Options:
26
+ --object <ApiName> the object to mask, one per run; without it, every object
27
+ the template masks, as the panel's Apply masks them \u2014
28
+ Account's person accounts among them, in an org that has
29
+ person accounts, when the template masks contacts
30
+ --where <clause> with --object: mask only the records this SOQL condition
31
+ selects, written without WHERE
32
+ --dry-run say what a run would mask \u2014 the fields, the records, the
33
+ first records masked as a run masks them \u2014 and write
34
+ nothing
35
+ --resume mask only what the last run of the same template, object
36
+ and filter left, from where it stopped
37
+ --restore <snapshot> put back the values a snapshot holds, by Id: the id a run
38
+ printed. It reads the org's values first and writes only
39
+ the rows where one of them differs from the snapshot, and
40
+ says how many it found unchanged
41
+ --rewrite-all with --restore: write every row of the snapshot back,
42
+ the ones the org already holds as the snapshot does
43
+ included
44
+ --include-changed with --restore of the snapshot a Sync run kept of what
45
+ it wrote over: put back the records changed or deleted
46
+ since the run too, which a restore of it otherwise
47
+ leaves as they are and counts, as removing the run does
48
+ --max-age-days <n> the retention, as sandforge.backup.maxAgeDays sets it:
49
+ snapshots taken more than <n> days ago are removed as
50
+ the command starts, each named on stderr \u2014 the one a
51
+ Sync run kept of what it wrote over too, which removing
52
+ that run then no longer puts back; 0 keeps them all
53
+ (default: 30)
54
+ --store <dir> where snapshots, saved templates and checkpoints live, a
55
+ folder of your own; the one sandforge backup reads and
56
+ lists (default: ~/.sandforge/backups, under the folder
57
+ SANDFORGE_JOURNAL_DIR names when it is set)
58
+ --max-records <n> most records of the object a snapshot holds, as
59
+ sandforge.backup.maxRecordsPerObject sets it; a run with
60
+ more writes nothing, and a dry run says so (default:
61
+ 50000; 100 to 1000000, any other refused, exit 2:
62
+ past that, mask in slices with --where, each run
63
+ taking its own snapshot)
64
+ ${Ae("written over","--dry-run")} --yes do not ask before writing. Without it, a command with no
65
+ terminal to answer the question \u2014 a CI step \u2014 stops
66
+ there, exit 2, and writes nothing. It answers no to a
67
+ restore into a sandbox refreshed since its snapshot,
68
+ which only a yes typed in a terminal writes
69
+ --json emit what the panel would receive, every other line on
70
+ stderr; a preview's original values are left out
71
+ --help this text
72
+
73
+ A run takes a snapshot of the records it masks, their masked fields as they are,
74
+ before its first write, and writes nothing unless the snapshot holds every one of
75
+ them. A production org is refused.
76
+
77
+ Before it writes, a run and a --restore say what the org runs as the records are
78
+ written over \u2014 its record-triggered flows, Apex triggers, processes and workflow
79
+ rules on update, and on undelete for what a restore brings back from the recycle
80
+ bin \u2014, the emails that sends against what the org has left today, and whether
81
+ the org delivers them; a dry run says it too, and what a real run would be
82
+ refused for (with --json, the dataops:automation:response it carries).
83
+
84
+ Ctrl-C stops a run as the panel's Cancel does: before its next page, what it
85
+ masked recorded in the audit trail of the store, and --resume masks only what it
86
+ left. It stops a --restore before its next batch, what it put back recorded the
87
+ same way, and the same --restore puts back the rest. Ctrl-C again ends the
88
+ process at once. A SIGTERM \u2014 a CI job cancelled or timed out \u2014 or a SIGHUP
89
+ stops it the same way.
90
+
91
+ Exit codes: 0 the run masked every record it counted, or the restore put back
92
+ every value; 1 it could not start, was refused or failed \u2014 what the org runs as
93
+ it writes, without --accept-automation (AUTOMATION_NOT_ACCEPTED), emails it
94
+ delivers, without --accept-emails (EMAILS_NOT_ACCEPTED), more emails than it
95
+ has left today (EMAILS_EXCEEDED), or a mute refused among the reasons \u2014, or a
96
+ --dry-run saw that a run would be refused; 2 a bad command line,
97
+ or a question with no terminal to answer it (give --yes); 3 the run left
98
+ records unmasked, their personal data still in the org (--resume masks what
99
+ it left), or the restore left values as they are (rows the org refused, a
100
+ snapshot that holds part of the records, or records of a Sync run's snapshot
101
+ changed since the run, held back without --include-changed); 130 Ctrl-C
102
+ stopped the run, 143 a SIGTERM, 129 a SIGHUP.
103
+ `,_e=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,Me={words:1,switches:["--dry-run","--resume","--rewrite-all","--include-changed","--yes","--json",...ke],values:["--org","--object","--template","--rules","--where","--restore","--store","--max-records","--max-age-days"]};function h(o){process.stderr.write(`${o}
104
+ `),process.exit(2)}function Fe(o){let e;try{e=JSON.parse(De(o,"utf8"))}catch(a){h(`Cannot read the rules in ${o}: ${a instanceof Error?a.message:String(a)}`)}let r=Array.isArray(e)?{rules:e}:e,s=typeof r=="object"&&r!==null&&!("name"in r)?{...r,name:`Rules from ${Pe(o)}`}:r,i=se.safeParse(s);if(!i.success){let a=i.error.issues.map(w=>`${w.path.join(".")||"(file)"}: ${w.message}`).join("; ");h(`The rules in ${o} are not rules the panel saves: ${a}`)}return i.data}function ze(o){let e=o.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(Te),process.exit(0)),e[0]!=="anonymize"&&h(`The command is anonymize: ${U("dataops")} anonymize --org \u2026 Run with --help.`),X(e,Me);let r=p=>{let m=e.indexOf(p),L=m>=0?e[m+1]:void 0;return m>=0&&(L===void 0||L.startsWith("--"))&&h(`${p} needs a value.`),L},s=p=>e.filter(m=>m===p).length,i=r("--org");i||h("Missing --org. Run with --help."),K.test(i)||h(`Not an sf alias: "${i}"`);let a=r("--restore"),w=e.includes("--dry-run"),C=e.includes("--resume"),g=r("--max-records");g!==void 0&&!/^[1-9]\d*$/.test(g)&&h(`Not a number of records: "${g}"`),g!==void 0&&(Number(g)<E||Number(g)>N)&&h(`--max-records takes ${E} to ${N} records, not ${g}: a snapshot holds at least ${E} records of one object and at most ${N}; past that, mask in slices with --where, each run taking its own snapshot.`);let c=e.includes("--rewrite-all");c&&a===void 0&&h("--rewrite-all goes with --restore.");let A=e.includes("--include-changed");A&&a===void 0&&h("--include-changed goes with --restore.");let f=we(r("--max-age-days")),k={org:i,rewriteAll:c,includeChanged:A,...f!==void 0?{maxAgeDays:f}:{},storeDir:r("--store")??fe(),...g!==void 0?{maxRecords:Number(g)}:{},yes:e.includes("--yes"),json:e.includes("--json"),accord:$e(e)};if(a!==void 0){let p=["--object","--template","--rules","--where","--dry-run","--resume"].filter(m=>e.includes(m));return p.length>0&&h(`--restore puts a snapshot back as it is: drop ${p.join(", ")}.`),{...k,mode:"restore",restoreId:a}}s("--object")>1&&h("Give one --object at most: a run masks one object, or every object its template masks.");let l=r("--object");l!==void 0&&!_e.test(l)&&h(`Not an SObject API name: "${l}"`);let y=r("--template"),$=r("--rules");y===void 0==($===void 0)&&h("Give one of --template or --rules: the rules a run masks with."),w&&C&&h("Give one of --dry-run or --resume.");let u=r("--where")?.trim();return u!==void 0&&(u===""||!ee(u))&&h(`Not a filter --where can take: "${u}". ${te}`),u!==void 0&&l===void 0&&h("--where filters the records of one object: give it with --object."),{...k,mode:w?"dry-run":C?"resume":"run",...l!==void 0?{object:l}:{},...y!==void 0?{templateId:y}:{},...$!==void 0?{rules:Fe($)}:{},...u!==void 0?{where:u}:{}}}function Ne(o,e){let r=`${e.toLowerCase()}.`;return o.rules.filter(s=>s.fieldPattern.toLowerCase().startsWith(r)||s.fieldPattern==="*")}function We(o,e){return Ne(o,e).length>0?!0:e.toLowerCase()===re.toLowerCase()&&ne(o.rules).length>0}function Ue(o,e){let r=s=>JSON.stringify(s.map(i=>[i.fieldPattern.toLowerCase(),i.ruleType,i.config??null]).sort((i,a)=>String(i[0]).localeCompare(String(a[0]))));return r(o)===r(e)}function Be(o){if(o==null||o==="")return"(empty)";let e=typeof o=="string"?o:JSON.stringify(o);return JSON.stringify(e.length>40?`${e.slice(0,39)}\u2026`:e)}function Ge(o,e){let r=[];typeof o.message=="string"&&r.push(o.message);for(let a of o.objects??[])r.push(` ${a.objectApiName.padEnd(28)} counted ${a.total} masked ${a.processed} refused ${a.failed} still original ${a.notMasked}`);let s=o.errors??[];s[0]&&r.push(` e.g. ${s[0].objectApiName}: ${s[0].message}`);let i=o.snapshot;return i&&r.push(`snapshot ${i.operationId}: ${i.totalRecords} record(s) as they were before the run. To put their values back:`,` ${e(i.operationId)}`),r}function He(o,e){return`${o}.${e}: the org has no such field, or field-level security hides it from this user \u2014 a run is refused and masks nothing (give the user read and edit access to it, or take it out of the template)`}function Se(o,e){return e===void 0?`${o}: this user may not edit its records \u2014 a run is refused (CRUD_FLS_DENIED) and masks nothing (give the user edit access to the object)`:`${o}.${e}: this user may read it and not edit it \u2014 a run is refused (CRUD_FLS_DENIED) and masks nothing (give the user edit access to it, or take it out of the template)`}function qe(o,e={}){let r=o.fieldsNotFound??[],s=o.objects??[],i=e.objects??[];return r.length>0||s.some(a=>a.notCovered===!0||a.error!==void 0||a.writeDenied!==void 0)||i.some(a=>a.count===null)}function Je(o,e){return o.flatMap(({objectApiName:r,count:s})=>{if(s===null||s<=e)return[];let i=`${r} holds ${s} record(s) a run would mask, more than`;return[s>N?`${i} a snapshot holds of one object, ${N} at most, and nothing raises that: mask it in slices, each a run of its own with --object ${r} and a --where that selects fewer (a range of CreatedDate, say), each taking its own snapshot`:`${i} the ${e} a snapshot holds of one object: give --max-records up to ${N}, or narrow the run with --object and --where`]})}function Qe(o,e,r){let s=["dry run \u2014 nothing is written"],i=e.objects??[],a=r.objects??[],w=r.fieldsNotFound??[];for(let c of i){let A=c.count===null?"an unknown number of":String(c.count);s.push(` ${c.objectApiName}: ${A} record(s) to mask`),c.count===null&&s.push(" not counted by the org: a run stops at its count and masks nothing");let f=a.find(u=>u.objectApiName===c.objectApiName);if(f?.error){s.push(` not read: ${f.error}`);continue}let k=new Map([...Ne(o,c.objectApiName).map(u=>[u.fieldPattern.split(".").pop()?.toLowerCase()??"",u.ruleType]),...Object.entries(f?.methods??{}).map(([u,p])=>[u.toLowerCase(),p])]),l=f?.fields??[];s.push(` fields: ${l.map(u=>`${u} (${k.get(u.toLowerCase())??"?"})`).join(", ")||"(none)"}`);for(let u of w.filter(p=>p.objectApiName===c.objectApiName))s.push(` ${He(u.objectApiName,u.fieldApiName)}`);f?.notCovered&&s.push(" no field of it can be masked: a run is refused and masks nothing");let y=f?.writeDenied?.deniedFields;y?.length===0&&s.push(` ${Se(c.objectApiName)}`);for(let u of y??[])s.push(` ${Se(c.objectApiName,u)}`);let $=f?.rows??[];if($.length>0){s.push(" the first records, masked as a run masks them (a run draws its own key, so its made-up names and digests differ from these):");for(let u of $)s.push(` ${u.id}: ${l.map(p=>`${p} ${Be(u.after[p])}`).join(", ")}`)}}let C=i.reduce((c,A)=>c+(A.count??0),0);C>0&&s.push(` a run takes a snapshot of these ${C} record(s) first, and writes nothing without it`);let g=e.checkpoint;return g&&s.push(` a run of this template, object and filter stopped short on ${g.savedAt}: --resume masks only what it left`),s}function Xe(o){return`interrupted: the restore stopped before it was through; what it restored is in the audit trail, and the same line puts back the rest: ${o}`}function Ke(){return"interrupted: the masking stopped before it was through; what it masked is in the audit trail, the snapshot puts their values back (--restore), and the same line with --resume masks only what it left"}function Ze(o){return o.map(e=>{if(e.type!=="dataops:anonymize:preview:response")return e;let r=e.payload?.objects??[];return{...e,payload:{...e.payload,objects:r.map(s=>({...s,rows:(s.rows??[]).map(({id:i,after:a})=>({id:i,after:a}))}))}}})}async function Ve(o=process.argv){let e=ze(o),r=t=>{process[e.json?"stderr":"stdout"].write(`${t}
105
+ `)},s=t=>{process.stderr.write(`${t}
106
+ `),process.exitCode=1},i=ge(e.storeDir);if(i!==void 0){s(i);return}let a=await Z(e.org),w=await new ve().validateConnection(a.accessToken,a.instanceUrl),C={alias:e.org,orgType:Q({isSandbox:w.isSandbox,edition:w.orgType}),metadata:{apiVersion:"66.0",edition:w.orgType}};r(`sandforge dataops ${e.org} (${w.isSandbox?"sandbox":w.orgType||"production"}) store: ${e.storeDir}`);let g=pe(Ee(e.storeDir,"snapshots.json")),c=[],A=new Map,f=new Re,k=new de({log:t=>{/^\[(WARN|INFO)\]/.test(t)&&r(` ${t}`)},broker:{postToWebview:t=>{if(c.push(t),t.type!=="operation:progress")return;let n=String(t.payload?.operationId??""),d=Number(t.payload?.percentage??0);(d-(A.get(n)??-10)>=10||d===100)&&(A.set(n,d),r(` ${d}% ${String(t.payload?.currentStep??"")}`))}},orgManager:{getOrg:()=>C},orgRegistry:{getCredentials:async()=>({accessToken:a.accessToken,instanceUrl:a.instanceUrl})},configStore:g,services:{getSandforgeSetting:ye(e)},infraServices:{backgroundRegistry:f,productionGuard:new ae({requestConfirmation:(t,n)=>(r(`refused: ${e.org} is taken for a ${n} org, and this command writes to none (${t})`),Promise.resolve(!1))}),confirmRestoreIntoReplacedOrg:({alias:t,backedUpFrom:n,now:d})=>e.yes?Promise.resolve(!1):T(`${t} answered as org ${n} when this snapshot was taken and answers as org ${d} now. Write its saved values into the org it is now?`)},nextId:()=>`cli-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});k.setExpiryListener(t=>process.stderr.write(`${be(t)}
107
+ `)),k.setBackupRecordStore(new ce(ue(e.storeDir))),await k.swept(),k.setSyncRuns(oe(he())),k.setMuteOffered(le("--mute-automation")),k.setOnCommandLine(!0);let l=async(t,n)=>{let d=`cli-${t.replaceAll(":","-")}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return await k.handle({id:d,type:t,timestamp:Date.now(),payload:n}),c.find(v=>v.correlationId===d&&(v.type===`${t}:response`||v.type==="dataops:error"))??{type:"dataops:error",payload:{message:`${t} was not answered.`}}},y=t=>t.type==="dataops:error",$=t=>String(t.payload?.message??t.type),u=t=>`${U("dataops")} anonymize --org ${e.org} --restore ${t} --store ${e.storeDir}`,p=async(t,n)=>{let d=await l("dataops:automation",{orgId:e.org,act:t,objects:n,...e.accord});if(y(d)){s($(d));return}let S=d.payload;for(let v of S.lines)r(v);return S},m=t=>{e.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-dataops",command:t,org:e.org,posted:Ze(c)},null,2)}
108
+ `)};if(e.mode==="restore"){let t=e.restoreId,n=g.get(`backup:${t}`);if(!n){s(`No snapshot "${t}" in ${e.storeDir}.`);return}let d=(n.objects??[]).map(R=>R.objectApiName).join(", "),S=await p("restore",(n.objects??[]).map(R=>({objectApiName:R.objectApiName,records:R.recordCount??0})));if(!S){m("restore");return}if(S.refusals.length>0){m("restore");for(let R of S.refusals)s(H(R));return}if(!e.yes&&!await T(`Put back into ${e.org} the values snapshot ${t} holds? ${n.totalRecords??"?"} record(s) of ${d} will have those fields written over.`)){r("Nothing written.");return}r(`restoring ${t} into ${e.org}${e.rewriteAll?", every row written back":""}\u2026`);let v,Oe=G(R=>{v=R,process.stderr.write(`
109
+ interrupted: the restore stops before its next batch, and says what it restored (Ctrl-C again ends it at once)
110
+ `);for(let Ie of f.getRunning())f.abort(Ie.operationId)}),O;try{O=await l("dataops:rollback",{orgId:e.org,operationId:t,...e.rewriteAll?{rewriteAll:!0}:{},...e.includeChanged?{includeChanged:!0}:{},...e.accord})}finally{Oe()}if(m("restore"),y(O)){s($(O)),e.yes&&O.payload?.code==="ORG_REPLACED_SINCE_BACKUP"&&s("--yes does not answer this question: it is answered yes only when typed in a terminal. Run the same line without --yes in a terminal to answer it; nothing answers it from a CI step.");return}if(r(String(O.payload?.message??"")),v){process.stderr.write(`${Xe(u(t))}
111
+ `),process.exitCode=B(v);return}Y(V(O.payload??{}));return}let _=(await l("dataops:anonymization-templates",{})).payload?.templates??[],b;if(e.rules){let t=e.rules,n=_.find(d=>d.saved===!0&&d.name.trim().toLowerCase()===t.name.toLowerCase());if(n&&Ue(n.rules,t.rules))b=n;else{n&&await l("dataops:anonymization-template:delete",{templateId:n.id});let d=await l("dataops:anonymization-template:save",{name:t.name,rules:t.rules});if(y(d)){s($(d));return}b=d.payload?.template,r(`rules saved in the store as template "${b.name}" (${b.id})`)}}else if(b=_.find(t=>t.id===e.templateId),!b){s(`No template "${e.templateId??""}". Templates: `+_.map(t=>`${t.id}${t.saved?` (saved: ${t.name})`:""}`).join(", "));return}let j=e.object;if(j!==void 0&&!We(b,j)){s(`Template "${b.name}" has no rule for ${j}: a run would mask nothing.`);return}let M={orgId:e.org,templateId:b.id,...j!==void 0?{objects:[j]}:{},...e.where!==void 0?{where:e.where}:{}};r(`template: ${b.name} (${b.id}) `+(j!==void 0?`object: ${j}`:"objects: every object the template masks")+(e.where!==void 0?` where: ${e.where}`:""));let x=await l("dataops:anonymize:coverage",M);if(y(x)){s($(x));return}let I=x.payload?.objects??[],q=I.reduce((t,n)=>t+(n.count??0),0),D=Je(I,ie(e.maxRecords)),J=I.map(t=>({objectApiName:t.objectApiName,records:t.count??0}));if(e.mode==="dry-run"){let t=await l("dataops:anonymize:preview",M);if(y(t)){m("dry-run"),s($(t));return}for(let d of Qe(b,x.payload??{},t.payload??{}))r(d);let n=await p("masking",J);if(m("dry-run"),!n)return;for(let d of je(n))r(d);for(let d of D)r(` a run would be refused: ${d}`);(D.length>0||n.refusals.length>0||qe(t.payload??{},x.payload??{}))&&(process.exitCode=1);return}let F=x.payload?.checkpoint;if(e.mode==="resume"&&!F){s(`There is nothing to resume: no run of this template, object and filter stopped short in ${e.storeDir}.`);return}if(e.mode==="run"&&q===0){let t=I.filter(n=>n.count===null).map(n=>n.objectApiName);if(t.length>0){s(`${t.join(", ")}: the org did not count the records a run would mask, so nothing was masked (its reason is in the warning above).`);return}r(j!==void 0?"Nothing to mask: no record of the object is under the filter.":"Nothing to mask: no object the template masks holds a record."),m("run");return}if(e.mode==="run"&&D.length>0){m("run");for(let t of D)s(`Nothing was masked: ${t}.`);return}let z=await p("masking",J);if(!z){m(e.mode);return}if(z.refusals.length>0){m(e.mode);for(let t of z.refusals)s(H(t));return}if(!e.yes){let t=j??I.map(d=>d.objectApiName).join(", "),n=e.mode==="resume"?`Resume the masking of ${t} in ${e.org} that stopped on ${F.savedAt}? What it left is written over; the snapshot the first run took holds their values.`:`Mask ${q} record(s) of ${t} in ${e.org} with ${b.name}? A snapshot of their values is taken first.`;if(!await T(n)){r("Nothing written.");return}}r(e.mode==="resume"?"resuming\u2026":"masking\u2026");let W,xe=G(t=>{W=t,process.stderr.write(`
112
+ interrupted: the masking stops before its next page, and says what it masked (Ctrl-C again ends it at once)
113
+ `);for(let n of f.getRunning())f.abort(n.operationId)}),P;try{P=await l("dataops:anonymize",{...M,...e.mode==="resume"?{resumeFrom:F.id}:{snapshot:!0},...e.accord})}finally{xe()}m(e.mode);for(let t of Ge(P.payload??{},u))r(t);if(W){process.stderr.write(`${Ke()}
114
+ `),process.exitCode=B(W);return}if(y(P)){process.exitCode=1;return}Number(P.payload?.recordsNotMasked??0)>0&&(r("A resume masks only what this run left: the same line with --resume, in place of the snapshot it does not take again."),process.exitCode=3)}/sandforge-dataops\.[cm]?[jt]s$/.test(process.argv[1]??"")&&(me(),Ve().then(()=>process.exit()).catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
115
+ `),process.exit(1)}));export{ze as a,We as b,Ge as c,He as d,Se as e,qe as f,Je as g,Qe as h,Xe as i,Ke as j,Ve as k};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as R}from"./chunk-CE6ZDGBB.mjs";import{E as g,F as u,J as w,M as m,N as I,O as k}from"./chunk-CGWXQX75.mjs";import{g as T}from"./chunk-SIOZXPFG.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{vb as y}from"./chunk-B45CNPUX.mjs";var b="Opportunity",v=new Set(["Id","OpportunityId",u,"IsPrimary"]),O=200,l=s=>s.slice(0,15);function S(s){return`The contact roles the platform wrote with the run's opportunities were not looked up, so written as generated: an opportunity may hold the role of its contact twice. ${s}`}var P=class{constructor(e){this.deps=e}deps;sentWith=new Map;untold;linkedIds=[];said;unread;alike=0;opportunitiesWritten(e,d){let r=t=>{let n=t?.[u];return typeof n=="string"&&n!==""?n:void 0},o=d.rows&&(d.rows.length===e.length||d.stopped)?d.rows:void 0;if(!o){d.successIds.length>0&&e.some(t=>r(t))&&(this.untold??="The opportunities' insert did not say which record each id it answered is.");return}o.forEach((t,n)=>{let a=r(e[n]);if(!(!t.id||a===void 0)){if(t.unmatched){this.untold??="The opportunities' insert did not say which record each id it answered is.";return}this.sentWith.set(l(t.id),a)}})}async link(e){if(e.length>0&&this.untold!==void 0&&(this.unread??=this.untold),this.sentWith.size===0||e.length===0)return new Map;let d=e.map(i=>({OpportunityId:i.OpportunityId,[u]:i[u],IsPrimary:i.IsPrimary})),r=i=>this.sentWith.get(l(i)),o=this.deps.readTarget;if(!o)return W(d,r)&&(this.unread??="This run cannot read the target."),new Map;let t;try{t=await k(o,d,r,A(e))}catch(i){return this.unread??=h(i),new Map}let{found:n,alike:a}=t;this.alike+=a.length;for(let i of[...n.keys(),...a])this.sentWith.delete(l(String(e[i].OpportunityId)));return n.size>0&&await this.give(e,n),n}async give(e,d){let r=this.said??={records:0,given:0},o=[];for(let[n,a]of d){let i=String(a.Id);this.linkedIds.push(i),r.records++;let p=Object.entries(e[n]??{}).filter(([f,c])=>!v.has(f)&&c!==null&&c!==void 0&&String(a[f]??"")!==String(c));p.length>0&&o.push({Id:i,...Object.fromEntries(p)})}if(o.length===0)return;let t=n=>{r.refusal??=n};if(!this.deps.update)return t("This run cannot update the target.");for(let n=0;n<o.length;n+=O){if(this.deps.stopped())return t("The run was stopped before they were given them.");let a=o.slice(n,n+O),i;try{i=await this.deps.update(this.deps.orgId,g,a)}catch(p){t(h(p));continue}a.forEach((p,f)=>{let c=i[f];c?.success?r.given++:t(c?.error??"The org gave no answer for it.")})}}resultOf(e){return e!==g?{linkedIds:[],notes:[]}:{linkedIds:this.linkedIds,...this.said?{writtenByThePlatform:{...this.said}}:{},notes:[...this.unread!==void 0?[S(this.unread)]:[],...this.alike>0?[m(this.alike,"generated")]:[]]}}};function A(s){return[...new Set(s.flatMap(e=>Object.keys(e)))].filter(e=>!v.has(e))}function W(s,e){return s.some(d=>{let r=d.OpportunityId,o=d[u];if(typeof r!="string"||typeof o!="string")return!1;let t=e(r);return t!==void 0&&l(t)===l(o)})}function j(){let s=new Map,e=0;return{inserted(d,r,o){d===b&&r.forEach((t,n)=>{let a=t[u],i=o[n];i!==void 0&&typeof a=="string"&&a!==""&&s.set(i,a)})},readTarget:async d=>{let r=w(d);if(!r)throw new Error("A dry run reads nothing else of the target here.");let o=new Date().toISOString();return r.opportunities.flatMap(t=>{let n=s.get(t);return n===void 0?[]:[I({...Object.fromEntries(r.fields.map(a=>[a,null])),Id:`dry-role-${e++}`,OpportunityId:t,[u]:n,...r.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},o)]})},update:async(d,r,o)=>o.map(()=>({success:!0}))}}function _(s){if(s)return`${s.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${s.given} given the fields the seed generated for ${s.given===1?"it":"them"}`+(s.refusal!==void 0?`, the others left as the platform wrote them (${s.refusal}).`:".")}function B(s){return{readTarget:e=>R(s,e),update:async(e,d,r)=>{let o=await s.sobject(d).update(r,{allOrNone:!1,headers:y()}),t=Array.isArray(o)?o:[o];return r.map((n,a)=>{let i=t[a];return i?.success===!0?{success:!0}:{success:!1,error:(i?.errors??[]).length>0?T(i?.errors):"The org gave no answer for it."}})}}}export{b as a,S as b,P as c,j as d,_ as e,B as f};
7
+ import{a as R}from"./chunk-CE6ZDGBB.mjs";import{E as g,F as u,J as w,M as m,N as I,O as k}from"./chunk-A527W53V.mjs";import{g as T}from"./chunk-GGD7ON3M.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{yb as y}from"./chunk-TTFDUKUS.mjs";var b="Opportunity",v=new Set(["Id","OpportunityId",u,"IsPrimary"]),O=200,l=s=>s.slice(0,15);function S(s){return`The contact roles the platform wrote with the run's opportunities were not looked up, so written as generated: an opportunity may hold the role of its contact twice. ${s}`}var P=class{constructor(e){this.deps=e}deps;sentWith=new Map;untold;linkedIds=[];said;unread;alike=0;opportunitiesWritten(e,d){let r=t=>{let n=t?.[u];return typeof n=="string"&&n!==""?n:void 0},o=d.rows&&(d.rows.length===e.length||d.stopped)?d.rows:void 0;if(!o){d.successIds.length>0&&e.some(t=>r(t))&&(this.untold??="The opportunities' insert did not say which record each id it answered is.");return}o.forEach((t,n)=>{let a=r(e[n]);if(!(!t.id||a===void 0)){if(t.unmatched){this.untold??="The opportunities' insert did not say which record each id it answered is.";return}this.sentWith.set(l(t.id),a)}})}async link(e){if(e.length>0&&this.untold!==void 0&&(this.unread??=this.untold),this.sentWith.size===0||e.length===0)return new Map;let d=e.map(i=>({OpportunityId:i.OpportunityId,[u]:i[u],IsPrimary:i.IsPrimary})),r=i=>this.sentWith.get(l(i)),o=this.deps.readTarget;if(!o)return W(d,r)&&(this.unread??="This run cannot read the target."),new Map;let t;try{t=await k(o,d,r,A(e))}catch(i){return this.unread??=h(i),new Map}let{found:n,alike:a}=t;this.alike+=a.length;for(let i of[...n.keys(),...a])this.sentWith.delete(l(String(e[i].OpportunityId)));return n.size>0&&await this.give(e,n),n}async give(e,d){let r=this.said??={records:0,given:0},o=[];for(let[n,a]of d){let i=String(a.Id);this.linkedIds.push(i),r.records++;let p=Object.entries(e[n]??{}).filter(([f,c])=>!v.has(f)&&c!==null&&c!==void 0&&String(a[f]??"")!==String(c));p.length>0&&o.push({Id:i,...Object.fromEntries(p)})}if(o.length===0)return;let t=n=>{r.refusal??=n};if(!this.deps.update)return t("This run cannot update the target.");for(let n=0;n<o.length;n+=O){if(this.deps.stopped())return t("The run was stopped before they were given them.");let a=o.slice(n,n+O),i;try{i=await this.deps.update(this.deps.orgId,g,a)}catch(p){t(h(p));continue}a.forEach((p,f)=>{let c=i[f];c?.success?r.given++:t(c?.error??"The org gave no answer for it.")})}}resultOf(e){return e!==g?{linkedIds:[],notes:[]}:{linkedIds:this.linkedIds,...this.said?{writtenByThePlatform:{...this.said}}:{},notes:[...this.unread!==void 0?[S(this.unread)]:[],...this.alike>0?[m(this.alike,"generated")]:[]]}}};function A(s){return[...new Set(s.flatMap(e=>Object.keys(e)))].filter(e=>!v.has(e))}function W(s,e){return s.some(d=>{let r=d.OpportunityId,o=d[u];if(typeof r!="string"||typeof o!="string")return!1;let t=e(r);return t!==void 0&&l(t)===l(o)})}function j(){let s=new Map,e=0;return{inserted(d,r,o){d===b&&r.forEach((t,n)=>{let a=t[u],i=o[n];i!==void 0&&typeof a=="string"&&a!==""&&s.set(i,a)})},readTarget:async d=>{let r=w(d);if(!r)throw new Error("A dry run reads nothing else of the target here.");let o=new Date().toISOString();return r.opportunities.flatMap(t=>{let n=s.get(t);return n===void 0?[]:[I({...Object.fromEntries(r.fields.map(a=>[a,null])),Id:`dry-role-${e++}`,OpportunityId:t,[u]:n,...r.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},o)]})},update:async(d,r,o)=>o.map(()=>({success:!0}))}}function _(s){if(s)return`${s.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${s.given} given the fields the seed generated for ${s.given===1?"it":"them"}`+(s.refusal!==void 0?`, the others left as the platform wrote them (${s.refusal}).`:".")}function B(s){return{readTarget:e=>R(s,e),update:async(e,d,r)=>{let o=await s.sobject(d).update(r,{allOrNone:!1,headers:y()}),t=Array.isArray(o)?o:[o];return r.map((n,a)=>{let i=t[a];return i?.success===!0?{success:!0}:{success:!1,error:(i?.errors??[]).length>0?T(i?.errors):"The org gave no answer for it."}})}}}export{b as a,S as b,P as c,j as d,_ as e,B as f};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{c as I}from"./chunk-UNDIBZWG.mjs";import{a as N,b as O}from"./chunk-CA5NAXSU.mjs";import{b as l,n as m}from"./chunk-7EANH5PY.mjs";var V="tooling",M={GenAiPlannerDefinition:["Id","DeveloperName","MasterLabel"],GenAiPlannerFunctionDef:["PlannerId","Plugin"],GenAiPluginDefinition:["Id","DeveloperName","LocalDeveloperName","MasterLabel","Description"],GenAiPluginFunctionDef:["PluginId","Function"],GenAiFunctionDefinition:["Id","DeveloperName","LocalDeveloperName","MasterLabel","Description"],GenAiPlannerAttrDefinition:["ParentId","DeveloperName","ParameterName"]},_="DeveloperName",y=200,j="This org has no Agentforce agent: the records this run wrote stay, usable as they are. Create an agent in Setup > Agentforce Agents, then write the test file from this run.",v="This org has no Agentforce, which takes a Salesforce license: it has no GenAiPlannerDefinition, the object that lists its agents. The records this run wrote stay, usable as they are.",g=l().nullish().transform(n=>n==null||n===""?void 0:n),z={GenAiPlannerDefinition:m({Id:l().min(1),DeveloperName:l().min(1),MasterLabel:g}),GenAiPlannerFunctionDef:m({PlannerId:l().min(1),Plugin:g}),GenAiPluginDefinition:m({Id:l().min(1),DeveloperName:l().min(1),LocalDeveloperName:g,MasterLabel:g,Description:g}),GenAiPluginFunctionDef:m({PluginId:l().min(1),Function:g}),GenAiFunctionDefinition:m({Id:l().min(1),DeveloperName:l().min(1),LocalDeveloperName:g,MasterLabel:g,Description:g}),GenAiPlannerAttrDefinition:m({ParentId:l().min(1),DeveloperName:l().min(1),ParameterName:g})},D=class extends Error{constructor(t,d,s){super(s);this.object=t;this.code=d;this.name="CatalogRefusal"}object;code};async function W(n){try{let e=await E(n,"GenAiPlannerDefinition");if(e.length===0)return{kind:"no-agent",reason:"none",message:j};let t=e.map(a=>a.Id),d=await A(n,"GenAiPlannerFunctionDef","PlannerId",t),s=await A(n,"GenAiPlannerAttrDefinition","ParentId",t),o=await A(n,"GenAiPluginDefinition","Id",d.map(a=>a.Plugin)),i=await A(n,"GenAiPluginFunctionDef","PluginId",o.map(a=>a.Id)),r=await A(n,"GenAiFunctionDefinition","Id",i.map(a=>a.Function)),f=G(o),L=G(r),T=a=>{let u=R(i.filter(p=>b(p.PluginId,a)).map(p=>p.Function),L);return{actions:u.items,unnamedActions:u.unnamed}};return{kind:"agents",catalog:{agents:e.map(a=>{let u=R(d.filter(c=>b(c.PlannerId,a.Id)).map(c=>c.Plugin),f),p=u.items.map((c,x)=>{let w=u.rows[x];return w?{...c,...T(w.Id)}:{...c,actions:[],unnamedActions:0}});return{id:a.Id,name:a.DeveloperName,...a.MasterLabel!==void 0?{label:a.MasterLabel}:{},topics:p,unnamedTopics:u.unnamed,variables:s.filter(c=>b(c.ParentId,a.Id)).map(c=>({name:c.DeveloperName,...c.ParameterName!==void 0?{parameterName:c.ParameterName}:{}}))}}).sort((a,u)=>C(a.name,u.name))}}}catch(e){if(!(e instanceof D))throw e;return e.object==="GenAiPlannerDefinition"&&e.code==="INVALID_TYPE"?{kind:"no-agent",reason:"no-agentforce",message:v}:{kind:"unreadable",object:e.object,message:`The org would not read ${e.object}: ${e.message}`}}}function H(n,e){return n.agents.find(t=>t.name===e)}function Z(n,e){return n.topics.find(t=>t.name===e)?.actions.map(t=>t.name)??[]}var h=["Off_Topic"];function B(n){return n.topics.find(e=>h.includes(e.name)||h.includes(e.localName??""))?.name}function U(n,e){return n.variables.some(t=>t.name===e||t.parameterName===e)}async function E(n,e,t){let d=`SELECT ${M[e].join(", ")} FROM ${e}${t?` WHERE ${t}`:""}`,s;try{s=await n(d)}catch(i){let r=O(i);throw new D(e,k(i)??N(r),r)}let o=z[e];return s.map(i=>{let r=o.safeParse(i);if(!r.success){let f=r.error.issues[0];throw new D(e,void 0,`a row has no ${f.path.join(".")} the catalog can read (${f.message})`)}return r.data})}async function A(n,e,t,d){let s=[...new Set(d.filter(i=>i!==void 0&&I(i)))],o=[];for(let i=0;i<s.length;i+=y){let r=s.slice(i,i+y).map(f=>`'${f}'`);o.push(...await E(n,e,`${t} IN (${r.join(", ")})`))}return o}function k(n){if(typeof n!="object"||n===null)return;let{errorCode:e,name:t}=n;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(t))return t}function P(n){return n.slice(0,15)}function b(n,e){return P(n)===P(e)}function G(n){return new Map(n.map(e=>[P(e.Id),e]))}function R(n,e){let t=new Map,d=0;for(let o of n){if(o===void 0)continue;if(!I(o)){t.has(o)||t.set(o,{item:{name:o,described:!1}});continue}let i=e.get(P(o));if(!i){d++;continue}let r=i[_];t.has(r)||t.set(r,{row:i,item:{name:r,...i.LocalDeveloperName!==void 0?{localName:i.LocalDeveloperName}:{},...i.MasterLabel!==void 0?{label:i.MasterLabel}:{},...i.Description!==void 0?{description:i.Description}:{},described:!0}})}let s=[...t.values()].sort((o,i)=>C(o.item.name,i.item.name));return{items:s.map(o=>o.item),rows:s.map(o=>o.row),unnamed:d}}function C(n,e){return n<e?-1:n>e?1:0}export{V as a,M as b,_ as c,j as d,v as e,W as f,H as g,Z as h,h as i,B as j,U as k};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{i as E}from"./chunk-57VHUYNG.mjs";import{b as j,c as S,e as U,m as O,n as P,o as C}from"./chunk-342FN7AO.mjs";import{h as B}from"./chunk-PA3MKJVH.mjs";import{ca as N}from"./chunk-CGWXQX75.mjs";import{Kc as A,Sc as y}from"./chunk-B45CNPUX.mjs";var h="No record was written.",l=e=>e.toLocaleString("en-US"),D=e=>e.toDelete.createdSince+e.toDelete.broughtBackSince+e.toDelete.comesBackWithParent,$=e=>e.toBringBack.inBin+e.toBringBack.withParent+e.toBringBack.deletedWhileTaken,k=e=>e.toRecreate??0,v=e=>e.toBringBack.carriers??0;function L(e){let n=t=>D(t)+t.toGiveBack.records+$(t)+v(t)+k(t)>0,o=e.objects.filter(n).map(t=>t.objectApiName),a=e.files;return a!==void 0&&a.unlink+a.relink+a.updateLinks>0&&o.push(B),o}function M(e){return e.objects.reduce((n,o)=>({toDelete:n.toDelete+D(o),toGiveBack:n.toGiveBack+o.toGiveBack.records,toBringBack:n.toBringBack+$(o),toRecreate:n.toRecreate+k(o)}),{toDelete:0,toGiveBack:0,toBringBack:0,toRecreate:0})}function te(e,n){let o=new Set(n.objects),a=new Map(n.acts.map(i=>[i.objectApiName,i]));return{...E(e,o),objects:e.objects.filter(i=>o.has(i.objectApiName)||a.has(i.objectApiName)).map(i=>{let s=a.get(i.objectApiName),r=o.has(i.objectApiName);return{...i,toDelete:{createdSince:s?.toDelete??0,broughtBackSince:0,comesBackWithParent:0},toGiveBack:{...i.toGiveBack,records:s?.toGiveBack??0},toBringBack:{inBin:s?.toBringBack??0,withParent:0,deletedWhileTaken:0,...r&&i.toBringBack.carriers!==void 0?{carriers:i.toBringBack.carriers}:{}},toRecreate:s?.toRecreate??0,cannotUndo:r?i.cannotUndo:[],unexplained:r?i.unexplained:0}}),undoCannot:[...n.undoCannot]}}function W(e){let n=e.objects.filter(t=>D(t)+v(t)>0).map(t=>t.objectApiName),o=e.files,a=(t,i)=>i>0?[...t,B]:t;return{bringBack:e.objects.filter(t=>$(t)+v(t)>0).map(t=>t.objectApiName),recreate:a(e.objects.filter(t=>k(t)>0).map(t=>t.objectApiName),o?.relink??0),giveBack:a(e.objects.filter(t=>j(t)+U(t)>0).map(t=>t.objectApiName),o?.updateLinks??0),setToDraft:e.objects.filter(t=>S(t)>0).map(t=>t.objectApiName),delete:a(n,o?.unlink??0)}}function z(e){return new Set(e.map(n=>`${n.objectApiName}
7
+ import{i as E}from"./chunk-TTKXMDBN.mjs";import{b as j,c as S,e as U,m as O,n as P,o as C}from"./chunk-NZC67CGR.mjs";import{h as B}from"./chunk-JWTSEDIQ.mjs";import{ca as N}from"./chunk-A527W53V.mjs";import{Nc as A,Vc as y}from"./chunk-TTFDUKUS.mjs";var h="No record was written.",l=e=>e.toLocaleString("en-US"),D=e=>e.toDelete.createdSince+e.toDelete.broughtBackSince+e.toDelete.comesBackWithParent,$=e=>e.toBringBack.inBin+e.toBringBack.withParent+e.toBringBack.deletedWhileTaken,k=e=>e.toRecreate??0,v=e=>e.toBringBack.carriers??0;function L(e){let n=t=>D(t)+t.toGiveBack.records+$(t)+v(t)+k(t)>0,o=e.objects.filter(n).map(t=>t.objectApiName),a=e.files;return a!==void 0&&a.unlink+a.relink+a.updateLinks>0&&o.push(B),o}function M(e){return e.objects.reduce((n,o)=>({toDelete:n.toDelete+D(o),toGiveBack:n.toGiveBack+o.toGiveBack.records,toBringBack:n.toBringBack+$(o),toRecreate:n.toRecreate+k(o)}),{toDelete:0,toGiveBack:0,toBringBack:0,toRecreate:0})}function te(e,n){let o=new Set(n.objects),a=new Map(n.acts.map(i=>[i.objectApiName,i]));return{...E(e,o),objects:e.objects.filter(i=>o.has(i.objectApiName)||a.has(i.objectApiName)).map(i=>{let s=a.get(i.objectApiName),r=o.has(i.objectApiName);return{...i,toDelete:{createdSince:s?.toDelete??0,broughtBackSince:0,comesBackWithParent:0},toGiveBack:{...i.toGiveBack,records:s?.toGiveBack??0},toBringBack:{inBin:s?.toBringBack??0,withParent:0,deletedWhileTaken:0,...r&&i.toBringBack.carriers!==void 0?{carriers:i.toBringBack.carriers}:{}},toRecreate:s?.toRecreate??0,cannotUndo:r?i.cannotUndo:[],unexplained:r?i.unexplained:0}}),undoCannot:[...n.undoCannot]}}function W(e){let n=e.objects.filter(t=>D(t)+v(t)>0).map(t=>t.objectApiName),o=e.files,a=(t,i)=>i>0?[...t,B]:t;return{bringBack:e.objects.filter(t=>$(t)+v(t)>0).map(t=>t.objectApiName),recreate:a(e.objects.filter(t=>k(t)>0).map(t=>t.objectApiName),o?.relink??0),giveBack:a(e.objects.filter(t=>j(t)+U(t)>0).map(t=>t.objectApiName),o?.updateLinks??0),setToDraft:e.objects.filter(t=>S(t)>0).map(t=>t.objectApiName),delete:a(n,o?.unlink??0)}}function z(e){return new Set(e.map(n=>`${n.objectApiName}
8
8
  ${n.kind}
9
9
  ${n.name}`)).size}function ne(e,n,o,a=!1){let t=(c,f)=>(c??[]).includes(f),i=o.filter(c=>!t(n.recreate,c)),s=o.filter(c=>N[c]!==void 0&&!t(n.giveBack,c)),r=new Set(e.objectsRead),d=[...i,...s];return{fired:y(e,{recreate:i,giveBack:s}),blind:d.length>0&&(!a&&A(e.unread)||d.some(c=>!r.has(c)))}}var T={limit:e=>`this step's limit of ${l(e)}`,mutes:!1,lift:{acceptAutomation:"turn on muteAutomation in the step for what a bypass keeps quiet, or acceptAutomation to let it run, and confirm it again to rewind all the same",acceptEmails:"turn on acceptEmails in the step and confirm it again to rewind all the same",acceptNoUndo:"turn on acceptNoUndo in the step and confirm it again to rewind all the same",acceptRecreate:"turn on acceptRecreate in the step and confirm it again to rewind all the same",acceptUnseen:"turn on acceptUnseen in the step and confirm it again to rewind all the same",maxRecords:"preview the rewind, then raise the step's maxRecords to what it rewinds and confirm it again",refuseWhenActive:"run it once they are done, or turn off refuseWhenActive in the step and confirm it again"}},oe={...T,lift:{...T.lift,acceptAutomation:"turn on acceptAutomation in the step to let what no bypass keeps quiet run, and confirm it again to rewind all the same"}},H=[{reason:"onlyWithParent",words:"Salesforce undeletes them only with their parent, which stays"},{reason:"deletedBeforeParent",words:"deleted before a record they point at, which the rewind deletes next, Salesforce cannot bring them back after that"}],Y="Add --accept-emails to rewind all the same";function q(e,n,o,a,t){let{automation:i,deliverability:s}=n;if(!i||!s)return;let r=W(n.diff),{refusal:d}=C({act:"rewind",orgName:e,automation:i,steps:r,accepted:o.acceptEmails===!0,mayMute:t,...P({automation:i,steps:r}),reading:s.reading});if(!d)return;let c=a.acceptEmails;return{...d,message:d.message.replace(Y,`${c.charAt(0).toUpperCase()}${c.slice(1)}`)}}function ie(e,n,o,a,t="the user SandForge connects as",i=!1){return _(e,n,o,a,t,i)[0]}function _(e,n,o,a,t="the user SandForge connects as",i=!1){let s=[],{diff:r,automation:d}=n;if(r.undoCannot.length>0&&!o.acceptNoUndo){let u=H.flatMap(({reason:w,words:g})=>{let R=r.undoCannot.filter(b=>(b.reason??"onlyWithParent")===w);if(R.length===0)return[];let F=R.reduce((b,G)=>b+G.count,0),I=[...new Set(R.map(b=>b.objectApiName))].join(", ");return[`Undo couldn't bring back ${l(F)} ${I} record(s) this rewind deletes: ${g}.`]});s.push({code:"NO_UNDO",message:`${u.join(" ")} Rewind refused; ${a.acceptNoUndo}. ${h}`})}let c=r.objects.filter(u=>k(u)>0);if(c.length>0&&!o.acceptRecreate){let u=c.reduce((w,g)=>w+k(g),0);s.push({code:"RECREATE",message:`${l(u)} ${c.map(w=>w.objectApiName).join(", ")} record(s) deleted since are no longer in the recycle bin, or Salesforce keeps them there for good: this rewind makes them again from the checkpoint, with new Ids. Anything outside Salesforce that names their old Ids \u2014 an integration, a link, a report filter \u2014 no longer finds them. Rewind refused; ${a.acceptRecreate}. ${h}`})}let f=r.unseen??[];if(f.length>0&&o.acceptUnseen!==!0){let u=f.map(({objectApiName:w,children:g,records:R})=>`Deleting ${l(R)} ${w} record(s) created since also deletes what ${t} can't see under them in ${g.join(", ")}: Rewind can't count those.`);s.push({code:"UNSEEN",message:`${u.join(" ")} Rewind refused; ${a.acceptUnseen}. ${h}`})}if(!d)return s;let m=K(e,n,o,a),p=q(e,n,o,a,i);return[...s,...m?[m]:[],...p?[p]:[]]}function K(e,n,o,a){let{diff:t,automation:i,emailsUncounted:s}=n;if(!i||o.acceptAutomation)return;let r=W(t),d=y(i,r);if(d.length===0&&!A(i.unread)&&s===void 0)return;let c=[...new Set(d.map(u=>u.objectApiName))],f=(r.recreate??[]).some(u=>u!==B)?"makes them again, ":"",m=d.length>0?`${z(d)} flow(s), trigger(s) or rule(s) of ${c.join(", ")} run as the rewind brings records back, ${f}gives them their values back or deletes them`:"what runs as the rewind writes could not all be read, so automation may run",p=s!==void 0?`The emails it sends as the rewind writes were not counted against its daily limits, as what sends them was not read (${s}). `:"";return{code:"AUTOMATION",message:`${e}: ${m}. ${p}Rewind refused; ${a.acceptAutomation}. `+h}}var x=e=>e.slice(0,15);async function ae(e){return(await J(e))[0]}async function J(e){let{orgName:n,preview:o,bounds:a,words:t}=e,{diff:i}=o;if(L(i).length===0)return[];let s=[],r=M(i),d=r.toDelete+r.toGiveBack+r.toBringBack+r.toRecreate;if(a.maxRecords!==void 0&&d>a.maxRecords){let f=[`${l(r.toDelete)} to delete`,`${l(r.toGiveBack)} to give back`,`${l(r.toBringBack)} to bring back`,...r.toRecreate>0?[`${l(r.toRecreate)} to make again`]:[]];s.push({code:"TOO_MANY_TO_REWIND",message:`The rewind of ${n} would rewind ${l(d)} records (${f.join(", ")}), past ${t.limit(a.maxRecords)}. Rewind refused; ${t.lift.maxRecords}. `+h})}if(a.refuseWhenActive&&i.activeLastHour.length>0){let f=new Set((await e.writers()).map(x)),m=new Set(i.activeLastHour.map(x).filter(p=>!f.has(p)));if(m.size>0){let p=m.size===1?"1 person":`${l(m.size)} people`;s.push({code:"PEOPLE_ACTIVE",message:`${p} other than the user the rewind writes as changed records of the checkpoint's objects in ${n} in the hour before the rewind read it: it would take their work back. Rewind refused; ${t.lift.refuseWhenActive}. `+h})}}let c=O("rewind",o.emails??[],n);return[...s,..._(n,o,e.accepted,t.lift,e.user,t.mutes),...c?[c]:[]]}function re(e,n,o){let a=n.map(t=>`${t.objectApiName} (${l(t.records)})`).join(", ");return{code:"UNDELETABLE_UNATTENDED",message:`The user SandForge connects to ${e} as may not delete the ${a} record(s) this rewind deletes. With nobody to ask whether to delete the rest, the deletion was left untouched. Give the user Delete on those objects, or rewind from the Checkpoints page, which asks. `+(o?"What the rewind's first pass wrote stays: its result says what, and Undo takes it back.":h)}}function se(e,n){return{code:"NOT_CONFIRMED",message:`Rewind step "${e}" has `+(n?"not been confirmed since it was changed":"never been confirmed")+": open it and type the org's alias, or, for an org that has none, its name or Organization Id. "+h}}export{L as a,M as b,te as c,W as d,z as e,ne as f,T as g,oe as h,ie as i,ae as j,J as k,re as l,se as m};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-PUOX4NBJ.mjs";import"./chunk-EQF2IJS2.mjs";import"./chunk-RSYICMZG.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-TEOLMRDO.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SCENARIO_SIDECAR_SUFFIX,f as compiledForSidecar,g as nodeScenarioSidecarFiles,j as readScenarioRunSidecar,c as scenarioPackFingerprint,d as scenarioRunSidecar,b as scenarioRunSidecarSchema,h as scenarioSidecarPath,e as withAgentChoice,i as writeScenarioRunSidecar};
7
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SCENARIO_SIDECAR_SUFFIX,f as compiledForSidecar,g as nodeScenarioSidecarFiles,j as readScenarioRunSidecar,c as scenarioPackFingerprint,d as scenarioRunSidecar,b as scenarioRunSidecarSchema,h as scenarioSidecarPath,e as withAgentChoice,i as writeScenarioRunSidecar};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{ic as c,jc as l,lc as d,mc as m}from"./chunk-B45CNPUX.mjs";var g=class{transform(n,r){let t=n;for(let o of r)t=p(t,o.type,o.config);return t}transformRecord(n,r){let t=d([{objectApiName:r.objectApiName,transformRules:r.transformRules}]);if(t.length>0)throw new Error(m(t));let o={...n},s=(r.externalIdField??"Id").toLowerCase(),R=a=>{let i=a.toLowerCase();return i!==s&&i!=="id"};for(let a of r.transformRules){let i=a.field?.trim();if(!i)throw new Error(l(c([r])));for(let f of h(o,i))R(f)&&(o[f]=p(o[f],a.type,a.config))}return o}};function h(e,n){let r=n.toLowerCase();return Object.keys(e).filter(t=>t.toLowerCase()===r)}function u(e){return(n,r)=>typeof n=="string"?e(n,r):n}function w(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isNaN(n)?void 0:n}var b={uppercase:u(e=>e.toUpperCase()),lowercase:u(e=>e.toLowerCase()),trim:u(e=>e.trim()),truncate:u((e,n)=>e.slice(0,n.length??e.length)),prefix:u((e,n)=>`${n.prefix??""}${e}`),suffix:u((e,n)=>`${e}${n.suffix??""}`),replace:u((e,n)=>n.search?e.split(n.search).join(n.replace??""):e),regex_replace:u((e,n)=>n.regex?e.replace(y(n.regex),n.replace??""):e),map_value:(e,n)=>{let r=String(e??""),t=n.valueMap??{};return r in t?t[r]:e},default_value:(e,n)=>e==null||e===""?n.defaultValue??"":e,format_date:u((e,n)=>T(e,n.dateFormat??"YYYY-MM-DD")),format_number:(e,n)=>{let r=w(e);if(r===void 0)return e;let t=n.numberFormat??"0";return k(r,t)},custom_formula:(e,n)=>{let r=n.formula??"";return x(e,r)}};function y(e){try{return new RegExp(e,"g")}catch(n){throw new Error(`The pattern "${e}" of a Regex replace rule is no regular expression: `+(n instanceof Error?n.message:String(n)))}}function p(e,n,r){let t=b[n];return t(e,r)}function T(e,n){let r=new Date(e);if(isNaN(r.getTime()))return e;let t=r.getUTCFullYear().toString(),o=(r.getUTCMonth()+1).toString().padStart(2,"0"),s=r.getUTCDate().toString().padStart(2,"0");return n.replace("YYYY",t).replace("MM",o).replace("DD",s)}function k(e,n){let r=n.indexOf(".");if(r===-1)return Math.round(e).toString();let t=n.length-r-1;return e.toFixed(t)}function x(e,n){if(n.includes("VALUE")){let r=w(e);if(r!==void 0){let t=n.replace(/VALUE/g,r.toString());return N(t)??e}}return e}function N(e){let n=e.replace(/\s/g,""),r=/^(-?\d+(?:\.\d+)?)([-+*/])(-?\d+(?:\.\d+)?)$/.exec(n);if(!r)return;let t=Number(r[1]),o=r[2],s=Number(r[3]);switch(o){case"+":return t+s;case"-":return t-s;case"*":return t*s;case"/":return s===0?void 0:t/s;default:return}}export{g as a};
7
+ import{lc as c,mc as l,oc as d,pc as m}from"./chunk-TTFDUKUS.mjs";var g=class{transform(n,r){let t=n;for(let o of r)t=p(t,o.type,o.config);return t}transformRecord(n,r){let t=d([{objectApiName:r.objectApiName,transformRules:r.transformRules}]);if(t.length>0)throw new Error(m(t));let o={...n},s=(r.externalIdField??"Id").toLowerCase(),R=a=>{let i=a.toLowerCase();return i!==s&&i!=="id"};for(let a of r.transformRules){let i=a.field?.trim();if(!i)throw new Error(l(c([r])));for(let f of h(o,i))R(f)&&(o[f]=p(o[f],a.type,a.config))}return o}};function h(e,n){let r=n.toLowerCase();return Object.keys(e).filter(t=>t.toLowerCase()===r)}function u(e){return(n,r)=>typeof n=="string"?e(n,r):n}function w(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isNaN(n)?void 0:n}var b={uppercase:u(e=>e.toUpperCase()),lowercase:u(e=>e.toLowerCase()),trim:u(e=>e.trim()),truncate:u((e,n)=>e.slice(0,n.length??e.length)),prefix:u((e,n)=>`${n.prefix??""}${e}`),suffix:u((e,n)=>`${e}${n.suffix??""}`),replace:u((e,n)=>n.search?e.split(n.search).join(n.replace??""):e),regex_replace:u((e,n)=>n.regex?e.replace(y(n.regex),n.replace??""):e),map_value:(e,n)=>{let r=String(e??""),t=n.valueMap??{};return r in t?t[r]:e},default_value:(e,n)=>e==null||e===""?n.defaultValue??"":e,format_date:u((e,n)=>T(e,n.dateFormat??"YYYY-MM-DD")),format_number:(e,n)=>{let r=w(e);if(r===void 0)return e;let t=n.numberFormat??"0";return k(r,t)},custom_formula:(e,n)=>{let r=n.formula??"";return x(e,r)}};function y(e){try{return new RegExp(e,"g")}catch(n){throw new Error(`The pattern "${e}" of a Regex replace rule is no regular expression: `+(n instanceof Error?n.message:String(n)))}}function p(e,n,r){let t=b[n];return t(e,r)}function T(e,n){let r=new Date(e);if(isNaN(r.getTime()))return e;let t=r.getUTCFullYear().toString(),o=(r.getUTCMonth()+1).toString().padStart(2,"0"),s=r.getUTCDate().toString().padStart(2,"0");return n.replace("YYYY",t).replace("MM",o).replace("DD",s)}function k(e,n){let r=n.indexOf(".");if(r===-1)return Math.round(e).toString();let t=n.length-r-1;return e.toFixed(t)}function x(e,n){if(n.includes("VALUE")){let r=w(e);if(r!==void 0){let t=n.replace(/VALUE/g,r.toString());return N(t)??e}}return e}function N(e){let n=e.replace(/\s/g,""),r=/^(-?\d+(?:\.\d+)?)([-+*/])(-?\d+(?:\.\d+)?)$/.exec(n);if(!r)return;let t=Number(r[1]),o=r[2],s=Number(r[3]);switch(o){case"+":return t+s;case"-":return t-s;case"*":return t*s;case"/":return s===0?void 0:t/s;default:return}}export{g as a};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{b as c,j as o,k as d}from"./chunk-MFG4MUIO.mjs";import{b as i}from"./chunk-CA5NAXSU.mjs";import{n as a}from"./chunk-TTFDUKUS.mjs";var u=6e4,g=class{tokenCache=new Map;sfdxBridge;setSfdxBridge(e){this.sfdxBridge=e}async authenticate(e){switch(e.method){case"oauth_web":return this.authenticateOAuth(e);case"oauth_device":return{success:!1,error:"OAuth device flow handled via DeviceLogin and SfdxBridge.loginWithRefreshToken()"};case"jwt":return this.authenticateJwt(e);case"usernamePassword":return this.authenticateUsernamePassword(e);case"sfdx_import":return this.importFromSfdx(e.username);default:return{success:!1,error:`Unsupported auth method: ${e.method}`}}}buildConnectionConfig(e,r){return{loginUrl:e.loginUrl,clientId:e.clientId,clientSecret:e.clientSecret,accessToken:r.accessToken,refreshToken:r.refreshToken,instanceUrl:r.instanceUrl,username:e.username}}async validateConnection(e,r){let t=await o({accessToken:e,instanceUrl:r}),{identity:s,orgResult:h}=await c(t,async()=>({identity:await t.identity(),orgResult:await t.query(`SELECT Id, Name, OrganizationType, IsSandbox FROM Organization LIMIT ${a.singleRecord}`)})),n=h.records[0];return{userId:s.user_id,username:s.username,displayName:s.display_name,orgId:n.Id,orgName:n.Name,orgType:n.OrganizationType,isSandbox:n.IsSandbox}}isTokenValid(e){let r=this.tokenCache.get(e);return r?Date.now()<r.expiresAt:!1}cacheToken(e,r,t){this.tokenCache.set(e,{token:r,expiresAt:Date.now()+t})}getCachedToken(e){let r=this.tokenCache.get(e);if(!r||Date.now()>=r.expiresAt){this.tokenCache.delete(e);return}return r.token}clearTokenCache(e){this.tokenCache.delete(e)}clearAllTokens(){this.tokenCache.clear()}async authenticateOAuth(e){return{success:!1,error:"OAuth handled via SfdxBridge.loginWeb()"}}async authenticateJwt(e){return{success:!1,error:"JWT handled via SfdxBridge.loginJwt()"}}async authenticateUsernamePassword(e){if(!e.username||!e.password)return{success:!1,error:"Username and password are required"};try{let r=await o({loginUrl:e.loginUrl}),t=await d(r.login(e.username,e.password+(e.securityToken??"")),u,`${new URL(e.loginUrl).host} did not answer within ${u/1e3} s: check that this machine reaches it, through its proxy if it has one`);return{success:!0,accessToken:r.accessToken??void 0,instanceUrl:r.instanceUrl,userId:t.id,orgId:t.organizationId}}catch(r){return{success:!1,error:`Login failed: ${i(r)}`}}}async importFromSfdx(e){if(!this.sfdxBridge)return{success:!1,error:"SFDX bridge not configured"};if(!e)return{success:!1,error:"An SFDX import needs the username of the org to import"};try{let r=await this.sfdxBridge.findOrg(e);return r?{success:!0,accessToken:r.credentials.accessToken,instanceUrl:r.credentials.instanceUrl,orgId:r.org.orgId}:{success:!1,error:`No connected org for ${e} found in SF CLI`}}catch(r){return{success:!1,error:`SFDX import failed: ${i(r)}`}}}};export{g as a};