sandforge 1.82.0 → 1.83.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 (200) hide show
  1. package/lib/{chunk-JLZRZL5E.mjs → chunk-262TP6UU.mjs} +1 -1
  2. package/lib/{chunk-Z42PHCVZ.mjs → chunk-27BBEGUD.mjs} +1 -1
  3. package/lib/{chunk-YGJF55VJ.mjs → chunk-2ADSD5WK.mjs} +1 -1
  4. package/lib/{chunk-KIMQQ6JQ.mjs → chunk-2GSMHGIV.mjs} +1 -1
  5. package/lib/chunk-2K5BYZQM.mjs +8 -0
  6. package/lib/{chunk-DJCGURW7.mjs → chunk-2KTGDYUH.mjs} +1 -1
  7. package/lib/{chunk-YAJQS3OL.mjs → chunk-2N73W63D.mjs} +1 -1
  8. package/lib/{chunk-LXDSRP2W.mjs → chunk-2R6GFNKF.mjs} +1 -1
  9. package/lib/{chunk-VZVICK7Q.mjs → chunk-2WMKJVD2.mjs} +1 -1
  10. package/lib/{chunk-CV47FDQW.mjs → chunk-36Y225OM.mjs} +1 -1
  11. package/lib/{chunk-3C2ZZIFN.mjs → chunk-3CM7LAPE.mjs} +1 -1
  12. package/lib/{chunk-HIHCYMSL.mjs → chunk-3OVTKRS4.mjs} +1 -1
  13. package/lib/{chunk-XFU3HRUV.mjs → chunk-3V4YH5KO.mjs} +1 -1
  14. package/lib/{chunk-XO5FBOQF.mjs → chunk-446GBKAC.mjs} +1 -1
  15. package/lib/{chunk-ZUOPC4W2.mjs → chunk-4GCYGQXD.mjs} +1 -1
  16. package/lib/{chunk-GCGHHN4K.mjs → chunk-4V3QO7HF.mjs} +1 -1
  17. package/lib/{chunk-VZT4E2OJ.mjs → chunk-4X5D3MSV.mjs} +1 -1
  18. package/lib/{chunk-P55MKIZX.mjs → chunk-5OGNK3JP.mjs} +1 -1
  19. package/lib/{chunk-3MGMNK3Q.mjs → chunk-6KOUYHEY.mjs} +1 -1
  20. package/lib/chunk-6QSHWIZI.mjs +48 -0
  21. package/lib/chunk-6VOQFISN.mjs +7 -0
  22. package/lib/{chunk-VYOYXTCU.mjs → chunk-6YC2ELCU.mjs} +1 -1
  23. package/lib/chunk-77IVKH7R.mjs +7 -0
  24. package/lib/{chunk-JKT5YAQ2.mjs → chunk-77MZRBWX.mjs} +1 -1
  25. package/lib/{chunk-PR74GYVI.mjs → chunk-7BQMBXKX.mjs} +1 -1
  26. package/lib/{chunk-SZGGFST2.mjs → chunk-7DPHZWA4.mjs} +1 -1
  27. package/lib/chunk-7V2UYZ6S.mjs +7 -0
  28. package/lib/{chunk-HKUWHVI7.mjs → chunk-7WSQ65WG.mjs} +1 -1
  29. package/lib/{chunk-LHU6CPGE.mjs → chunk-7ZBDACVG.mjs} +1 -1
  30. package/lib/{chunk-WT3SCUHS.mjs → chunk-AG24QMSY.mjs} +1 -1
  31. package/lib/{chunk-A65ADTCR.mjs → chunk-AHUGG3WU.mjs} +1 -1
  32. package/lib/{chunk-ZXFL2MSN.mjs → chunk-ALBY5SOH.mjs} +1 -1
  33. package/lib/chunk-AXFD2OH6.mjs +7 -0
  34. package/lib/{chunk-JESRFE2Z.mjs → chunk-BH76USTQ.mjs} +1 -1
  35. package/lib/{chunk-DBBPDSFN.mjs → chunk-BPHTA6KP.mjs} +1 -1
  36. package/lib/{chunk-3SKLBRPL.mjs → chunk-BT43WSOS.mjs} +1 -1
  37. package/lib/{chunk-32EUNQT6.mjs → chunk-BVZ5H3N4.mjs} +1 -1
  38. package/lib/{chunk-PWVDNN2C.mjs → chunk-C6RKM4BB.mjs} +1 -1
  39. package/lib/{chunk-27Z76O2O.mjs → chunk-CDWZGQAJ.mjs} +1 -1
  40. package/lib/chunk-CGZGL6VT.mjs +7 -0
  41. package/lib/{chunk-P63WJMXQ.mjs → chunk-CN5HGFG4.mjs} +1 -1
  42. package/lib/{chunk-Y4TDVDP2.mjs → chunk-CQAFVEKP.mjs} +1 -1
  43. package/lib/{chunk-G2JR3F63.mjs → chunk-CTPLYUXA.mjs} +1 -1
  44. package/lib/chunk-CXKZ6TYV.mjs +9 -0
  45. package/lib/{chunk-FKK5YBGZ.mjs → chunk-D6JT4PAB.mjs} +1 -1
  46. package/lib/{chunk-3CX7GPCR.mjs → chunk-D7XUNWWU.mjs} +1 -1
  47. package/lib/{chunk-PPHVWUFY.mjs → chunk-DB5RVDC5.mjs} +1 -1
  48. package/lib/{chunk-LAUOSXMN.mjs → chunk-DIGUC7S4.mjs} +1 -1
  49. package/lib/{chunk-6GQUZ4IP.mjs → chunk-DKDKCGXV.mjs} +1 -1
  50. package/lib/chunk-DMT5SCO3.mjs +7 -0
  51. package/lib/{chunk-KKOA62S4.mjs → chunk-DNQKVCUV.mjs} +4 -3
  52. package/lib/{chunk-3XG25GTF.mjs → chunk-DSR2MSBH.mjs} +1 -1
  53. package/lib/{chunk-ZHIZY3ZC.mjs → chunk-E3RQ575Y.mjs} +1 -1
  54. package/lib/{chunk-SAMWHL22.mjs → chunk-EOQON3E5.mjs} +1 -1
  55. package/lib/{chunk-2JZGCCPG.mjs → chunk-ETNQHIDI.mjs} +1 -1
  56. package/lib/chunk-F5SBGJWW.mjs +7 -0
  57. package/lib/chunk-FBXH4VRQ.mjs +7 -0
  58. package/lib/chunk-FKCIGJOI.mjs +15 -0
  59. package/lib/{chunk-NWOI25WY.mjs → chunk-FVLFO2S6.mjs} +1 -1
  60. package/lib/{chunk-MKTXJCXN.mjs → chunk-FYWNSMOZ.mjs} +1 -1
  61. package/lib/{chunk-52EXDVPN.mjs → chunk-GEEWPTV5.mjs} +1 -1
  62. package/lib/{chunk-XSKPYGMT.mjs → chunk-GLN4PI5P.mjs} +1 -1
  63. package/lib/{chunk-DWMRIWV5.mjs → chunk-GT5ZKU6V.mjs} +1 -1
  64. package/lib/chunk-GTRU5AV5.mjs +7 -0
  65. package/lib/chunk-H33DVU3D.mjs +7 -0
  66. package/lib/{chunk-YAIIRFKJ.mjs → chunk-HQZUQXDC.mjs} +1 -1
  67. package/lib/{chunk-MUEQRIK7.mjs → chunk-HVX2AFYW.mjs} +1 -1
  68. package/lib/chunk-I3ZO76LL.mjs +21 -0
  69. package/lib/{chunk-7WSLT5VX.mjs → chunk-I5C4O3VA.mjs} +1 -1
  70. package/lib/{chunk-6VSZNZHH.mjs → chunk-IHGYJZZ2.mjs} +1 -1
  71. package/lib/{chunk-DIS254AN.mjs → chunk-ISA2NYJV.mjs} +1 -1
  72. package/lib/{chunk-GGUOIDWP.mjs → chunk-ISAUCWYK.mjs} +1 -1
  73. package/lib/{chunk-ZUTUYBNW.mjs → chunk-ISOSTAJR.mjs} +1 -1
  74. package/lib/chunk-IXIY6Q4M.mjs +7 -0
  75. package/lib/{chunk-2UU42PTD.mjs → chunk-J3TIHLWG.mjs} +1 -1
  76. package/lib/{chunk-GGNUACTY.mjs → chunk-JAV6F6OA.mjs} +1 -1
  77. package/lib/chunk-JBWJ6UEZ.mjs +7 -0
  78. package/lib/{chunk-C2N2TNEU.mjs → chunk-JH4ZTVQN.mjs} +1 -1
  79. package/lib/{chunk-FOIWWK7G.mjs → chunk-JIPT5FUD.mjs} +1 -1
  80. package/lib/{chunk-7EYQYZJP.mjs → chunk-JREKJO3D.mjs} +1 -1
  81. package/lib/{chunk-VQJMP3DC.mjs → chunk-JUOQUG7U.mjs} +1 -1
  82. package/lib/chunk-JYUMD357.mjs +7 -0
  83. package/lib/{chunk-KP5G6FUC.mjs → chunk-K7G3W7XH.mjs} +1 -1
  84. package/lib/{chunk-T7WREYA5.mjs → chunk-KKS2KFBT.mjs} +1 -1
  85. package/lib/{chunk-TMA34QMA.mjs → chunk-KWAVSZ2B.mjs} +1 -1
  86. package/lib/{chunk-H4JUYUSL.mjs → chunk-KXUOHACP.mjs} +1 -1
  87. package/lib/{chunk-STRMWSIQ.mjs → chunk-L3I6DAHX.mjs} +1 -1
  88. package/lib/{chunk-TCBAE65A.mjs → chunk-L47JCNP3.mjs} +1 -1
  89. package/lib/{chunk-5K2I2DMP.mjs → chunk-L4MSL4U7.mjs} +1 -1
  90. package/lib/chunk-L4RJX7DG.mjs +7 -0
  91. package/lib/{chunk-47UHTN3Q.mjs → chunk-L6CLN664.mjs} +1 -1
  92. package/lib/chunk-LI2XNV7F.mjs +7 -0
  93. package/lib/chunk-LP2D3JJP.mjs +7 -0
  94. package/lib/{chunk-KJYEQHYP.mjs → chunk-LWES2KZE.mjs} +1 -1
  95. package/lib/{chunk-3HEMJTAP.mjs → chunk-LYOGCIYD.mjs} +2 -2
  96. package/lib/{chunk-VPDEJGPS.mjs → chunk-MJD6CPZZ.mjs} +1 -1
  97. package/lib/{chunk-SNEOKYV7.mjs → chunk-MTM4KG3T.mjs} +1 -1
  98. package/lib/{chunk-J24TIGSI.mjs → chunk-N2HYG3BL.mjs} +1 -1
  99. package/lib/chunk-N5UIE4IR.mjs +7 -0
  100. package/lib/{chunk-YMDFF657.mjs → chunk-NDFFIJL5.mjs} +1 -1
  101. package/lib/{chunk-WOOUISSO.mjs → chunk-NFEBX75O.mjs} +1 -1
  102. package/lib/{chunk-ZUBBEP75.mjs → chunk-NNV7IGM7.mjs} +1 -1
  103. package/lib/{chunk-Q3DY7TO2.mjs → chunk-NS6ONPWL.mjs} +1 -1
  104. package/lib/{chunk-IVZJSDJD.mjs → chunk-O7GCCRPW.mjs} +1 -1
  105. package/lib/{chunk-A7JJWOLT.mjs → chunk-OO24ZYYJ.mjs} +1 -1
  106. package/lib/chunk-OOIDCHBQ.mjs +9 -0
  107. package/lib/{chunk-AUS6NFLZ.mjs → chunk-OS5GE52G.mjs} +1 -1
  108. package/lib/chunk-OS6HFJ7L.mjs +7 -0
  109. package/lib/{chunk-V3R45ZWT.mjs → chunk-OTJH6AEA.mjs} +1 -1
  110. package/lib/{chunk-PBE44M2Y.mjs → chunk-OUU47Y7A.mjs} +1 -1
  111. package/lib/{chunk-BN33LVPQ.mjs → chunk-P6WRYJN3.mjs} +1 -1
  112. package/lib/{chunk-JJITOWZK.mjs → chunk-PDRXM5WN.mjs} +1 -1
  113. package/lib/{chunk-RYRMUPMY.mjs → chunk-PGRY365W.mjs} +1 -1
  114. package/lib/chunk-Q4PPI3KG.mjs +7 -0
  115. package/lib/chunk-QFTF2PGS.mjs +21 -0
  116. package/lib/chunk-QKJXIY6L.mjs +7 -0
  117. package/lib/{chunk-PYRZFUVU.mjs → chunk-QLRWU3MB.mjs} +1 -1
  118. package/lib/chunk-QO4MPHZD.mjs +7 -0
  119. package/lib/chunk-QP3JLFIO.mjs +7 -0
  120. package/lib/{chunk-NLB3RGIY.mjs → chunk-QQDZQCO2.mjs} +1 -1
  121. package/lib/{chunk-7CVDVBEE.mjs → chunk-QXB6U3ZP.mjs} +1 -1
  122. package/lib/chunk-R3OM3X4L.mjs +8 -0
  123. package/lib/chunk-R7GKMAT4.mjs +7 -0
  124. package/lib/{chunk-YT22LMF7.mjs → chunk-RVCPQVKM.mjs} +1 -1
  125. package/lib/{chunk-TWV4A5RK.mjs → chunk-RZKJQOOC.mjs} +1 -1
  126. package/lib/chunk-S4PRKKGC.mjs +8 -0
  127. package/lib/{chunk-JH27IKCO.mjs → chunk-SX6QWYCQ.mjs} +1 -1
  128. package/lib/{chunk-UHFLKP26.mjs → chunk-T36DZJPH.mjs} +1 -1
  129. package/lib/{chunk-CZLJZQCS.mjs → chunk-T7DDS4UQ.mjs} +1 -1
  130. package/lib/chunk-TCEXCHXR.mjs +7 -0
  131. package/lib/chunk-TMIESDE5.mjs +7 -0
  132. package/lib/chunk-TQJ5NPRC.mjs +7 -0
  133. package/lib/chunk-TUPZY2QJ.mjs +7 -0
  134. package/lib/{chunk-GBGHJTPC.mjs → chunk-U2CTKIPE.mjs} +1 -1
  135. package/lib/{chunk-3HROD5RE.mjs → chunk-U4YFYSF3.mjs} +1 -1
  136. package/lib/{chunk-Q6SXNKV2.mjs → chunk-UIR77ZJD.mjs} +1 -1
  137. package/lib/{chunk-FA4ZKDCU.mjs → chunk-UOHZW2L4.mjs} +1 -1
  138. package/lib/{chunk-7PY3VQP3.mjs → chunk-VXZ5PTOM.mjs} +1 -1
  139. package/lib/{chunk-7LKI7OAS.mjs → chunk-VZLJZEV2.mjs} +1 -1
  140. package/lib/{chunk-YH4DYI6D.mjs → chunk-W3BQGMTR.mjs} +1 -1
  141. package/lib/{chunk-CELEBWEZ.mjs → chunk-WABXKL4N.mjs} +1 -1
  142. package/lib/{chunk-EEFUE2ES.mjs → chunk-WAYQLQAD.mjs} +1 -1
  143. package/lib/{chunk-RCYEBY42.mjs → chunk-WBELLGNE.mjs} +1 -1
  144. package/lib/{chunk-SFGZFB4F.mjs → chunk-WJAZ5LHL.mjs} +1 -1
  145. package/lib/{chunk-JQZTMFO7.mjs → chunk-WXU6ZJIV.mjs} +1 -1
  146. package/lib/{chunk-GJ6SZVHT.mjs → chunk-WZN36ACK.mjs} +1 -1
  147. package/lib/{chunk-XU25YA46.mjs → chunk-X2XZQ434.mjs} +1 -1
  148. package/lib/{chunk-QAPVKPEC.mjs → chunk-X4HZD5U2.mjs} +1 -1
  149. package/lib/chunk-X6XNTOGO.mjs +7 -0
  150. package/lib/{chunk-XK5W7BVE.mjs → chunk-XAMMIPZ4.mjs} +1 -1
  151. package/lib/{chunk-DT3T7FRD.mjs → chunk-XAUQXYPW.mjs} +1 -1
  152. package/lib/{chunk-C3LNYAVJ.mjs → chunk-XCJUNX63.mjs} +1 -1
  153. package/lib/chunk-XJICAOAQ.mjs +7 -0
  154. package/lib/{chunk-CBL42DUU.mjs → chunk-XKFHTBAB.mjs} +1 -1
  155. package/lib/{chunk-O2PUGRNW.mjs → chunk-XMQ5R6TC.mjs} +1 -1
  156. package/lib/chunk-XPXEQKLR.mjs +7 -0
  157. package/lib/{chunk-6KP6WETK.mjs → chunk-Y7YUNRKK.mjs} +1 -1
  158. package/lib/{chunk-WSUKC2U3.mjs → chunk-YBZIDW6W.mjs} +1 -1
  159. package/lib/{chunk-RTWYLOCA.mjs → chunk-YEVB7LVK.mjs} +1 -1
  160. package/lib/{chunk-L4INJ5TZ.mjs → chunk-Z3MGN42K.mjs} +1 -1
  161. package/lib/{chunk-EOFO3PHS.mjs → chunk-ZB5E7NHU.mjs} +1 -1
  162. package/lib/chunk-ZCOSME6P.mjs +7 -0
  163. package/lib/{chunk-HFUDCNU5.mjs → chunk-ZOSESZ22.mjs} +1 -1
  164. package/lib/chunk-ZTHC42X6.mjs +7 -0
  165. package/lib/{chunk-XZISAZA6.mjs → chunk-ZXOUWHYE.mjs} +1 -1
  166. package/lib/sandforge-autopilot.mjs +1 -1
  167. package/lib/sandforge-backup.mjs +1 -1
  168. package/lib/sandforge-checkpoint.mjs +1 -1
  169. package/lib/sandforge-cleanup.mjs +1 -1
  170. package/lib/sandforge-clone.mjs +1 -1
  171. package/lib/sandforge-compare.mjs +1 -1
  172. package/lib/sandforge-dataops.mjs +1 -1
  173. package/lib/sandforge-empty.mjs +4 -4
  174. package/lib/sandforge-env.mjs +98 -99
  175. package/lib/sandforge-frozen.mjs +1 -1
  176. package/lib/sandforge-mcp.mjs +2 -2
  177. package/lib/sandforge-monitor.mjs +1 -1
  178. package/lib/sandforge-pipeline.mjs +1 -1
  179. package/lib/sandforge-seed.mjs +1 -1
  180. package/lib/sandforge-sync.mjs +1 -1
  181. package/lib/sandforge-users.mjs +21 -23
  182. package/oclif.manifest.json +1 -1
  183. package/package.json +1 -1
  184. package/lib/chunk-42BFLWHR.mjs +0 -7
  185. package/lib/chunk-466F37VD.mjs +0 -7
  186. package/lib/chunk-7SDZR6SR.mjs +0 -7
  187. package/lib/chunk-BMTNTBBM.mjs +0 -7
  188. package/lib/chunk-CCEH7L53.mjs +0 -7
  189. package/lib/chunk-DIL62SUN.mjs +0 -7
  190. package/lib/chunk-FZF23M6R.mjs +0 -7
  191. package/lib/chunk-GHPR5UVV.mjs +0 -7
  192. package/lib/chunk-HQQVANWQ.mjs +0 -20
  193. package/lib/chunk-IRZJU2PG.mjs +0 -22
  194. package/lib/chunk-ISSP2FZ5.mjs +0 -7
  195. package/lib/chunk-JFNLKHY6.mjs +0 -8
  196. package/lib/chunk-O4BROUGM.mjs +0 -7
  197. package/lib/chunk-PE435FVH.mjs +0 -15
  198. package/lib/chunk-RLWB7F26.mjs +0 -7
  199. package/lib/chunk-WEMLDUQA.mjs +0 -7
  200. package/lib/chunk-ZQO5PDX5.mjs +0 -48
