sandforge 1.79.0 → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
  2. package/lib/chunk-2CNCDM56.mjs +7 -0
  3. package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
  4. package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
  5. package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
  6. package/lib/chunk-3F6Q5E7I.mjs +14 -0
  7. package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
  8. package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
  9. package/lib/chunk-4VS2V6WU.mjs +25 -0
  10. package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
  11. package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
  12. package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
  13. package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
  14. package/lib/chunk-7ABODJ4G.mjs +7 -0
  15. package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
  16. package/lib/chunk-7FFGJWHN.mjs +7 -0
  17. package/lib/chunk-7YDNUBO5.mjs +7 -0
  18. package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
  19. package/lib/chunk-ADOAS63R.mjs +7 -0
  20. package/lib/chunk-AEKONPF4.mjs +7 -0
  21. package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
  22. package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
  23. package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
  24. package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
  25. package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
  26. package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
  27. package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
  28. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
  29. package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
  30. package/lib/chunk-CION3VMZ.mjs +7 -0
  31. package/lib/chunk-COFG7Q6R.mjs +7 -0
  32. package/lib/chunk-CSBS5U5I.mjs +7 -0
  33. package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
  34. package/lib/chunk-DB7RBE5D.mjs +7 -0
  35. package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
  36. package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
  37. package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
  38. package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
  39. package/lib/chunk-EFR2Y7E4.mjs +7 -0
  40. package/lib/chunk-EHQ3FX6X.mjs +7 -0
  41. package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
  42. package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
  43. package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
  44. package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
  45. package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
  46. package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
  47. package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
  48. package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
  49. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
  50. package/lib/chunk-G35N4P7D.mjs +7 -0
  51. package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
  52. package/lib/chunk-GSG7WZHM.mjs +7 -0
  53. package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
  54. package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
  55. package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
  56. package/lib/chunk-HOJYWTP7.mjs +20 -0
  57. package/lib/chunk-HS4YRX4J.mjs +7 -0
  58. package/lib/chunk-IFETCRWE.mjs +10 -0
  59. package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
  60. package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
  61. package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
  62. package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
  63. package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
  64. package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
  65. package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
  66. package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
  67. package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
  68. package/lib/chunk-JWTSEDIQ.mjs +7 -0
  69. package/lib/chunk-K327QKMD.mjs +7 -0
  70. package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
  71. package/lib/chunk-KDGMAGQR.mjs +7 -0
  72. package/lib/chunk-KRCA6IPH.mjs +8 -0
  73. package/lib/chunk-KYEDBS54.mjs +7 -0
  74. package/lib/chunk-L5FGY6YA.mjs +7 -0
  75. package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
  76. package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
  77. package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
  78. package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
  79. package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
  80. package/lib/chunk-MFG4MUIO.mjs +9 -0
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
  82. package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
  83. package/lib/chunk-MJU2PGZQ.mjs +15 -0
  84. package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
  85. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  86. package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
  87. package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
  88. package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
  89. package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
  90. package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
  91. package/lib/chunk-OAZRPP4I.mjs +7 -0
  92. package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
  93. package/lib/chunk-OLSGVAIL.mjs +341 -0
  94. package/lib/chunk-OO6CLPEH.mjs +7 -0
  95. package/lib/chunk-OPXCV2KL.mjs +7 -0
  96. package/lib/chunk-P33PSCXK.mjs +7 -0
  97. package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
  98. package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
  99. package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
  100. package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
  101. package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
  102. package/lib/chunk-RMBPOTD7.mjs +7 -0
  103. package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
  104. package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
  105. package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
  106. package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
  107. package/lib/chunk-SOU4FRYN.mjs +7 -0
  108. package/lib/chunk-SU65Z2BA.mjs +7 -0
  109. package/lib/chunk-T62WNR54.mjs +7 -0
  110. package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
  111. package/lib/chunk-TTFDUKUS.mjs +47 -0
  112. package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
  113. package/lib/chunk-UCD54V2M.mjs +7 -0
  114. package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
  115. package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
  116. package/lib/chunk-VS7ZXUII.mjs +824 -0
  117. package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
  118. package/lib/chunk-VYXMVJL5.mjs +7 -0
  119. package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
  120. package/lib/chunk-W7U5E5ZL.mjs +9 -0
  121. package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
  122. package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
  123. package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
  124. package/lib/chunk-WXAQ7FK3.mjs +115 -0
  125. package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
  126. package/lib/chunk-XAMBCQPU.mjs +7 -0
  127. package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
  128. package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
  129. package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
  130. package/lib/chunk-YRQGKDHM.mjs +7 -0
  131. package/lib/chunk-ZM6OJGIG.mjs +7 -0
  132. package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
  133. package/lib/sandforge-autopilot.mjs +29 -24
  134. package/lib/sandforge-backup.mjs +25 -21
  135. package/lib/sandforge-checkpoint.mjs +15 -14
  136. package/lib/sandforge-cleanup.mjs +14 -10
  137. package/lib/sandforge-clone.mjs +1 -1
  138. package/lib/sandforge-compare.mjs +9 -8
  139. package/lib/sandforge-dataops.mjs +1 -1
  140. package/lib/sandforge-empty.mjs +15 -15
  141. package/lib/sandforge-env.mjs +88 -88
  142. package/lib/sandforge-frozen.mjs +43 -34
  143. package/lib/sandforge-mcp.mjs +12 -12
  144. package/lib/sandforge-monitor.mjs +7 -7
  145. package/lib/sandforge-seed.mjs +1 -1
  146. package/lib/sandforge-sync.mjs +1 -1
  147. package/lib/sandforge.mjs +4 -4
  148. package/package.json +1 -1
  149. package/lib/chunk-2S5OMIIA.mjs +0 -7
  150. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  151. package/lib/chunk-3F5YMM2F.mjs +0 -7
  152. package/lib/chunk-3RYLICRX.mjs +0 -7
  153. package/lib/chunk-4GL773D5.mjs +0 -7
  154. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  155. package/lib/chunk-5AJRHRXA.mjs +0 -20
  156. package/lib/chunk-5HMAPZBV.mjs +0 -7
  157. package/lib/chunk-6LAXTAVN.mjs +0 -7
  158. package/lib/chunk-6MUEPV7M.mjs +0 -9
  159. package/lib/chunk-75ADZS6B.mjs +0 -7
  160. package/lib/chunk-B45CNPUX.mjs +0 -47
  161. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  162. package/lib/chunk-D3QRXG63.mjs +0 -787
  163. package/lib/chunk-EEVVGGM6.mjs +0 -7
  164. package/lib/chunk-ENLBYECD.mjs +0 -7
  165. package/lib/chunk-EQOQASDQ.mjs +0 -7
  166. package/lib/chunk-FQBRBBY4.mjs +0 -7
  167. package/lib/chunk-GAM726CK.mjs +0 -7
  168. package/lib/chunk-HUMEKZT5.mjs +0 -8
  169. package/lib/chunk-I3JKJTLO.mjs +0 -110
  170. package/lib/chunk-KLX67VPL.mjs +0 -7
  171. package/lib/chunk-L776PUMV.mjs +0 -7
  172. package/lib/chunk-NEVXIGR6.mjs +0 -10
  173. package/lib/chunk-NHWE66K5.mjs +0 -7
  174. package/lib/chunk-OQOZAPCI.mjs +0 -7
  175. package/lib/chunk-PA3MKJVH.mjs +0 -7
  176. package/lib/chunk-RH3N2H7P.mjs +0 -7
  177. package/lib/chunk-SRQDABQ2.mjs +0 -15
  178. package/lib/chunk-SVS6UMDU.mjs +0 -323
  179. package/lib/chunk-TNXUU6W7.mjs +0 -14
  180. package/lib/chunk-VXHDBYMI.mjs +0 -7
  181. package/lib/chunk-WRU5FJFC.mjs +0 -7
  182. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  183. package/lib/chunk-XEFDB2R4.mjs +0 -7
  184. package/lib/chunk-XETCPL7E.mjs +0 -7
  185. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  186. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  187. package/lib/chunk-YMJVMFPY.mjs +0 -7
  188. package/lib/chunk-YPSRZRIT.mjs +0 -7
  189. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  190. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  191. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  192. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -1,9 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ne,b as Fe}from"./chunk-TYYOBZMU.mjs";import{a as xe,b as be,c as $e}from"./chunk-RH3N2H7P.mjs";import{a as ue,b as Le,c as De}from"./chunk-TUACWKIH.mjs";import{a as Ue}from"./chunk-4TLYUZD5.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";import{$c as ae,_c as Pe,ac as ie,ad as Ce,dd as ce,ed as Me,fd as ve,gd as _e,j as Re,vb as Ie}from"./chunk-B45CNPUX.mjs";import{b as q,e as Ae,k as B,l as J,v as Oe,z as X}from"./chunk-7EANH5PY.mjs";var Y=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((f,c)=>f-c),r=s.reduce((f,c)=>f+c,0),o=Math.floor(s.length*.95),i=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(i,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var Z=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var je=["INVALID_SESSION_ID","INVALID_AUTH_HEADER","SESSION_EXPIRED"];function He(e){if(typeof e=="object"&&e!==null){let{errorCode:n,statusCode:s}=e;if(typeof n=="string"&&je.includes(n)||s===401)return!0}let t=S(e);return je.some(n=>t.includes(n))||t.includes("Session expired")?!0:/\b401\b/.test(t)&&/unauthorized/i.test(t)}var ze=0;function Sn(){return ze}async function de(e,t){let n=$e(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as yt,userInfo as Et}from"node:os";var kt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return kt.some(t=>t.test(e))}function le(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function Rn(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),n=qe.filter(c=>t.some(d=>d.toUpperCase()===c)),s=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),r=t.filter(c=>We(c)),o=r.filter(c=>c.startsWith("ELECTRON_")).sort(),i=r.length-o.length,f=r.length===0?"none":[...o,...i>0?[`${i} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${f}`}function St(){try{return Et().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=yt(),n=St()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function In(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Tt(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function Pn(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=le(),o,i;try{let g=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(g.stdout)}catch(g){let a=g;o=String(a.stdout??""),o.trim()===""&&(i=Je(a.message??String(g)))}let f=o.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.length>0).map(g=>Je(g)),c=g=>f.filter(a=>new RegExp(`(^|[\\\\/])${g}(\\.[A-Za-z0-9]+)?$`,"i").test(a)),d=c("sf"),u=Tt(d,r);return{sf:d,node:c("node"),...u!==void 0?{runs:u}:{},...i?{failure:i}:{}}}var At=10*1024*1024,he=3e4,Ve=he+2e3,ge=`sf did not answer within ${he/1e3} s \u2014 check the Salesforce CLI`;function Ge(e){return e instanceof Error&&e.message===ge}var fe=2e4;function Q(e,t,n){let s,r=new Promise((o,i)=>{s=setTimeout(()=>i(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var D=new Y,Ot=300*1e3,K=new Map,Rt={failureThreshold:3,resetTimeout:3e4},Xe=new Map;function Fn(){return D}function It(e){let t=Xe.get(e);return t||(t=new Z({...Rt}),Xe.set(e,t)),t}var Ye;var pe="panel";function jn(e){pe=e}function Pt(e,t=pe){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdxurl"), then run the command again, with its --resume if it stopped a run part way.`}function Ze(e=pe){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Ke(e,t){let n=t?.organization_id;if(!(!Ye||typeof n!="string"))try{Ye(e,{organizationId:n})}catch(s){Ue.warn("Identity observer threw",{orgId:e,error:S(s)})}}var Ct="[REDACTED]";function Qe(e){return typeof e=="string"&&e.length>0&&!e.startsWith(Ct)&&!/\s/.test(e)}async function Mt(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:At,timeout:he,windowsHide:!0,env:le()},o=a=>Q(s(t)("sf",a,r),Ve,ge),i=a=>{let h=!1,m,E=new Promise((T,M)=>{m=n(a,r,(k,R)=>{h=!0,k?M(k):T({stdout:R})})});return Q(E,Ve,ge).catch(T=>{throw!h&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},f=(a,h)=>process.platform==="win32"?i(a):o(h),c=(a,h)=>{let m=a.replace(/\[[0-9;]*m/g,""),E=m.search(/[{[]/);if(E===-1)throw new Error(`Failed to parse "${h}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(E)).result??{}},d;try{let{stdout:a}=await f(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=c(a,"sf org display");d=typeof h.instanceUrl=="string"?h.instanceUrl:void 0}catch(a){if(Ge(a))throw a;d=void 0}try{let{stdout:a}=await f(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),h=c(a,"sf org auth show-access-token");if(Qe(h.accessToken))return{accessToken:h.accessToken,instanceUrl:d}}catch(a){if(Ge(a))throw a}let{stdout:u}=await f(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=c(u,"sf org display");if(!Qe(g.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof g.instanceUrl=="string"&&(d=g.instanceUrl),{accessToken:g.accessToken,instanceUrl:d}}async function Hn(e,t){let{jsforce:n}=await import("./chunk-GAM726CK.mjs");return new n.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function zn(e){let{jsforce:t}=await import("./chunk-GAM726CK.mjs");return new t.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function qn(e,t,n){let{jsforce:s}=await import("./chunk-GAM726CK.mjs"),r=e,o=n.getOrg(e);if(!o)throw new Error(`Org not found: ${e}`);let i=await t.getCredentials(e);if(!i?.accessToken||!i.instanceUrl)throw new Error(`No credentials for org "${o.alias}" (${e}). Reconnect the org.`);let f=o.metadata.apiVersion||Re.DEFAULT_API_VERSION,c=D.get(r),d=Date.now()-(K.get(e)??0)<Ot;if(c&&c.active&&c.accessToken===i.accessToken&&d)return c.lastUsedAt=Date.now(),new s.Connection({instanceUrl:c.instanceUrl,accessToken:c.accessToken,version:f});let u=new s.Connection({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:f}),g=It(e);if(!g.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${o.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let a=Date.now(),h=`identity check did not answer within ${fe/1e3} s`;try{let m=await de(u,()=>Q(u.identity(),fe,h)),E=Date.now()-a;return g.recordSuccess(),D.acquire(r,i.instanceUrl,i.accessToken),D.recordLatency(r,E),K.set(e,Date.now()),Ke(e,m),u}catch(m){let E=Date.now()-a;if(D.remove(r),K.delete(e),He(m))try{let k=await Mt(o.username),R=k.instanceUrl??i.instanceUrl;if(k.accessToken===i.accessToken&&R===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let x=new s.Connection({instanceUrl:R,accessToken:k.accessToken,version:f}),re=await de(x,()=>Q(x.identity(),fe,h));return await t.saveOrg(o,{...i,accessToken:k.accessToken,instanceUrl:R}),g.recordSuccess(),D.acquire(r,R,k.accessToken),D.recordLatency(r,E),K.set(e,Date.now()),Ke(e,re),x}catch(k){g.recordFailure();let R=S(k);n.updateStatus(e,"expired");let x=ie(o,new Date().toISOString().slice(0,10));throw x!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${o.alias}" expired on ${x}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ze()} (cause: ${R})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${o.alias}" has expired and could not be renewed. ${Pt(o.alias)} (cause: ${R})`)}g.recordFailure();let T=S(m),M=ie(o,new Date().toISOString().slice(0,10));throw M!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${o.alias}" expired on ${M}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ze()} (cause: ${T})`)):new Error(`Connection failed for "${o.alias}": ${T}`)}finally{g.releasePermit()}}import{randomUUID as vt}from"node:crypto";import{hostname as _t,homedir as xt,uptime as bt}from"node:os";import{mkdir as $t,readFile as at,readdir as Ut,rename as ct,writeFile as Lt}from"node:fs/promises";import{dirname as me,join as ye}from"node:path";function et(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:S(e)}]}}function tt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function ts(e){return{typeOrg:()=>xe(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:Ie()}).then(tt,et),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(tt,et)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Dt(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var Nt=60,Ft=5*6e4,jt=3e4,Ht=6e4,zt=200,qt=448,Bt=384,se=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(se),Jt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Wt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Ae().int().nonnegative(),hostStartedAt:X.datetime({offset:!0}),acquiredAt:X.datetime({offset:!0}),endsAt:X.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Jt)}),ut=J({version:Oe(1),organizationId:H,userId:H,leases:B(Wt)}),Vt=J(Ne),Gt=Fe(e=>{let t=Vt.safeParse(e);return t.success?t.data:void 0});function dt(e=process.env,t=xt()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:ye(t,".sandforge","mute-leases")}function Xt(e,t,n){if(!se.test(t)||!se.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return ye(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var lt={host:_t(),pid:ue.pid,startedAt:ue.startedAt},Yt=6e4,N=new Set;function ft(e,t,n){return`${e}
8
- ${t}
9
- ${n}`}function Zt(e,t,n,s={}){let r=s.now?.()??Date.now();if(!(Date.parse(e.endsAt)>r)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return N.has(ft(t,e.runId,e.acquiredAt));let o=s.bootedAt?.()??Date.now()-bt()*1e3,i=Date.parse(e.hostStartedAt);return Number.isFinite(i)&&i<o-Yt?!1:(s.isAlive??De)(e.pid)}var Kt=e=>new Promise(t=>setTimeout(t,e));function ee(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${me(e)} could not be ${t}${typeof s=="string"?` (${s})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function Qt(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+Le).toISOString()}}function gt(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function en(e){return`nothing was assigned. ${gt(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function te(e,t,n,s,r=en,o=Ht){let i=n.self??lt,f={self:i,...n.checks?{checks:n.checks}:{}},c=Date.now()+o;for(await $t(me(e),{recursive:!0,mode:qt}).catch(d=>{throw ee(e,"made",d)});;){let d;try{d=Gt.acquire(`${e}.lock`,u=>u,f)}catch(u){throw ee(e,"locked",u)}if("lock"in d)try{let u=await tn(e,t).catch(a=>{throw ee(e,"read",a)});return await s(u,async a=>{let h=`${e}.${process.pid}-${vt()}.tmp`;try{await Lt(h,JSON.stringify(a,null,2),{encoding:"utf8",mode:Bt}),await ct(h,e)}catch(m){throw ee(e,"written",m)}})}finally{d.lock.release()}if(Date.now()>c){let u=Qt(d.busy,i);throw new j({code:"MUTE_FAILED",message:`The journal of the mute leases in ${me(e)} stayed locked for a minute by process ${u.pid} on ${u.host}: ${r(u)}`})}await Kt(zt)}}async function tn(e,t){let n={version:1,...t,leases:[]},s;try{s=await at(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=ut.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await ct(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var nn=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function ne(e,t,n,s){let r=t.leases.filter(u=>u!==n&&s(u)),o=[...n.created],i=new Set,f=n.assigning[0];if(f!==void 0){let u=new Set(t.leases.flatMap(a=>a===n?[]:a.created.map(h=>h.id))),g=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${f}')`).then(a=>a.records).catch(()=>[]);for(let a of g){let h=typeof a.Id=="string"?a.Id:void 0,m=typeof a.PermissionSetId=="string"?a.PermissionSetId:void 0;if(!h||!m||u.has(h)||o.some(T=>T.id===h))continue;let E=a.PermissionSet;o.push({id:h,permissionSetId:m,permissionSet:typeof E?.Name=="string"?E.Name:m}),i.add(h)}}let c={removed:[],passed:[],left:[],found:[]};for(let u of o){let g=r.find(m=>m.needs.includes(u.permissionSetId));if(g){g.created.some(m=>m.id===u.id)||g.created.push(u),c.passed.push(u);continue}let a=await e.deleteAssignment(u.id),h=a.errors?.[0]?.statusCode??a.errors?.[0]?.errorCode;a.success||h!==void 0&&nn.has(h)?(c.removed.push(u),i.has(u.id)&&c.found.push(u)):c.left.push({...u,why:a.errors?.[0]?.message??h??"the org refused the delete"})}let d=t.leases.indexOf(n);return c.left.length===0?t.leases.splice(d,1):t.leases[d]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:c.left.map(({id:u,permissionSetId:g,permissionSet:a})=>({id:u,permissionSetId:g,permissionSet:a}))},c}function F(e){return e.map(t=>t.permissionSet)}function nt(e,t){let n=r=>F(r).join(", "),s=[];return e.removed.length>0&&s.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&s.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&s.push(`${e.left.map(r=>`${r.permissionSet} (${r.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),s}function st(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function ht(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function sn(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await ne(e,t,r,n)).found);return s}async function rn(e){let t;try{t=(await e.query("SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess")).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${S(n)})`}if(!(t?.PermissionsAssignPermissionSets===!0||t?.PermissionsManageUsers===!0))return"the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)"}function rt(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var ot=/^[A-Za-z][A-Za-z0-9_]*$/;async function on(e,t){let s=t.map(rt).filter(i=>ot.test(i.developerName)&&(!i.namespace||ot.test(i.namespace)));if(s.length===0)return new Map;let r=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(s.map(i=>`'${i.developerName}'`))].join(", ")+")"),o=new Map;for(let i of t){let{namespace:f,developerName:c}=rt(i),d=r.records.find(u=>String(u.Name??"").toLowerCase()===c.toLowerCase()&&String(u.NamespacePrefix??"").toLowerCase()===f.toLowerCase());typeof d?.Id=="string"&&o.set(i,d.Id)}return o}async function it(e,t,n){if(n.length===0)return new Map;let s=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(o=>`'${o}'`).join(", ")})`),r=new Map;for(let o of s.records){let i=o.PermissionSetId,f=o.Id;typeof i=="string"&&typeof f=="string"&&r.set(i,f)}return r}function we(e,t,n){return{state:t,assigned:[],held:[],permissions:ae(e),silenced:e.silenced.map(s=>({...s})),stillRan:e.stillRuns.map(s=>({...s})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(s=>({...s}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(s=>({...s}))}:{},...n?{reason:n}:{}}}var pt="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function an(e,t,n={}){let s,r;try{let d=await e.typeOrg();s=be(d),r=d.id}catch(d){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${S(d)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(s)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:o,automation:i,planned:f}=dn(t,n.writes);if(o.assign.length===0)return{plan:o,automation:t,planned:f,acquire:async()=>({outcome:f,release:async()=>f})};let c=await rn(e);return c!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${c}. Nothing was assigned.`}}:(mt.set(o,await un(n.dir??dt(),r)),{plan:o,automation:i,planned:f,acquire:d=>ln(e,o,d,n)})}var mt=new WeakMap,cn=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function un(e,t){if(!se.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ut(e)}catch{return 0}let r=0;for(let o of s)if(!(!o.startsWith(n)||!cn.test(o)))try{let i=ut.safeParse(JSON.parse(await at(ye(e,o),"utf8")));if(!i.success)continue;for(let f of i.data.leases)r+=(f.assigning.length>0?1:0)+f.created.length}catch{}return r}function dn(e,t){let n=Pe(e,t);return n.assign.length===0?{plan:n,automation:e,planned:we(n,"nothing",pt)}:{plan:n,automation:Ce(e,ae(n)),planned:we(n,"planned")}}async function ln(e,t,n,s={}){let r=s.self??lt,o=()=>s.checks?.now?.()??Date.now(),i=s.minutes??Nt,f=l=>{throw new j({code:"MUTE_FAILED",message:l})},c=await e.identity().catch(l=>f(`The target would not say who the run writes as (${S(l)}).`)),d={organizationId:c.organization_id,userId:c.user_id},u=Xt(s.dir??dt(),d.organizationId,d.userId),g=t.assign.map(l=>l.permissionSet),a=await on(e,g).catch(l=>f(`The permission sets to assign could not be read (${S(l)}).`)),h=g.filter(l=>!a.has(l));h.length>0&&f(`The target holds no permission set ${h.join(", ")}: nothing was assigned.`);let m=g.map(l=>a.get(l)),E=new Map(g.map(l=>[a.get(l),l])),T=l=>Zt(l,u,r,s.checks),M=new Date(o()).toISOString(),k=ft(u,n,M),R=!1,x=m.map(l=>E.get(l)),re=s.retryEveryMs??jt,W,Ee=(l,A)=>{if(W!==void 0)return;let p=new Set(l.map(y=>y.id)),O=!1,I=()=>clearInterval(W);W=setInterval(()=>{O||(O=!0,te(u,d,s,async(y,V)=>{let v=y.leases.find(b=>b.runId===n&&b.acquiredAt===M);if(v){v.assigning=[],v.created=[...v.created,...A.filter(U=>!v.created.some(G=>G.id===U.id))].filter(U=>!p.has(U.id));let b=await ne(e,y,v,T);for(let U of b.removed)p.add(U.id);await V(y)}I()},void 0,0).catch(()=>{}).finally(()=>{O=!1}))},re),W.unref?.()},z=await te(u,d,s,async(l,A)=>{let p=F(await sn(e,l,T)),O=await it(e,d.userId,m),I=m.filter(w=>!O.has(w)),y={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:M,endsAt:new Date(o()+i*6e4).toISOString(),needs:m,assigning:[...I],created:[]};l.leases.push(y),N.add(k),await A(l),R=!0;let V=[...y.assigning],v=()=>A(l).then(()=>{V=[...y.assigning]},w=>S(w)),b=async w=>{y.assigning=[];let C=await ne(e,l,y,T);N.delete(k);let P=await v();P!==void 0&&Ee(C.removed,[...C.passed,...C.left]);let _=P!==void 0&&V.length===0?{sets:x,until:y.endsAt}:void 0,Te=nt(C,P===void 0);return f([w,...P!==void 0&&P!==w?[P]:[],...Te.length>0?Te:["Nothing was assigned."],...P!==void 0&&(C.passed.length>0||C.left.length>0||_)?[st(r.pid,_)]:[],...p.length>0?[`Taking its lease, the run took back ${p.join(", ")}, ${ht(p)}.`]:[]].join(" "))};for(let w of I){let C=await e.createAssignment({AssigneeId:d.userId,PermissionSetId:w});if(y.assigning=y.assigning.filter(_=>_!==w),C.success&&C.id){y.created.push({id:C.id,permissionSetId:w,permissionSet:E.get(w)});let _=await v();if(_!==void 0)return b(_);continue}let P=C.errors?.[0];if((P?.statusCode??P?.errorCode)==="DUPLICATE_VALUE"){let _=await v();if(_!==void 0)return b(_);continue}return b(`${E.get(w)} could not be assigned to the user the run writes as: ${P?.message??P?.statusCode??"the org refused it"}.`)}let U=await it(e,d.userId,m).catch(()=>new Map),G=m.filter(w=>!U.has(w));if(G.length>0)return b(`Read back, the user the run writes as does not hold ${G.map(w=>E.get(w)).join(", ")}.`);let wt=new Set(y.created.map(w=>w.permissionSetId));return{endsAt:y.endsAt,assigned:y.created.map(w=>w.permissionSet),held:m.filter(w=>!wt.has(w)).map(w=>E.get(w)),found:p}}).catch(l=>{if(N.delete(k),Dt(l))throw l;return f(`${S(l)}${R?"":" Nothing was assigned."}`)}),$={...we(t,"muted"),assigned:z.assigned,held:z.held,leaseEndsAt:z.endsAt,...z.found.length>0?{tookBackOfEnded:z.found}:{}},ke=s.renewEveryMs??Ft,oe=ke>0?setInterval(()=>{te(u,d,s,async(l,A)=>{let p=l.leases.find(I=>I.runId===n&&I.acquiredAt===M);if(!p||!N.has(k))return;let O=new Date(o()+i*6e4).toISOString();p.endsAt=O,await A(l),$.leaseEndsAt=O}).catch(()=>{})},ke):void 0;oe?.unref?.();let Se;return{outcome:$,release:()=>(Se??=(async()=>{oe&&clearInterval(oe);let l={};try{await te(u,d,s,async(p,O)=>{let I=p.leases.find(y=>y.runId===n&&y.acquiredAt===M);N.delete(k),I&&(l.done=await ne(e,p,I,T),await O(p))},p=>`nothing was taken back. ${gt(p)} Should none of its runs be muting this org, end process ${p.pid}`);let A=l.done?.left??[];return{...$,released:A.length===0,takenBack:F(l.done?.removed??[]),...l.done&&l.done.passed.length>0?{passed:F(l.done.passed)}:{},...A.length>0?{notTakenBack:F(A),reason:`${A.map(p=>`${p.permissionSet} (${p.why})`).join(", ")} could not be taken back: the lease ends at ${$.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(A){N.delete(k);let p=l.done;if(Ee(p?.removed??[],p?[...p.passed,...p.left]:[]),p!==void 0){let O=$.leaseEndsAt,I=O!==void 0&&Date.parse(O)>o()?{sets:x,until:O}:void 0;return{...$,released:!1,takenBack:F(p.removed),notTakenBack:F([...p.passed,...p.left]),reason:[S(A),...nt({...p,removed:[]},!1),st(r.pid,I)].join(" ")}}return{...$,released:!1,takenBack:[],reason:`the assignments could not be taken back (${S(A)}): this process tries again while it runs, and takes them back once it can use the journal; past ${$.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),Se)}}var fn=2,gn=3;function hn(e){return!e||e.assign.length===0?0:fn+gn+2*e.assign.length+(mt.get(e)??0)}function ns(e){let t=hn(e);return t>0?{mute:t}:{}}function pn(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function ss(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function rs(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:pn(`the target's automation could not be read (${t.unread})`)};let s=await an(await e(),t,n);if("refused"in s)throw new j(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function os(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function is(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??pt}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+ht(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${ce(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${ce(r)} (${Me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${ve(r)}`);for(let r of e.liftsUnread??[])n.push(` ${_e(r)}`);let s=e.takenBack??(e.released===!0?e.assigned:[]);if(s.length>0&&n.push(` taken back: ${s.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let r=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${r?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}export{He as a,Sn as b,de as c,L as d,le as e,Rn as f,Je as g,In as h,Pn as i,Q as j,Fn as k,jn as l,Qe as m,Mt as n,Hn as o,zn as p,qn as q,ts as r,Dt as s,an as t,dn as u,hn as v,ns as w,ss as x,rs as y,os as z,is as A};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-57VHUYNG.mjs";import"./chunk-MYTIL2JD.mjs";import"./chunk-JVL444U5.mjs";import"./chunk-5CD257T7.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{d as diffOfPicked,b as heldInPlaceReason,g as planSelection,c as rewindPlan,a as rewindWriters,f as selectionPlanOf,e as snapshotRowsOf};