@@ -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 u,b as a,c as h,d as g,e as l,f as m}from"./chunk-DMT5SCO3.mjs";import{k as p}from"./chunk-N2HYG3BL.mjs";import{randomBytes as k}from"node:crypto";import{mkdir as v,open as O,readdir as w,rename as S,rm as $}from"node:fs/promises";import{homedir as b}from"node:os";import{dirname as x,join as f,resolve as y}from"node:path";var E=448,D=384,A="_recovery",I="Back into service",T=/^(\d{8}T\d{9}Z)-(00D[A-Za-z0-9]{15})\.md$/;function J(e=process.env){let t=e.SANDFORGE_JOURNAL_DIR;return t!==void 0&&t.trim()!==""?y(t):f(b(),".sandforge")}function R(e){return f(y(e),"handoff",A)}function M(e,t){let n=new Date(t.at).toISOString().replace(/[-:.]/g,"");return f(R(e),`${n}-${p(t.organizationId)}.md`)}function _(e){return`${e.slice(0,4)}-${e.slice(4,6)}-${e.slice(6,8)}T${e.slice(9,11)}:${e.slice(11,13)}:${e.slice(13,15)}.${e.slice(15,18)}Z`}async function F(e,t){let n=p(t),o=R(e),i;try{i=await w(o)}catch(r){let s=r?.code;if(s==="ENOENT"||s==="ENOTDIR")return;throw r}let c=i.flatMap(r=>{let s=T.exec(r);return s?.[1]!==void 0&&s[2]===n?[{stamp:s[1],name:r}]:[]}).sort((r,s)=>r.stamp<s.stamp?-1:1).at(-1);return c!==void 0?{at:_(c.stamp),path:f(o,c.name)}:void 0}async function W(e,t){return(await F(e,t))?.at}var H={refresh:"Refresh noticed",users:"Users",masking:"Masking of the data copied from production",replay:"Replay of the checkpoint of before",frozen:"Frozen dataset loaded",testersCheckpoint:"Testers' starting checkpoint",deliverability:"Email deliverability",scheduledJobs:"Scheduled jobs",endpoints:"Endpoints that still name production",handoff:"Handoff note"},N={refreshDetected:"noticed",ranAfterRefresh:"ran on the sandbox since its refresh",markedDone:"checked and marked done",ready:"kept",toDo:"to do",skipped:"skipped",noRefreshDetected:"no refresh was noticed",nothingCopied:"nothing of production was copied into this sandbox",noCheckpointBefore:"no checkpoint of the sandbox was taken before its refresh",noManifest:"no frozen dataset is kept on this machine",noInventoryBefore:"no inventory of its jobs was kept before the refresh",noUserToBringBack:"no user is under .invalid, frozen or inactive",stagingSandbox:"the sandbox is marked Staging"},B={todo:"to do",done:"done",skipped:"skipped",notApplicable:"not applicable",refused:"refused"};function z(e,t,n){let o=[B[e.status]];return e.status!=="todo"&&e.status!=="skipped"&&o.push(N[e.reason]),e.at!==void 0&&o.push(a(e.at)),e.id==="users"&&n.lastUsersRun!==void 0&&o.push(`last run ${n.lastUsersRun.run}, ${n.lastUsersRun.status}`),e.id==="replay"&&n.checkpointBefore!==void 0&&o.push(`checkpoint ${u(n.checkpointBefore.name)} of ${a(n.checkpointBefore.takenAt)}`),`${t+1}. ${H[e.id]}: ${o.join(", ")}.`}function Y(e){let{status:t,org:n}=e,o=t.refresh,i=o!==void 0?`- Refresh: noticed ${a(o.detectedAt)}`+(o.previousOrganizationId!==void 0?`; the sandbox was ${u(o.previousOrganizationId)} before.`:"."):"- Refresh: none was noticed; the steps are of the org the sandbox is.",d=t.steps.find(r=>r.id==="testersCheckpoint");return`${[h(I,n),"","## Sandbox","",g(n),i,`- Written: ${a(e.at)}`+(e.sandforgeVersion!==void 0?`, by SandForge ${e.sandforgeVersion}`:"")+`; ${t.done} of ${t.total} steps done.`,"","## Steps","",...t.steps.map((r,s)=>z(r,s,t)),"","## Testers' starting point","",d?.status==="done"&&d.at!==void 0?`- A checkpoint of the sandbox taken ${a(d.at)}: what the testers start from, and what a rewind takes it back to.`:"- No checkpoint of the sandbox was taken since its refresh: take one before the testers start, to rewind to.","",...l(e.audits,{endpoints:"step 9 of Back into service lists those that still name production.",schedules:"step 8 of Back into service compares them with their inventory."}),"",...m()].join(`
8
+ `)}
9
+ `}async function Z(e,t){await v(x(e),{recursive:!0,mode:E});let n=`${e}.${process.pid}-${k(4).toString("hex")}.tmp`,o=await O(n,"wx",D);try{try{await o.writeFile(t,"utf8"),await o.sync()}finally{await o.close()}await S(n,e)}catch(i){throw await $(n,{force:!0}),i}}export{E as a,D as b,A as c,J as d,R as e,M as f,F as g,W as h,Y as i,Z as j};
@@ -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{b as te}from"./chunk-DBBPDSFN.mjs";import{c as nt,d as ot}from"./chunk-GBGHJTPC.mjs";import{i as et,k as tt}from"./chunk-YMDFF657.mjs";import{a as st,b as it,c as rt,d as at,e as ct,f as dt,h as lt}from"./chunk-7WSLT5VX.mjs";import{d as He,j as Ke}from"./chunk-YT22LMF7.mjs";import{c as Oe,d as Ce,p as Ge}from"./chunk-PE435FVH.mjs";import{a as Te}from"./chunk-PWVDNN2C.mjs";import{h as ze,i as Ve}from"./chunk-XU25YA46.mjs";import{A as _e,C as Ue,t as Be,u as We,z as q}from"./chunk-O2PUGRNW.mjs";import{A as qe,B as x,D as ee,G as Ze,b as je,f as Re,h as Ne,i as Q,j as X,k as Fe,n as Le,o as Ie,r as xe,t as Z,u as Je,v as Qe,w as Xe,z as Ye}from"./chunk-SAMWHL22.mjs";import{A as ve,B as I,H as Ee,K as $e,a as De,e as Me,o as Y,z as Pe}from"./chunk-J24TIGSI.mjs";import{f as H}from"./chunk-ZUOPC4W2.mjs";import{E as Se}from"./chunk-XZISAZA6.mjs";import{f as be,g as ke,h as L,m as we,n as ye,o as K,t as Ae,u as J}from"./chunk-L4INJ5TZ.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Hc as F,Va as me,Wa as $,Za as ge,le as he}from"./chunk-ZQO5PDX5.mjs";import{b as pe,k as fe,l as V}from"./chunk-WZQEK4WT.mjs";import{readdir as It,rm as gt,stat as ht}from"node:fs/promises";import{existsSync as xt,readFileSync as Bt,writeFileSync as Wt}from"node:fs";import{hostname as _t}from"node:os";import{join as oe}from"node:path";var Gt=5e5,B=1e6,Ut=100,zt="taking",ut=500;function Xn(e){let t=Ne(e),n=[H(e)];return{get version(){return e.version},request:o=>t.request(o),query:(o,s)=>t.query(o,s),queryMore:o=>t.queryMore(o),describeGlobal:async()=>await e.describeGlobal(),toolingObjects:async()=>{try{return(await e.tooling.describeGlobal()).sobjects.map(s=>s.name)}catch{return[]}},serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp,userId:async()=>(await e.soap.getUserInfo()).userId,requestsSent:()=>n.reduce((o,s)=>o+s(),0),countAlso:o=>{n.push(H(o))}}}function Vt(e){return Fe(ze(e))}var D=class extends Error{constructor(){super("The checkpoint was stopped before it was taken: nothing of it was kept."),this.name="CheckpointTakeStopped"}},W="No record was read.",Ht={excludedByUser:"Left out as asked.",notFound:"The org has no object of this name.",chatter:"Chatter posts, comments and feeds are left out: Salesforce brings a post back only with what it was posted on.",history:"History is left out: it is the org's own trace of changes.",sharing:"Sharing is left out: the org keeps it itself.",changeEvent:"Change events are left out.",unsupportedKind:"Left out: neither the recycle bin nor an update reaches this kind of object as it reaches a record.",customSetting:"Custom settings are left out unless you pick them as custom settings: they are configuration, which a rewind sets back.",notCustomSetting:"Picked as a custom setting: the org has no custom setting of this name.",files:"Documents of the Documents tab are left out: they are shared content kept in folders, as setup is.",heldWithFiles:"Held with its file (ContentDocument): Salesforce neither deletes nor brings back a file's version on its own, and reads the links of a file through the records they tie it to.",setup:"Users, permissions and setup are left out, and so are the org's own logs and jobs.",platformCreated:"Left out: Salesforce alone creates its records, such as approvals, Einstein insights, Data.com clean info and invoices, and no permission lets a user create one.",metadata:"Left out: it is metadata, which a checkpoint doesn't hold.",notWritable:"Left out: the user SandForge connects as may not create, edit and delete its records.",notDescribed:"Left out: the org would not describe it.",noSystemModstamp:"Left out: it has no SystemModstamp, so nothing would tell a record changed since.",noRecycleBin:"Left out: the org deletes its records for good, with no recycle bin, so nothing would tell one deleted since, nor bring it back.",unreadable:"Left out: the org refuses to read it whole.",noViewAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has neither on this one: a record they cannot see would read as deleted since.",noModifyAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has View All on this one, not Modify All: a rewind could not put back what others changed.",activities:"Without View All Data and Modify All Data, tasks and events are left out: Salesforce has no View All for activities, and a private one linked to no record stays out of sight.",catalog:"Without View All Data and Modify All Data, products and price books are left out: Salesforce has no View All or Modify All for them.",filesNotProven:"Without View All Data and Modify All Data, files are left out: nothing proves the user sees every file.",settingNotProven:"Without View All Data and Modify All Data, custom settings are left out: no permission on an object proves the user sees and writes every row.",parentNotSeen:"Without View All Data and Modify All Data, an object with no permissions of its own is held only when the user has View All and Modify All on every record it hangs from, which is not proven here."};function bt(e){let t=Ht[e.reason],n=e.detail===void 0?t:`${t.replace(/\.$/,"")} (${e.detail}).`;return{objectApiName:e.objectApiName,code:e.reason,reason:pt(n),...e.detail===void 0?{}:{detail:pt(e.detail)}}}function Kt(e,t,n){return{objectApiName:e,code:"pastTheLimit",records:t,limit:n,reason:t>B?`${e} has ${t} records, more than any checkpoint holds of one object (${B}): left out of the checkpoint, and a rewind to it does not touch ${e}. Data Export, in Setup, or a Bulk API query keeps a copy of it.`:`${e} has ${t} records, past the checkpoint's limit of ${n} for one object: left out of the checkpoint, as part of it would be taken for all of it.`}}function Jt(e,t){let n=t;for(;;){let o=e.filter(s=>s<=Math.min(n,B)).reduce((s,r)=>s+r,0);if(o<=n)return n;n=o}}function pt(e){return e.length<=ut?e:`${e.slice(0,ut-1)}\u2026`}function kt(e,t){return{code:"RUN_WRITING",message:`${t.operation==="take"?`A checkpoint of ${e} is being taken`:t.operation==="rewind"?`A rewind is writing to ${e}`:t.operation==="undo"?`An undo is writing to ${e}`:t.operation==="empty"?`An emptying of its objects is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${t.pid} on ${t.host}): take the checkpoint once it has ended. ${W}`}}function wt(e){return typeof e!="object"||e===null?void 0:typeof e.errorCode=="string"?v(e):void 0}function _(e,t){return e instanceof Q||e instanceof Te||e instanceof D||t?.aborted===!0}var Qt=V({sobjects:fe(be)}).loose();function M(e){return e.toLowerCase()===ke.toLowerCase()}function Xt(e,t,n){if(e===void 0)return{why:`the org lists no ${L}`};let o=t.get(e);if(o===void 0)return{why:n.get(e)??"it was not described"};let r=o.fields.find(d=>d.name.toLowerCase()==="linkedentityid")?.referenceTo??[];return r.length===0?{why:"its describe names no record a link ties a file to"}:{linkable:new Set(r.map(d=>d.toLowerCase()))}}async function se(e,t,n){let o=new Map,s=new Map,r=0,d=await Promise.allSettled(n.map(p=>t.describe(p)));for(let[p,i]of d.entries()){let c=n[p],l;if(i.status==="fulfilled"&&"body"in i.value)l=i.value.body;else{if(i.status==="rejected"&&i.reason instanceof Q)throw i.reason;r++;try{l=await e.request({method:"GET",url:`/services/data/v${e.version}/sobjects/${F(c)}/describe`})}catch(h){let a=wt(h);if(a===void 0)throw new Error(`The org did not answer the describe of ${c}: ${v(h)}`);s.set(c,a);continue}}let u=He.safeParse(l);u.success?o.set(c,u.data):s.set(c,"its describe does not read as one")}return{describes:o,errors:s,alone:r}}async function yt(e,t,n){let o=Qt.parse(await e.describeGlobal()),s=await e.toolingObjects?.()??[],r=ye(o.sobjects,{mode:n.mode,...n.objects?{objects:n.objects}:{},...n.excluded?{excluded:n.excluded}:{},...n.customSettings?{customSettings:n.customSettings}:{}},s),d=r.candidates.some(M),p=d?o.sobjects.find(m=>m.name.toLowerCase()===L.toLowerCase())?.name:void 0,i=p===void 0?r.candidates:[...r.candidates,p],{describes:c,errors:l,alone:u}=await se(e,t,i),h,a;if(d){let m=Xt(p,c,l);"linkable"in m?h=m.linkable:a=m.why,p!==void 0&&c.delete(p)}let g=Ae(r,c,l);if(a!==void 0){let m=g.objects.find(({objectApiName:C})=>M(C));m!==void 0&&(g=J(g,new Map([[m.objectApiName,`its links to records, ${L}, could not be described: ${a}`]])))}let w=await je(async m=>(await e.query(m)).records),A=new Map(o.sobjects.map(m=>[m.name,ft(m)])),S=o.sobjects.filter(we),f=new Set(S.map(m=>m.name)),k=[...c.values()],y=[];for(let m of g.objects){let C=c.get(m.objectApiName);C&&y.push({scoped:m,label:A.get(m.objectApiName)??m.objectApiName,describe:C,capture:await Ke(C,k,{viewsEncryptedData:w}),...f.has(m.objectApiName)?{customSetting:K(C)}:{}})}return{described:i.length,describedAlone:u,objects:y,leftOut:g.leftOut,addedToPicked:r.addedToPicked,...h!==void 0&&y.some(({scoped:m})=>M(m.objectApiName))?{linkable:h}:{},settings:S.map(m=>({objectApiName:m.name,label:ft(m)}))}}function ft(e){let t=e.label;return typeof t=="string"&&t!==""?t:e.name}async function Yt(e,t,n,o){let s=await ee(t,n.map(({capture:i})=>({objectApiName:i.objectApiName,readMode:i.readMode})),o),r=new Map,d=new Map,p=0;for(let[i,c]of s.entries()){let{objectApiName:l,readMode:u}=n[i].capture;if("count"in c){r.set(l,c.count);continue}p++;let h=Qe(l,u);try{let a=await e.query(h.soql,{scanAll:h.scanAll});if(typeof a.totalSize!="number")throw new Error("The org gave no count of its records.");r.set(l,a.totalSize)}catch(a){let g=wt(a);if(g===void 0)throw new Error(`The org did not count the records of ${l}: ${v(a)}`);d.set(l,g)}}return{counts:r,refused:d,alone:p}}function At(e,t){return t?.has(e.toLowerCase())===!0&&!M(e)}async function qt(e,t,n,o,s){let r=[];for(let{objectApiName:i,records:c}of t){let l=F(i);r.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE IsDeleted = true AND SystemModstamp < ${Z(o)}`,scanAll:!0,counts:"inBin"}),c!==0&&(r.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE SystemModstamp >= ${Je(o)}`,scanAll:!0,counts:"stampedSince"}),At(l,n)&&r.push({...et(l),counts:"links"}))}let d=await Ye(e,r,()=>{},s),p=new Map;return d.forEach((i,c)=>{let{objectApiName:l,counts:u}=r[c],h=i.read?i.totalSize:void 0,a=p.get(l)??{};u==="links"?a.links=h??null:h!==void 0&&(a[u]=h),p.set(l,a)}),{asked:r.length,of:p}}function St({scoped:e,capture:t,customSetting:n,access:o},s,r,d){return{objectApiName:e.objectApiName,records:s,inBin:r,readOrder:e.readOrder,readMode:t.readMode,undeletable:t.undeletable,cascadeParents:t.cascadeParents,restrictParents:t.restrictParents,fingerprint:d,fields:t.fields,leftOutFields:t.leftOutFields,...n!==void 0?{customSetting:n}:{},...o!==void 0?{access:o}:{}}}function Ot(e){return{personAccounts:rt(e.map(({describe:t})=>t)),catalog:at(e.map(({scoped:t})=>t.objectApiName))}}function Zt(e){let t=e?.orgType==="Sandbox"||e?.orgType==="Scratch";return Oe(Ce(t)).defaultQueryLimit}async function Ct(e,t,n,o,s,r,d,p=Tt){let i=n.maxTotal??Gt;if(!Number.isInteger(i)||i<1)throw new RangeError(`Not a number of records: ${i}`);let c=Math.min(i,B),{counts:l,refused:u,alone:h}=await Yt(e,t,o.objects,d),a=J({mode:n.mode,objects:o.objects.map(({scoped:b})=>b),leftOut:o.leftOut,packages:[]},u),g=new Map(o.objects.map(b=>[b.scoped.objectApiName,b])),w=a.leftOut.map(bt),A=[];for(let b of a.objects){let O=g.get(b.objectApiName),P=l.get(b.objectApiName);if(!(O===void 0||P===void 0)){if(P>c){w.push(Kt(b.objectApiName,P,c));continue}A.push({...O,scoped:{...b,readOrder:A.length},records:P,otherGroups:Be(b.objectApiName,O.capture.fields,O.capture.readMode),recount:{}})}}let S=A.some(({scoped:b})=>M(b.objectApiName))?o.linkable:void 0,f=await qt(t,A.map(({scoped:b,records:O})=>({objectApiName:b.objectApiName,records:O})),S,r,d);for(let b of A)b.recount=f.of.get(b.scoped.objectApiName)??{};w.sort((b,O)=>b.objectApiName<O.objectApiName?-1:b.objectApiName>O.objectApiName?1:0);let k={};for(let{scoped:b,describe:O}of A)k[b.objectApiName]=De(O.fields);let y=en(p,We({described:o.described,describedAlone:o.describedAlone,counted:o.objects.length,countedAlone:h,recounted:f.asked,objects:A.map(b=>({records:b.records,otherGroups:b.otherGroups,...b.recount,entry:St(b,b.records,0,k[b.scoped.objectApiName].digest)})),pageRows:Zt(n.registered),leftOut:w,printsBytes:(await $e(k)).length,annexCalls:ct(Ot(A))})),m={...y,apiRequestsLeft:s.remaining},C={objects:A,leftOut:w,estimate:m,objectLimit:c,prints:k,...S!==void 0?{linkable:S}:{}};if(y.records>i){let b=[...A.map(O=>O.records),...w.flatMap(O=>O.code==="pastTheLimit"?[O.records??0]:[])];return{...C,refusal:{code:"TOO_MANY_RECORDS",message:`The objects this checkpoint would keep hold ${y.records} records in ${n.orgName}, past its limit of ${i}: pick fewer objects. ${W}`,holdingLimit:Jt(b,y.records)}}}let R=_e("take",y.apiRequests,s,n.orgName);return R===void 0?C:{...C,refusal:R}}function jt(e){return{query:t=>e.query(t),queryMore:t=>e.queryMore(t)}}var Tt={guard:0,scope:0};function en(e,t){if(e.guard+e.scope===0)return t;let n=t.requestsByPhase;return{...t,apiRequests:t.apiRequests+e.guard+e.scope,...n!==void 0?{requestsByPhase:{...n,guard:n.guard+e.guard,scope:n.scope+e.scope}}:{}}}function tn(e){let t=[...e.mode==="picked"?e.objects??[]:[],...Array.isArray(e.customSettings)?e.customSettings:[]];return new Set(t.map(n=>n.toLowerCase()))}function nn(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}async function Rt(e,t,n,o,s,r){if(s.kind==="org")return{scope:{...o,objects:o.objects.map(f=>({...f,access:"org"}))},reads:Tt};let d=o.objects.map(({scoped:f})=>f.objectApiName),p={grants:s.objects,describes:o.objects.map(({describe:f})=>f),customSettings:o.objects.filter(({customSetting:f})=>f!==void 0).map(({scoped:f})=>f.objectApiName)},i=nt(d,p),c=[],l=0;if(i.length>0)try{let f=await se(e,t,i);c=[...f.describes.values()],l=Math.ceil(i.length/Re)+f.alone}catch(f){if(_(f,r))throw f}let u=ot(d,{...p,describes:[...p.describes,...c]}),h=tn(n),a=[],g=[...o.leftOut],w=[];for(let f of o.objects){let k=f.scoped.objectApiName,y=u.get(k);if(y!==void 0&&"access"in y){a.push({...f,access:y.access});continue}let m={objectApiName:k,reason:y?.reason??"noViewAll",...y?.detail!==void 0?{detail:y.detail}:{}};g.push(m),h.has(k.toLowerCase())&&n.unprovenLeftOut!==!0&&w.push(m)}let A=new Set(a.map(({scoped:f})=>f.objectApiName)),S={scope:{...o,objects:a,leftOut:g,addedToPicked:o.addedToPicked.filter(f=>A.has(f))},reads:{guard:s.requests,scope:l}};if(w.length>0){let f=w.length===1;return{...S,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, and the checkpoint can't hold ${nn(w.map(k=>k.objectApiName))}, asked for by name. ${w.map(k=>`${k.objectApiName}: ${bt(k).reason}`).join(" ")} Leave ${f?"it":"them"} out, or give the user View All Data and Modify All Data. ${W}`}}}return a.length===0&&o.objects.length>0?{...S,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, nor View All and Modify All on any object this checkpoint would hold: without them, a checkpoint holds only the objects its user sees and puts back whole. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. `+W}}:S}function on(e){return e.objects.map(({scoped:t,label:n,capture:o,records:s,customSetting:r,access:d})=>({objectApiName:t.objectApiName,label:n,...t.namespace!==void 0?{namespace:t.namespace}:{},records:s,undeletable:o.undeletable,leftOutFields:o.leftOutFields,...r!==void 0?{customSetting:r}:{},...d!==void 0?{access:d}:{}}))}function Nt(e){let t=e.customSettings;return t!==void 0&&(t==="all"||t.length>0)}async function sn(e,t,n,o,s){let r=new Map(o.objects.map(u=>[u.scoped.objectApiName,u])),d=n.settings.filter(({objectApiName:u})=>!r.has(u)),p=new Map;if(d.length>0)try{({describes:p}=await se(e,t,d.map(({objectApiName:u})=>u)))}catch(u){if(_(u,s))throw u}let i=d.filter(({objectApiName:u})=>p.has(u)),c=await ee(t,i.map(({objectApiName:u})=>({objectApiName:u,readMode:"query"})),s),l=new Map;return c.forEach((u,h)=>{"count"in u&&l.set(i[h].objectApiName,u.count)}),n.settings.map(({objectApiName:u,label:h})=>{let a=r.get(u);if(a?.customSetting!==void 0)return{objectApiName:u,label:h,kind:a.customSetting,records:a.records};let g=p.get(u),w=l.get(u);return{objectApiName:u,label:h,...g!==void 0?{kind:K(g)}:{},...w!==void 0?{records:w}:{}}})}var rn={records:0,apiRequests:0,apiRequestsLeft:0,seconds:0,bytes:0};async function Yn(e,t){let n={mode:t.mode,objects:[],leftOut:[],estimate:rn},o=await te(jt(e.org),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:Nt(t)},{userId:()=>e.org.userId()});if(!o.allowed)return{...n,refusal:o.refusal};let s=e.store.heldBy(o.org.id),r=s===void 0?await e.runWriting?.(o.org.id):void 0,d=X(e.org,e.signal);try{let p=await q(e.org,t.orgName),i=await Rt(e.org,d,t,await yt(e.org,d,t),o.grants,e.signal),{scope:c}=i,l=await e.org.serverTime(),u=await Ct(e.org,d,t,c,p,l,e.signal,i.reads),h={mode:t.mode,objects:on(u),leftOut:u.leftOut,estimate:u.estimate,files:{held:u.objects.some(({scoped:g})=>M(g.objectApiName)),queryAllFiles:o.queryAllFiles,addedToPicked:c.addedToPicked},customSettings:await sn(e.org,d,c,u,e.signal)},a=s!==void 0?kt(t.orgName,s):r!==void 0?{code:"RUN_WRITING",message:r}:i.refusal??u.refusal;return a===void 0?h:{...h,refusal:a}}catch(p){throw _(p,e.signal)?new D:p}}function an(e){let t=e.requestsSent?()=>e.requestsSent?.()??0:void 0,n={guard:0,scope:0,start:0,counts:0,bin:0,snapshot:0,stability:0},o="guard",s=t?.()??0,r=()=>{if(!t)return;let d=t();n[o]+=d-s,s=d};return{enter(d){r(),o=d},requests(){return t?(r(),{total:Object.values(n).reduce((p,i)=>p+i,0),byPhase:{...n}}):void 0}}}async function cn(e,t){if(t.edition!==void 0)return t.edition;let o=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;if(typeof o!="string"||o==="")throw new Error("The org did not say its edition (Organization.OrganizationType).");return o}var dn="Automated Process";async function ln(e){let n=(await e.query("SELECT Id, Name FROM User WHERE UserType = 'AutomatedProcess'")).records.filter(s=>typeof s.Id=="string"),o=n.find(s=>s.Name===dn);return o!==void 0?o.Id:n.length===1?n[0].Id:void 0}function Dt(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function mt(e,t){return e.split(he).join(Dt(t))}function ne(e){let t=Se(e);return t===null?Number.NaN:Date.parse(t)}function Mt(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}async function un(e,t){let n=new Set;for await(let o of x(Y(e,t))){let s=Mt(o.Id);s!==void 0&&n.add(s)}return n}async function pn(e,t,n,o,s,r){let d={changed:0,deleted:0,created:0};if(!o.live&&!o.deleted)return d;let p=await xe.read(e,t,n);if(o.live)for await(let i of x(o.live.file)){let c=ne(i.SystemModstamp);if(!(c<=r))continue;let l=p.stampOf(i.Id);l===void 0?d.created++:l!==c&&d.changed++}if(o.deleted){let i;for await(let c of x(o.deleted.file)){if(!(ne(c.SystemModstamp)<=r))continue;if(p.has(c.Id)){d.deleted++;continue}if(!(ne(c.CreatedDate)<s))continue;i??=await un(e,n);let l=Mt(c.Id);l!==void 0&&!i.has(l)&&d.deleted++}}return d}async function Pt(e){let t=0;for(let n of await It(e,{withFileTypes:!0})){let o=oe(e,n.name);n.isDirectory()?t+=await Pt(o):n.isFile()&&(t+=(await ht(o)).size)}return t}async function fn(e,t){let n=await Pt(e.dir)-(await ht(e.checkpointFile)).size,o=r=>Buffer.byteLength(`${JSON.stringify({...t,bytes:r},null,2)}
7
+ import{b as te}from"./chunk-BPHTA6KP.mjs";import{c as nt,d as ot}from"./chunk-U2CTKIPE.mjs";import{i as et,k as tt}from"./chunk-NDFFIJL5.mjs";import{a as st,b as it,c as rt,d as at,e as ct,f as dt,h as lt}from"./chunk-I5C4O3VA.mjs";import{d as He,j as Ke}from"./chunk-RVCPQVKM.mjs";import{c as Oe,d as Ce,p as Ge}from"./chunk-FKCIGJOI.mjs";import{a as Te}from"./chunk-C6RKM4BB.mjs";import{h as ze,i as Ve}from"./chunk-X2XZQ434.mjs";import{A as _e,C as Ue,t as Be,u as We,z as q}from"./chunk-XMQ5R6TC.mjs";import{A as qe,B as x,D as ee,G as Ze,b as je,f as Re,h as Ne,i as Q,j as X,k as Fe,n as Le,o as Ie,r as xe,t as Z,u as Je,v as Qe,w as Xe,z as Ye}from"./chunk-EOQON3E5.mjs";import{A as ve,B as I,H as Ee,K as $e,a as De,e as Me,o as Y,z as Pe}from"./chunk-N2HYG3BL.mjs";import{f as H}from"./chunk-4GCYGQXD.mjs";import{E as Se}from"./chunk-ZXOUWHYE.mjs";import{f as be,g as ke,h as L,m as we,n as ye,o as K,t as Ae,u as J}from"./chunk-Z3MGN42K.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Uc as F,Va as me,Wa as $,Za as ge,ye as he}from"./chunk-6QSHWIZI.mjs";import{b as pe,k as fe,l as V}from"./chunk-WZQEK4WT.mjs";import{readdir as It,rm as gt,stat as ht}from"node:fs/promises";import{existsSync as xt,readFileSync as Bt,writeFileSync as Wt}from"node:fs";import{hostname as _t}from"node:os";import{join as oe}from"node:path";var Gt=5e5,B=1e6,Ut=100,zt="taking",ut=500;function Xn(e){let t=Ne(e),n=[H(e)];return{get version(){return e.version},request:o=>t.request(o),query:(o,s)=>t.query(o,s),queryMore:o=>t.queryMore(o),describeGlobal:async()=>await e.describeGlobal(),toolingObjects:async()=>{try{return(await e.tooling.describeGlobal()).sobjects.map(s=>s.name)}catch{return[]}},serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp,userId:async()=>(await e.soap.getUserInfo()).userId,requestsSent:()=>n.reduce((o,s)=>o+s(),0),countAlso:o=>{n.push(H(o))}}}function Vt(e){return Fe(ze(e))}var D=class extends Error{constructor(){super("The checkpoint was stopped before it was taken: nothing of it was kept."),this.name="CheckpointTakeStopped"}},W="No record was read.",Ht={excludedByUser:"Left out as asked.",notFound:"The org has no object of this name.",chatter:"Chatter posts, comments and feeds are left out: Salesforce brings a post back only with what it was posted on.",history:"History is left out: it is the org's own trace of changes.",sharing:"Sharing is left out: the org keeps it itself.",changeEvent:"Change events are left out.",unsupportedKind:"Left out: neither the recycle bin nor an update reaches this kind of object as it reaches a record.",customSetting:"Custom settings are left out unless you pick them as custom settings: they are configuration, which a rewind sets back.",notCustomSetting:"Picked as a custom setting: the org has no custom setting of this name.",files:"Documents of the Documents tab are left out: they are shared content kept in folders, as setup is.",heldWithFiles:"Held with its file (ContentDocument): Salesforce neither deletes nor brings back a file's version on its own, and reads the links of a file through the records they tie it to.",setup:"Users, permissions and setup are left out, and so are the org's own logs and jobs.",platformCreated:"Left out: Salesforce alone creates its records, such as approvals, Einstein insights, Data.com clean info and invoices, and no permission lets a user create one.",metadata:"Left out: it is metadata, which a checkpoint doesn't hold.",notWritable:"Left out: the user SandForge connects as may not create, edit and delete its records.",notDescribed:"Left out: the org would not describe it.",noSystemModstamp:"Left out: it has no SystemModstamp, so nothing would tell a record changed since.",noRecycleBin:"Left out: the org deletes its records for good, with no recycle bin, so nothing would tell one deleted since, nor bring it back.",unreadable:"Left out: the org refuses to read it whole.",noViewAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has neither on this one: a record they cannot see would read as deleted since.",noModifyAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has View All on this one, not Modify All: a rewind could not put back what others changed.",activities:"Without View All Data and Modify All Data, tasks and events are left out: Salesforce has no View All for activities, and a private one linked to no record stays out of sight.",catalog:"Without View All Data and Modify All Data, products and price books are left out: Salesforce has no View All or Modify All for them.",filesNotProven:"Without View All Data and Modify All Data, files are left out: nothing proves the user sees every file.",settingNotProven:"Without View All Data and Modify All Data, custom settings are left out: no permission on an object proves the user sees and writes every row.",parentNotSeen:"Without View All Data and Modify All Data, an object with no permissions of its own is held only when the user has View All and Modify All on every record it hangs from, which is not proven here."};function bt(e){let t=Ht[e.reason],n=e.detail===void 0?t:`${t.replace(/\.$/,"")} (${e.detail}).`;return{objectApiName:e.objectApiName,code:e.reason,reason:pt(n),...e.detail===void 0?{}:{detail:pt(e.detail)}}}function Kt(e,t,n){return{objectApiName:e,code:"pastTheLimit",records:t,limit:n,reason:t>B?`${e} has ${t} records, more than any checkpoint holds of one object (${B}): left out of the checkpoint, and a rewind to it does not touch ${e}. Data Export, in Setup, or a Bulk API query keeps a copy of it.`:`${e} has ${t} records, past the checkpoint's limit of ${n} for one object: left out of the checkpoint, as part of it would be taken for all of it.`}}function Jt(e,t){let n=t;for(;;){let o=e.filter(s=>s<=Math.min(n,B)).reduce((s,r)=>s+r,0);if(o<=n)return n;n=o}}function pt(e){return e.length<=ut?e:`${e.slice(0,ut-1)}\u2026`}function kt(e,t){return{code:"RUN_WRITING",message:`${t.operation==="take"?`A checkpoint of ${e} is being taken`:t.operation==="rewind"?`A rewind is writing to ${e}`:t.operation==="undo"?`An undo is writing to ${e}`:t.operation==="empty"?`An emptying of its objects is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${t.pid} on ${t.host}): take the checkpoint once it has ended. ${W}`}}function wt(e){return typeof e!="object"||e===null?void 0:typeof e.errorCode=="string"?v(e):void 0}function _(e,t){return e instanceof Q||e instanceof Te||e instanceof D||t?.aborted===!0}var Qt=V({sobjects:fe(be)}).loose();function M(e){return e.toLowerCase()===ke.toLowerCase()}function Xt(e,t,n){if(e===void 0)return{why:`the org lists no ${L}`};let o=t.get(e);if(o===void 0)return{why:n.get(e)??"it was not described"};let r=o.fields.find(d=>d.name.toLowerCase()==="linkedentityid")?.referenceTo??[];return r.length===0?{why:"its describe names no record a link ties a file to"}:{linkable:new Set(r.map(d=>d.toLowerCase()))}}async function se(e,t,n){let o=new Map,s=new Map,r=0,d=await Promise.allSettled(n.map(p=>t.describe(p)));for(let[p,i]of d.entries()){let c=n[p],l;if(i.status==="fulfilled"&&"body"in i.value)l=i.value.body;else{if(i.status==="rejected"&&i.reason instanceof Q)throw i.reason;r++;try{l=await e.request({method:"GET",url:`/services/data/v${e.version}/sobjects/${F(c)}/describe`})}catch(h){let a=wt(h);if(a===void 0)throw new Error(`The org did not answer the describe of ${c}: ${v(h)}`);s.set(c,a);continue}}let u=He.safeParse(l);u.success?o.set(c,u.data):s.set(c,"its describe does not read as one")}return{describes:o,errors:s,alone:r}}async function yt(e,t,n){let o=Qt.parse(await e.describeGlobal()),s=await e.toolingObjects?.()??[],r=ye(o.sobjects,{mode:n.mode,...n.objects?{objects:n.objects}:{},...n.excluded?{excluded:n.excluded}:{},...n.customSettings?{customSettings:n.customSettings}:{}},s),d=r.candidates.some(M),p=d?o.sobjects.find(m=>m.name.toLowerCase()===L.toLowerCase())?.name:void 0,i=p===void 0?r.candidates:[...r.candidates,p],{describes:c,errors:l,alone:u}=await se(e,t,i),h,a;if(d){let m=Xt(p,c,l);"linkable"in m?h=m.linkable:a=m.why,p!==void 0&&c.delete(p)}let g=Ae(r,c,l);if(a!==void 0){let m=g.objects.find(({objectApiName:C})=>M(C));m!==void 0&&(g=J(g,new Map([[m.objectApiName,`its links to records, ${L}, could not be described: ${a}`]])))}let w=await je(async m=>(await e.query(m)).records),A=new Map(o.sobjects.map(m=>[m.name,ft(m)])),S=o.sobjects.filter(we),f=new Set(S.map(m=>m.name)),k=[...c.values()],y=[];for(let m of g.objects){let C=c.get(m.objectApiName);C&&y.push({scoped:m,label:A.get(m.objectApiName)??m.objectApiName,describe:C,capture:await Ke(C,k,{viewsEncryptedData:w}),...f.has(m.objectApiName)?{customSetting:K(C)}:{}})}return{described:i.length,describedAlone:u,objects:y,leftOut:g.leftOut,addedToPicked:r.addedToPicked,...h!==void 0&&y.some(({scoped:m})=>M(m.objectApiName))?{linkable:h}:{},settings:S.map(m=>({objectApiName:m.name,label:ft(m)}))}}function ft(e){let t=e.label;return typeof t=="string"&&t!==""?t:e.name}async function Yt(e,t,n,o){let s=await ee(t,n.map(({capture:i})=>({objectApiName:i.objectApiName,readMode:i.readMode})),o),r=new Map,d=new Map,p=0;for(let[i,c]of s.entries()){let{objectApiName:l,readMode:u}=n[i].capture;if("count"in c){r.set(l,c.count);continue}p++;let h=Qe(l,u);try{let a=await e.query(h.soql,{scanAll:h.scanAll});if(typeof a.totalSize!="number")throw new Error("The org gave no count of its records.");r.set(l,a.totalSize)}catch(a){let g=wt(a);if(g===void 0)throw new Error(`The org did not count the records of ${l}: ${v(a)}`);d.set(l,g)}}return{counts:r,refused:d,alone:p}}function At(e,t){return t?.has(e.toLowerCase())===!0&&!M(e)}async function qt(e,t,n,o,s){let r=[];for(let{objectApiName:i,records:c}of t){let l=F(i);r.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE IsDeleted = true AND SystemModstamp < ${Z(o)}`,scanAll:!0,counts:"inBin"}),c!==0&&(r.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE SystemModstamp >= ${Je(o)}`,scanAll:!0,counts:"stampedSince"}),At(l,n)&&r.push({...et(l),counts:"links"}))}let d=await Ye(e,r,()=>{},s),p=new Map;return d.forEach((i,c)=>{let{objectApiName:l,counts:u}=r[c],h=i.read?i.totalSize:void 0,a=p.get(l)??{};u==="links"?a.links=h??null:h!==void 0&&(a[u]=h),p.set(l,a)}),{asked:r.length,of:p}}function St({scoped:e,capture:t,customSetting:n,access:o},s,r,d){return{objectApiName:e.objectApiName,records:s,inBin:r,readOrder:e.readOrder,readMode:t.readMode,undeletable:t.undeletable,cascadeParents:t.cascadeParents,restrictParents:t.restrictParents,fingerprint:d,fields:t.fields,leftOutFields:t.leftOutFields,...n!==void 0?{customSetting:n}:{},...o!==void 0?{access:o}:{}}}function Ot(e){return{personAccounts:rt(e.map(({describe:t})=>t)),catalog:at(e.map(({scoped:t})=>t.objectApiName))}}function Zt(e){let t=e?.orgType==="Sandbox"||e?.orgType==="Scratch";return Oe(Ce(t)).defaultQueryLimit}async function Ct(e,t,n,o,s,r,d,p=Tt){let i=n.maxTotal??Gt;if(!Number.isInteger(i)||i<1)throw new RangeError(`Not a number of records: ${i}`);let c=Math.min(i,B),{counts:l,refused:u,alone:h}=await Yt(e,t,o.objects,d),a=J({mode:n.mode,objects:o.objects.map(({scoped:b})=>b),leftOut:o.leftOut,packages:[]},u),g=new Map(o.objects.map(b=>[b.scoped.objectApiName,b])),w=a.leftOut.map(bt),A=[];for(let b of a.objects){let O=g.get(b.objectApiName),P=l.get(b.objectApiName);if(!(O===void 0||P===void 0)){if(P>c){w.push(Kt(b.objectApiName,P,c));continue}A.push({...O,scoped:{...b,readOrder:A.length},records:P,otherGroups:Be(b.objectApiName,O.capture.fields,O.capture.readMode),recount:{}})}}let S=A.some(({scoped:b})=>M(b.objectApiName))?o.linkable:void 0,f=await qt(t,A.map(({scoped:b,records:O})=>({objectApiName:b.objectApiName,records:O})),S,r,d);for(let b of A)b.recount=f.of.get(b.scoped.objectApiName)??{};w.sort((b,O)=>b.objectApiName<O.objectApiName?-1:b.objectApiName>O.objectApiName?1:0);let k={};for(let{scoped:b,describe:O}of A)k[b.objectApiName]=De(O.fields);let y=en(p,We({described:o.described,describedAlone:o.describedAlone,counted:o.objects.length,countedAlone:h,recounted:f.asked,objects:A.map(b=>({records:b.records,otherGroups:b.otherGroups,...b.recount,entry:St(b,b.records,0,k[b.scoped.objectApiName].digest)})),pageRows:Zt(n.registered),leftOut:w,printsBytes:(await $e(k)).length,annexCalls:ct(Ot(A))})),m={...y,apiRequestsLeft:s.remaining},C={objects:A,leftOut:w,estimate:m,objectLimit:c,prints:k,...S!==void 0?{linkable:S}:{}};if(y.records>i){let b=[...A.map(O=>O.records),...w.flatMap(O=>O.code==="pastTheLimit"?[O.records??0]:[])];return{...C,refusal:{code:"TOO_MANY_RECORDS",message:`The objects this checkpoint would keep hold ${y.records} records in ${n.orgName}, past its limit of ${i}: pick fewer objects. ${W}`,holdingLimit:Jt(b,y.records)}}}let R=_e("take",y.apiRequests,s,n.orgName);return R===void 0?C:{...C,refusal:R}}function jt(e){return{query:t=>e.query(t),queryMore:t=>e.queryMore(t)}}var Tt={guard:0,scope:0};function en(e,t){if(e.guard+e.scope===0)return t;let n=t.requestsByPhase;return{...t,apiRequests:t.apiRequests+e.guard+e.scope,...n!==void 0?{requestsByPhase:{...n,guard:n.guard+e.guard,scope:n.scope+e.scope}}:{}}}function tn(e){let t=[...e.mode==="picked"?e.objects??[]:[],...Array.isArray(e.customSettings)?e.customSettings:[]];return new Set(t.map(n=>n.toLowerCase()))}function nn(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}async function Rt(e,t,n,o,s,r){if(s.kind==="org")return{scope:{...o,objects:o.objects.map(f=>({...f,access:"org"}))},reads:Tt};let d=o.objects.map(({scoped:f})=>f.objectApiName),p={grants:s.objects,describes:o.objects.map(({describe:f})=>f),customSettings:o.objects.filter(({customSetting:f})=>f!==void 0).map(({scoped:f})=>f.objectApiName)},i=nt(d,p),c=[],l=0;if(i.length>0)try{let f=await se(e,t,i);c=[...f.describes.values()],l=Math.ceil(i.length/Re)+f.alone}catch(f){if(_(f,r))throw f}let u=ot(d,{...p,describes:[...p.describes,...c]}),h=tn(n),a=[],g=[...o.leftOut],w=[];for(let f of o.objects){let k=f.scoped.objectApiName,y=u.get(k);if(y!==void 0&&"access"in y){a.push({...f,access:y.access});continue}let m={objectApiName:k,reason:y?.reason??"noViewAll",...y?.detail!==void 0?{detail:y.detail}:{}};g.push(m),h.has(k.toLowerCase())&&n.unprovenLeftOut!==!0&&w.push(m)}let A=new Set(a.map(({scoped:f})=>f.objectApiName)),S={scope:{...o,objects:a,leftOut:g,addedToPicked:o.addedToPicked.filter(f=>A.has(f))},reads:{guard:s.requests,scope:l}};if(w.length>0){let f=w.length===1;return{...S,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, and the checkpoint can't hold ${nn(w.map(k=>k.objectApiName))}, asked for by name. ${w.map(k=>`${k.objectApiName}: ${bt(k).reason}`).join(" ")} Leave ${f?"it":"them"} out, or give the user View All Data and Modify All Data. ${W}`}}}return a.length===0&&o.objects.length>0?{...S,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, nor View All and Modify All on any object this checkpoint would hold: without them, a checkpoint holds only the objects its user sees and puts back whole. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. `+W}}:S}function on(e){return e.objects.map(({scoped:t,label:n,capture:o,records:s,customSetting:r,access:d})=>({objectApiName:t.objectApiName,label:n,...t.namespace!==void 0?{namespace:t.namespace}:{},records:s,undeletable:o.undeletable,leftOutFields:o.leftOutFields,...r!==void 0?{customSetting:r}:{},...d!==void 0?{access:d}:{}}))}function Nt(e){let t=e.customSettings;return t!==void 0&&(t==="all"||t.length>0)}async function sn(e,t,n,o,s){let r=new Map(o.objects.map(u=>[u.scoped.objectApiName,u])),d=n.settings.filter(({objectApiName:u})=>!r.has(u)),p=new Map;if(d.length>0)try{({describes:p}=await se(e,t,d.map(({objectApiName:u})=>u)))}catch(u){if(_(u,s))throw u}let i=d.filter(({objectApiName:u})=>p.has(u)),c=await ee(t,i.map(({objectApiName:u})=>({objectApiName:u,readMode:"query"})),s),l=new Map;return c.forEach((u,h)=>{"count"in u&&l.set(i[h].objectApiName,u.count)}),n.settings.map(({objectApiName:u,label:h})=>{let a=r.get(u);if(a?.customSetting!==void 0)return{objectApiName:u,label:h,kind:a.customSetting,records:a.records};let g=p.get(u),w=l.get(u);return{objectApiName:u,label:h,...g!==void 0?{kind:K(g)}:{},...w!==void 0?{records:w}:{}}})}var rn={records:0,apiRequests:0,apiRequestsLeft:0,seconds:0,bytes:0};async function Yn(e,t){let n={mode:t.mode,objects:[],leftOut:[],estimate:rn},o=await te(jt(e.org),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:Nt(t)},{userId:()=>e.org.userId()});if(!o.allowed)return{...n,refusal:o.refusal};let s=e.store.heldBy(o.org.id),r=s===void 0?await e.runWriting?.(o.org.id):void 0,d=X(e.org,e.signal);try{let p=await q(e.org,t.orgName),i=await Rt(e.org,d,t,await yt(e.org,d,t),o.grants,e.signal),{scope:c}=i,l=await e.org.serverTime(),u=await Ct(e.org,d,t,c,p,l,e.signal,i.reads),h={mode:t.mode,objects:on(u),leftOut:u.leftOut,estimate:u.estimate,files:{held:u.objects.some(({scoped:g})=>M(g.objectApiName)),queryAllFiles:o.queryAllFiles,addedToPicked:c.addedToPicked},customSettings:await sn(e.org,d,c,u,e.signal)},a=s!==void 0?kt(t.orgName,s):r!==void 0?{code:"RUN_WRITING",message:r}:i.refusal??u.refusal;return a===void 0?h:{...h,refusal:a}}catch(p){throw _(p,e.signal)?new D:p}}function an(e){let t=e.requestsSent?()=>e.requestsSent?.()??0:void 0,n={guard:0,scope:0,start:0,counts:0,bin:0,snapshot:0,stability:0},o="guard",s=t?.()??0,r=()=>{if(!t)return;let d=t();n[o]+=d-s,s=d};return{enter(d){r(),o=d},requests(){return t?(r(),{total:Object.values(n).reduce((p,i)=>p+i,0),byPhase:{...n}}):void 0}}}async function cn(e,t){if(t.edition!==void 0)return t.edition;let o=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;if(typeof o!="string"||o==="")throw new Error("The org did not say its edition (Organization.OrganizationType).");return o}var dn="Automated Process";async function ln(e){let n=(await e.query("SELECT Id, Name FROM User WHERE UserType = 'AutomatedProcess'")).records.filter(s=>typeof s.Id=="string"),o=n.find(s=>s.Name===dn);return o!==void 0?o.Id:n.length===1?n[0].Id:void 0}function Dt(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function mt(e,t){return e.split(he).join(Dt(t))}function ne(e){let t=Se(e);return t===null?Number.NaN:Date.parse(t)}function Mt(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}async function un(e,t){let n=new Set;for await(let o of x(Y(e,t))){let s=Mt(o.Id);s!==void 0&&n.add(s)}return n}async function pn(e,t,n,o,s,r){let d={changed:0,deleted:0,created:0};if(!o.live&&!o.deleted)return d;let p=await xe.read(e,t,n);if(o.live)for await(let i of x(o.live.file)){let c=ne(i.SystemModstamp);if(!(c<=r))continue;let l=p.stampOf(i.Id);l===void 0?d.created++:l!==c&&d.changed++}if(o.deleted){let i;for await(let c of x(o.deleted.file)){if(!(ne(c.SystemModstamp)<=r))continue;if(p.has(c.Id)){d.deleted++;continue}if(!(ne(c.CreatedDate)<s))continue;i??=await un(e,n);let l=Mt(c.Id);l!==void 0&&!i.has(l)&&d.deleted++}}return d}async function Pt(e){let t=0;for(let n of await It(e,{withFileTypes:!0})){let o=oe(e,n.name);n.isDirectory()?t+=await Pt(o):n.isFile()&&(t+=(await ht(o)).size)}return t}async function fn(e,t){let n=await Pt(e.dir)-(await ht(e.checkpointFile)).size,o=r=>Buffer.byteLength(`${JSON.stringify({...t,bytes:r},null,2)}
8
8
  `,"utf8"),s=n+o(n);return s=n+o(s),s}function mn(e){let t=e.snapshotsFile,n=new Ue({getData:()=>xt(t)?JSON.parse(Bt(t,"utf8")):{},setData:o=>Wt(t,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})});return n.initialize(),n}var gn=V({organizationId:pe().optional()}).loose();async function hn(e,t,n,o,s){let r=mn(e),d=0,p={log:n.handler.log,orgManager:n.handler.orgManager,orgRegistry:n.handler.orgRegistry,configStore:r,broker:{postToWebview:c=>{if(c.type!=="operation:progress")return;let l=c.payload;typeof l.percentage=="number"&&typeof l.currentStep=="string"&&s(l.percentage,l.currentStep)}},services:{getSandforgeSetting:(c,l)=>c==="backup.maxRecordsPerObject"?o:l},nextId:()=>`${e.checkpointId}-${++d}`},i=new Ge(p);return i.setBackupRecordStore(new Ve(t)),await i.swept(),{handler:i,config:r}}function bn(e,t){return e.slice(0,15)===t.slice(0,15)}async function qn(e,t){let{org:n,store:o,signal:s}=e,r=e.now??(()=>new Date),d=me.parse([...t.ignoredFields??[]]),p=t.name===void 0?void 0:$.parse(t.name),i=t.nameWithDate;i!==void 0&&$.parse(mt(i,r().toISOString()));let c=t.customSettings==="all"?[]:t.customSettings??[];for(let y of[...t.objects??[],...t.excluded??[],...c])F(y);let l=t.beforeRun===void 0?void 0:ge.parse(t.beforeRun),u=t.keepDays??Me;I(r(),u);let h=(y,m,C=0,R=0)=>e.onProgress?.({percentage:Math.round(y),processedObjects:C,totalObjects:R,step:m});h(0,`Checking ${t.orgName}`);let a=an(n),g=await te(jt(n),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:Nt(t)},{userId:()=>n.userId()});if(!g.allowed)return{taken:!1,refusal:g.refusal};let w=g.org.id,A=ve("ck",r()),S=o.lock(w,"take",A);if("busy"in S)return{taken:!1,refusal:kt(t.orgName,S.busy)};let f,k;try{let y=await e.runWriting?.(w);if(y!==void 0)return{taken:!1,refusal:{code:"RUN_WRITING",message:y}};let m=X(n,s),C=await cn(n,g.org),R=await q(n,t.orgName);h(2,`Reading the objects of ${t.orgName}`),a.enter("scope");let b=await Rt(n,m,t,await yt(n,m,t),g.grants,s);if(b.refusal!==void 0)return{taken:!1,refusal:b.refusal};let{scope:O}=b;a.enter("start");let P=await n.userId(),ie=await ln(n),N=await n.serverTime();h(8,`Counting the records of ${O.objects.length} objects`),a.enter("counts");let T=await Ct(n,m,t,O,R,N,s,b.reads);if(T.refusal!==void 0)return{taken:!1,refusal:T.refusal};if(T.objects.length===0)throw new Error(`None of the objects asked for can be kept in a checkpoint of ${t.orgName}: ${T.leftOut.map(j=>`${j.objectApiName}: ${j.reason}`).join(" ")||"there are none."}`);if(s?.aborted)throw new D;f=await o.create(w,A);let E=`snapshot-${A}`;k={version:1,checkpointId:A,name:p??(i!==void 0?$.parse(mt(i,N)):Dt(N)),org:{organizationId:w,...t.alias!==void 0?{alias:t.alias}:{},username:t.username,instanceUrl:t.instanceUrl,isSandbox:g.org.sandbox,organizationType:C,tier:g.tier,...t.scratchExpiresAt!==void 0?{scratchExpiresAt:t.scratchExpiresAt}:{},...R.dataStorageMaxMB!==void 0?{dataStorageMaxMB:R.dataStorageMaxMB}:{},...t.registered?.staging===!0&&g.org.sandbox?{staging:!0}:{}},takenBy:{userId:P,...ie!==void 0?{automatedProcessUserId:ie}:{},viewAllData:g.grants.kind==="org"||g.grants.viewAllData,modifyAllData:g.grants.kind==="org"||g.grants.modifyAllData,queryAllFiles:g.queryAllFiles},readFrom:N,takenAt:N,scope:{mode:t.mode,leftOut:T.leftOut},objects:[],ignoredFields:d,snapshotId:E,movedWhileTaken:{changed:0,deleted:0,created:0},bytes:0,expiresAt:I(r(),u),status:"taking",takenOn:{host:_t(),pid:process.pid},...l!==void 0?{beforeRun:l}:{}},await o.write(k),h(12,"Reading the recycle bin as it was at the checkpoint"),a.enter("bin");let vt=await qe(m,T.objects.map(({scoped:j})=>({...Xe(j.objectApiName,N),file:Y(f,j.objectApiName)})),s),re=new Map;for(let j of vt){if(!j.read)throw new Error(`The recycle bin of ${j.objectApiName} could not be read whole: ${j.reason}`);re.set(j.objectApiName,j.rows)}a.enter("snapshot");let{records:Et,files:ae}=await kn(f,E,T,t,e,w,m,h);h(88,`Reading the record types, users and queues ${t.orgName} names`);let $t=await wn(f,E,T,m,w,s);h(89,"Reading the time on the org"),a.enter("stability");let ce=await n.serverTime();h(90,`Checking what changed in ${t.orgName} while it was read`);let{movedWhileTaken:Ft,notChecked:Lt}=await yn(f,E,T,m,N,ce,s),{prints:de}=T;await o.writeFingerprints(f,de);let G=T.objects.map(j=>{let z=j.scoped.objectApiName;return St(j,Et.get(z)??0,re.get(z)??0,de[z].digest)});if(s?.aborted)throw new D;let le={...k,takenAt:ce,objects:G,movedWhileTaken:Ft,bytes:0,expiresAt:I(r(),u),status:"ready",...ae!==void 0?{files:ae}:{},replayAnnex:$t},U={...le,bytes:await fn(f,le)};await o.write(U),h(100,`Checkpoint '${U.name}' taken`,G.length,G.length);let ue=a.requests();return{taken:!0,checkpoint:U,notChecked:Lt,...ue!==void 0?{requests:ue}:{},estimate:T.estimate}}catch(y){throw f!==void 0&&await An(o,f,k,e),_(y,s)?new D:y}finally{S.lock.release()}}async function kn(e,t,n,o,s,r,d,p){let i=n.objects.filter(a=>a.records>0),c=new Map,l=(s.snapshotFiles??Vt)(e.dir);if(i.length>0){let a=Math.max(Ut,n.objectLimit),{handler:g,config:w}=await hn(e,l,s,a,(k,y)=>p(15+k*.65,y)),A=await g.backupForPipeline({operationId:t,orgId:o.orgId,objects:i.map(({scoped:k})=>k.objectApiName),fields:new Map(i.map(({scoped:k,capture:y})=>[k.objectApiName,y.fields])),scanAll:i.filter(({capture:k})=>k.readMode==="scanAllLive").map(({scoped:k})=>k.objectApiName),origin:"checkpoint",failWhenTruncated:!0,onConnection:k=>s.org.countAlso?.(k)},s.signal),S=gn.safeParse(w.get(`backup:${t}`)),f=S.success?S.data.organizationId:void 0;if(f===void 0||!bn(f,r))throw new Error(`The snapshot was read from ${f===void 0?"an org that did not say which it is":`another org (${f})`}, not from ${o.orgName}: it is not kept.`);for(let k of A.objects)c.set(k.objectApiName,k.recordCount)}p(82,"Indexing the snapshot",0,n.objects.length);for(let[a,{scoped:g}]of n.objects.entries()){let w=g.objectApiName,A=c.get(w)??0;c.has(w)||(await Pe(oe(e.dir,"backups")),await l.writeFile(Le(e,t,w),""),c.set(w,0));let S=await Ie(e,t,w);if(S.rows!==A)throw new Ee("damaged",`The snapshot of ${w} holds ${S.rows} records where its read kept ${A}: it is not kept.`);p(82+6*(a+1)/n.objects.length,`Indexed ${w}`,a+1,n.objects.length)}let u=n.objects.find(({scoped:a})=>M(a.objectApiName));if(u===void 0||n.linkable===void 0)return{records:c};p(88,"Reading the links of files to the records read");let h=await tt({reader:d,folder:e,snapshotId:t,linked:n.objects.map(({scoped:a})=>a.objectApiName).filter(a=>(c.get(a)??0)>0&&At(a,n.linkable)),documentsInSnapshot:(c.get(u.scoped.objectApiName)??0)>0,...s.signal!==void 0?{signal:s.signal}:{}});return{records:c,files:h}}async function wn(e,t,n,o,s,r){let d=await it(e,t,n.objects.map(({scoped:i,describe:c,capture:l})=>({objectApiName:i.objectApiName,userLookups:st(c,l.fields)}))),p=await dt({reader:o,organizationId:s,users:d,...Ot(n.objects),...r!==void 0?{signal:r}:{}});return lt(e,p)}async function yn(e,t,n,o,s,r,d){let p=oe(e.dir,zt),i={changed:0,deleted:0,created:0},c=[];try{let l=await Ze(o,n.objects.map(({capture:a})=>({objectApiName:a.objectApiName,readMode:a.readMode,held:!1})),s,p,d),u=Date.parse(Z(s)),h=Date.parse(r);for(let a of l){if("unread"in a){c.push({objectApiName:a.objectApiName,reason:a.unread});continue}if(!a.moved)continue;let g=await pn(e,t,a.objectApiName,a,u,h);i.changed+=g.changed,i.deleted+=g.deleted,i.created+=g.created}}finally{await gt(p,{recursive:!0,force:!0})}return{movedWhileTaken:i,notChecked:c}}async function An(e,t,n,o){try{n!==void 0&&await e.write({...n,status:"failed"})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: not marked failed: ${v(s)}`)}try{await gt(t.dir,{recursive:!0,force:!0})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: what its take wrote was not removed: ${v(s)}`)}}export{Gt as a,B as b,Xn as c,D as d,Kt as e,Jt as f,Yn as g,qn as h};
@@ -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{a,b,c}from"./chunk-3OVTKRS4.mjs";import"./chunk-BH76USTQ.mjs";import"./chunk-XKFHTBAB.mjs";import"./chunk-FYWNSMOZ.mjs";import"./chunk-WBELLGNE.mjs";import"./chunk-OS5GE52G.mjs";import"./chunk-BPHTA6KP.mjs";import"./chunk-U2CTKIPE.mjs";import"./chunk-NDFFIJL5.mjs";import"./chunk-I5C4O3VA.mjs";import"./chunk-RVCPQVKM.mjs";import"./chunk-ALBY5SOH.mjs";import"./chunk-FKCIGJOI.mjs";import"./chunk-C6RKM4BB.mjs";import"./chunk-IHGYJZZ2.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import"./chunk-AXFD2OH6.mjs";import"./chunk-X2XZQ434.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-O7GCCRPW.mjs";import"./chunk-4X5D3MSV.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-XMQ5R6TC.mjs";import"./chunk-IXIY6Q4M.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-QIRO4HTE.mjs";import"./chunk-BT43WSOS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-EOQON3E5.mjs";import"./chunk-Y7YUNRKK.mjs";import"./chunk-4JKR4PTZ.mjs";import"./chunk-N2HYG3BL.mjs";import"./chunk-7WSQ65WG.mjs";import"./chunk-MJD6CPZZ.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-OUU47Y7A.mjs";import"./chunk-4GCYGQXD.mjs";import"./chunk-WXU6ZJIV.mjs";import"./chunk-R3OM3X4L.mjs";import"./chunk-77IVKH7R.mjs";import"./chunk-2WMKJVD2.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-VXZ5PTOM.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-ZOSESZ22.mjs";import"./chunk-ZXOUWHYE.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-Z3MGN42K.mjs";import"./chunk-2GSMHGIV.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ISOSTAJR.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-7BQMBXKX.mjs";import"./chunk-KWAVSZ2B.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{b as UNDO_AUTOMATION_LIFTED_BY,a as UndoStopped,c as undoCheckpoint};
@@ -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-NWOI25WY.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-ZQO5PDX5.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-FVLFO2S6.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-6QSHWIZI.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{f as $}from"./chunk-ZUOPC4W2.mjs";import{a as F}from"./chunk-PPGDAUEQ.mjs";import{a as N}from"./chunk-4TLYUZD5.mjs";import{b as O}from"./chunk-CA5NAXSU.mjs";import{Qc as k,k as M}from"./chunk-ZQO5PDX5.mjs";var x=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,r){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=r?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=r?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,r,n){let s=this.connections.get(t);if(s&&s.active)return s.lastUsedAt=Date.now(),s.accessToken=n,s;this.connections.size>=this.config.maxConnections&&this.evictOldest();let i={orgId:t,instanceUrl:r,accessToken:n,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,i),i}release(t){let r=this.connections.get(t);r&&(r.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,r){if(!Number.isFinite(r)||r<0)return;let n=this.latencySamples.get(t);n||(n=[],this.latencySamples.set(t,n)),n.push(r),n.length>1e3&&n.splice(0,n.length-1e3)}getLatencyMetrics(t){let r=this.latencySamples.get(t);if(!r||r.length===0)return;let n=[...r].sort((a,c)=>a-c),s=n.reduce((a,c)=>a+c,0),i=Math.floor(n.length*.95),u=Math.floor(n.length*.99);return{min:n[0],max:n[n.length-1],avg:Math.round(s/n.length),p95:n[Math.min(i,n.length-1)],p99:n[Math.min(u,n.length-1)],sampleCount:n.length}}getAllLatencyMetrics(){let t=new Map;for(let r of this.latencySamples.keys()){let n=this.getLatencyMetrics(r);n&&t.set(r,n)}return t}cleanupIdle(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(n),r++);return r}recycleStale(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.createdAt>this.recycleIntervalMs&&(s.active=!1,this.connections.delete(n),r++);return r}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,r=1/0;for(let[n,s]of this.connections)s.lastUsedAt<r&&(r=s.lastUsedAt,t=n);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var S=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 B=0;function we(){return B}async function I(e,t){let r=$(e);try{return await t()}finally{B+=r()}}var C=class extends Error{constructor(r,n,s){super(`${r}: ${s}`);this.code=r;this.orgId=n;this.name="OrgConnectionError"}code;orgId};import{homedir as ee,userInfo as te}from"node:os";var ne=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],V=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function X(e){return ne.some(t=>t.test(e))}function P(e=process.env){let t={};for(let[r,n]of Object.entries(e))X(r)||(t[r]=n);return t.NO_COLOR="1",t}function Ee(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),r=V.filter(c=>t.some(d=>d.toUpperCase()===c)),n=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),s=t.filter(c=>X(c)),i=s.filter(c=>c.startsWith("ELECTRON_")).sort(),u=s.length-i.length,a=s.length===0?"none":[...i,...u>0?[`${u} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${r.length>0?r.join(", "):"none of "+V.join(", ")}; SF_/SFDX_: ${n.length>0?n.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${a}`}function re(){try{return te().username}catch{return process.env.USERNAME??process.env.USER??""}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,t=ee(),r=re()){let n=e;return t.length>3&&(n=n.replace(new RegExp(H(t),"gi"),"~")),r.length>=2&&(n=n.replace(new RegExp(`(?<=[\\\\/])${H(r)}(?=[\\\\/]|$)`,"gim"),"<user>")),n.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function ve(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function se(e,t){if(process.platform!=="win32")return e[0];let n=(Object.entries(t).find(([s])=>s.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);return e.find(s=>{let i=s.lastIndexOf(".");return i>Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))&&n.includes(s.slice(i).toLowerCase())})}async function Oe(e=1e4){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=process.platform==="win32"?"where sf node":"which -a sf node",s=P(),i,u;try{let l=await r(t)(n,{timeout:e,windowsHide:!0,env:s});i=String(l.stdout)}catch(l){let o=l;i=String(o.stdout??""),i.trim()===""&&(u=j(o.message??String(l)))}let a=i.split(/\r?\n/).map(l=>l.trim()).filter(l=>l.length>0).map(l=>j(l)),c=l=>a.filter(o=>new RegExp(`(^|[\\\\/])${l}(\\.[A-Za-z0-9]+)?$`,"i").test(o)),d=c("sf"),p=se(d,s);return{sf:d,node:c("node"),...p!==void 0?{runs:p}:{},...u?{failure:u}:{}}}function R(e,t){let r=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return r===""?void 0:r}function ie(e,t){if(t===void 0)return!1;let r=e.hostname.toLowerCase(),n=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(s=>s!=="").some(s=>{if(s==="*")return!0;let[,i="",u]=/^(.*?)(?::(\d+))?$/.exec(s.toLowerCase())??[];if(u!==void 0&&u!==n)return!1;let a=i.replace(/^\*?\.?/,"");return a!==""&&(r===a||r.endsWith(`.${a}`))})}function G(e,t=process.env){let r;try{r=new URL(e)}catch{return}let n=r.protocol==="https:"?R(t,"https_proxy")??R(t,"http_proxy"):R(t,"http_proxy");if(n!==void 0)return ie(r,R(t,"no_proxy"))?void 0:n}var oe="https://login.salesforce.com";async function v(e,t=process.env){let{jsforce:r,HttpProxyTransport:n}=await import("./chunk-L5FGY6YA.mjs"),s=G(e.instanceUrl??e.loginUrl??oe,t),i=new r.Connection({...e,...s!==void 0?{httpProxy:s}:{}});return s===void 0&&(i._transport=new n("")),i}var ae=10*1024*1024,L=3e4,q=L+2e3,A=`sf did not answer within ${L/1e3} s \u2014 check the Salesforce CLI`;function J(e){return e instanceof Error&&e.message===A}var D=2e4;function U(e,t,r){let n,s=new Promise((i,u)=>{n=setTimeout(()=>u(new Error(r)),t)});return Promise.race([e,s]).finally(()=>clearTimeout(n))}var E=new x,ce=300*1e3,_=new Map,le={failureThreshold:3,resetTimeout:3e4},z=new Map;function Ne(){return E}function ue(e){let t=z.get(e);return t||(t=new S({...le}),z.set(e,t)),t}var Y;var b="panel";function Be(e){b=e}function fe(e,t=b){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 sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function W(e=b){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function K(e,t){let r=t?.organization_id;if(!(!Y||typeof r!="string"))try{Y(e,{organizationId:r})}catch(n){N.warn("Identity observer threw",{orgId:e,error:O(n)})}}var de="[REDACTED]";function Z(e){return typeof e=="string"&&e.length>0&&!e.startsWith(de)&&!/\s/.test(e)}async function pe(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:r}=await import("child_process"),{promisify:n}=await import("util"),s={maxBuffer:ae,timeout:L,windowsHide:!0,env:P()},i=o=>U(n(t)("sf",o,s),q,A),u=o=>{let f=!1,h,y=new Promise((T,m)=>{h=r(o,s,(g,w)=>{f=!0,g?m(g):T({stdout:w})})});return U(y,q,A).catch(T=>{throw!f&&h?.pid!==void 0&&t("taskkill",["/pid",String(h.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},a=(o,f)=>process.platform==="win32"?u(o):i(f),c=(o,f)=>{let h=o.replace(/\[[0-9;]*m/g,""),y=h.search(/[{[]/);if(y===-1)throw new Error(`Failed to parse "${f}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(h.slice(y)).result??{}},d;try{let{stdout:o}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),f=c(o,"sf org display");d=typeof f.instanceUrl=="string"?f.instanceUrl:void 0}catch(o){if(J(o))throw o;d=void 0}try{let{stdout:o}=await a(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),f=c(o,"sf org auth show-access-token");if(Z(f.accessToken))return{accessToken:f.accessToken,instanceUrl:d}}catch(o){if(J(o))throw o}let{stdout:p}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),l=c(p,"sf org display");if(!Z(l.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 l.instanceUrl=="string"&&(d=l.instanceUrl),{accessToken:l.accessToken,instanceUrl:d}}async function Ve(e,t){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function He(e){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function je(e,t,r){let n=e,s=r.getOrg(e);if(!s)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 "${s.alias}" (${e}). Reconnect the org.`);let u=s.metadata.apiVersion||M.DEFAULT_API_VERSION,a=E.get(n),c=Date.now()-(_.get(e)??0)<ce;if(a&&a.active&&a.accessToken===i.accessToken&&c)return a.lastUsedAt=Date.now(),v({instanceUrl:a.instanceUrl,accessToken:a.accessToken,version:u});let d=await v({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:u}),p=ue(e);if(!p.acquirePermit())throw new C("ORG_TEMPORARILY_UNREACHABLE",e,`"${s.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let l=Date.now(),o=`identity check did not answer within ${D/1e3} s`;try{let f=await I(d,()=>U(d.identity(),D,o)),h=Date.now()-l;return p.recordSuccess(),E.acquire(n,i.instanceUrl,i.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,f),d}catch(f){let h=Date.now()-l;if(E.remove(n),_.delete(e),F(f))try{let m=await pe(s.username),g=m.instanceUrl??i.instanceUrl;if(m.accessToken===i.accessToken&&g===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let w=await v({instanceUrl:g,accessToken:m.accessToken,version:u}),Q=await I(w,()=>U(w.identity(),D,o));return await t.saveOrg(s,{...i,accessToken:m.accessToken,instanceUrl:g}),p.recordSuccess(),E.acquire(n,g,m.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,Q),w}catch(m){p.recordFailure();let g=O(m);r.updateStatus(e,"expired");let w=k(s,new Date().toISOString().slice(0,10));throw w!==void 0?new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${w}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${g})`):new C("ORG_AUTH_EXPIRED",e,`The session with "${s.alias}" has expired and could not be renewed. ${fe(s.alias)} (cause: ${g})`)}p.recordFailure();let y=O(f),T=k(s,new Date().toISOString().slice(0,10));throw T!==void 0?(r.updateStatus(e,"expired"),new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${y})`)):new Error(`Connection failed for "${s.alias}": ${y}`)}finally{p.releasePermit()}}export{we as a,I as b,C as c,P as d,Ee as e,j as f,ve as g,Oe as h,G as i,v as j,U as k,Ne as l,Be as m,Z as n,pe as o,Ve as p,He as q,je as r};
7
+ import{f as $}from"./chunk-4GCYGQXD.mjs";import{a as F}from"./chunk-PPGDAUEQ.mjs";import{a as N}from"./chunk-4TLYUZD5.mjs";import{b as O}from"./chunk-CA5NAXSU.mjs";import{bd as k,k as M}from"./chunk-6QSHWIZI.mjs";var x=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,r){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=r?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=r?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,r,n){let s=this.connections.get(t);if(s&&s.active)return s.lastUsedAt=Date.now(),s.accessToken=n,s;this.connections.size>=this.config.maxConnections&&this.evictOldest();let i={orgId:t,instanceUrl:r,accessToken:n,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,i),i}release(t){let r=this.connections.get(t);r&&(r.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,r){if(!Number.isFinite(r)||r<0)return;let n=this.latencySamples.get(t);n||(n=[],this.latencySamples.set(t,n)),n.push(r),n.length>1e3&&n.splice(0,n.length-1e3)}getLatencyMetrics(t){let r=this.latencySamples.get(t);if(!r||r.length===0)return;let n=[...r].sort((a,c)=>a-c),s=n.reduce((a,c)=>a+c,0),i=Math.floor(n.length*.95),u=Math.floor(n.length*.99);return{min:n[0],max:n[n.length-1],avg:Math.round(s/n.length),p95:n[Math.min(i,n.length-1)],p99:n[Math.min(u,n.length-1)],sampleCount:n.length}}getAllLatencyMetrics(){let t=new Map;for(let r of this.latencySamples.keys()){let n=this.getLatencyMetrics(r);n&&t.set(r,n)}return t}cleanupIdle(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(n),r++);return r}recycleStale(){let t=Date.now(),r=0;for(let[n,s]of this.connections)t-s.createdAt>this.recycleIntervalMs&&(s.active=!1,this.connections.delete(n),r++);return r}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,r=1/0;for(let[n,s]of this.connections)s.lastUsedAt<r&&(r=s.lastUsedAt,t=n);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var S=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 B=0;function we(){return B}async function I(e,t){let r=$(e);try{return await t()}finally{B+=r()}}var C=class extends Error{constructor(r,n,s){super(`${r}: ${s}`);this.code=r;this.orgId=n;this.name="OrgConnectionError"}code;orgId};import{homedir as ee,userInfo as te}from"node:os";var ne=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],V=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function X(e){return ne.some(t=>t.test(e))}function P(e=process.env){let t={};for(let[r,n]of Object.entries(e))X(r)||(t[r]=n);return t.NO_COLOR="1",t}function Ee(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),r=V.filter(c=>t.some(d=>d.toUpperCase()===c)),n=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),s=t.filter(c=>X(c)),i=s.filter(c=>c.startsWith("ELECTRON_")).sort(),u=s.length-i.length,a=s.length===0?"none":[...i,...u>0?[`${u} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${r.length>0?r.join(", "):"none of "+V.join(", ")}; SF_/SFDX_: ${n.length>0?n.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${a}`}function re(){try{return te().username}catch{return process.env.USERNAME??process.env.USER??""}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,t=ee(),r=re()){let n=e;return t.length>3&&(n=n.replace(new RegExp(H(t),"gi"),"~")),r.length>=2&&(n=n.replace(new RegExp(`(?<=[\\\\/])${H(r)}(?=[\\\\/]|$)`,"gim"),"<user>")),n.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function ve(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function se(e,t){if(process.platform!=="win32")return e[0];let n=(Object.entries(t).find(([s])=>s.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);return e.find(s=>{let i=s.lastIndexOf(".");return i>Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))&&n.includes(s.slice(i).toLowerCase())})}async function Oe(e=1e4){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=process.platform==="win32"?"where sf node":"which -a sf node",s=P(),i,u;try{let l=await r(t)(n,{timeout:e,windowsHide:!0,env:s});i=String(l.stdout)}catch(l){let o=l;i=String(o.stdout??""),i.trim()===""&&(u=j(o.message??String(l)))}let a=i.split(/\r?\n/).map(l=>l.trim()).filter(l=>l.length>0).map(l=>j(l)),c=l=>a.filter(o=>new RegExp(`(^|[\\\\/])${l}(\\.[A-Za-z0-9]+)?$`,"i").test(o)),d=c("sf"),p=se(d,s);return{sf:d,node:c("node"),...p!==void 0?{runs:p}:{},...u?{failure:u}:{}}}function R(e,t){let r=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return r===""?void 0:r}function ie(e,t){if(t===void 0)return!1;let r=e.hostname.toLowerCase(),n=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(s=>s!=="").some(s=>{if(s==="*")return!0;let[,i="",u]=/^(.*?)(?::(\d+))?$/.exec(s.toLowerCase())??[];if(u!==void 0&&u!==n)return!1;let a=i.replace(/^\*?\.?/,"");return a!==""&&(r===a||r.endsWith(`.${a}`))})}function G(e,t=process.env){let r;try{r=new URL(e)}catch{return}let n=r.protocol==="https:"?R(t,"https_proxy")??R(t,"http_proxy"):R(t,"http_proxy");if(n!==void 0)return ie(r,R(t,"no_proxy"))?void 0:n}var oe="https://login.salesforce.com";async function v(e,t=process.env){let{jsforce:r,HttpProxyTransport:n}=await import("./chunk-L5FGY6YA.mjs"),s=G(e.instanceUrl??e.loginUrl??oe,t),i=new r.Connection({...e,...s!==void 0?{httpProxy:s}:{}});return s===void 0&&(i._transport=new n("")),i}var ae=10*1024*1024,L=3e4,q=L+2e3,A=`sf did not answer within ${L/1e3} s \u2014 check the Salesforce CLI`;function J(e){return e instanceof Error&&e.message===A}var D=2e4;function U(e,t,r){let n,s=new Promise((i,u)=>{n=setTimeout(()=>u(new Error(r)),t)});return Promise.race([e,s]).finally(()=>clearTimeout(n))}var E=new x,ce=300*1e3,_=new Map,le={failureThreshold:3,resetTimeout:3e4},z=new Map;function Ne(){return E}function ue(e){let t=z.get(e);return t||(t=new S({...le}),z.set(e,t)),t}var Y;var b="panel";function Be(e){b=e}function fe(e,t=b){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 sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function W(e=b){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function K(e,t){let r=t?.organization_id;if(!(!Y||typeof r!="string"))try{Y(e,{organizationId:r})}catch(n){N.warn("Identity observer threw",{orgId:e,error:O(n)})}}var de="[REDACTED]";function Z(e){return typeof e=="string"&&e.length>0&&!e.startsWith(de)&&!/\s/.test(e)}async function pe(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:r}=await import("child_process"),{promisify:n}=await import("util"),s={maxBuffer:ae,timeout:L,windowsHide:!0,env:P()},i=o=>U(n(t)("sf",o,s),q,A),u=o=>{let f=!1,h,y=new Promise((T,m)=>{h=r(o,s,(g,w)=>{f=!0,g?m(g):T({stdout:w})})});return U(y,q,A).catch(T=>{throw!f&&h?.pid!==void 0&&t("taskkill",["/pid",String(h.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},a=(o,f)=>process.platform==="win32"?u(o):i(f),c=(o,f)=>{let h=o.replace(/\[[0-9;]*m/g,""),y=h.search(/[{[]/);if(y===-1)throw new Error(`Failed to parse "${f}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(h.slice(y)).result??{}},d;try{let{stdout:o}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),f=c(o,"sf org display");d=typeof f.instanceUrl=="string"?f.instanceUrl:void 0}catch(o){if(J(o))throw o;d=void 0}try{let{stdout:o}=await a(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),f=c(o,"sf org auth show-access-token");if(Z(f.accessToken))return{accessToken:f.accessToken,instanceUrl:d}}catch(o){if(J(o))throw o}let{stdout:p}=await a(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),l=c(p,"sf org display");if(!Z(l.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 l.instanceUrl=="string"&&(d=l.instanceUrl),{accessToken:l.accessToken,instanceUrl:d}}async function Ve(e,t){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function He(e){return v({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function je(e,t,r){let n=e,s=r.getOrg(e);if(!s)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 "${s.alias}" (${e}). Reconnect the org.`);let u=s.metadata.apiVersion||M.DEFAULT_API_VERSION,a=E.get(n),c=Date.now()-(_.get(e)??0)<ce;if(a&&a.active&&a.accessToken===i.accessToken&&c)return a.lastUsedAt=Date.now(),v({instanceUrl:a.instanceUrl,accessToken:a.accessToken,version:u});let d=await v({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:u}),p=ue(e);if(!p.acquirePermit())throw new C("ORG_TEMPORARILY_UNREACHABLE",e,`"${s.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let l=Date.now(),o=`identity check did not answer within ${D/1e3} s`;try{let f=await I(d,()=>U(d.identity(),D,o)),h=Date.now()-l;return p.recordSuccess(),E.acquire(n,i.instanceUrl,i.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,f),d}catch(f){let h=Date.now()-l;if(E.remove(n),_.delete(e),F(f))try{let m=await pe(s.username),g=m.instanceUrl??i.instanceUrl;if(m.accessToken===i.accessToken&&g===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let w=await v({instanceUrl:g,accessToken:m.accessToken,version:u}),Q=await I(w,()=>U(w.identity(),D,o));return await t.saveOrg(s,{...i,accessToken:m.accessToken,instanceUrl:g}),p.recordSuccess(),E.acquire(n,g,m.accessToken),E.recordLatency(n,h),_.set(e,Date.now()),K(e,Q),w}catch(m){p.recordFailure();let g=O(m);r.updateStatus(e,"expired");let w=k(s,new Date().toISOString().slice(0,10));throw w!==void 0?new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${w}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${g})`):new C("ORG_AUTH_EXPIRED",e,`The session with "${s.alias}" has expired and could not be renewed. ${fe(s.alias)} (cause: ${g})`)}p.recordFailure();let y=O(f),T=k(s,new Date().toISOString().slice(0,10));throw T!==void 0?(r.updateStatus(e,"expired"),new C("SCRATCH_ORG_EXPIRED",e,`The scratch org "${s.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${W()} (cause: ${y})`)):new Error(`Connection failed for "${s.alias}": ${y}`)}finally{p.releasePermit()}}export{we as a,I as b,C as c,P as d,Ee as e,j as f,ve as g,Oe as h,G as i,v as j,U as k,Ne as l,Be as m,Z as n,pe as o,Ve as p,He as q,je as r};
@@ -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 T,b as F,d as B,k as R}from"./chunk-3XG25GTF.mjs";import{a as L,f as C,i as $,j as _}from"./chunk-54HYHHVL.mjs";import{b as j,l as x,o as N}from"./chunk-WSUKC2U3.mjs";import{a as I}from"./chunk-4TLYUZD5.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{dd as A}from"./chunk-ZQO5PDX5.mjs";var w=class{byObject=new Map;add(e){let t=this.byObject.get(e.objectApiName);t||(t=new Map,this.byObject.set(e.objectApiName,t));let s=t.get(e.recordId),r=s?.[e.fieldName];if(r!==void 0&&r!==e.value)return{taken:!1,kept:r};let n=s??{Id:e.recordId};return n[e.fieldName]=e.value,t.set(e.recordId,n),{taken:!0}}updates(){return[...this.byObject].map(([e,t])=>[e,[...t.values()]])}};var J="DUPLICATES_DETECTED",X=3,Y=2e3;function Z(i){return new Promise(e=>setTimeout(e,i))}function z(i){let e=i.errorDetails??[];return N(i.errors,e.length===i.errors.length?e:void 0)}function q(i){let e=i.errorDetails;return e?.length!==1||e[0].statusCode===J||z(i)}function Q(i){let e=Object.keys(i).find(s=>s!=="Id"),t=e===void 0?void 0:i[e];return typeof t=="string"?t:""}function U(i){return{objectApiName:i,op:"update"}}function V(i){let e=i.automation??"the target's automation";I.warn(`[forge] ${i.objectApiName}: ${e} hit ${i.limit??"a Salesforce limit"} on an update of ${i.from} records \u2014 sending a record on its own, then smaller calls.`)}function y(i){return Object.keys(i).filter(e=>e!=="Id").length}async function fe(i){if(!i.enabled||!i.updateRecords||i.pendingFkUpdates.length===0)return null;let e=new E(i);return await e.patch(i.pendingFkUpdates),e.finish()}var ee=1024,te=.6;function K(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function M(i){let e=2538058380;for(let t=0;t<i.length;t++)e=Math.imul(e^i.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var H=class{capacity=ee;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);firstPart=new Float64Array(this.capacity);several=new Uint8Array(this.capacity);note(e,t){let s=K(t),r=M(t),n=this.find(s,r);if(n>=0){this.firstPart[n]!==e+1&&(this.several[n]=1);return}this.used+1>this.capacity*te&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=s,this.h2[o]=r,this.firstPart[o]=e+1,this.used++}spans(e){let t=this.find(K(e),M(e));return t>=0&&this.several[t]===1}find(e,t){let s=this.capacity-1;for(let r=t&s;;r=r+1&s){if(this.firstPart[r]===0)return-1;if(this.h1[r]===e&&this.h2[r]===t)return r}}freeSlotFor(e){let t=this.capacity-1,s=e&t;for(;this.firstPart[s]!==0;)s=s+1&t;return s}grow(){let{h1:e,h2:t,firstPart:s,several:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.firstPart=new Float64Array(this.capacity),this.several=new Uint8Array(this.capacity);for(let n=0;n<s.length;n++){if(s[n]===0)continue;let o=this.freeSlotFor(t[n]);this.h1[o]=e[n],this.h2[o]=t[n],this.firstPart[o]=s[n],this.several[o]=r[n]}}},E=class{constructor(e){this.input=e;this.splits=e.splitting!==void 0,this.splitting=e.splitting??L(0),this.bulkUnsupported=e.bulkUnsupported??new Set}input;resolvedCount=0;unresolvedCount=0;insertOnlyLost=0;unresolved=[];pass2Failed=0;pass2Samples=[];notSent=0;notSentObjects=new Set;cancelled=!1;handed=0;held=new w;splitting;splits;bulkUnsupported;backoff=new x({initialDelay:Y});limitOf(e){return this.splits&&e&&!e.success?A(e.errors):void 0}async patch(e,t){let{input:s}=this;if(!s.enabled||!s.updateRecords||e.length===0)return;this.handed+=e.length;let r=new w;for(let n of e)this.take(n,t?.(n)===!0?this.held:r);await this.send(r)}async sendHeld(){await this.send(this.held)}take(e,t){let{input:s}=this,{remapper:r}=s,n=r.get(e.sourceRefId);if(!n){if(s.deferUnresolved){s.stillPending?.push(e);return}if(s.outsideTheSample?.(e)){s.onLeftOutsideTheSample?.(e.objectApiName,e.fieldName);return}this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}=<source ${e.sourceRefId}>`,messages:[`Cycle FK '${e.fieldName}' could not be resolved \u2014 referenced parent (source ${e.sourceRefId}) was not cloned`]});return}if(e.insertOnly){this.insertOnlyLost++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Lookup '${e.fieldName}' left empty: only an insert sets it, and the record it names (source ${e.sourceRefId}) was written after this one`]});return}let o=t.add({objectApiName:e.objectApiName,recordId:e.newId,fieldName:e.fieldName,value:n});if(!o.taken){this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Conflicting cycle FK update for ${e.fieldName}: ${String(o.kept)} vs ${n}`]});return}this.resolvedCount++}async send(e){for(let[t,s]of e.updates()){if(this.jobsFor(t,s.length)){await this.sendAsJobs(t,s);continue}await this.sendObject(t,s)}}jobsFor(e,t){let{input:s}=this;return s.bulkUpdate!==void 0&&t>=2e3&&s.restOnly?.has(e)!==!0&&!this.bulkUnsupported.has(e)}leaveNotSent(e,t){for(let s of t)this.notSent+=y(s);t.length>0&&this.notSentObjects.add(e)}async sendObject(e,t,s,r){let{input:n}=this,{targetOrgId:o}=n,d=n.updateRecords;if(!d||t.length===0)return;let c=()=>(this.cancelled||(this.cancelled=n.stopped?.()===!0),this.cancelled);if(c()){this.leaveNotSent(e,t);return}let l,a=await _(t,{key:U(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,maxSize:B.rest,...r,beforeEachSend:()=>c()?"stop":void 0,send:async p=>{try{return{answers:await d(o,e,[...p])}}catch(h){return l={error:h},{answers:[]}}},limited:p=>this.limitOf(p),settle:(p,h,k,S)=>{let v=l;l=void 0,v?this.callThrew(e,p,v.error):this.settleAnswers(e,p,h,k,S,s),n.onAnswered?.()},onFirstRefusal:V});a.stopped&&this.leaveNotSent(e,[...a.stopped.part,...a.stopped.rest])}settleAnswers(e,t,s,r,n,o){let{input:d}=this;for(let c=0;c<t.length;c++){if(r.has(c))continue;let l=s[c];l?l.success?d.onPatched?.(e,t[c]):o&&z(l)?o.push(t[c]):this.refused(e,t[c],l,n.get(c)):(this.pass2Failed+=y(t[c]),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t[c]),messages:[`No result returned for record (API truncated batch: ${s.length}/${t.length})`]}))}}refused(e,t,s,r){this.tellRefusedByFilter(e,t,s),this.pass2Failed+=y(t),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t),messages:r===void 0?s.errors:[...s.errors,C(r,$(this.splitting.allowance,U(e)),"run")]})}callThrew(e,t,s){for(let r of t)this.pass2Failed+=y(r);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e} batch failed`,messages:[P(s)]})}async sendAsJobs(e,t){let{input:s}=this,r=s.bulkUpdate;if(!r)return;let n=t.map((l,a)=>({record:l,at:a,value:Q(l)})).sort((l,a)=>l.value===a.value?l.at-a.at:l.value<a.value?-1:1).map(({record:l})=>l),o=U(e),{sizes:d,allowance:c}=this.splitting;for(let l=0;l<n.length;l+=F){let a=n.slice(l,l+F);if(this.cancelled||(this.cancelled=s.stopped?.()===!0),this.cancelled){this.leaveNotSent(e,a);continue}let p=d.of(o);if(p<200){let u=Math.ceil(a.length/p),f=c.take(o,u);d.countExtraCalls(o,f);let m=a.slice(0,f*p);try{await this.sendObject(e,m,void 0,{pricedAs:"job",paid:{calls:f}})}finally{f<u&&d.spend(o)}if(f===u)continue;if(a=a.slice(m.length),this.cancelled){this.leaveNotSent(e,a);continue}if(a.length<2e3){await this.sendObject(e,a);continue}}let h;try{h=await r(e,a)}catch(u){if(!(u instanceof T)){await this.sendObject(e,a);continue}for(let f of a)this.pass2Failed+=y(f);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e}: a Bulk API job of ${a.length} updates was lost`,messages:[P(u),"The target may hold any of these lookups: they are counted as left empty."]}),s.onAnswered?.();continue}if(h.aborted){this.cancelled=!0,this.leaveNotSent(e,a);continue}if(h.untouched){h.untouched.unsupported&&this.bulkUnsupported.add(e),await this.sendObject(e,a);continue}let k=[],S=[],v=[],b;a.forEach((u,f)=>{let m=h.rows[f]??"unprocessed",g=h.answers[f],O=m==="answered"?this.limitOf(g):void 0;O&&g?(b??=O,S.push(u),v.push(g)):m==="answered"&&g?.success?s.onPatched?.(e,u):m==="may-have-written"?(this.pass2Failed+=y(u),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(u),messages:["The Bulk API job may have written this update without saying so."]})):m!=="answered"||!g||q(g)?k.push(u):this.refused(e,u,g)}),s.onAnswered?.(),await this.sendAgainByRest(e,k),await this.sendObject(e,S,void 0,{refusedIn:{from:200,answers:v,...b?{cause:b}:{}}})}}async sendAgainByRest(e,t){let s=t;for(let r=0;s.length>0;r++){r>0&&await(this.input.wait??Z)(this.backoff.calculateDelay(r-1));let n=[];await this.sendObject(e,s,r<X-1?n:void 0),s=n}}tellRefusedByFilter(e,t,s){let r=this.input.onRefusedByFilter,n=t.Id;if(!r||typeof n!="string")return;let o=new Set((s.errorDetails??[]).filter(d=>d.statusCode===j).flatMap(d=>d.fields));for(let d of Object.keys(t))d!=="Id"&&o.has(d)&&r(e,d,n)}finish(){let{resolvedCount:e,unresolvedCount:t,insertOnlyLost:s,pass2Failed:r,notSent:n}=this;if(this.handed===0)return null;let o=e+t+s;if(this.input.deferUnresolved&&e===0&&r===0&&s===0)return null;let d=r+t+s+n;if(this.input.onProgress({objectName:"__pass2__",status:d>0?"error":"done",progress:100,message:`Pass 2 (cycle FK update): ${e-r-n}/${o} resolved`+(n>0?`; cancelled with ${n} not sent`:"")}),d>0){let c=n>0?[{recordSummary:`${[...this.notSentObjects].join(", ")}: ${n} lookup${n===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}]:[];return{objectApiName:"__pass2__",stage:"insert",failedCount:d,attemptedCount:o,samples:[...c,...this.pass2Samples,...this.unresolved].slice(0,3)}}return null}};export{w as a,fe as b,H as c,E as d};
7
+ import{a as T,b as F,d as B,k as R}from"./chunk-DSR2MSBH.mjs";import{a as L,f as C,i as $,j as _}from"./chunk-54HYHHVL.mjs";import{b as j,l as x,o as N}from"./chunk-YBZIDW6W.mjs";import{a as I}from"./chunk-4TLYUZD5.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{qd as A}from"./chunk-6QSHWIZI.mjs";var w=class{byObject=new Map;add(e){let t=this.byObject.get(e.objectApiName);t||(t=new Map,this.byObject.set(e.objectApiName,t));let s=t.get(e.recordId),r=s?.[e.fieldName];if(r!==void 0&&r!==e.value)return{taken:!1,kept:r};let n=s??{Id:e.recordId};return n[e.fieldName]=e.value,t.set(e.recordId,n),{taken:!0}}updates(){return[...this.byObject].map(([e,t])=>[e,[...t.values()]])}};var J="DUPLICATES_DETECTED",X=3,Y=2e3;function Z(i){return new Promise(e=>setTimeout(e,i))}function z(i){let e=i.errorDetails??[];return N(i.errors,e.length===i.errors.length?e:void 0)}function q(i){let e=i.errorDetails;return e?.length!==1||e[0].statusCode===J||z(i)}function Q(i){let e=Object.keys(i).find(s=>s!=="Id"),t=e===void 0?void 0:i[e];return typeof t=="string"?t:""}function U(i){return{objectApiName:i,op:"update"}}function V(i){let e=i.automation??"the target's automation";I.warn(`[forge] ${i.objectApiName}: ${e} hit ${i.limit??"a Salesforce limit"} on an update of ${i.from} records \u2014 sending a record on its own, then smaller calls.`)}function y(i){return Object.keys(i).filter(e=>e!=="Id").length}async function fe(i){if(!i.enabled||!i.updateRecords||i.pendingFkUpdates.length===0)return null;let e=new E(i);return await e.patch(i.pendingFkUpdates),e.finish()}var ee=1024,te=.6;function K(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function M(i){let e=2538058380;for(let t=0;t<i.length;t++)e=Math.imul(e^i.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var H=class{capacity=ee;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);firstPart=new Float64Array(this.capacity);several=new Uint8Array(this.capacity);note(e,t){let s=K(t),r=M(t),n=this.find(s,r);if(n>=0){this.firstPart[n]!==e+1&&(this.several[n]=1);return}this.used+1>this.capacity*te&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=s,this.h2[o]=r,this.firstPart[o]=e+1,this.used++}spans(e){let t=this.find(K(e),M(e));return t>=0&&this.several[t]===1}find(e,t){let s=this.capacity-1;for(let r=t&s;;r=r+1&s){if(this.firstPart[r]===0)return-1;if(this.h1[r]===e&&this.h2[r]===t)return r}}freeSlotFor(e){let t=this.capacity-1,s=e&t;for(;this.firstPart[s]!==0;)s=s+1&t;return s}grow(){let{h1:e,h2:t,firstPart:s,several:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.firstPart=new Float64Array(this.capacity),this.several=new Uint8Array(this.capacity);for(let n=0;n<s.length;n++){if(s[n]===0)continue;let o=this.freeSlotFor(t[n]);this.h1[o]=e[n],this.h2[o]=t[n],this.firstPart[o]=s[n],this.several[o]=r[n]}}},E=class{constructor(e){this.input=e;this.splits=e.splitting!==void 0,this.splitting=e.splitting??L(0),this.bulkUnsupported=e.bulkUnsupported??new Set}input;resolvedCount=0;unresolvedCount=0;insertOnlyLost=0;unresolved=[];pass2Failed=0;pass2Samples=[];notSent=0;notSentObjects=new Set;cancelled=!1;handed=0;held=new w;splitting;splits;bulkUnsupported;backoff=new x({initialDelay:Y});limitOf(e){return this.splits&&e&&!e.success?A(e.errors):void 0}async patch(e,t){let{input:s}=this;if(!s.enabled||!s.updateRecords||e.length===0)return;this.handed+=e.length;let r=new w;for(let n of e)this.take(n,t?.(n)===!0?this.held:r);await this.send(r)}async sendHeld(){await this.send(this.held)}take(e,t){let{input:s}=this,{remapper:r}=s,n=r.get(e.sourceRefId);if(!n){if(s.deferUnresolved){s.stillPending?.push(e);return}if(s.outsideTheSample?.(e)){s.onLeftOutsideTheSample?.(e.objectApiName,e.fieldName);return}this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}=<source ${e.sourceRefId}>`,messages:[`Cycle FK '${e.fieldName}' could not be resolved \u2014 referenced parent (source ${e.sourceRefId}) was not cloned`]});return}if(e.insertOnly){this.insertOnlyLost++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Lookup '${e.fieldName}' left empty: only an insert sets it, and the record it names (source ${e.sourceRefId}) was written after this one`]});return}let o=t.add({objectApiName:e.objectApiName,recordId:e.newId,fieldName:e.fieldName,value:n});if(!o.taken){this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Conflicting cycle FK update for ${e.fieldName}: ${String(o.kept)} vs ${n}`]});return}this.resolvedCount++}async send(e){for(let[t,s]of e.updates()){if(this.jobsFor(t,s.length)){await this.sendAsJobs(t,s);continue}await this.sendObject(t,s)}}jobsFor(e,t){let{input:s}=this;return s.bulkUpdate!==void 0&&t>=2e3&&s.restOnly?.has(e)!==!0&&!this.bulkUnsupported.has(e)}leaveNotSent(e,t){for(let s of t)this.notSent+=y(s);t.length>0&&this.notSentObjects.add(e)}async sendObject(e,t,s,r){let{input:n}=this,{targetOrgId:o}=n,d=n.updateRecords;if(!d||t.length===0)return;let c=()=>(this.cancelled||(this.cancelled=n.stopped?.()===!0),this.cancelled);if(c()){this.leaveNotSent(e,t);return}let l,a=await _(t,{key:U(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,maxSize:B.rest,...r,beforeEachSend:()=>c()?"stop":void 0,send:async p=>{try{return{answers:await d(o,e,[...p])}}catch(h){return l={error:h},{answers:[]}}},limited:p=>this.limitOf(p),settle:(p,h,k,S)=>{let v=l;l=void 0,v?this.callThrew(e,p,v.error):this.settleAnswers(e,p,h,k,S,s),n.onAnswered?.()},onFirstRefusal:V});a.stopped&&this.leaveNotSent(e,[...a.stopped.part,...a.stopped.rest])}settleAnswers(e,t,s,r,n,o){let{input:d}=this;for(let c=0;c<t.length;c++){if(r.has(c))continue;let l=s[c];l?l.success?d.onPatched?.(e,t[c]):o&&z(l)?o.push(t[c]):this.refused(e,t[c],l,n.get(c)):(this.pass2Failed+=y(t[c]),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t[c]),messages:[`No result returned for record (API truncated batch: ${s.length}/${t.length})`]}))}}refused(e,t,s,r){this.tellRefusedByFilter(e,t,s),this.pass2Failed+=y(t),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t),messages:r===void 0?s.errors:[...s.errors,C(r,$(this.splitting.allowance,U(e)),"run")]})}callThrew(e,t,s){for(let r of t)this.pass2Failed+=y(r);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e} batch failed`,messages:[P(s)]})}async sendAsJobs(e,t){let{input:s}=this,r=s.bulkUpdate;if(!r)return;let n=t.map((l,a)=>({record:l,at:a,value:Q(l)})).sort((l,a)=>l.value===a.value?l.at-a.at:l.value<a.value?-1:1).map(({record:l})=>l),o=U(e),{sizes:d,allowance:c}=this.splitting;for(let l=0;l<n.length;l+=F){let a=n.slice(l,l+F);if(this.cancelled||(this.cancelled=s.stopped?.()===!0),this.cancelled){this.leaveNotSent(e,a);continue}let p=d.of(o);if(p<200){let u=Math.ceil(a.length/p),f=c.take(o,u);d.countExtraCalls(o,f);let m=a.slice(0,f*p);try{await this.sendObject(e,m,void 0,{pricedAs:"job",paid:{calls:f}})}finally{f<u&&d.spend(o)}if(f===u)continue;if(a=a.slice(m.length),this.cancelled){this.leaveNotSent(e,a);continue}if(a.length<2e3){await this.sendObject(e,a);continue}}let h;try{h=await r(e,a)}catch(u){if(!(u instanceof T)){await this.sendObject(e,a);continue}for(let f of a)this.pass2Failed+=y(f);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e}: a Bulk API job of ${a.length} updates was lost`,messages:[P(u),"The target may hold any of these lookups: they are counted as left empty."]}),s.onAnswered?.();continue}if(h.aborted){this.cancelled=!0,this.leaveNotSent(e,a);continue}if(h.untouched){h.untouched.unsupported&&this.bulkUnsupported.add(e),await this.sendObject(e,a);continue}let k=[],S=[],v=[],b;a.forEach((u,f)=>{let m=h.rows[f]??"unprocessed",g=h.answers[f],O=m==="answered"?this.limitOf(g):void 0;O&&g?(b??=O,S.push(u),v.push(g)):m==="answered"&&g?.success?s.onPatched?.(e,u):m==="may-have-written"?(this.pass2Failed+=y(u),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(u),messages:["The Bulk API job may have written this update without saying so."]})):m!=="answered"||!g||q(g)?k.push(u):this.refused(e,u,g)}),s.onAnswered?.(),await this.sendAgainByRest(e,k),await this.sendObject(e,S,void 0,{refusedIn:{from:200,answers:v,...b?{cause:b}:{}}})}}async sendAgainByRest(e,t){let s=t;for(let r=0;s.length>0;r++){r>0&&await(this.input.wait??Z)(this.backoff.calculateDelay(r-1));let n=[];await this.sendObject(e,s,r<X-1?n:void 0),s=n}}tellRefusedByFilter(e,t,s){let r=this.input.onRefusedByFilter,n=t.Id;if(!r||typeof n!="string")return;let o=new Set((s.errorDetails??[]).filter(d=>d.statusCode===j).flatMap(d=>d.fields));for(let d of Object.keys(t))d!=="Id"&&o.has(d)&&r(e,d,n)}finish(){let{resolvedCount:e,unresolvedCount:t,insertOnlyLost:s,pass2Failed:r,notSent:n}=this;if(this.handed===0)return null;let o=e+t+s;if(this.input.deferUnresolved&&e===0&&r===0&&s===0)return null;let d=r+t+s+n;if(this.input.onProgress({objectName:"__pass2__",status:d>0?"error":"done",progress:100,message:`Pass 2 (cycle FK update): ${e-r-n}/${o} resolved`+(n>0?`; cancelled with ${n} not sent`:"")}),d>0){let c=n>0?[{recordSummary:`${[...this.notSentObjects].join(", ")}: ${n} lookup${n===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}]:[];return{objectApiName:"__pass2__",stage:"insert",failedCount:d,attemptedCount:o,samples:[...c,...this.pass2Samples,...this.unresolved].slice(0,3)}}return null}};export{w as a,fe as b,H as c,E as d};
@@ -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{jd as u}from"./chunk-ZQO5PDX5.mjs";var m={BusinessHours:["Name"]},j=["DUPLICATE_VALUE","DUPLICATES_DETECTED","duplicate value found"];var A=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,P=/^[A-Za-z][A-Za-z0-9_]*$/;function l(e){return e.slice(0,15)}function g(e,r){let t=e.mapping.get(r);return typeof t=="string"&&A.test(t)?t:void 0}function f(e){let r=new Set((e.created??[]).flatMap(i=>i.referenceIds)),t=new Set;for(let i of e.mapping.keys()){if(r.has(i))continue;let n=g(e,i);n&&t.add(l(n))}return t}function h(e){let r=new Set((e.created??[]).flatMap(n=>n.referenceIds)),t=[...Object.entries(e.personContacts??{}),...Object.entries(e.withTheirRecord??{})];for(let n=!0;n;){n=!1;for(let[o,s]of t)r.has(o)||!r.has(s)||(r.add(o),n=!0)}let i=new Set;for(let[n]of t){let o=r.has(n)?g(e,n):void 0;o&&i.add(l(o))}return i}function b(e){let r=f(e),t=new Map;for(let{objectApiName:o,referenceIds:s}of e.created??[])P.test(o)&&t.set(o,[...t.get(o)??[],...s]);let i=new Set,n=[];for(let[o,s]of[...t].reverse()){let a=[];for(let y of[...s].reverse()){let c=g(e,y);if(!c)continue;let d=l(c);r.has(d)||i.has(d)||(i.add(d),a.push(c))}a.length>0&&n.push({objectApiName:o,ids:a})}return n}function p(e){return u(e.removal)?[]:b(e).filter(r=>!R(r.objectApiName))}function R(e){return Object.prototype.hasOwnProperty.call(m,e)}function k(e){return b(e).filter(r=>R(r.objectApiName)).map(({objectApiName:r,ids:t})=>({objectApiName:r,count:t.length}))}function I(e){return e.find(r=>p(r).length>0)??e[0]}function O(e,r){return e.filter(t=>t.endedAt!==r.endedAt&&t.created!==void 0&&p(t).length===0)}function v(e){let r=e.created!==void 0,t=h(e),i=[...f(e)].filter(o=>!t.has(o)),n=k(e);return{orgId:e.orgId,loadedAt:e.endedAt,created:p(e).map(({objectApiName:o,ids:s})=>({objectApiName:o,count:s.length})),linked:r?i.length:0,recorded:r,...e.removal?{removed:e.removal}:{},...e.earlier?{earlier:!0}:{},...n.length>0?{keptByThePlatform:n}:{}}}export{m as a,j as b,b as c,p as d,k as e,I as f,O as g,v as h};
7
+ import{wd as u}from"./chunk-6QSHWIZI.mjs";var m={BusinessHours:["Name"]},j=["DUPLICATE_VALUE","DUPLICATES_DETECTED","duplicate value found"];var A=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,P=/^[A-Za-z][A-Za-z0-9_]*$/;function l(e){return e.slice(0,15)}function g(e,r){let t=e.mapping.get(r);return typeof t=="string"&&A.test(t)?t:void 0}function f(e){let r=new Set((e.created??[]).flatMap(i=>i.referenceIds)),t=new Set;for(let i of e.mapping.keys()){if(r.has(i))continue;let n=g(e,i);n&&t.add(l(n))}return t}function h(e){let r=new Set((e.created??[]).flatMap(n=>n.referenceIds)),t=[...Object.entries(e.personContacts??{}),...Object.entries(e.withTheirRecord??{})];for(let n=!0;n;){n=!1;for(let[o,s]of t)r.has(o)||!r.has(s)||(r.add(o),n=!0)}let i=new Set;for(let[n]of t){let o=r.has(n)?g(e,n):void 0;o&&i.add(l(o))}return i}function b(e){let r=f(e),t=new Map;for(let{objectApiName:o,referenceIds:s}of e.created??[])P.test(o)&&t.set(o,[...t.get(o)??[],...s]);let i=new Set,n=[];for(let[o,s]of[...t].reverse()){let a=[];for(let y of[...s].reverse()){let c=g(e,y);if(!c)continue;let d=l(c);r.has(d)||i.has(d)||(i.add(d),a.push(c))}a.length>0&&n.push({objectApiName:o,ids:a})}return n}function p(e){return u(e.removal)?[]:b(e).filter(r=>!R(r.objectApiName))}function R(e){return Object.prototype.hasOwnProperty.call(m,e)}function k(e){return b(e).filter(r=>R(r.objectApiName)).map(({objectApiName:r,ids:t})=>({objectApiName:r,count:t.length}))}function I(e){return e.find(r=>p(r).length>0)??e[0]}function O(e,r){return e.filter(t=>t.endedAt!==r.endedAt&&t.created!==void 0&&p(t).length===0)}function v(e){let r=e.created!==void 0,t=h(e),i=[...f(e)].filter(o=>!t.has(o)),n=k(e);return{orgId:e.orgId,loadedAt:e.endedAt,created:p(e).map(({objectApiName:o,ids:s})=>({objectApiName:o,count:s.length})),linked:r?i.length:0,recorded:r,...e.removal?{removed:e.removal}:{},...e.earlier?{earlier:!0}:{},...n.length>0?{keptByThePlatform:n}:{}}}export{m as a,j as b,b as c,p as d,k as e,I as f,O as g,v as h};
@@ -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}from"./chunk-C2N2TNEU.mjs";import"./chunk-YAJQS3OL.mjs";import"./chunk-Z42PHCVZ.mjs";import"./chunk-H4OBZIX3.mjs";import"./chunk-V3R45ZWT.mjs";import"./chunk-NWOI25WY.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-JKT5YAQ2.mjs";import"./chunk-3SKLBRPL.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DX_PROJECT_FILE,b as scenarioProjectOf,c as writeRunTestFile};
7
+ import{a,b,c}from"./chunk-JH4ZTVQN.mjs";import"./chunk-2N73W63D.mjs";import"./chunk-27BBEGUD.mjs";import"./chunk-H4OBZIX3.mjs";import"./chunk-OTJH6AEA.mjs";import"./chunk-FVLFO2S6.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-77MZRBWX.mjs";import"./chunk-BT43WSOS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DX_PROJECT_FILE,b as scenarioProjectOf,c as writeRunTestFile};
@@ -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{d as Y,f as Z}from"./chunk-QP3JLFIO.mjs";import{h as J}from"./chunk-OOIDCHBQ.mjs";import"./chunk-CXKZ6TYV.mjs";import{b as G}from"./chunk-S4PRKKGC.mjs";import"./chunk-DMT5SCO3.mjs";import"./chunk-H33DVU3D.mjs";import{a as V}from"./chunk-TUPZY2QJ.mjs";import{a as K}from"./chunk-7V2UYZ6S.mjs";import{d as H}from"./chunk-2K5BYZQM.mjs";import"./chunk-JBWJ6UEZ.mjs";import"./chunk-UV74P4H2.mjs";import{k as D}from"./chunk-N2HYG3BL.mjs";import"./chunk-4GCYGQXD.mjs";import{b as R}from"./chunk-77IVKH7R.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-Z3MGN42K.mjs";import"./chunk-2GSMHGIV.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ISOSTAJR.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import{Jb as C,Kb as B,Lb as M,Ua as E,Zc as U,_c as L,dd as h,s as v,zb as F}from"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";import{readFile as W}from"node:fs/promises";import{homedir as ee}from"node:os";import{join as b}from"node:path";var ne="none";function p(e){return e!==void 0&&E.safeParse(e).success?e:void 0}function te(e,n){return D(e)===D(n)}function l(e,n){return e!==void 0&&e!==""&&e.length<=n?e:void 0}function re(e,n,t){return B(e,n!==void 0?K(n,t):ne)}function oe(e,n){let t=M.safeParse(e.get(n));return t.success?t.data:{steps:{}}}function be(e,n=ee()){let t=e.get("frozen:config");if(typeof t?.datasetDir=="string"&&t.datasetDir!=="")return t.datasetDir;let i=typeof t?.sasDir=="string"&&t.sasDir!==""?t.sasDir:b(n,".sandforge-sas");return b(i,"dataset")}async function ie(e){let n;try{n=await W(b(e,"manifest.json"),"utf8")}catch{return}try{let t=H(JSON.parse(n)),i=Object.values(t.volumetry.measured),s=l(t.source.orgAlias,255);return{frozenAt:new Date(t.frozenAt).toISOString(),...s!==void 0?{sourceAlias:s}:{},objects:i.length,records:i.reduce((r,o)=>r+Math.max(0,Math.trunc(o)),0)}}catch{return}}function X(e,n,t,i){let s=i!==void 0?Date.parse(i):Number.NEGATIVE_INFINITY;return new R(e).list({orgId:n,limit:v}).entries.find(o=>o.action===t&&o.outcome==="success"&&Date.parse(o.timestamp)>s)?.timestamp}var se=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function ae(e,n){let t=new R(e).list({limit:v}).entries.filter(r=>r.action==="anonymize_execute").map(r=>({orgId:r.orgId,objects:[...new Set((Array.isArray(r.objects)?r.objects:[]).map(o=>o.objectApiName).filter(o=>typeof o=="string"&&se.test(o)))].slice(0,C)})).filter(r=>r.objects.length>0),i=t.find(r=>r.orgId===n),s=i??t[0];return s!==void 0?{objects:s.objects,from:i!==void 0?"org":"machine"}:void 0}function de(e){return(e.removals??[]).some(n=>n.status==="success"||n.undone>0)}function ce(e,n){return Object.values(e.getByCategory("pipelines")).some(t=>{let i=t?.triggers;return Array.isArray(i)&&i.some(s=>{let r=s;return r?.type==="sandbox_refresh"&&r.enabled!==!1&&r.config?.orgId===n})})}function fe(e,n,t){let i=p(e.organizationId),s=l(e.previousInstanceName,40),r=l(e.instanceName,40),o=e.reportedBy!==void 0?t(e.reportedBy):void 0,d=l(o!==void 0?h(o,o.username):void 0,255);return{detectedAt:new Date(e.detectedAt).toISOString(),evidence:e.evidence,...n!==void 0?{previousOrganizationId:n}:{},...i!==void 0?{organizationId:i}:{},...s!==void 0?{previousInstanceName:s}:{},...r!==void 0?{instanceName:r}:{},...d!==void 0?{reportedBy:d}:{},cachesForgotten:!0}}async function $(e,n){return(await e.list({organizationId:n})).flatMap(i=>i.checkpoint?.status==="ready"?[{checkpointId:i.checkpointId,name:i.checkpoint.name,takenAt:new Date(i.checkpoint.takenAt).toISOString(),keptUntilDeleted:i.checkpoint.expiresAt===null}]:[]).sort((i,s)=>Date.parse(s.takenAt)-Date.parse(i.takenAt))}async function Ie(e,n){let t=e.orgOf(n);if(t===void 0)return{refused:"ORG_NOT_FOUND"};if(!L(t))return{refused:"NOT_A_DEVELOPMENT_ORG"};let i=U(t);if(i==="production")return{refused:"NOT_A_DEVELOPMENT_ORG"};let s=t.orgType==="Sandbox"?"sandbox":t.orgType==="Scratch"?"scratch":"developer",r=s==="sandbox"?e.refreshesOf(n)[0]:void 0,o=p(r!==void 0?r.organizationId:e.organizationIdOf(n)??t.orgId),d=r!==void 0?p(r.previousOrganizationId??(r.organizationId===void 0?e.organizationIdOf(n):void 0)):void 0,y=V(t.instanceUrl),f=y!==void 0&&F.safeParse(y).success?y:void 0,I=r?.detectedAt,z=await e.checkpoints(),q=d!==void 0?await $(z,d):[],Q=o!==void 0?await $(z,o):[],u=q[0],k;d!==void 0&&o!==void 0&&(k=(await e.replays().list({sourceOrganizationId:d,targetOrganizationId:o})).flatMap(a=>a.replayedAt!==void 0&&a.removed!==!0?[a.replayedAt]:[]).sort().at(-1));let c=(o!==void 0?await e.users().list(o):[]).find(a=>a.status!=="running"),O,A;if(f!==void 0){let{kept:a}=await G(e.journalDir,f),g=S=>o!==void 0&&te(S.inventory.organizationId,o),m=a.find(S=>!g(S));m!==void 0&&(O={savedAt:m.inventory.savedAt,organizationId:m.inventory.organizationId,jobs:m.inventory.jobs.length}),A=a.find(g)?.inventory.savedAt}let N=Z(e.configStore,Y(f,n)),w=await ie(e.frozenDatasetDir()),_=o!==void 0?await J(e.journalDir,o):void 0,T=o!==void 0?e.usersListed?.(n,o):void 0,j=X(e.configStore,n,"anonymize_execute",I),P=X(e.configStore,n,"frozen_load",I),x=ae(e.configStore,n);return{facts:{orgId:n,alias:h(t,t.username)||n,tier:i,kind:s,...s==="sandbox"&&t.sandboxType!==void 0?{sandboxType:t.sandboxType}:{},...f!==void 0?{myDomainHost:f}:{},...o!==void 0?{organizationId:o}:{},...r!==void 0?{refresh:fe(r,d,e.orgOf)}:{},acks:oe(e.configStore,re(n,r,a=>e.organizationIdOf(a))),...u!==void 0?{checkpointBefore:{checkpointId:u.checkpointId,name:u.name,takenAt:u.takenAt}}:{},...k!==void 0?{replayedAt:k}:{},checkpointsNow:Q.map(({takenAt:a,keptUntilDeleted:g})=>({takenAt:a,keptUntilDeleted:g})),...c!==void 0?{lastUsersRun:{run:c.run,at:c.endedAt??c.startedAt,status:c.status}}:{},...c!==void 0&&de(c)?{lastUsersRunTakenBack:!0}:{},...T!==void 0?{usersToBringBack:T}:{},...j!==void 0?{maskedAt:j}:{},...x!==void 0?{maskObjects:x}:{},...P!==void 0?{frozenLoadedAt:P}:{},...w!==void 0?{frozenManifest:w}:{},...O!==void 0?{inventoryBefore:O}:{},...A!==void 0?{inventoryNowAt:A}:{},..._!==void 0?{handoffAt:_}:{},...N!==void 0?{testersSavedAt:N.savedAt}:{},refreshPipeline:ce(e.configStore,n)}}}export{ne as NO_REFRESH_KEY,be as frozenDatasetDirOf,oe as readAcks,re as recoveryAckKeyOf,Ie as recoveryFactsOf};