sandforge 1.81.0 → 1.82.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 (208) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-users.mjs +12 -0
  3. package/lib/{chunk-C4YGSK6W.mjs → chunk-27Z76O2O.mjs} +1 -1
  4. package/lib/{chunk-TKQQVB2D.mjs → chunk-2JZGCCPG.mjs} +1 -1
  5. package/lib/{chunk-TPHXRHOA.mjs → chunk-2UU42PTD.mjs} +1 -1
  6. package/lib/{chunk-ZWZXQTAK.mjs → chunk-32EUNQT6.mjs} +14 -14
  7. package/lib/{chunk-HYOOJVR6.mjs → chunk-3C2ZZIFN.mjs} +1 -1
  8. package/lib/{chunk-AELFEK3G.mjs → chunk-3CX7GPCR.mjs} +1 -1
  9. package/lib/{chunk-YJEXE6HZ.mjs → chunk-3HEMJTAP.mjs} +2 -2
  10. package/lib/{chunk-DQR5NDMI.mjs → chunk-3HROD5RE.mjs} +1 -1
  11. package/lib/{chunk-D7P7DTWL.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  12. package/lib/{chunk-MNITSYI2.mjs → chunk-3SKLBRPL.mjs} +1 -1
  13. package/lib/{chunk-MAHZMPMZ.mjs → chunk-3XG25GTF.mjs} +1 -1
  14. package/lib/{chunk-N7J6NJQ6.mjs → chunk-42BFLWHR.mjs} +1 -1
  15. package/lib/chunk-466F37VD.mjs +7 -0
  16. package/lib/chunk-47UHTN3Q.mjs +7 -0
  17. package/lib/{chunk-DHGPDSXS.mjs → chunk-52EXDVPN.mjs} +1 -1
  18. package/lib/{chunk-5344TZBT.mjs → chunk-5K2I2DMP.mjs} +1 -1
  19. package/lib/{chunk-2OZG6GRW.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  20. package/lib/{chunk-SW2NUKQL.mjs → chunk-6KP6WETK.mjs} +1 -1
  21. package/lib/{chunk-FSZTXLNW.mjs → chunk-6VSZNZHH.mjs} +1 -1
  22. package/lib/{chunk-6NADW3OI.mjs → chunk-7CVDVBEE.mjs} +1 -1
  23. package/lib/{chunk-67CC7RAE.mjs → chunk-7EYQYZJP.mjs} +1 -1
  24. package/lib/{chunk-IBURU7T7.mjs → chunk-7LKI7OAS.mjs} +1 -1
  25. package/lib/{chunk-CULAOP3U.mjs → chunk-7PY3VQP3.mjs} +1 -1
  26. package/lib/chunk-7SDZR6SR.mjs +7 -0
  27. package/lib/{chunk-V4RKM4QZ.mjs → chunk-7WSLT5VX.mjs} +1 -1
  28. package/lib/chunk-A32ISQ6M.mjs +28 -0
  29. package/lib/{chunk-K77NR3UK.mjs → chunk-A65ADTCR.mjs} +1 -1
  30. package/lib/chunk-A7JJWOLT.mjs +7 -0
  31. package/lib/{chunk-MWLFFVQV.mjs → chunk-AUS6NFLZ.mjs} +1 -1
  32. package/lib/{chunk-NWPQF5XR.mjs → chunk-BMTNTBBM.mjs} +1 -1
  33. package/lib/{chunk-FTA5LOVX.mjs → chunk-BN33LVPQ.mjs} +1 -1
  34. package/lib/chunk-BNKT3R3F.mjs +7 -0
  35. package/lib/{chunk-WM5JI4JI.mjs → chunk-C2N2TNEU.mjs} +1 -1
  36. package/lib/{chunk-5UT2ZBGF.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  37. package/lib/{chunk-GYKNCYES.mjs → chunk-CBL42DUU.mjs} +1 -1
  38. package/lib/{chunk-W2AAGIZF.mjs → chunk-CCEH7L53.mjs} +1 -1
  39. package/lib/{chunk-WWTXRWNZ.mjs → chunk-CELEBWEZ.mjs} +1 -1
  40. package/lib/{chunk-D62KWDDT.mjs → chunk-CV47FDQW.mjs} +1 -1
  41. package/lib/{chunk-AJPSGVMD.mjs → chunk-CZLJZQCS.mjs} +1 -1
  42. package/lib/{chunk-YIGFYZQY.mjs → chunk-DBBPDSFN.mjs} +1 -1
  43. package/lib/{chunk-T5VAULLQ.mjs → chunk-DIL62SUN.mjs} +1 -1
  44. package/lib/chunk-DIS254AN.mjs +7 -0
  45. package/lib/{chunk-GK7VEYFM.mjs → chunk-DJCGURW7.mjs} +1 -1
  46. package/lib/{chunk-MHW6DV6T.mjs → chunk-DT3T7FRD.mjs} +1 -1
  47. package/lib/{chunk-PYUEHBA6.mjs → chunk-DWMRIWV5.mjs} +1 -1
  48. package/lib/{chunk-E2OBAWSH.mjs → chunk-EEFUE2ES.mjs} +1 -1
  49. package/lib/{chunk-MKNAZPOT.mjs → chunk-EOFO3PHS.mjs} +1 -1
  50. package/lib/{chunk-UUSLTW5V.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  51. package/lib/{chunk-DHIW4IO5.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  52. package/lib/{chunk-BZFIOZS3.mjs → chunk-FOIWWK7G.mjs} +1 -1
  53. package/lib/chunk-FZF23M6R.mjs +7 -0
  54. package/lib/{chunk-XIZ5LMQM.mjs → chunk-G2JR3F63.mjs} +1 -1
  55. package/lib/{chunk-2Z54GB6X.mjs → chunk-GBGHJTPC.mjs} +1 -1
  56. package/lib/{chunk-2NAIUKVL.mjs → chunk-GCGHHN4K.mjs} +1 -1
  57. package/lib/{chunk-TQM2XJ27.mjs → chunk-GGNUACTY.mjs} +1 -1
  58. package/lib/{chunk-2IB7I3IQ.mjs → chunk-GGUOIDWP.mjs} +1 -1
  59. package/lib/chunk-GHPR5UVV.mjs +7 -0
  60. package/lib/{chunk-YHIOS2PU.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  61. package/lib/{chunk-WI4HYWV6.mjs → chunk-H4JUYUSL.mjs} +1 -1
  62. package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
  63. package/lib/{chunk-KRNFVAGC.mjs → chunk-HFUDCNU5.mjs} +1 -1
  64. package/lib/{chunk-OIIL4NVI.mjs → chunk-HIHCYMSL.mjs} +1 -1
  65. package/lib/chunk-HKUWHVI7.mjs +9 -0
  66. package/lib/chunk-HQQVANWQ.mjs +20 -0
  67. package/lib/{chunk-V2QO6KOE.mjs → chunk-IRZJU2PG.mjs} +14 -11
  68. package/lib/{chunk-CAFUNR6D.mjs → chunk-ISSP2FZ5.mjs} +1 -1
  69. package/lib/{chunk-OEHVAJAB.mjs → chunk-IVZJSDJD.mjs} +1 -1
  70. package/lib/{chunk-E2YJVSX6.mjs → chunk-J24TIGSI.mjs} +1 -1
  71. package/lib/{chunk-YCSFP6ER.mjs → chunk-JESRFE2Z.mjs} +1 -1
  72. package/lib/{chunk-KOQV4WXC.mjs → chunk-JFNLKHY6.mjs} +2 -2
  73. package/lib/{chunk-NJ3EOEHS.mjs → chunk-JH27IKCO.mjs} +1 -1
  74. package/lib/{chunk-DXOXLUZA.mjs → chunk-JJITOWZK.mjs} +1 -1
  75. package/lib/{chunk-KNIRA333.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  76. package/lib/{chunk-J6G23RUI.mjs → chunk-JLZRZL5E.mjs} +1 -1
  77. package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
  78. package/lib/{chunk-6IGEASOF.mjs → chunk-JQZTMFO7.mjs} +1 -1
  79. package/lib/{chunk-55LQD3Y3.mjs → chunk-KIMQQ6JQ.mjs} +1 -1
  80. package/lib/{chunk-EH5YUA5W.mjs → chunk-KJYEQHYP.mjs} +1 -1
  81. package/lib/chunk-KKOA62S4.mjs +474 -0
  82. package/lib/{chunk-56MPPWLA.mjs → chunk-KP5G6FUC.mjs} +1 -1
  83. package/lib/{chunk-EAFLDSQ2.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  84. package/lib/{chunk-MO3N5XVV.mjs → chunk-LAUOSXMN.mjs} +2 -2
  85. package/lib/{chunk-HVC5CYIB.mjs → chunk-LHU6CPGE.mjs} +1 -1
  86. package/lib/{chunk-7PK5QDQI.mjs → chunk-LXDSRP2W.mjs} +1 -1
  87. package/lib/{chunk-YOGMP72T.mjs → chunk-MKTXJCXN.mjs} +1 -1
  88. package/lib/{chunk-VSU74RQ3.mjs → chunk-MUEQRIK7.mjs} +1 -1
  89. package/lib/{chunk-UCHAZ4ZU.mjs → chunk-NLB3RGIY.mjs} +1 -1
  90. package/lib/{chunk-OVOLG3AL.mjs → chunk-NWOI25WY.mjs} +1 -1
  91. package/lib/{chunk-6SEDOIO3.mjs → chunk-O2PUGRNW.mjs} +1 -1
  92. package/lib/chunk-O4BROUGM.mjs +7 -0
  93. package/lib/{chunk-KGYXLSQ5.mjs → chunk-P55MKIZX.mjs} +1 -1
  94. package/lib/{chunk-KE2PGD6C.mjs → chunk-P63WJMXQ.mjs} +1 -1
  95. package/lib/chunk-PBE44M2Y.mjs +7 -0
  96. package/lib/{chunk-OMZJ37JI.mjs → chunk-PE435FVH.mjs} +2 -2
  97. package/lib/{chunk-GR3NGDVM.mjs → chunk-PPHVWUFY.mjs} +1 -1
  98. package/lib/{chunk-ZUA5BNAO.mjs → chunk-PR74GYVI.mjs} +1 -1
  99. package/lib/{chunk-43K2C6H2.mjs → chunk-PWVDNN2C.mjs} +1 -1
  100. package/lib/{chunk-DMBR24CK.mjs → chunk-PYRZFUVU.mjs} +1 -1
  101. package/lib/{chunk-OXKZ4Y3B.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  102. package/lib/{chunk-EOSEMFPU.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  103. package/lib/chunk-QAPVKPEC.mjs +7 -0
  104. package/lib/chunk-QROPNEGY.mjs +14 -0
  105. package/lib/{chunk-6CDIIFNX.mjs → chunk-RCYEBY42.mjs} +1 -1
  106. package/lib/chunk-RLWB7F26.mjs +7 -0
  107. package/lib/{chunk-X2ZVSQ54.mjs → chunk-RTWYLOCA.mjs} +1 -1
  108. package/lib/chunk-RYRMUPMY.mjs +7 -0
  109. package/lib/{chunk-ETT5GP4P.mjs → chunk-SAMWHL22.mjs} +1 -1
  110. package/lib/{chunk-LO527YLT.mjs → chunk-SFGZFB4F.mjs} +1 -1
  111. package/lib/{chunk-33ZX3A56.mjs → chunk-SNEOKYV7.mjs} +1 -1
  112. package/lib/{chunk-GTIXJCGS.mjs → chunk-STRMWSIQ.mjs} +1 -1
  113. package/lib/{chunk-OQQHNYR7.mjs → chunk-SZGGFST2.mjs} +2 -2
  114. package/lib/{chunk-OU5W7SCB.mjs → chunk-T7WREYA5.mjs} +1 -1
  115. package/lib/{chunk-FLNLG43R.mjs → chunk-TCBAE65A.mjs} +1 -1
  116. package/lib/{chunk-RKALOKAU.mjs → chunk-TMA34QMA.mjs} +1 -1
  117. package/lib/{chunk-WEZLXE34.mjs → chunk-TWV4A5RK.mjs} +1 -1
  118. package/lib/{chunk-ONMBSACW.mjs → chunk-UHFLKP26.mjs} +1 -1
  119. package/lib/chunk-UV74P4H2.mjs +7 -0
  120. package/lib/{chunk-HYBH5PFM.mjs → chunk-V3R45ZWT.mjs} +1 -1
  121. package/lib/{chunk-BNO5GIJ6.mjs → chunk-VPDEJGPS.mjs} +1 -1
  122. package/lib/{chunk-3AOKLIVE.mjs → chunk-VQJMP3DC.mjs} +1 -1
  123. package/lib/{chunk-742SSN7I.mjs → chunk-VYOYXTCU.mjs} +1 -1
  124. package/lib/{chunk-GWRKS3AL.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  125. package/lib/{chunk-2OIRJEYE.mjs → chunk-VZVICK7Q.mjs} +1 -1
  126. package/lib/chunk-WEMLDUQA.mjs +7 -0
  127. package/lib/{chunk-FDGFUEK3.mjs → chunk-WOOUISSO.mjs} +1 -1
  128. package/lib/{chunk-UIUPPEFB.mjs → chunk-WSUKC2U3.mjs} +1 -1
  129. package/lib/{chunk-XC2QKQT5.mjs → chunk-WT3SCUHS.mjs} +1 -1
  130. package/lib/{chunk-UT27HXE7.mjs → chunk-XFU3HRUV.mjs} +1 -1
  131. package/lib/{chunk-5VQNKDFU.mjs → chunk-XK5W7BVE.mjs} +1 -1
  132. package/lib/{chunk-OZNLOV4U.mjs → chunk-XO5FBOQF.mjs} +1 -1
  133. package/lib/{chunk-FSDO4DJA.mjs → chunk-XSKPYGMT.mjs} +1 -1
  134. package/lib/{chunk-AITNZWLB.mjs → chunk-XU25YA46.mjs} +1 -1
  135. package/lib/{chunk-XEB6HZ34.mjs → chunk-XZISAZA6.mjs} +1 -1
  136. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  137. package/lib/{chunk-4L7FBOJS.mjs → chunk-YAIIRFKJ.mjs} +1 -1
  138. package/lib/{chunk-T3PLRQ2T.mjs → chunk-YAJQS3OL.mjs} +1 -1
  139. package/lib/{chunk-Y5ZCPY36.mjs → chunk-YGJF55VJ.mjs} +1 -1
  140. package/lib/chunk-YH4DYI6D.mjs +7 -0
  141. package/lib/{chunk-R6TF26V4.mjs → chunk-YMDFF657.mjs} +1 -1
  142. package/lib/{chunk-JU2XEKEO.mjs → chunk-YT22LMF7.mjs} +1 -1
  143. package/lib/{chunk-NWVVCZUK.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  144. package/lib/{chunk-O6ADMP36.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  145. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  146. package/lib/{chunk-QXLZINZB.mjs → chunk-ZUBBEP75.mjs} +1 -1
  147. package/lib/{chunk-SQGP46QS.mjs → chunk-ZUOPC4W2.mjs} +1 -1
  148. package/lib/{chunk-3B5H24ZG.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  149. package/lib/{chunk-K55LH4ZQ.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  150. package/lib/sandforge-autopilot.mjs +1 -1
  151. package/lib/sandforge-backup.mjs +1 -1
  152. package/lib/sandforge-checkpoint.mjs +1 -1
  153. package/lib/sandforge-cleanup.mjs +1 -1
  154. package/lib/sandforge-clone.mjs +1 -1
  155. package/lib/sandforge-compare.mjs +1 -1
  156. package/lib/sandforge-dataops.mjs +1 -1
  157. package/lib/sandforge-empty.mjs +1 -1
  158. package/lib/sandforge-env.mjs +185 -139
  159. package/lib/sandforge-frozen.mjs +1 -1
  160. package/lib/sandforge-mcp.mjs +14 -14
  161. package/lib/sandforge-monitor.mjs +1 -1
  162. package/lib/sandforge-pipeline.mjs +1 -1
  163. package/lib/sandforge-seed.mjs +1 -1
  164. package/lib/sandforge-sync.mjs +1 -1
  165. package/lib/sandforge-users.mjs +157 -0
  166. package/lib/sandforge.mjs +1 -22
  167. package/lib/sf/sandforge/autopilot.mjs +20 -0
  168. package/lib/sf/sandforge/backup.mjs +20 -0
  169. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  170. package/lib/sf/sandforge/cleanup.mjs +20 -0
  171. package/lib/sf/sandforge/clone.mjs +20 -0
  172. package/lib/sf/sandforge/compare.mjs +20 -0
  173. package/lib/sf/sandforge/dataops.mjs +20 -0
  174. package/lib/sf/sandforge/empty.mjs +20 -0
  175. package/lib/sf/sandforge/env.mjs +20 -0
  176. package/lib/sf/sandforge/frozen.mjs +20 -0
  177. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  178. package/lib/sf/sandforge/index.mjs +20 -0
  179. package/lib/sf/sandforge/mcp.mjs +20 -0
  180. package/lib/sf/sandforge/monitor.mjs +20 -0
  181. package/lib/sf/sandforge/pipeline.mjs +20 -0
  182. package/lib/sf/sandforge/seed.mjs +20 -0
  183. package/lib/sf/sandforge/sync.mjs +20 -0
  184. package/lib/sf/sandforge/users.mjs +20 -0
  185. package/lib/sfHelpHook.mjs +7 -0
  186. package/lib/sfPlugin.mjs +11 -0
  187. package/oclif.manifest.json +1 -0
  188. package/package.json +17 -3
  189. package/lib/chunk-2ZMGVBLW.mjs +0 -7
  190. package/lib/chunk-5C5XEVZN.mjs +0 -11
  191. package/lib/chunk-5CKWGZX4.mjs +0 -9
  192. package/lib/chunk-5ZKCLBTN.mjs +0 -474
  193. package/lib/chunk-7DALDJMO.mjs +0 -7
  194. package/lib/chunk-DPYTG6DM.mjs +0 -48
  195. package/lib/chunk-G4VXPS3A.mjs +0 -7
  196. package/lib/chunk-GF247DA7.mjs +0 -7
  197. package/lib/chunk-IKGHRYCN.mjs +0 -7
  198. package/lib/chunk-IM2XA6JI.mjs +0 -7
  199. package/lib/chunk-K5HV4YRO.mjs +0 -7
  200. package/lib/chunk-N6HHNR6J.mjs +0 -7
  201. package/lib/chunk-O7DAFE6M.mjs +0 -14
  202. package/lib/chunk-R2BJWO5N.mjs +0 -20
  203. package/lib/chunk-T26C576X.mjs +0 -9
  204. package/lib/chunk-V473C7LY.mjs +0 -7
  205. package/lib/chunk-WD47PGUS.mjs +0 -10
  206. package/lib/chunk-XC54KKKC.mjs +0 -7
  207. package/lib/chunk-XGKSSCW7.mjs +0 -7
  208. package/lib/chunk-ZWCRWF7E.mjs +0 -7
package/README.md CHANGED
@@ -45,11 +45,59 @@ The tools, the `confirm` rule a write needs, and what each answer carries: [Sand
45
45
  | `frozen` | build and replay a Frozen Dataset |
46
46
  | `mcp` | the MCP server: these scripts as tools for an AI agent, on stdio |
47
47
  | `monitor` | read an org the way the Monitor page does |
48
+ | `pipeline` | plan and run an Automation pipeline exported from VS Code |
48
49
  | `seed` | fill an org from a seed template |
49
50
  | `sync` | run a Sync between two orgs |
51
+ | `users` | set up the users of a sandbox after its refresh, and take them back |
50
52
 
51
53
  `sandforge <command> --help` gives its options and its exit codes. Every command refuses a flag it does not read with exit code `2`, before any org is reached; every command that writes to an org refuses a production one before it writes anything. What each one does, its flags, the exit codes and the pipelines that run them: [Command line & CI](https://github.com/StephaneBerthoz/sandforge/blob/master/ci-examples/README.md).
52
54
 
55
+ ## As an sf plugin
56
+
57
+ The same package installs into the Salesforce CLI:
58
+
59
+ ```sh
60
+ sf plugins trust allowlist add --name sandforge
61
+ sf plugins install sandforge
62
+ sf sandforge --help
63
+ sf sandforge clone --help
64
+ ```
65
+
66
+ `sf sandforge <command>` is `npx sandforge <command>`: the same script, run in sf's own process, with the same flags, the same guards, the same exit codes and the same output, `--json` and the MCP server included. `--help` and `-h` print the command's own help, word for word. sf's own flags are not read: `--target-org` is refused with exit code `2` like any flag a command does not take, before any org is reached, and no command takes sf's default org. Each one names its org by its alias, with `--org`, `--source` or `--target`, as under npx.
67
+
68
+ **The question at install.** sf takes a plugin's signature from Salesforce's own site only, and Salesforce does not sign this one, so sf asks before it installs it, "sandforge isn't signed by Salesforce. Only install the plugin if you trust its creator. Do you want to continue the installation?", unless its name is on your allowlist. `sf plugins trust allowlist add --name sandforge` puts it there, once; it trusts the name, whatever version sf installs under it. Before you add it, check where the package was built: from 1.80.0, each version is published by the repository's own workflow with npm provenance, which `npm view sandforge dist.attestations` shows, and which `npm audit signatures` verifies in a folder where the package is installed.
69
+
70
+ **Node.** sf runs the commands on its own Node, and they need Node.js 20.19 or later there too. sf 2.150.5 and later run on Node 22 or later; on an older sf, which can run on an older Node, a Node before 20.19 is refused before anything runs, as `npx sandforge` refuses it.
71
+
72
+ **Telemetry.** sf records each command it runs, `sf sandforge clone` among them: the command, the plugin and its version, the exit code and the time it took. Of the flags, it records only those a command declares to it, and the plugin declares none: neither a flag of a SandForge command nor its value reaches it. `sf config set disable-telemetry=true`, or `SF_DISABLE_TELEMETRY=true`, turns it off. SandForge adds no telemetry of its own.
73
+
74
+ **The help hook.** Once installed, the plugin's `init` hook is loaded by every sf command, SandForge's or not. It prints a SandForge command's own help when `--help` or `-h` comes before any `--`, and does nothing for any other command.
75
+
76
+ The lines the commands print keep `npx sandforge …`, the line that takes a run back or the launcher of an exported pipeline: they run wherever sf runs, a CI job included. Out of a global install, npx runs the latest version published, which can be newer than the plugin's. `sf plugins uninstall sandforge` removes the plugin.
77
+
78
+ ### In sfdx-hardis's menus
79
+
80
+ `sf sandforge:hardis-commands --json` gives the VS Code extension of sfdx-hardis a SandForge menu of four entries, each of them read only and none reaching an org:
81
+
82
+ - `sf sandforge --help`
83
+ - `sf sandforge seed --list-templates`
84
+ - `sf sandforge env validate`, which checks the `sandforge.yaml` of the folder the command runs in
85
+ - `sf sandforge env state`, which lists the environments kept on this machine
86
+
87
+ sfdx-hardis asks every plugin installed for its menu entries. To list SandForge in its Dependencies panel for everyone who works in a project, add it to the project's `.sfdx-hardis.yml`:
88
+
89
+ ```yaml
90
+ customPlugins:
91
+ - name: sandforge
92
+ helpUrl: https://github.com/StephaneBerthoz/sandforge/blob/master/packages/cli/README.md#as-an-sf-plugin
93
+ ```
94
+
95
+ From that panel, a click installs the plugin, or updates it, with `echo y|sf plugins:install sandforge@latest`, which answers yes to the question above. The SandForge menu, as sfdx-hardis shows it, is not yet proven.
96
+
97
+ ### Where it is proven
98
+
99
+ On Linux, with sf 2.154 on Node 22. An sf before 2.151, which runs on oclif 4, is not yet proven, and neither is Node 20.19 under sf. macOS and Windows are not yet proven.
100
+
53
101
  ## Versions and license
54
102
 
55
103
  The package is published with each release of the extension, at the same version. MIT; the notices of the packages it bundles are in `THIRD-PARTY-NOTICES.md`.
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ const [major, minor] = process.versions.node.split('.').map(Number);
3
+ if (major < 20 || (major === 20 && minor < 19)) {
4
+ process.stderr.write(
5
+ 'sandforge needs Node.js 20.19 or later, and this is ' + process.versions.node + '. Nothing was run.\n',
6
+ );
7
+ process.exit(1);
8
+ }
9
+ const { fileURLToPath } = await import('node:url');
10
+ const entry = new URL('../lib/sandforge-users.mjs', import.meta.url);
11
+ process.argv[1] = fileURLToPath(entry);
12
+ await import(entry.href);
@@ -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}from"./chunk-56MPPWLA.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as describedFieldsOf,b as requiredForAccountKinds};
7
+ import{a,b}from"./chunk-KP5G6FUC.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as describedFieldsOf,b as requiredForAccountKinds};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as d,b as g,c as f}from"./chunk-SQGP46QS.mjs";import{a as s}from"./chunk-PPGDAUEQ.mjs";import{a}from"./chunk-SU65Z2BA.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
7
+ import{a as d,b as g,c as f}from"./chunk-ZUOPC4W2.mjs";import{a as s}from"./chunk-PPGDAUEQ.mjs";import{a}from"./chunk-SU65Z2BA.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
8
8
  `),process.exit(u)}let r=c(t,o,e);return r!==void 0&&(process.stderr.write(`${r}
9
9
  `),process.exit(u)),o}export{p as a,y as b};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as n,b as p,h as a}from"./chunk-BWWQXU2B.mjs";import{a as o}from"./chunk-EADHKH3A.mjs";import{q as d}from"./chunk-55LQD3Y3.mjs";var R=`SELECT Id FROM RecordType WHERE SobjectType = '${d}' AND IsPersonType = true`;async function S(i,t){let[y,c]=await Promise.all([o(i,n).then(({records:e})=>p(e)),o(t,n).then(({records:e})=>p(e))]),r;try{let{records:e}=await o(t,R);r=new Set(e.flatMap(s=>typeof s.Id=="string"?[s.Id.slice(0,15)]:[]))}catch{r=void 0}return{mappings:new a().buildMapping(y,c),source:y,target:c,...r?{personTypes:r}:{}}}export{S as a};
7
+ import{a as n,b as p,h as a}from"./chunk-BWWQXU2B.mjs";import{a as o}from"./chunk-EADHKH3A.mjs";import{q as d}from"./chunk-KIMQQ6JQ.mjs";var R=`SELECT Id FROM RecordType WHERE SobjectType = '${d}' AND IsPersonType = true`;async function S(i,t){let[y,c]=await Promise.all([o(i,n).then(({records:e})=>p(e)),o(t,n).then(({records:e})=>p(e))]),r;try{let{records:e}=await o(t,R);r=new Set(e.flatMap(s=>typeof s.Id=="string"?[s.Id.slice(0,15)]:[]))}catch{r=void 0}return{mappings:new a().buildMapping(y,c),source:y,target:c,...r?{personTypes:r}:{}}}export{S as a};
@@ -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{c as is,d as ds,i as cs}from"./chunk-WI4HYWV6.mjs";import{b as ls,c as us}from"./chunk-WM5JI4JI.mjs";import{a as Ke,b as It}from"./chunk-56MPPWLA.mjs";import{a as Tt,b as Ur}from"./chunk-67CC7RAE.mjs";import{c as es,e as ts,g as ns,h as We}from"./chunk-OU5W7SCB.mjs";import{g as as}from"./chunk-T3PLRQ2T.mjs";import{f as Ge}from"./chunk-5WGA5CZB.mjs";import{d as rs,g as Je,i as ss,j as os}from"./chunk-NWVVCZUK.mjs";import{b as Yr}from"./chunk-HYBH5PFM.mjs";import{a as Nr}from"./chunk-FSDO4DJA.mjs";import{a as _r}from"./chunk-MHW6DV6T.mjs";import{a as Dr}from"./chunk-QXLZINZB.mjs";import{a as Lr}from"./chunk-OZNLOV4U.mjs";import{a as Pr}from"./chunk-2OZG6GRW.mjs";import{H as Er,J as jt,K as xr,O as Ot,P as Cr}from"./chunk-MO3N5XVV.mjs";import{b as ln}from"./chunk-TKQQVB2D.mjs";import{a as pr,b as Mr,d as Br,e as zr,f as Kr,g as Gr,h as Wr,j as Jr,k as Vr,l as Et,m as xt,p as Zr,q as Hr,r as Xr,s as Qr}from"./chunk-AELFEK3G.mjs";import{d as qr}from"./chunk-K77NR3UK.mjs";import{a as Fr}from"./chunk-OVOLG3AL.mjs";import{f as hr}from"./chunk-FQGHL7GR.mjs";import{I as $r,J as Ar,L as jr,Q as Or,R as Ir,S as Tr,T as $t,U as At,a as fr,c as mr,j as gr,k as wr,u as br}from"./chunk-IM2XA6JI.mjs";import{a as yr,c as Rr}from"./chunk-5UT2ZBGF.mjs";import{d as Sr,e as kr,f as vr}from"./chunk-YHIOS2PU.mjs";import{Ab as dr,Bb as qe,Cb as cr,Db as lr,Eb as ur,Wa as ve,b as K,cb as er,d as St,db as kt,e as Kn,f as Gn,g as Wn,h as Jn,i as Vn,k as ze,l as Zn,lb as tr,n as Hn,o as Xn,p as Qn,pb as nr,qb as $e,rb as rr,sb as vt,tb as sr,xb as or,yb as ar,zb as ir}from"./chunk-YJEXE6HZ.mjs";import{b as Rt,c as zn,d as qn}from"./chunk-KNIRA333.mjs";import{a as ce,d as Dn,j as Ue,k as Ln}from"./chunk-O7DAFE6M.mjs";import{b as _e,e as De}from"./chunk-BZ24IAP5.mjs";import{a as en}from"./chunk-SCKUIE3R.mjs";import{a as ct,b as fn,c as Le,d as Y,e as pn,f as hn,g as lt,h as mn,j as gn}from"./chunk-6FARZYMJ.mjs";import{_ as bn,yc as vn,zc as $n}from"./chunk-CAFUNR6D.mjs";import{Ha as Mn,Wa as yt,Xa as Bn,db as Un,f as _n}from"./chunk-KGYXLSQ5.mjs";import{b as yn}from"./chunk-6SEDOIO3.mjs";import{C as ft,N as ye,Q as pt,a as wn}from"./chunk-ZWCRWF7E.mjs";import{h as Sn,l as kn,n as Me,p as Be}from"./chunk-MNITSYI2.mjs";import{b as be,c as ue}from"./chunk-HVC5CYIB.mjs";import{B as fe,s as ht,t as Re,x as In,y as Tn,z as mt}from"./chunk-T26C576X.mjs";import{a as we,b as cn,f as it}from"./chunk-SQGP46QS.mjs";import{b as An,c as jn,g as On}from"./chunk-6IGEASOF.mjs";import{Ic as wt,Jc as bt,Pb as Pn,bc as Nn,eb as xn,fc as Fn,hb as Se,lb as Cn,mc as ke,tc as gt}from"./chunk-KOQV4WXC.mjs";import{q as En}from"./chunk-2OIRJEYE.mjs";import{b as Fe,d as un,f as dt,h as Yn}from"./chunk-LCDPCUXS.mjs";import{d as Rn}from"./chunk-TUACWKIH.mjs";import{b as ut}from"./chunk-HFSBDM7B.mjs";import{q as de}from"./chunk-55LQD3Y3.mjs";import{Ad as at,Ea as nt,Eb as Ne,Fb as st,Ib as nn,Jb as rn,Lc as sn,Wc as on,e as le,h as tn,sb as rt,xd as ot,yd as an,zd as dn}from"./chunk-DPYTG6DM.mjs";import{A as P}from"./chunk-WZQEK4WT.mjs";import{randomInt as Xs,randomUUID as Qs}from"node:crypto";import{existsSync as Rs,readFileSync as je,renameSync as Ys,writeFileSync as eo}from"node:fs";import{dirname as to,join as no}from"node:path";import{existsSync as ps,readFileSync as hs}from"node:fs";import{dirname as fs,resolve as Ct}from"node:path";function Pt(t,n=e=>hs(e,"utf8")){let e=st.find(i=>i.id===t);if(e)return{pack:e,from:"built-in"};if(!ps(t))return{refusal:`--scenario takes the id of a scenario SandForge ships (${st.map(i=>i.id).join(", ")}) or a scenario file, not "${t}".`};let r;try{r=n(t)}catch(i){return{refusal:`${t} could not be read: ${i instanceof Error?i.message:String(i)}`}}let o=ds(r);return"issues"in o?{refusal:`${t} is not a scenario pack:
7
+ import{c as es,e as ts,g as ns,h as We}from"./chunk-T7WREYA5.mjs";import{c as is,d as ds,i as cs}from"./chunk-H4JUYUSL.mjs";import{b as ls,c as us}from"./chunk-C2N2TNEU.mjs";import{g as as}from"./chunk-YAJQS3OL.mjs";import{d as rs,g as Je,i as ss,j as os}from"./chunk-Z42PHCVZ.mjs";import{a as _r}from"./chunk-DT3T7FRD.mjs";import{a as Dr}from"./chunk-ZUBBEP75.mjs";import{a as Lr}from"./chunk-XO5FBOQF.mjs";import{a as Ke,b as It}from"./chunk-KP5G6FUC.mjs";import{a as Tt,b as Ur}from"./chunk-7EYQYZJP.mjs";import{f as Ge}from"./chunk-H4OBZIX3.mjs";import{b as Yr}from"./chunk-V3R45ZWT.mjs";import{a as Nr}from"./chunk-XSKPYGMT.mjs";import{a as Pr}from"./chunk-6GQUZ4IP.mjs";import{H as Er,J as jt,K as xr,O as Ot,P as Cr}from"./chunk-LAUOSXMN.mjs";import{b as ln}from"./chunk-2JZGCCPG.mjs";import{a as pr,b as Mr,d as Br,e as zr,f as Kr,g as Gr,h as Wr,j as Jr,k as Vr,l as Et,m as xt,p as Zr,q as Hr,r as Xr,s as Qr}from"./chunk-3CX7GPCR.mjs";import{d as qr}from"./chunk-A65ADTCR.mjs";import{a as Fr}from"./chunk-NWOI25WY.mjs";import{f as hr}from"./chunk-FQGHL7GR.mjs";import{I as $r,J as Ar,L as jr,Q as Or,R as Ir,S as Tr,T as $t,U as At,a as fr,c as mr,j as gr,k as wr,u as br}from"./chunk-A7JJWOLT.mjs";import{a as yr,c as Rr}from"./chunk-C3LNYAVJ.mjs";import{d as Sr,e as kr,f as vr}from"./chunk-GJ6SZVHT.mjs";import{Ab as dr,Bb as qe,Cb as cr,Db as lr,Eb as ur,Wa as ve,b as K,cb as er,d as St,db as kt,e as Kn,f as Gn,g as Wn,h as Jn,i as Vn,k as ze,l as Zn,lb as tr,n as Hn,o as Xn,p as Qn,pb as nr,qb as $e,rb as rr,sb as vt,tb as sr,xb as or,yb as ar,zb as ir}from"./chunk-3HEMJTAP.mjs";import{b as Rt,c as zn,d as qn}from"./chunk-JKT5YAQ2.mjs";import{a as ce,d as Dn,j as Ue,k as Ln}from"./chunk-BNKT3R3F.mjs";import{b as _e,e as De}from"./chunk-BZ24IAP5.mjs";import{a as en}from"./chunk-SCKUIE3R.mjs";import{a as ct,b as fn,c as Le,d as Y,e as pn,f as hn,g as lt,h as mn,j as gn}from"./chunk-6FARZYMJ.mjs";import{_ as bn,yc as vn,zc as $n}from"./chunk-ISSP2FZ5.mjs";import{Ha as Mn,Wa as yt,Xa as Bn,db as Un,f as _n}from"./chunk-P55MKIZX.mjs";import{b as yn}from"./chunk-O2PUGRNW.mjs";import{C as ft,N as ye,Q as pt,a as wn}from"./chunk-7SDZR6SR.mjs";import{h as Sn,l as kn,n as Me,p as Be}from"./chunk-3SKLBRPL.mjs";import{a as ht,b as Re,f as In,g as Tn,h as mt,j as fe}from"./chunk-HKUWHVI7.mjs";import{b as be,c as ue}from"./chunk-LHU6CPGE.mjs";import{a as we,b as cn,f as it}from"./chunk-ZUOPC4W2.mjs";import{b as An,c as jn,g as On}from"./chunk-JQZTMFO7.mjs";import{Ic as wt,Jc as bt,Pb as Pn,bc as Nn,eb as xn,fc as Fn,hb as Se,lb as Cn,mc as ke,tc as gt}from"./chunk-JFNLKHY6.mjs";import{q as En}from"./chunk-VZVICK7Q.mjs";import{b as Fe,d as un,f as dt,h as Yn}from"./chunk-LCDPCUXS.mjs";import{b as ut}from"./chunk-HFSBDM7B.mjs";import{q as de}from"./chunk-KIMQQ6JQ.mjs";import{d as Rn}from"./chunk-TUACWKIH.mjs";import{Ea as nt,Eb as rt,Jd as ot,Kd as an,Ld as dn,Md as at,Qb as Ne,Rb as st,Ub as nn,Vb as rn,Xc as sn,e as le,gd as on,h as tn}from"./chunk-ZQO5PDX5.mjs";import{A as P}from"./chunk-WZQEK4WT.mjs";import{randomInt as Xs,randomUUID as Qs}from"node:crypto";import{existsSync as Rs,readFileSync as je,renameSync as Ys,writeFileSync as eo}from"node:fs";import{dirname as to,join as no}from"node:path";import{existsSync as ps,readFileSync as hs}from"node:fs";import{dirname as fs,resolve as Ct}from"node:path";function Pt(t,n=e=>hs(e,"utf8")){let e=st.find(i=>i.id===t);if(e)return{pack:e,from:"built-in"};if(!ps(t))return{refusal:`--scenario takes the id of a scenario SandForge ships (${st.map(i=>i.id).join(", ")}) or a scenario file, not "${t}".`};let r;try{r=n(t)}catch(i){return{refusal:`${t} could not be read: ${i instanceof Error?i.message:String(i)}`}}let o=ds(r);return"issues"in o?{refusal:`${t} is not a scenario pack:
8
8
  ${o.issues.map(i=>` ${i}`).join(`
9
9
  `)}`}:{pack:o.pack,from:Ct(t)}}async function ms(t,n,e){let r=ns(n,{caseStatus:await es(t.query),knowledge:await ts(t.objectAccess,t.describe),...e!==void 0?{seed:e}:{}});if("issues"in r)return r;let{options:o}=r.preparation;return{...r,compiled:Yr(n,o),options:o}}function gs(t,n){let{options:e,knowledge:r,caseStatusFrom:o}=n;return[`scenario: ${t.id} (${t.name}), seed ${e.seed} (--scenario-seed ${e.seed} writes the same again)`,...n.objects.map(i=>` ${i.objectApiName}: ${i.recordCount} record(s)`+(i.optional?", skipped by an org without it":"")),` cases: open "${e.caseStatus.open}", closed "${e.caseStatus.closed}"`+(o.from==="org"?" (the org's)":` (a new org's: ${o.reason})`),r.available?" articles: published once written, each closed case linked to the article of its topic, "+(e.articleBodyField?`their body in ${e.articleBodyField}`+(e.articleBodyLength!==void 0?` (${e.articleBodyLength} characters, every fact kept)`:""):"with their summary alone: the org offers no field for a body"):` articles: skipped, ${r.reason}: the tests that answer from Knowledge are written, and the agent will have no article to cite`,` tests: ${n.tests}, written to a file once the run has ended (--test-file)`]}function ws(t){if(!t)return[];if(t.skipped!==void 0)return[`articles: ${t.skipped}`];let n=(e,r)=>r?[`${e}: ${r.done} of ${r.asked}`,...r.notDone.map(({key:o,reason:i})=>` ${o}: ${i}`)]:[];return[...n("articles published",t.publish),...n("closed cases linked to their article",t.links)]}async function bs(t){let n=new Set(t.compiled.tests.flatMap(o=>o.openCase?[o.openCase.caseKey]:[])),e=Object.keys(t.caseIds).filter(o=>n.has(o)).length,r={packId:t.pack.id,tests:t.compiled.tests.length,openCases:n.size,openCasesWritten:e};if(e===0)return r;try{let o=await ss(Je(),t.journalDir,rs({runId:t.runId,pack:t.pack,compiled:t.compiled,options:t.options,caseIds:t.caseIds}));return{...r,companion:o}}catch(o){return{...r,unkept:o instanceof Error?o.message:String(o)}}}function Nt(t,n,e){return[`${en("seed")} --test-file`,t,"--target",n,"--agent <agent API name>",...e.topics.map(r=>`--topic ${r.key}=<agent topic>`)].join(" ")}function Gs(t){return t.flatMap(n=>[` ${n.name}${n.label?` (${n.label})`:""}`,...n.topics.map(e=>` topic ${e.name}`+(e.actions.length>0?`: ${e.actions.map(r=>r.name).join(", ")}`:""))])}var Ws={switches:["--overwrite","--json"],values:["--test-file","--target","--agent","--topic","--guard-topic","--test-runner","--scenario","--project"]},Js=/^([a-z][a-z0-9-]*)=([^\s:=,]+)(?::([^\s:=]+))?$/;function Vs(t){let n=t.slice(2);Fe(n,Ws);let e=c=>{process.stderr.write(`${c}
10
10
  `),process.exit(2)},r=c=>{let p=n.indexOf(c);return p>=0&&p+1<n.length?n[p+1]:void 0},o=r("--test-file"),i=r("--target");(!o||!i)&&e("--test-file takes the file of a scenario run, or its run id, and --target the org it wrote to. Run with --help.");let s=[];for(let c=0;c<n.length;c++){if(n[c]!=="--topic")continue;let p=n[c+1]??"",g=Js.exec(p);g||e(`--topic wants "<scenario topic>=<agent topic>" or "<scenario topic>=<agent topic>:<action>,<action>", not "${p}".`);let[,R,A,b]=g;s.push({packTopic:R,agentTopic:A,actions:b?b.split(","):[]})}let d=r("--test-runner")??"testing-center";rt.includes(d)||e(`--test-runner takes ${rt.join(" or ")}, not "${d}".`);let u=r("--agent"),f=r("--scenario");return{run:o,target:i,...u!==void 0?{agent:u}:{},topics:s,guardTopic:r("--guard-topic")??null,runner:d,...f!==void 0?{scenario:f}:{},project:Ct(r("--project")??process.cwd()),overwrite:n.includes("--overwrite"),json:n.includes("--json")}}function Zs(t,n){if(ps(t)&&t.endsWith(".ndjson")){let e=Me(hs(t,"utf8"));if(e)return{runId:e.runId,storagePath:fs(fs(Ct(t))),targetOrgId:e.targetOrgId,...e.targetOrganizationId?{targetOrganizationId:e.targetOrganizationId}:{}}}return{runId:t,storagePath:n}}async function ys(t,n,e){let r=Vs(t),o=b=>{process[r.json?"stderr":"stdout"].write(`${b}
@@ -381,7 +381,7 @@ its file keeps what it created.
381
381
  `),process.exit(2));let p=e("--run-id");p!==void 0&&!so.test(p)&&r(`--run-id takes "env-" then lowercase letters, digits and hyphens, 200 characters at most, not "${p}".`);let g=f.map(m=>{let j=m.lastIndexOf(":"),y=j>0?m.slice(0,j):m,O=j>0?Number(m.slice(j+1)):NaN;return Es.test(y)||(process.stderr.write(`Not an SObject API name: "${y}"
382
382
  `),process.exit(2)),(!Number.isInteger(O)||O<1||O>1e5)&&(process.stderr.write(`--object wants "Name:<count>", not "${m}".
383
383
  `),process.exit(2)),{objectApiName:y,recordCount:O}}),R=Number(e("--batch-size","200")??"200");(!Number.isInteger(R)||R<1||R>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
384
- `),process.exit(2));let A=fo(n,r);A.length>0&&s&&r("--relation goes with --object: a built-in template carries its own links.");let b;if(n.includes("--seed")){let m=e("--seed");b=Number(m),(m===void 0||!/^\d+$/.test(m)||!Number.isSafeInteger(b)||b>Ae)&&r(`--seed takes a whole number from 0 to ${Ae}, not "${m??""}".`)}let E=e("--locale");n.includes("--locale")&&(E===void 0||!Dt.includes(E))&&r(`--locale takes one of ${Dt.join(", ")}, not "${E??""}".`);let x={};for(let m of o("--record-type")){let j=/^([A-Za-z][A-Za-z0-9_]{0,79})=([A-Za-z][A-Za-z0-9_]{0,79}(?:,[A-Za-z][A-Za-z0-9_]{0,79})*)$/.exec(m);j||r(`--record-type wants "Object=Name" or "Object=Name,Other", not "${m}".`);let[,y,O]=j;d===void 0&&!g.some(D=>D.objectApiName===y)&&r(`--record-type ${y}: give ${y} with --object too.`),x[y]=[...new Set(O.split(","))]}let z=mo(n,r),k=Gn(n);return{target:i,templateId:s,...d!==void 0?{templateFile:d}:{},...u!==void 0?{scenario:u}:{},...c!==void 0?{scenarioSeed:c}:{},...p!==void 0?{runId:p}:{},objects:po(g,A,r),relations:A,batchSize:R,dryRun:n.includes("--dry-run"),json:n.includes("--json"),failOnPartial:n.includes("--fail-on-partial"),muteAutomation:n.includes("--mute-automation"),acceptEmails:n.includes("--accept-emails"),...b!==void 0?{seed:b}:{},...E!==void 0?{locale:E}:{},recordTypes:x,...z?{fit:z}:{},...k!==void 0?{checkpointFirst:k}:{}}}var go=no(__dirname,"catalogue.en.json"),Ve;function wo(){if(Ve===void 0)try{Ve=JSON.parse(je(go,"utf8"))}catch{Ve=null}return Ve}function xs(t,n=wo()){if(!t.name.startsWith("seed.templates.")||!n)return t.name;let e=n;for(let r of t.name.split(".")){if(e===null||typeof e!="object")return t.name;e=e[r]}return typeof e=="string"&&e.trim()!==""?e:t.name}var bo=10;function yo(t,n){let e;try{e=je(t,"utf8")}catch(d){return{refusal:`--template-file ${t} cannot be read: ${d instanceof Error?d.message:String(d)}`}}let r;try{r=JSON.parse(e)}catch(d){return{refusal:`--template-file ${t} is not JSON: ${d instanceof Error?d.message:String(d)}`}}let o=bn.safeParse(r);if(!o.success){let{issues:d}=o.error,u=d.slice(0,bo).map(c=>` ${c.path.join(".")||"(the template)"}: ${c.message}`),f=d.length-u.length;return{refusal:[`--template-file ${t} is not a seed template the panel would run:`,...u,...f>0?[` and ${f} more`]:[]].join(`
384
+ `),process.exit(2));let A=fo(n,r);A.length>0&&s&&r("--relation goes with --object: a built-in template carries its own links.");let b;if(n.includes("--seed")){let m=e("--seed");b=Number(m),(m===void 0||!/^\d+$/.test(m)||!Number.isSafeInteger(b)||b>Ae)&&r(`--seed takes a whole number from 0 to ${Ae}, not "${m??""}".`)}let E=e("--locale");n.includes("--locale")&&(E===void 0||!Dt.includes(E))&&r(`--locale takes one of ${Dt.join(", ")}, not "${E??""}".`);let x={};for(let m of o("--record-type")){let j=/^([A-Za-z][A-Za-z0-9_]{0,79})=([A-Za-z][A-Za-z0-9_]{0,79}(?:,[A-Za-z][A-Za-z0-9_]{0,79})*)$/.exec(m);j||r(`--record-type wants "Object=Name" or "Object=Name,Other", not "${m}".`);let[,y,O]=j;d===void 0&&!g.some(L=>L.objectApiName===y)&&r(`--record-type ${y}: give ${y} with --object too.`),x[y]=[...new Set(O.split(","))]}let z=mo(n,r),k=Gn(n);return{target:i,templateId:s,...d!==void 0?{templateFile:d}:{},...u!==void 0?{scenario:u}:{},...c!==void 0?{scenarioSeed:c}:{},...p!==void 0?{runId:p}:{},objects:po(g,A,r),relations:A,batchSize:R,dryRun:n.includes("--dry-run"),json:n.includes("--json"),failOnPartial:n.includes("--fail-on-partial"),muteAutomation:n.includes("--mute-automation"),acceptEmails:n.includes("--accept-emails"),...b!==void 0?{seed:b}:{},...E!==void 0?{locale:E}:{},recordTypes:x,...z?{fit:z}:{},...k!==void 0?{checkpointFirst:k}:{}}}var go=no(__dirname,"catalogue.en.json"),Ve;function wo(){if(Ve===void 0)try{Ve=JSON.parse(je(go,"utf8"))}catch{Ve=null}return Ve}function xs(t,n=wo()){if(!t.name.startsWith("seed.templates.")||!n)return t.name;let e=n;for(let r of t.name.split(".")){if(e===null||typeof e!="object")return t.name;e=e[r]}return typeof e=="string"&&e.trim()!==""?e:t.name}var bo=10;function yo(t,n){let e;try{e=je(t,"utf8")}catch(d){return{refusal:`--template-file ${t} cannot be read: ${d instanceof Error?d.message:String(d)}`}}let r;try{r=JSON.parse(e)}catch(d){return{refusal:`--template-file ${t} is not JSON: ${d instanceof Error?d.message:String(d)}`}}let o=bn.safeParse(r);if(!o.success){let{issues:d}=o.error,u=d.slice(0,bo).map(c=>` ${c.path.join(".")||"(the template)"}: ${c.message}`),f=d.length-u.length;return{refusal:[`--template-file ${t} is not a seed template the panel would run:`,...u,...f>0?[` and ${f} more`]:[]].join(`
385
385
  `)}}let i=new Date().toISOString(),s=o.data;return{template:{...s,id:typeof s.id=="string"&&s.id!==""?s.id:`cli-${Date.now()}`,version:typeof s.version=="number"?s.version:1,createdAt:typeof s.createdAt=="string"?s.createdAt:i,updatedAt:typeof s.updatedAt=="string"?s.updatedAt:i,objects:o.data.objects.map(d=>({...d,batchSize:d.batchSize??n}))}}}function Ro(t,n){let e=Ot(t,n,Rt);return e===void 0?void 0:`--run-id ${t}: a run of that id is kept already, in ${e}. Give an id no run has.`}function So(t,n){for(let e of Object.keys(n)){let r=t.objects.find(o=>o.objectApiName===e);if(r===void 0)return`--record-type ${e}: the template file writes no ${e}; it writes ${t.objects.map(o=>o.objectApiName).join(", ")}.`;if(r.fieldRules.some(o=>o.fieldApiName==="RecordTypeId"))return`--record-type ${e}: the template file gives ${e} its record type already, by a RecordTypeId rule: give it in one place.`}}function ko(t){if(!t)return null;let n=Ne.find(e=>e.id===t);if(!n){let e=Ne.map(r=>r.id).join(", ");process.stderr.write(`No template "${t}". There is: ${e}
386
386
  `),process.exit(2)}return n}function vo(t,n,e="business"){let r=e==="person"&&n===de,o=t.filter(s=>s.createable&&!sn(n??"",s.name,r?"person":"business")&&(s.name==="Name"||$o(s)||r&&Ao.has(s.name)||!s.nillable&&s.defaultedOnCreate!==!0)),i=[];for(let s of o){let d=rn({fieldApiName:s.name,type:s.type,picklistValues:(s.picklistValues??[]).filter(u=>u.active!==!1&&typeof u.value=="string").map(u=>u.value),referenceTo:[],length:s.length??0,integerDigits:nn(s),objectApiName:n});d.ruleType==="static"&&d.config.staticValue===void 0||i.push({fieldApiName:s.name,fieldType:s.type,ruleType:d.ruleType,config:d.config})}return i}function $o(t){return(t.type==="email"||t.type==="phone")&&!t.name.includes("__")}var Ao=new Set(["FirstName","LastName"]),jo="SELECT DeveloperName FROM RecordType WHERE SobjectType = 'Account' AND IsPersonType = true";async function Oo(t){try{let n=await t.query(jo);return new Set(n.records.flatMap(e=>typeof e.DeveloperName=="string"?[e.DeveloperName]:[]))}catch{return new Set}}function Io(t,n){let e=t.filter(o=>n.has(o));if(e.length===0)return{kind:"business"};if(e.length===t.length)return{kind:"person"};let r=t.filter(o=>!n.has(o));return{refusal:`--record-type ${de}: ${e.join(", ")} ${e.length===1?"is a person account record type":"are person account record types"} and ${r.join(", ")} ${r.length===1?"is":"are"} not: a person account and a business account take different fields. Seed one kind in a run.`}}function To(t){return` ${de}: ${t.join(", ")} ${t.length===1?"is a person account record type":"are person account record types"}: the accounts are written as person accounts, with a first and last name, the person\u2019s email and phones, and no Name, which the org builds from the two names`}function $s(t,n,e){let r=ut(e).filter(s=>!s.master),o=r.filter(s=>s.active&&s.available),i=[];for(let s of n){let d=r.find(u=>u.developerName===s);if(!d||!d.active||!d.available){let u=o.map(f=>f.developerName).join(", ")||"none";return{refusal:`--record-type ${t}=${s}: `+(d?d.active?`the running user may not use record type ${s}`:`record type ${s} is inactive`:`${t} has no record type ${s}`)+`. Open to them: ${u}.`}}i.push(d.recordTypeId)}return{rule:i.length===1?{fieldApiName:"RecordTypeId",fieldType:"reference",ruleType:"static",config:{staticValue:i[0]}}:{fieldApiName:"RecordTypeId",fieldType:"reference",ruleType:"picklist_random",config:{picklistValues:i}}}}function Eo(t,n){let e=ut(n).filter(i=>!i.master&&i.active&&i.available);if(e.length<2)return;let r=e.find(i=>i.defaultRecordTypeMapping),o=Dn()?.startsWith("sandforge env")===!0?`the resource's recordTypes for ${t}, in the file, chooses`:`${Ln("--record-type")} ${t}=<Name> chooses`;return` ${t}: ${e.length} record types open to you (${e.map(i=>i.developerName).join(", ")}); the records take ${r?`your default, ${r.developerName}`:"your default"}: ${o}`}function xo(t){switch(t.mode){case"perParent":return`${t.count} per parent`;case"range":return`${t.min} to ${t.max} per parent`;case"ratio":return`${t.ratio} per parent on average`;case"byKey":return"each under the parent row its key names"}}function Co(t){return new $r({...t.signal?{signal:t.signal}:{},...t.onRowIds?{onRowIds:t.onRowIds}:{},...t.knowledge?{knowledge:t.knowledge}:{},validator:new Pr,readExistingParentIds:t.readExistingParentIds,...t.readPresentParentIds?{readPresentParentIds:t.readPresentParentIds}:{},...t.describeKeyPrefix?{describeKeyPrefix:t.describeKeyPrefix}:{},describeCreateableFields:t.describeCreateableFields,...t.describeVisibleFields?{describeVisibleFields:t.describeVisibleFields}:{},...t.describeComputedFields?{describeComputedFields:t.describeComputedFields}:{},...t.describePicklistValues?{describePicklistValues:t.describePicklistValues}:{},...t.describeFieldLengths?{describeFieldLengths:t.describeFieldLengths}:{},...t.describeRequiredFields?{describeRequiredFields:t.describeRequiredFields}:{},...t.objectAccess?{objectAccess:t.objectAccess}:{},...t.readTarget?{readTarget:t.readTarget}:{},...t.update?{update:t.update}:{},planBuilder:new Nr,fieldMapper:new _r({aiGenerator:new Fr(()=>{throw new Error("This template has an AI field rule. sandforge seed runs without an AI key: use the panel for it, or replace the rule with a faker one.")}),fakerFallback:new Lr(t.locale,{random:Ft(t.seed^oo)}),random:Ft(t.seed^ao)}),referenceLinker:new Dr,insert:t.insert,generateId:()=>`cli-${Math.random().toString(36).slice(2)}`,now:()=>new Date().toISOString(),random:Ft(t.seed)})}function Po(t,n,e){return t<=n?"(REST)":e===!0?"(REST: an active duplicate rule watches the object, which a Bulk API job cannot waive)":e===!1?"(a Bulk API job)":"(a Bulk API job, or REST when an active duplicate rule watches the object)"}function No(t,n){return Ir(t,n)}async function Fo(t){let n=await Zr({org:t.target,objects:t.objects.map(r=>r.objectApiName),readAutomation:t.readAutomation,readLimits:t.readLimits}),e=Xr(n,t.objects,t.target);return{lines:[...Qr(n,t.target),...Nn(e.checks,t.target),...(e.unknown??[]).map(r=>` emails: ${r}`)],gate:e}}function _o(t,n,e,r){return{storage:{bytes:Or(t,n),...e.check,...e.refusedFor==="storage"?{refusal:e.refusal}:{}},apiRequests:Cs(e,r)}}function Cs(t,n){return{...t.api,...n!==void 0?{sent:n}:{},...t.refusedFor==="apiRequests"?{refusal:t.refusal}:{}}}function Do(t){switch(t.kind){case"trigger":return`what Apex trigger ${t.name} on ${t.objectApiName} creates`;case"notRead":return`what "${t.name}" on ${t.objectApiName} creates: it was not read`;case"share":return`the ${t.name} rows the flows of ${t.objectApiName} create`}}function Lo(t){return`${Math.floor(t*1e3)/10} %`}function As(t,n,e){let{proposal:r}=t,o=r.budget,i=e.applied?"fit":"--fit share would seed";if(r.cannotFit!==void 0)return[`${i}: the seed cannot be fitted: ${r.cannotFit}`];if(t.heldBy==="whole")return[`${i}: the seed fits as it is, ${t.records} records, about ${ke(r.estimateMB)} MB: nothing cut`];let s=ke(o.budgetMB+o.automationMB),d=t.heldBy==="apiRequests"?`the largest whose writes leave ${n} a tenth of its daily API requests`:t.heldBy==="within"?`the largest that fits the ${o.withinMB??s} MB asked (--fit-within)`:`the largest that fits ${s} MB: ${o.share*100} % of the ${o.remainingMB} MB ${n} says it has left of ${o.maxMB}, ${o.roundingMB} MB kept first for the rounding of what it says`,u=e.roomUnread!==void 0?`no room kept for what its automation creates: it could not be read (${e.roomUnread})`:o.automationMB>0?`${ke(o.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(e.muted?" (--mute-automation keeps the others quiet)":""),f=Math.max(...r.objects.map(c=>c.objectApiName.length));return[t.heldBy==="caps"?`${i}: the caps asked, within the ${s} MB that fit; ${u}`:`${i}: share ${Lo(r.share)}, ${d}; ${u}`,...r.objects.map(c=>` ${c.objectApiName.padEnd(f)} ${c.after} of ${c.before}`+(c.keptWhole==="rows"?" (kept whole: the rows the template gives)":c.keptWhole==="byKey"?" (kept whole: each under the parent row its key names)":"")),...(o.notCounted??[]).map(c=>` not counted: ${Do(c)}`),` fitted seed: ${t.records} records, about ${ke(r.estimateMB)} MB`+(o.automationMB>0?" with what its flows create under them":"")+`, ${t.requests} API requests`,` ${_n(n)}`]}function Mo(t,n,e){return{applied:n,...t.proposal,heldBy:t.heldBy,records:t.records,requests:t.requests,...e?.caps?{caps:e.caps}:{},...e?.withinMB!==void 0?{withinMB:e.withinMB}:{}}}async function Bo(t=process.argv){if(t.slice(2).includes("--remove"))return Yo(t);if(t.slice(2).includes("--test-file"))return(t.slice(2).includes("--help")||t.slice(2).includes("-h"))&&vs(t),ys(t,Uo,ce());let n=Date.now(),e=vs(t),r;if(e.scenario!==void 0){let a=Pt(e.scenario);"refusal"in a&&(process.stderr.write(`${a.refusal}
387
387
  `),process.exit(2)),r=a.pack}let o;if(e.templateFile!==void 0){let a=yo(e.templateFile,e.batchSize);"refusal"in a&&(process.stderr.write(`${a.refusal}
@@ -391,18 +391,18 @@ its file keeps what it created.
391
391
  `)},d=e.seed??Xs(0,Ae+1),u=new Date().toISOString();s(`sandforge seed -> ${e.target}`),s(`seed: ${d} (--seed ${d} draws the same again)`);let f=await be(e.target),c=ue(f),p=[it(c)],g=()=>p.reduce((a,l)=>a+l(),0),R=e.dryRun?void 0:await ln(c,e.target,{tool:"sandforge seed",action:"write",readOnly:"--dry-run"}),A=await zr(e.locale,c),b=a=>c.sobject(a).describe(),E=new Map,x=a=>{let l=E.get(a);return l||(l=b(a),E.set(a,l)),l};s(`locale: ${A}${e.locale?"":" (the org's; --locale draws in another)"}`);let z=new Date().toISOString(),k=o??ko(e.templateId),m;if(r!==void 0){let a=await ms({query:async l=>(await c.query(l)).records,objectAccess:Tt(c),describe:l=>c.sobject(l).describe()},r,e.scenarioSeed);"issues"in a&&(process.stderr.write(`The scenario cannot be compiled: ${a.issues.join("; ")}
392
392
  `),process.exit(2)),m=a,k=a.compiled.template;for(let l of gs(r,a.preparation))s(l)}for(let a of e.relations){let l=a.parents.kind==="generated"?`the ${a.parentObject} records this run writes`:a.parents.kind==="records"?`the ${a.parents.ids.length} ${a.parentObject} records named by id`:`at most ${a.parents.limit} ${a.parentObject} records already in the org`+(a.parents.where?` where ${a.parents.where}`:""),h=e.objects.find(T=>T.objectApiName===a.childObject)?.recordCount;s(` relation ${a.childObject}.${a.lookupField}: up to ${h} record(s), ${xo(a.distribution)}, over ${l}`)}let j=[],y=[];if(o!==void 0&&Object.keys(e.recordTypes).length>0){let a=[];for(let l of o.objects){let h=e.recordTypes[l.objectApiName];if(!h){a.push(l);continue}let T=await x(l.objectApiName),C=$s(l.objectApiName,h,T.recordTypeInfos);"refusal"in C&&(process.stderr.write(`${C.refusal}
393
393
  `),process.exit(2)),a.push({...l,fieldRules:[...l.fieldRules,C.rule]})}o={...o,objects:a},k=o}if(o?.objects.some(a=>a.objectApiName===de)){let a=Br(o,await Mr(c));"refusal"in a&&(process.stderr.write(`${a.refusal}
394
- `),process.exit(2)),k=a.template,y.push(...a.personObjects);for(let l of a.personObjects){let h=` ${l}: the template gives it person account record types: the accounts are written as person accounts, without Name, which the org builds from the two names`;s(h),j.push(h.trim())}}if(!k){let a=[];for(let[l,h]of e.objects.entries()){let T=await x(h.objectApiName),C=e.recordTypes[h.objectApiName],ie="business";if(C&&h.objectApiName===de){let _=Io(C,await Oo(c));if("refusal"in _&&(process.stderr.write(`${_.refusal}
395
- `),process.exit(2)),ie=_.kind,ie==="person"){y.push(de);let Yt=To(C);s(Yt),j.push(Yt.trim())}}let Pe=T.createable===!1,Qt=T.fields,tt=vo(Pe?Qt.map(_=>({..._,createable:!0})):Qt,h.objectApiName,ie);if(C){let _=$s(h.objectApiName,C,T.recordTypeInfos);"refusal"in _&&(process.stderr.write(`${_.refusal}
396
- `),process.exit(2)),tt.push(_.rule)}else{let _=Eo(h.objectApiName,T.recordTypeInfos);_&&s(_)}s(Pe?` ${h.objectApiName}: the user this seed runs as may not create its records: skipped (give that user Create on it in a permission set)`:` ${h.objectApiName}: ${tt.map(_=>_.fieldApiName).join(", ")||"(none)"}`),a.push({objectApiName:h.objectApiName,recordCount:h.recordCount,fieldRules:tt,excludedFields:[],insertOrder:l,batchSize:e.batchSize})}k={id:`cli-${Date.now()}`,name:"sandforge seed",description:"Headless run",version:1,strategy:"faker",objects:a,...e.relations.length>0?{relations:e.relations}:{},tags:["cli"],createdAt:z,updatedAt:z}}for(let a of Object.keys(e.fit?.caps?.objects??{}))k.objects.some(l=>l.objectApiName===a)||(process.stderr.write(`--fit-cap ${a}: the seed writes no ${a}.
397
- `),process.exit(2));let O=await ve(c).read(e.target,k.objects.map(a=>a.objectApiName)).catch(a=>({unread:a instanceof Error?a.message:String(a)})),D=Wr(k,m!==void 0),v=(a,l=[])=>{throw e.json&&process.stdout.write(hn({tool:"sandforge-seed",target:e.target,elapsedMs:K(n)},a,l)),new Error([a,...l].map(Le).join(`
398
- `))},I,L;if(e.muteAutomation)try{I=await mt(async()=>ht(c),O,{writes:D});for(let a of fe(I.muted,e.target))s(` ${a}`)}catch(a){if(!Re(a))throw a;L=a.refusal,e.dryRun&&s(` ${Y(a.refusal)}`)}let M=await Vr(k,O,Ke(x).unset),U=Jr(O,I?.plan,D,M),Z={...U.unread!==void 0?{roomUnread:U.unread}:{},muted:(I?.plan?.assign.length??0)>0},H=e.runId??`sandforge-seed-${Qs()}`,X=e.checkpointFirst?Jn({module:"seed",operationId:H,request:e.checkpointFirst,session:f,org:Wn(f,R??await we(c)),connect:a=>{let l=ue(a);return p.push(it(l)),l},journalDir:ce(),say:s,own:{runId:H}}):void 0,G,ee=[],te=a=>{let l={code:Se,message:a};ee.push(l),e.dryRun&&s(` ${Y(l)}`)},pe=k.objects.filter(a=>a.recordCount>0);if(X&&pe.length>0){let a={written:pe.map(l=>l.objectApiName),running:U.running??{firing:[]}};try{G={ask:a,estimate:await X.scope(a)}}catch(l){te(En(l))}}let W=await On({read:O,...I?.plan?{plan:I.plan}:{},writes:D,readDeliverability:async()=>cn(R??await we(c))?An:jn(c),accepted:e.acceptEmails===!0,target:e.target,run:"seed",keepsAddresses:!0,mayMute:e.muteAutomation!==!0&&Ue("--mute-automation")}),w=Fn(W.ofRun),$={...w,...In(I?.plan)},N=Tt(c),S=await Ur(k,N),he=()=>g()-(w.deliverability??0),J=Ke(x),_s=await jr(S,{describeCreateableFields:J.createable,describeRequiredFields:It(J,y)}),ne={duplicateRules:Mn(O),slices:_s,bulkThreshold:nt.bulk.threshold,typedFirst:e.dryRun,sentBefore:he()},F=await $t(c,S,y,e.target,G?.estimate,$,ne,U.room),me,Ze,Lt=a=>{Ze=a,e.dryRun&&s(` ${Y(a)}`)};if(e.fit&&F.refusedFor!=="checkpoint"&&ee.length===0){let a=At(F,e.fit.withinMB);if("unread"in a)Lt({code:Kr,message:`The seed was refused before it wrote anything: it cannot be fitted to ${e.target}, whose data storage left could not be read (${a.unread}): give --fit-within <MB>, the most it may take, to fit it to that. Nothing was written.`});else{let l=xt({template:S,personObjects:y,budget:a,room:U.room,ask:e.fit,path:ne});me={applied:!0,fit:l};for(let h of As(l,e.target,{applied:!0,...Z}))s(h);l.proposal.cannotFit!==void 0?Lt({code:Gr,message:`The seed was refused before it wrote anything: it cannot be fitted to ${e.target}: ${l.proposal.cannotFit}. Nothing was written.`}):l.heldBy!=="whole"&&(k=Et(k,l.proposal),S=Et(S,l.proposal),ne={...ne,sentBefore:he()},F=await $t(c,S,y,e.target,G?.estimate,$,ne,U.room))}}s(No(F.check,e.target));let Oe;if(G)for(let a of Vn(G.estimate))s(a);if(F.refusedFor==="checkpoint")te(ze({code:Se,message:F.refusal??"",...F.checkpointRefusal?{refusal:F.checkpointRefusal}:{}}));else if(F.refusal){if(!e.fit){let a=At(F);if(!("unread"in a)){let l=xt({template:S,personObjects:y,budget:a,room:U.room,path:ne});me={applied:!1,fit:l};for(let h of As(l,e.target,{applied:!1,...Z}))s(` ${h}`)}}Oe={code:F.refusedFor==="apiRequests"?xn:Tr,message:F.refusal},e.dryRun&&s(` ${Y(Oe)}`)}let re=await Fo({target:e.target,objects:k.objects,readAutomation:async()=>{let a=I?.automation??O;if(typeof a.unread=="string")throw new Error(a.unread);return a},readLimits:()=>Pn(c)});for(let a of re.lines)s(a);W.gate.line!==void 0&&s(` ${W.gate.line}`);let Ie=re.gate.refusal!==void 0?{code:Hr,message:re.gate.refusal}:void 0;Ie&&e.dryRun&&s(` ${Y(Ie)}`);let ge=W.gate.stop;ge&&e.dryRun&&s(` ${Y(ge)}`);let Mt=[...L!==void 0?[L]:[],...ee,...Ze!==void 0?[Ze]:[],...Oe!==void 0?[Oe]:[],...Ie!==void 0?[Ie]:[],...ge?[ge]:[]],[Bt,...Ds]=Mt;!e.dryRun&&Bt!==void 0&&v(Bt,Ds),s(`template: ${xs(k)} (${k.objects.length} object(s))`);let Ut=e.dryRun?void 0:qn(ce()),V=Ut?.recorder({runId:H,targetOrgId:R?.id??e.target,targetAlias:e.target,startedAt:u,...R?{targetOrganizationId:R.id}:{}});Un(V,()=>c.identity(),"sandforge seed");let q=Ut?.pathOf(H),se=new AbortController,He,Ls=a=>{He=a,process.stderr.write(`
394
+ `),process.exit(2)),k=a.template,y.push(...a.personObjects);for(let l of a.personObjects){let h=` ${l}: the template gives it person account record types: the accounts are written as person accounts, without Name, which the org builds from the two names`;s(h),j.push(h.trim())}}if(!k){let a=[];for(let[l,h]of e.objects.entries()){let T=await x(h.objectApiName),C=e.recordTypes[h.objectApiName],ie="business";if(C&&h.objectApiName===de){let D=Io(C,await Oo(c));if("refusal"in D&&(process.stderr.write(`${D.refusal}
395
+ `),process.exit(2)),ie=D.kind,ie==="person"){y.push(de);let Yt=To(C);s(Yt),j.push(Yt.trim())}}let Pe=T.createable===!1,Qt=T.fields,tt=vo(Pe?Qt.map(D=>({...D,createable:!0})):Qt,h.objectApiName,ie);if(C){let D=$s(h.objectApiName,C,T.recordTypeInfos);"refusal"in D&&(process.stderr.write(`${D.refusal}
396
+ `),process.exit(2)),tt.push(D.rule)}else{let D=Eo(h.objectApiName,T.recordTypeInfos);D&&s(D)}s(Pe?` ${h.objectApiName}: the user this seed runs as may not create its records: skipped (give that user Create on it in a permission set)`:` ${h.objectApiName}: ${tt.map(D=>D.fieldApiName).join(", ")||"(none)"}`),a.push({objectApiName:h.objectApiName,recordCount:h.recordCount,fieldRules:tt,excludedFields:[],insertOrder:l,batchSize:e.batchSize})}k={id:`cli-${Date.now()}`,name:"sandforge seed",description:"Headless run",version:1,strategy:"faker",objects:a,...e.relations.length>0?{relations:e.relations}:{},tags:["cli"],createdAt:z,updatedAt:z}}for(let a of Object.keys(e.fit?.caps?.objects??{}))k.objects.some(l=>l.objectApiName===a)||(process.stderr.write(`--fit-cap ${a}: the seed writes no ${a}.
397
+ `),process.exit(2));let O=await ve(c).read(e.target,k.objects.map(a=>a.objectApiName)).catch(a=>({unread:a instanceof Error?a.message:String(a)})),L=Wr(k,m!==void 0),v=(a,l=[])=>{throw e.json&&process.stdout.write(hn({tool:"sandforge-seed",target:e.target,elapsedMs:K(n)},a,l)),new Error([a,...l].map(Le).join(`
398
+ `))},I,M;if(e.muteAutomation)try{I=await mt(async()=>ht(c),O,{writes:L});for(let a of fe(I.muted,e.target))s(` ${a}`)}catch(a){if(!Re(a))throw a;M=a.refusal,e.dryRun&&s(` ${Y(a.refusal)}`)}let F=await Vr(k,O,Ke(x).unset),U=Jr(O,I?.plan,L,F),Z={...U.unread!==void 0?{roomUnread:U.unread}:{},muted:(I?.plan?.assign.length??0)>0},H=e.runId??`sandforge-seed-${Qs()}`,X=e.checkpointFirst?Jn({module:"seed",operationId:H,request:e.checkpointFirst,session:f,org:Wn(f,R??await we(c)),connect:a=>{let l=ue(a);return p.push(it(l)),l},journalDir:ce(),say:s,own:{runId:H}}):void 0,G,ee=[],te=a=>{let l={code:Se,message:a};ee.push(l),e.dryRun&&s(` ${Y(l)}`)},pe=k.objects.filter(a=>a.recordCount>0);if(X&&pe.length>0){let a={written:pe.map(l=>l.objectApiName),running:U.running??{firing:[]}};try{G={ask:a,estimate:await X.scope(a)}}catch(l){te(En(l))}}let W=await On({read:O,...I?.plan?{plan:I.plan}:{},writes:L,readDeliverability:async()=>cn(R??await we(c))?An:jn(c),accepted:e.acceptEmails===!0,target:e.target,run:"seed",keepsAddresses:!0,mayMute:e.muteAutomation!==!0&&Ue("--mute-automation")}),w=Fn(W.ofRun),$={...w,...In(I?.plan)},N=Tt(c),S=await Ur(k,N),he=()=>g()-(w.deliverability??0),J=Ke(x),_s=await jr(S,{describeCreateableFields:J.createable,describeRequiredFields:It(J,y)}),ne={duplicateRules:Mn(O),slices:_s,bulkThreshold:nt.bulk.threshold,typedFirst:e.dryRun,sentBefore:he()},_=await $t(c,S,y,e.target,G?.estimate,$,ne,U.room),me,Ze,Lt=a=>{Ze=a,e.dryRun&&s(` ${Y(a)}`)};if(e.fit&&_.refusedFor!=="checkpoint"&&ee.length===0){let a=At(_,e.fit.withinMB);if("unread"in a)Lt({code:Kr,message:`The seed was refused before it wrote anything: it cannot be fitted to ${e.target}, whose data storage left could not be read (${a.unread}): give --fit-within <MB>, the most it may take, to fit it to that. Nothing was written.`});else{let l=xt({template:S,personObjects:y,budget:a,room:U.room,ask:e.fit,path:ne});me={applied:!0,fit:l};for(let h of As(l,e.target,{applied:!0,...Z}))s(h);l.proposal.cannotFit!==void 0?Lt({code:Gr,message:`The seed was refused before it wrote anything: it cannot be fitted to ${e.target}: ${l.proposal.cannotFit}. Nothing was written.`}):l.heldBy!=="whole"&&(k=Et(k,l.proposal),S=Et(S,l.proposal),ne={...ne,sentBefore:he()},_=await $t(c,S,y,e.target,G?.estimate,$,ne,U.room))}}s(No(_.check,e.target));let Oe;if(G)for(let a of Vn(G.estimate))s(a);if(_.refusedFor==="checkpoint")te(ze({code:Se,message:_.refusal??"",..._.checkpointRefusal?{refusal:_.checkpointRefusal}:{}}));else if(_.refusal){if(!e.fit){let a=At(_);if(!("unread"in a)){let l=xt({template:S,personObjects:y,budget:a,room:U.room,path:ne});me={applied:!1,fit:l};for(let h of As(l,e.target,{applied:!1,...Z}))s(` ${h}`)}}Oe={code:_.refusedFor==="apiRequests"?xn:Tr,message:_.refusal},e.dryRun&&s(` ${Y(Oe)}`)}let re=await Fo({target:e.target,objects:k.objects,readAutomation:async()=>{let a=I?.automation??O;if(typeof a.unread=="string")throw new Error(a.unread);return a},readLimits:()=>Pn(c)});for(let a of re.lines)s(a);W.gate.line!==void 0&&s(` ${W.gate.line}`);let Ie=re.gate.refusal!==void 0?{code:Hr,message:re.gate.refusal}:void 0;Ie&&e.dryRun&&s(` ${Y(Ie)}`);let ge=W.gate.stop;ge&&e.dryRun&&s(` ${Y(ge)}`);let Mt=[...M!==void 0?[M]:[],...ee,...Ze!==void 0?[Ze]:[],...Oe!==void 0?[Oe]:[],...Ie!==void 0?[Ie]:[],...ge?[ge]:[]],[Bt,...Ds]=Mt;!e.dryRun&&Bt!==void 0&&v(Bt,Ds),s(`template: ${xs(k)} (${k.objects.length} object(s))`);let Ut=e.dryRun?void 0:qn(ce()),V=Ut?.recorder({runId:H,targetOrgId:R?.id??e.target,targetAlias:e.target,startedAt:u,...R?{targetOrganizationId:R.id}:{}});Un(V,()=>c.identity(),"sandforge seed");let q=Ut?.pathOf(H),se=new AbortController,He,Ls=a=>{He=a,process.stderr.write(`
399
399
  interrupted: the seed stops before its next call to the org, and says what it wrote
400
400
  `),se.abort()},Te=nt,zt=new Map,qt=!1,Ms=pr({conn:c,bulkThreshold:Te.bulk.threshold,bulkManager:new wn(Te.bulk.maxConcurrentJobs),retry:new fr({retryConfig:Te.retry,signal:se.signal}),signal:se.signal,label:"sandforge seed",log:a=>s(` ${a}`),onProgress:(a,l,h)=>{let T=l>0?Math.floor(a/l*10):10;(zt.get(h)??-1)>=T||(zt.set(h,T),s(` ${h}: ${a} of ${l}`))},...V?{calls:{sending:(a,l,h)=>V.sending(a,l,h),answered:(a,l)=>V.answered(a,l)}}:{}}),Ee=e.dryRun?Sr():void 0,Bs=0,Us=async(a,l,h,T)=>{if(e.dryRun){s(` [dry-run] ${l}: ${h.length} record(s) `+Po(h.length,Te.bulk.threshold,Ar(ne.duplicateRules,l)));let ie=h.map(()=>`dry-${Bs++}`);return Ee?.inserted(l,h,ie),{successIds:ie,errors:[],rows:ie.map(Pe=>({id:Pe}))}}h.length>0&&(qt=!0);let C=await Ms(a,l,h,T);return V?.note(l,C.successIds),s(` ${l}: ${C.successIds.length} written, ${C.errors.length} refused`+(C.stopped?", stopped":"")),C},oe=Ke(a=>c.sobject(a).describe()),Kt={},zs=Co({readExistingParentIds:(a,l,h)=>yr(c,a,l,h),readPresentParentIds:(a,l)=>Rr(c,a,l),describeKeyPrefix:oe.keyPrefix,describeCreateableFields:oe.createable,describeVisibleFields:oe.visible,describeComputedFields:oe.computed,describePicklistValues:oe.picklistValues,describeFieldLengths:oe.lengths,describeRequiredFields:It(oe,y),objectAccess:N,insert:Us,...Ee?{readTarget:Ee.readTarget,update:async(a,l,h)=>(s(` [dry-run] ${l}: ${h.length} record(s) the platform writes with their opportunity, given the fields generated for them (REST update)`),Ee.update(a,l,h))}:vr(c),seed:d,locale:A,signal:se.signal,...m?{onRowIds:(a,l)=>{a==="Case"&&Object.assign(Kt,l)}}:{},...m&&!e.dryRun?{knowledge:qr({org:c,plan:{publish:!0,links:m.compiled.closedCaseArticles},...V?{journal:V}:{},signal:se.signal})}:{}});s(e.dryRun?`
401
401
  executing\u2026 (DRY-RUN)`:`
402
402
  executing\u2026 (REAL)`),q!==void 0&&s(`run file: ${q} (--remove ${q} takes back what the run creates)`);let qs=e.dryRun?()=>{}:De(Ls),B,Xe,Gt=a=>{Xe=a instanceof Error?a.message:String(a)},ae=I?.muted,Qe,Ye,Wt=async()=>{!X||!Qe||Ye||(Ye=await Hn(X,Qe,qt,e.target,s))};try{if(!e.dryRun&&X&&G){let h=G,T=await Cn(()=>X.take(h.ask,h.estimate,{signal:se.signal}));if("stop"in T){T.stop.code===Se&&v({code:Se,message:ze(T.stop)}),process.stderr.write(`${ze(T.stop)}
403
403
  `),dt(_e(He??"SIGINT"));return}Qe=T.checkpoint,V?.checkpoint?.(T.checkpoint);for(let C of Zn(T.checkpoint,e.target,e.muteAutomation===!0))s(C)}let a=!e.dryRun&&I?.prepared?await I.prepared.acquire(H).catch(h=>{if(!Re(h))throw h;return v(h.refusal)}):void 0;a&&(ae=a.outcome);let l=a?W.afterLease(a.outcome,e.acceptEmails===!0):void 0;if(a&&l){ae=await a.release();for(let h of fe(ae,e.target))s(h);v(l)}B=await zs.execute(k,e.target,H).finally(async()=>{if(a){ae=await a.release();for(let h of fe(ae,e.target))s(h)}}),ae&&!e.dryRun&&(B={...B,mutedAutomation:ae}),await Wt()}catch(a){throw await V?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(Gt),await Wt(),q!==void 0&&Rs(q)&&process.stderr.write(`the seed stopped on an error; what it created is kept in ${q}, and --remove ${q} takes it back
404
404
  `),a}finally{qs()}await V?.end({finishedAt:new Date().toISOString(),status:B.status,...B.cancelled?{cancelled:!0}:{},objectResults:B.objectResults}).catch(Gt),Xe!==void 0&&process.stderr.write(`what the run created could not all be written to ${q??"its file"} (${Xe}): --remove takes it back from the --json summary
405
- `);let Q=q!==void 0&&Rs(q)?q:void 0,xe=m&&r&&Q!==void 0?await bs({journalDir:ce(),runId:H,pack:r,compiled:m.compiled,options:m.options,caseIds:Kt}):void 0,Jt=xe?.companion!==void 0?await Ge(We(Ps(c))).catch(()=>{}):void 0,Vt=K(n),Ce=se.signal.aborted;dt(Ce?_e(He??"SIGINT"):un(B.status,e.failOnPartial));let et=B.objectResults.reduce((a,l)=>a+l.createdIds.length,0),Zt=!e.dryRun&&et>0?R?.id??await Ns(c):void 0,Ht=e.dryRun?G?.estimate:Ye,Xt=re.gate.refusal??ge?.message,Ks=Mt;if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-seed",target:e.target,...Zt?{targetOrgId:Zt}:{},dryRun:e.dryRun,seed:d,startedAt:u,finishedAt:new Date().toISOString(),...j.length>0?{notes:j}:{},emails:{checks:re.gate.checks,...Xt!==void 0?{refusal:Xt}:{},...re.gate.unknown?{unknown:re.gate.unknown}:{},...W.gate.deliverability?{deliverability:W.gate.deliverability}:{}},...e.dryRun?_o(S,y,F,g()):{apiRequests:Cs(F,g())},...me?{fit:Mo(me.fit,me.applied,e.fit)}:{},...e.dryRun?Tn(I):{},...Ht?{checkpoint:Ht}:{},...pn(Ks),result:B,...Q?{runFile:Q}:{},...m&&r?{scenario:{packId:r.id,options:m.options,tests:m.compiled.tests.length,...xe??{},...Jt?.kind==="no-agent"?{agents:"none"}:{}}}:{},elapsedMs:Vt,...Ce?{interrupted:!0}:{}},null,2)}
405
+ `);let Q=q!==void 0&&Rs(q)?q:void 0,xe=m&&r&&Q!==void 0?await bs({journalDir:ce(),runId:H,pack:r,compiled:m.compiled,options:m.options,caseIds:Kt}):void 0,Jt=xe?.companion!==void 0?await Ge(We(Ps(c))).catch(()=>{}):void 0,Vt=K(n),Ce=se.signal.aborted;dt(Ce?_e(He??"SIGINT"):un(B.status,e.failOnPartial));let et=B.objectResults.reduce((a,l)=>a+l.createdIds.length,0),Zt=!e.dryRun&&et>0?R?.id??await Ns(c):void 0,Ht=e.dryRun?G?.estimate:Ye,Xt=re.gate.refusal??ge?.message,Ks=Mt;if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-seed",target:e.target,...Zt?{targetOrgId:Zt}:{},dryRun:e.dryRun,seed:d,startedAt:u,finishedAt:new Date().toISOString(),...j.length>0?{notes:j}:{},emails:{checks:re.gate.checks,...Xt!==void 0?{refusal:Xt}:{},...re.gate.unknown?{unknown:re.gate.unknown}:{},...W.gate.deliverability?{deliverability:W.gate.deliverability}:{}},...e.dryRun?_o(S,y,_,g()):{apiRequests:Cs(_,g())},...me?{fit:Mo(me.fit,me.applied,e.fit)}:{},...e.dryRun?Tn(I):{},...Ht?{checkpoint:Ht}:{},...pn(Ks),result:B,...Q?{runFile:Q}:{},...m&&r?{scenario:{packId:r.id,options:m.options,tests:m.compiled.tests.length,...xe??{},...Jt?.kind==="no-agent"?{agents:"none"}:{}}}:{},elapsedMs:Vt,...Ce?{interrupted:!0}:{}},null,2)}
406
406
  `),Ce&&process.stderr.write(`${Os(Q)}
407
407
  `);return}s(`
408
408
  status: ${String(B.status??"unknown")}`),s(`created: ${String(B.totalRecordsCreated??0)}`);for(let a of B.objectResults??[]){s(` ${a.objectApiName}: ${a.recordsCreated} created, ${a.recordsFailed} failed`);let l=kr(a.writtenByThePlatform);l!==void 0&&s(` ${l}`);for(let h of qo(a.errors??[]))s(` ${h}`)}for(let a of ws(B.knowledge))s(a);if(s(`seed: ${d}`),!e.dryRun&&et>0&&s(`
@@ -430,12 +430,12 @@ scenario ${t.packId}: ${t.openCasesWritten} of its ${t.openCases} open case(s) w
430
430
  `);for(let J of vt($,e))r(J);return}for(let J of S?sr(S):[])r(J);for(let J of xr(w,$))r(J);for(let J of vt($,e))r(J);r(`
431
431
  done in ${K(n)}ms`)},c=i.runs!==void 0&&(d.jobs??[]).length>0;if(Be(d).length===0&&!c&&!e.sweep&&!e.sweepList){r(s?.undo?`what the run created was removed already, on ${s.undo.removedAt}`:"The run created nothing: there is nothing of it to remove."),f("success",[],0);return}let p=await be(e.target),g=ue(p),R=await we(g),A=e.sweepList?void 0:jt(e.target,R,"sandforge seed");if(A&&v({code:"PRODUCTION_TARGET",message:A}),i.targetOrgId!==void 0&&i.targetOrgId.slice(0,15)!==R.id.slice(0,15)&&v({code:ct,message:`${e.target} is not the org the run wrote to (${i.targetOrgId}), and what it created is removed from that org only. Nothing was deleted.`}),c&&i.runs){let w=i.runs,$=await mr(w,d,g,()=>ye(g,"sandforge seed --remove").serverTime());for(let N of Cr($,e.target))r(N);$.some(N=>N.answered)&&(d=await w.get(d.runId)??d)}let b=Be(d),E=w=>Fs(g,e.target,R.id,d,i,w);if(e.sweepList){let w=await yt(qe(g,"sandforge seed --sweep-list"),await E(),s?.removalSpans??[]);for(let $ of $e(w,e.target,e,!0))r($);e.json?process.stdout.write(`${JSON.stringify({tool:"sandforge-seed",action:"sweep-list",summary:e.summaryPath,target:e.target,listing:w,elapsedMs:K(n)},null,2)}
432
432
  `):r(`
433
- done in ${K(n)}ms`),w.refusal!==void 0&&process.exit(Ts);return}r(`sandforge seed --remove ${e.summaryPath} from ${e.target}`);for(let{objectApiName:w,ids:$}of b)r(` ${w}: ${$.length} to remove`);b.length===0&&r("nothing left of the run to remove"),e.sweep&&r(`before them, a sweep deletes what the target's automation made for the run, as the run's user, tied to its records \u2014 run ${nr("--sweep-list")} to see what`);let x=new AbortController,z=De(()=>x.abort()),k=s??{},m=e.sweep?Bn(qe(g,"sandforge seed --sweep",x.signal),await E(x.signal),{includeChanged:e.includeChanged,removalSpans:k.removalSpans??[],...ir(e),approve:async w=>{u=w,r("");for(let $ of $e(w,e.target,e))r($)}}):void 0;await m?.ask();let j=rr(m,u);if(j){u=j,r("");for(let w of $e(j,e.target,e))r(w)}let y=[...new Set(b.map(({objectApiName:w})=>w))],O=ot({setToDraft:ft(y),delete:pt(y)},m?.takes??[]),D=O.delete??[];function v(w){return process.stderr.write(`${Le(w)}
434
- `),e.json&&process.stdout.write(lt({tool:"sandforge-seed",...e.preview?{action:"remove-preview"}:{},summary:e.summaryPath,target:e.target,elapsedMs:K(n)},w)),process.exit(1)}let I=w=>(z(),v(w)),L;if(D.length>0&&!x.signal.aborted){let w=await ve(g).read(e.target,D);r("");for(let S of wt(w,e.target,O))r(S);if(e.muteAutomation)try{L=await mt(async()=>ht(g),w,{writes:dn(O)});for(let S of fe(L.muted,e.target))r(` ${S}`)}catch(S){if(!Re(S))throw S;I(S.refusal)}let $=L?.automation??w,N=bt($,e.target,{steps:O,assign:gt($,at($,O)),mayMute:L===void 0&&Ue("--mute-automation")});N&&!e.acceptAutomation&&I({code:"AUTOMATION_NOT_ACCEPTED",message:N})}let M,U,Z=L?.muted,H=async()=>{!L?.prepared||x.signal.aborted||(U=await L.prepared.acquire(`sandforge seed --remove ${d.runId}`).catch(w=>{if(!Re(w))throw w;return I(w.refusal)}),Z=U.outcome)},X=ye(g,"sandforge seed --remove"),G=await gr(X,d.created),ee;try{M=await vn({run:d,org:X,includeChanged:e.includeChanged,...dr(m),...i.runUserId?{runUserId:i.runUserId}:{},onUndeletable:Qn(e.leaveUndeletable,e.target,w=>{ee=w}),beforeFirstWrite:H,signal:x.signal,store:{updateRemoval:(w,$)=>i.updateRemoval(N=>(k=$(N),k))}})}finally{z();let w=m?.made??new Set,$=m?.late??new Set,N=m?.gone??new Set;if((w.size>0||$.size>0||N.size>0)&&await i.updateRemoval(S=>br(S,w,$,N)).catch(S=>{process.stderr.write(`What the sweep found made for the run could not be kept (${S instanceof Error?S.message:String(S)}): a later --sweep may list it as tied to nothing.
435
- `)}),U){Z=await U.release();for(let S of fe(Z,e.target))r(S)}}Z&&(M={...M,result:{...M.result,mutedAutomation:Z}}),M.stoppedForUndeletable&&(ee&&v(ee),process.exit(1));let te=M.result.status==="cancelled"?{}:await G.take();for(let w of[...M.notes,...te.note?[te.note]:[]])process.stderr.write(`${w}
436
- `);let pe=m?.result(),W=yn(M.result.status,pe);f(W,te.object?[...M.result.objects,te.object]:M.result.objects,M.planned,pe,Z),W!=="success"&&process.exit(Ts)}var ea="not read by a preview: what the target's automation does as the records go \u2014 a trigger or a flow that deletes, keeps or creates other records \u2014 and what hangs from them, which a removal reads at each object\u2019s turn: a record kept for records that stay is counted with those to delete";function ta(t){return`${JSON.stringify({tool:"sandforge-seed",action:"remove-preview",summary:t.summary,target:t.target,includeChanged:t.includeChanged,preview:t.preview,...t.sweepListing?{sweepListing:t.sweepListing}:{},refusals:t.refusals.map(({message:n})=>n),refusalCodes:t.refusals.map(({code:n})=>n),notes:t.notes,elapsedMs:t.elapsedMs},null,2)}
437
- `}function na(t,n,e,r){let o=s=>t.userNames[s]??s,i=["preview: what a removal would do; nothing was written"];for(let s of t.objects){let d=[s.toDelete>0?`${s.toDelete} to delete`:"",r&&s.changedSince>0?`${s.changedSince} of them changed since the run`:"",s.alreadyGone>0?`${s.alreadyGone} gone already`:"",s.notVisible>0?`${s.notVisible} not visible`:"",s.keptChanged>0?`${s.keptChanged} kept, changed since the run`:"",s.undeletable>0?`${s.undeletable} left, the user may not delete them`:"",s.unread>0?`${s.unread} left, not read`:""].filter(Boolean);i.push(` ${s.objectApiName}: ${d.join(", ")||"nothing"} of ${s.planned}${tr(s)}`);let u=Object.entries(s.changedBy).sort((f,c)=>c[1]-f[1]);u.length>0&&i.push(` last changed by: ${u.map(([f,c])=>`${o(f)} ${c}`).join(" \xB7 ")}`);for(let f of s.reasons)i.push(` ${f}`)}for(let s of n)i.push(Y(s,"a removal"));return[...i,...e]}async function ra(t,n,e,r,o){let i=Be(e),s=[],d,u=n.runs!==void 0?(e.jobs??[]).length:0;u>0&&s.push(`the run's file names ${u} Bulk API job(s) no line of it answers: a removal reads back what they created first and removes it with the rest; this preview counts only what the file holds`);let f=(v,I)=>{if(s.push(ea),t.json){process.stdout.write(ta({summary:t.summaryPath,target:t.target,includeChanged:t.includeChanged,preview:v,refusals:I,notes:s,elapsedMs:K(o),...d?{sweepListing:d}:{}}));return}r("");for(let L of na(v,I,s,t.includeChanged))r(L);r(`
433
+ done in ${K(n)}ms`),w.refusal!==void 0&&process.exit(Ts);return}r(`sandforge seed --remove ${e.summaryPath} from ${e.target}`);for(let{objectApiName:w,ids:$}of b)r(` ${w}: ${$.length} to remove`);b.length===0&&r("nothing left of the run to remove"),e.sweep&&r(`before them, a sweep deletes what the target's automation made for the run, as the run's user, tied to its records \u2014 run ${nr("--sweep-list")} to see what`);let x=new AbortController,z=De(()=>x.abort()),k=s??{},m=e.sweep?Bn(qe(g,"sandforge seed --sweep",x.signal),await E(x.signal),{includeChanged:e.includeChanged,removalSpans:k.removalSpans??[],...ir(e),approve:async w=>{u=w,r("");for(let $ of $e(w,e.target,e))r($)}}):void 0;await m?.ask();let j=rr(m,u);if(j){u=j,r("");for(let w of $e(j,e.target,e))r(w)}let y=[...new Set(b.map(({objectApiName:w})=>w))],O=ot({setToDraft:ft(y),delete:pt(y)},m?.takes??[]),L=O.delete??[];function v(w){return process.stderr.write(`${Le(w)}
434
+ `),e.json&&process.stdout.write(lt({tool:"sandforge-seed",...e.preview?{action:"remove-preview"}:{},summary:e.summaryPath,target:e.target,elapsedMs:K(n)},w)),process.exit(1)}let I=w=>(z(),v(w)),M;if(L.length>0&&!x.signal.aborted){let w=await ve(g).read(e.target,L);r("");for(let S of wt(w,e.target,O))r(S);if(e.muteAutomation)try{M=await mt(async()=>ht(g),w,{writes:dn(O)});for(let S of fe(M.muted,e.target))r(` ${S}`)}catch(S){if(!Re(S))throw S;I(S.refusal)}let $=M?.automation??w,N=bt($,e.target,{steps:O,assign:gt($,at($,O)),mayMute:M===void 0&&Ue("--mute-automation")});N&&!e.acceptAutomation&&I({code:"AUTOMATION_NOT_ACCEPTED",message:N})}let F,U,Z=M?.muted,H=async()=>{!M?.prepared||x.signal.aborted||(U=await M.prepared.acquire(`sandforge seed --remove ${d.runId}`).catch(w=>{if(!Re(w))throw w;return I(w.refusal)}),Z=U.outcome)},X=ye(g,"sandforge seed --remove"),G=await gr(X,d.created),ee;try{F=await vn({run:d,org:X,includeChanged:e.includeChanged,...dr(m),...i.runUserId?{runUserId:i.runUserId}:{},onUndeletable:Qn(e.leaveUndeletable,e.target,w=>{ee=w}),beforeFirstWrite:H,signal:x.signal,store:{updateRemoval:(w,$)=>i.updateRemoval(N=>(k=$(N),k))}})}finally{z();let w=m?.made??new Set,$=m?.late??new Set,N=m?.gone??new Set;if((w.size>0||$.size>0||N.size>0)&&await i.updateRemoval(S=>br(S,w,$,N)).catch(S=>{process.stderr.write(`What the sweep found made for the run could not be kept (${S instanceof Error?S.message:String(S)}): a later --sweep may list it as tied to nothing.
435
+ `)}),U){Z=await U.release();for(let S of fe(Z,e.target))r(S)}}Z&&(F={...F,result:{...F.result,mutedAutomation:Z}}),F.stoppedForUndeletable&&(ee&&v(ee),process.exit(1));let te=F.result.status==="cancelled"?{}:await G.take(F.duplicateSets);for(let w of[...F.notes,...te.note?[te.note]:[]])process.stderr.write(`${w}
436
+ `);let pe=m?.result(),W=yn(F.result.status,pe);f(W,te.object?[...F.result.objects,te.object]:F.result.objects,F.planned,pe,Z),W!=="success"&&process.exit(Ts)}var ea="not read by a preview: what the target's automation does as the records go \u2014 a trigger or a flow that deletes, keeps or creates other records \u2014 and what hangs from them, which a removal reads at each object\u2019s turn: a record kept for records that stay is counted with those to delete";function ta(t){return`${JSON.stringify({tool:"sandforge-seed",action:"remove-preview",summary:t.summary,target:t.target,includeChanged:t.includeChanged,preview:t.preview,...t.sweepListing?{sweepListing:t.sweepListing}:{},refusals:t.refusals.map(({message:n})=>n),refusalCodes:t.refusals.map(({code:n})=>n),notes:t.notes,elapsedMs:t.elapsedMs},null,2)}
437
+ `}function na(t,n,e,r){let o=s=>t.userNames[s]??s,i=["preview: what a removal would do; nothing was written"];for(let s of t.objects){let d=[s.toDelete>0?`${s.toDelete} to delete`:"",r&&s.changedSince>0?`${s.changedSince} of them changed since the run`:"",s.alreadyGone>0?`${s.alreadyGone} gone already`:"",s.notVisible>0?`${s.notVisible} not visible`:"",s.keptChanged>0?`${s.keptChanged} kept, changed since the run`:"",s.undeletable>0?`${s.undeletable} left, the user may not delete them`:"",s.unread>0?`${s.unread} left, not read`:""].filter(Boolean);i.push(` ${s.objectApiName}: ${d.join(", ")||"nothing"} of ${s.planned}${tr(s)}`);let u=Object.entries(s.changedBy).sort((f,c)=>c[1]-f[1]);u.length>0&&i.push(` last changed by: ${u.map(([f,c])=>`${o(f)} ${c}`).join(" \xB7 ")}`);for(let f of s.reasons)i.push(` ${f}`)}for(let s of n)i.push(Y(s,"a removal"));return[...i,...e]}async function ra(t,n,e,r,o){let i=Be(e),s=[],d,u=n.runs!==void 0?(e.jobs??[]).length:0;u>0&&s.push(`the run's file names ${u} Bulk API job(s) no line of it answers: a removal reads back what they created first and removes it with the rest; this preview counts only what the file holds`);let f=(v,I)=>{if(s.push(ea),t.json){process.stdout.write(ta({summary:t.summaryPath,target:t.target,includeChanged:t.includeChanged,preview:v,refusals:I,notes:s,elapsedMs:K(o),...d?{sweepListing:d}:{}}));return}r("");for(let M of na(v,I,s,t.includeChanged))r(M);r(`
438
438
  done in ${K(o)}ms`)};if(r(`sandforge seed --remove ${t.summaryPath} --preview of ${t.target}`),i.length===0&&!t.sweep){s.push(n.earlier?.undo?`what the run created was removed already, on ${n.earlier.undo.removedAt}`:"The run created nothing: there is nothing of it to remove."),f({planned:0,objects:[],userNames:{}},[]);return}let c=await be(t.target),p=ue(c),g=await we(p);if(n.targetOrgId!==void 0&&n.targetOrgId.slice(0,15)!==g.id.slice(0,15)){let v={code:ct,message:`${t.target} is not the org the run wrote to (${n.targetOrgId}): its records are read in that org only. Nothing of the run was read.`};process.stderr.write(`${Le(v)}
439
439
  `),t.json&&process.stdout.write(lt({tool:"sandforge-seed",action:"remove-preview",summary:t.summaryPath,target:t.target,elapsedMs:K(o)},v)),process.exit(1)}let R=[],A=jt(t.target,g,"sandforge seed");if(A&&R.push({code:"PRODUCTION_TARGET",message:A}),t.sweep){d=await yt(qe(p,"sandforge seed --remove --preview --sweep"),await Fs(p,t.target,g.id,e,n),n.earlier?.removalSpans??[]),r("");for(let v of $e(d,t.target,t,!0))r(v)}let b=[...new Set(i.map(({objectApiName:v})=>v))],E=ot({setToDraft:ft(b),delete:pt(b)},d?an(d,t):[]),x=await ve(p).read(t.target,E.delete??[]);r("");for(let v of wt(x,t.target,E))r(v);let z=bt(x,t.target,{steps:E,assign:gt(x,at(x,E)),mayMute:!t.muteAutomation&&Ue("--mute-automation")});if(z&&!t.acceptAutomation&&R.push({code:"AUTOMATION_NOT_ACCEPTED",message:z}),i.length===0){s.push("nothing left of the run to remove"),f({planned:0,objects:[],userNames:{}},R);return}let k=new AbortController,m,j=De(v=>{m=v,k.abort()}),y;try{y=await $n({run:e,org:ye(p,"sandforge seed --remove --preview"),includeChanged:t.includeChanged,signal:k.signal})}finally{j()}let O=y.outcome.preview;O||(process.stderr.write(`interrupted: the preview stopped before it was through, and wrote nothing
440
- `),process.exit(_e(m??"SIGINT")));let D=y.outcome.undeletable??[];if(D.length>0&&!t.leaveUndeletable){let v=D.map(I=>`${I.objectApiName} (${I.records} records)`).join(", ");R.push({code:Xn,message:`The user SandForge connects as may not delete the records of ${v} in ${t.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}f({planned:y.planned,objects:O.objects,...D.length>0?{undeletable:D}:{},userNames:O.userNames},R)}process.argv[1]?.includes("sandforge-seed")&&(Yn(),Bo().then(()=>process.exit(process.exitCode??0)).catch(t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
440
+ `),process.exit(_e(m??"SIGINT")));let L=y.outcome.undeletable??[];if(L.length>0&&!t.leaveUndeletable){let v=L.map(I=>`${I.objectApiName} (${I.records} records)`).join(", ");R.push({code:Xn,message:`The user SandForge connects as may not delete the records of ${v} in ${t.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}f({planned:y.planned,objects:O.objects,...L.length>0?{undeletable:L}:{},userNames:O.userNames},R)}process.argv[1]?.includes("sandforge-seed")&&(Yn(),Bo().then(()=>process.exit(process.exitCode??0)).catch(t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
441
441
  `),process.exit(1)}));export{so as a,Ft as b,mo as c,vs as d,xs as e,yo as f,Ro as g,So as h,ko as i,vo as j,Oo as k,Io as l,To as m,$s as n,Eo as o,xo as p,Co as q,Po as r,No as s,Fo as t,_o as u,Cs as v,As as w,Mo as x,Bo as y,zo as z,qo as A,Os as B,Go as C,Jo as D,Vo as E,Yo as F,ea as G,ta as H,na as I};
@@ -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{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-DXOXLUZA.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as loadCreatedRecords,f as loadRecordsInfo,c as loadRecordsKept,b as loadRecordsLeft,d as loadToRemove,e as loadsSweptWith};
7
+ import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-JJITOWZK.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as loadCreatedRecords,f as loadRecordsInfo,c as loadRecordsKept,b as loadRecordsLeft,d as loadToRemove,e as loadsSweptWith};
@@ -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 Re}from"./chunk-K77NR3UK.mjs";import{K as we,Q as Se,b as ye}from"./chunk-IM2XA6JI.mjs";import{Ga as he,Ia as be,h as x,i as fe,j as ge,k as D}from"./chunk-KGYXLSQ5.mjs";import{o as se,p as ie,q as ae,r as de,s as ue}from"./chunk-UIUPPEFB.mjs";import{g as oe}from"./chunk-6IGEASOF.mjs";import{$b as B,Rb as ce,Sb as le,Tb as N,Ub as me,nc as pe}from"./chunk-KOQV4WXC.mjs";import{h as re}from"./chunk-KRNFVAGC.mjs";import{b as z}from"./chunk-HFSBDM7B.mjs";import{q as F}from"./chunk-55LQD3Y3.mjs";import{c as ee,d as te,g as ne}from"./chunk-3B5H24ZG.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Bd as V,Ed as X,Fd as J,Gd as Y,Hd as Z,Lc as H,Yb as G,h as W,i as O,k as U,ld as K,od as Q,qd as P}from"./chunk-DPYTG6DM.mjs";var L=1e4,$e=U.REST_API_BATCH_SIZE;function Oe(e){return e.id===void 0&&e.error!==void 0&&(e.errorDetails?.length??0)>0&&se([e.error],e.errorDetails)}function Pe(e,r){return e.error===void 0?e:{...e,error:ae(e.error,r)}}function C(e){return{successIds:e.flatMap(r=>r.id===void 0?[]:[r.id]),errors:e.flatMap(r=>r.error===void 0?[]:[r.error])}}function Ae(e,r){if(e.aborted||e.outcomes.length!==r||(e.unmatchedIds?.length??0)>0||(e.failures??[]).some(n=>n.recordIndex<0))return;let t=new Array(r);for(let n of e.outcomes){if(n.recordIndex<0||n.recordIndex>=r)return;if(n.success){if(!n.id)return;t[n.recordIndex]={id:n.id}}else{let o=n.error??"Unknown error",s=te(o);t[n.recordIndex]={error:o,...s?{errorDetails:[s]}:{}}}}return t.every(n=>n!==void 0)?t:void 0}function ze(e){let{conn:r,bulkManager:t,retry:n,signal:o,label:s}=e,p=new re(e.bulkThreshold),g,y=async(f,a,c)=>{g??=be(r).then(l=>(l||e.log(`[WARN] ${s}: the org's duplicate rules could not be read: an object of more than the Bulk API threshold goes as a Bulk API job, which a duplicate rule may refuse`),l));let h=await g;if(h===void 0)return he.has(f)?(e.log(`[INFO] ${s}: ${f} goes through REST: the duplicate rules could not be read, and a standard rule watches it`),!0):!1;let b=h.has(f);return b&&e.log(`[INFO] ${s}: ${f} goes through REST: an active duplicate rule watches it, which a Bulk API job cannot waive`+(a>L?` \u2014 ${a} records in ${Math.ceil(a/Math.max(1,c))} calls, slower than one job`:"")),b},R=async(f,a,c)=>{let h=[];for(let b=0;b<a.length;b+=c){if(o.aborted)return{rows:h,stopped:!0};let l=a.slice(b,b+c);e.calls?.sending(f,l.length);let w=await n.execute(async()=>r.sobject(f).create(l,{headers:G()}));if(w.cancelled)return e.calls?.answered(f,[]),{rows:h,stopped:!0};if(w.success&&w.result){let i=[];for(let m of w.result)if(m.success&&m.id)i.push(m.id),h.push({id:m.id});else{let d=ne(m.errors);h.push({error:d,errorDetails:(m.errors??[]).map(ee)})}e.calls?.answered(f,i)}else{let i=w.error?.message??"Insert failed after retries";for(let m=0;m<l.length;m++)h.push({error:i});e.calls?.answered(f,[])}}return{rows:h}},u=e.wait??(f=>ie(f,o)),A=async(f,a,c,h)=>{let b=Math.min(Math.max(1,h),$e),l=await de({outcomes:c,locked:Oe,written:i=>i.id!==void 0,send:async i=>(await R(f,i.map(m=>a[m]),b)).rows,note:Pe,wait:u,stopped:()=>o.aborted}),w=ue("record(s)",l);return{rows:l.outcomes,notes:w===void 0?[]:[`${f}: ${w}.`]}};return async(f,a,c,h)=>{let b=(c.length>L||p.shouldUseBulkApi(c.length))&&await y(a,c.length,h),l=b&&await g===void 0?[`The org's duplicate rules could not be read (the user SandForge connects as needs View Setup and Configuration): ${a}, which a standard duplicate rule watches, was sent through REST, whose header lets its matches be saved, rather than as a Bulk API job.`]:[];if(c.length>L&&!b){if(o.aborted)return{successIds:[],errors:[],stopped:!0};let d=new ye({signal:o}),S={connection:r,bulkManager:t,onProgress:(T,Ie)=>{e.onProgress(T,Ie,`Streaming insert ${a}`)},onOpened:T=>e.calls?.sending(a,c.length,{job:T})};e.calls?.sending(a,c.length);let E=await d.executeChunked(S,a,"insert",d.createChunkGenerator(c),c.length);e.calls?.answered(a,E.aborted?[]:E.successIds);let j=E.aborted?void 0:Ae({outcomes:E.outcomes??[],unmatchedIds:E.unmatchedIds},c.length),k=j&&await A(a,c,j,h);return k&&k.notes.length>0?{...C(k.rows),notes:k.notes}:{successIds:E.successIds,errors:E.errors,...E.aborted?{stopped:!0}:{}}}if(p.shouldUseBulkApi(c.length)&&!b){if(o.aborted)return{successIds:[],errors:[],stopped:!0};let d={connection:r,bulkManager:t,onProgress:(k,T)=>{e.onProgress(k,T,`Bulk insert ${a}`)},signal:o,onOpened:k=>e.calls?.sending(a,c.length,{job:k})};e.calls?.sending(a,c.length);let S=await p.executeBulk(d,a,"insert",c);e.calls?.answered(a,S.aborted?[]:S.successIds);let E=Ae(S,c.length),j=E&&await A(a,c,E,h);return j&&j.notes.length>0?{...C(j.rows),rows:j.rows,notes:j.notes}:{successIds:S.successIds,errors:S.failures.map(k=>k.error),...E?{rows:E}:{},...S.aborted?{stopped:!0}:{}}}let w=await R(a,c,h);if(w.stopped)return{...C(w.rows),rows:w.rows,stopped:!0};let i=await A(a,c,w.rows,h),m=[...l,...i.notes];return{...C(i.rows),rows:i.rows,...m.length>0?{notes:m}:{}}}}var xe="SELECT Id, DeveloperName FROM RecordType WHERE SobjectType = 'Account' AND IsPersonType = true";async function rt(e){try{return(await e.query(xe)).records.flatMap(t=>typeof t.Id=="string"&&typeof t.DeveloperName=="string"?[{id:t.Id,developerName:t.DeveloperName}]:[])}catch{return[]}}function ot(e,r,t){let n=new Set(e===F?t.map(o=>o.id.slice(0,15)):[]);return z(r).filter(o=>!o.master&&o.active&&o.available).map(o=>({recordTypeId:o.recordTypeId,developerName:o.developerName,label:o.name,person:n.has(o.recordTypeId.slice(0,15)),isDefault:o.defaultRecordTypeMapping}))}function Ce(e){let{staticValue:r,picklistValues:t}=e.config;return e.ruleType==="static"&&typeof r=="string"?[r]:e.ruleType==="picklist_random"?[...t??[]]:[]}function st(e,r){if(r.length===0)return{template:e,personObjects:[]};let t=new Map(r.map(s=>[s.id.slice(0,15),s.developerName])),n=[],o=[];for(let s of e.objects){if(s.objectApiName!==F){o.push(s);continue}let p=s.fieldRules.find(u=>u.fieldApiName==="RecordTypeId"),g=p?Ce(p):[],y=g.filter(u=>t.has(u.slice(0,15)));if(y.length>0&&y.length<g.length){let u=y.map(A=>t.get(A.slice(0,15))).join(", ");return{refusal:`${F}: ${u} ${y.length===1?"is a person account record type":"are person account record types"} and the other record types chosen are not: a person account and a business account take different fields. Seed one kind in a run.`}}let R=y.length>0?"person":"business";R==="person"&&n.push(s.objectApiName),o.push({...s,fieldRules:s.fieldRules.filter(u=>!H(F,u.fieldApiName,R))})}return{template:{...e,objects:o},personObjects:n}}var Me=/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/;async function ve(e){try{let t=(await e.query("SELECT DefaultLocaleSidKey FROM Organization LIMIT 1")).records[0]?.DefaultLocaleSidKey;return typeof t=="string"&&Me.test(t)?t:void 0}catch{return}}async function at(e,r){return e??await ve(r)??"en_US"}var ft="SEED_FIT_STORAGE_UNREAD",gt="SEED_CANNOT_FIT";function ht(e,r=!1){return q(e.objects.filter(t=>t.recordCount>0).map(t=>t.objectApiName),r)}function q(e,r=!1){let t=new Set(e);return(n,o)=>t.has(n)&&(o==="insert"||o==="update"&&r&&n===Re)}function bt(e,r,t,n){if(typeof e.unread=="string")return{room:{perRecord:[],notCounted:[],unread:e.unread},unread:e.unread};let o=Z(e,r,t);if(!n)return{running:o,room:x(o,t)};let s=[],p=new Set,g=[];for(let u of o.firing){let A=u.flow,f=A?.requiresFilled??[];if(u.write!=="insert"||A?.condition!=="read"||!A.creates?.length)continue;let a=f.filter(b=>n(u.objectApiName,b)==="every"),c=f.filter(b=>n(u.objectApiName,b)==="some"),h={objectApiName:u.objectApiName,name:u.name};a.length>0&&!Ne(o.firing,u)?(p.add(u),s.push({...h,fields:a,why:"leftEmpty"})):(a.length>0||c.length>0)&&(g.push(u),s.push({...h,fields:a.length>0?a:c,why:a.length>0?"automationMayFill":"mayBeLeftEmpty"}))}let y=x({firing:o.firing.filter(u=>!p.has(u))},t),R=x({firing:g},t).perRecord;return{running:o,room:{...y,...R.length>0?{atMost:R}:{},...s.length>0?{starts:s}:{}}}}function Ne(e,r){return e.some(t=>t!==r&&t.objectApiName===r.objectApiName&&t.write==="insert"&&(t.kind==="trigger"||t.kind==="process"||t.kind==="workflowRule"||t.flow?.timing==="beforeSave"))}async function yt(e,r,t){let n=new Set("objects"in r?r.objects.filter(s=>s.flows.some(p=>(p.requiresFilled??[]).length>0)).map(s=>s.objectApiName):[]),o=new Map;for(let s of e.objects)s.recordCount<=0||!n.has(s.objectApiName)||o.set(s.objectApiName,await t(s.objectApiName).catch(()=>{}));return(s,p)=>{let g=e.objects.find(a=>a.objectApiName===s);if(!g)return"none";let y=a=>a.toLowerCase()===p.toLowerCase();if(g.fieldRules.some(a=>y(a.fieldApiName)))return"none";let R=O(s,e.relations);if(R&&y(R.lookupField))return"none";let u=g.rows??[],A=u.filter(a=>Object.entries(a.values).some(([c,h])=>y(c)&&h!==null&&h!=="")).length;if(u.length>0&&A===u.length)return"none";let f=o.get(s);return f?[...f.filled].some(y)?"none":A>0?"some":[...f.empty].some(y)?"every":"some":"some"}}function M(e,r){return O(e.objectApiName,r)?.distribution.mode==="byKey"?"byKey":e.rows!==void 0?"rows":void 0}function ke(e,r){let t=O(e,r.relations);if(!(!t||t.parents.kind!=="generated"||t.distribution.mode==="byKey"||t.parentObject===e||!r.objects.some(n=>n.objectApiName===t.parentObject)))return t}function Ee(e,r){let t=r?.objects?.[e.objectApiName]??r?.all;return t!==void 0?Math.min(e.recordCount,Math.max(1,Math.floor(t))):e.recordCount}function Be(e,r,t){let n=new Map(e.objects.map(g=>[g.objectApiName,g])),o=new Map,s=new Set,p=g=>{let y=o.get(g);if(y!==void 0)return y;let R=n.get(g);if(M(R,e.relations))return o.set(g,R.recordCount),R.recordCount;s.add(g);let u=Math.round(r*Ee(R,t)),A=ke(g,e),f=A&&!s.has(A.parentObject)?Math.max(1,Math.min(u,W(A.distribution,p(A.parentObject)))):Math.max(1,u);return s.delete(g),o.set(g,f),f};return new Map(e.objects.map(g=>[g.objectApiName,p(g.objectApiName)]))}function De(e,r){if(r.cannotFit!==void 0)return e;let t=new Map(r.objects.map(n=>[n.objectApiName,n.after]));return{...e,objects:e.objects.map(n=>{let o=t.get(n.objectApiName);return o!==void 0&&o<n.recordCount?{...n,recordCount:o}:n})}}function Le(e,r){let t=e.objects.filter(s=>!M(s,e.relations)),n=t.filter(s=>!ke(s.objectApiName,e)),o;for(let s of n.length>0?n:t){let p=Ee(s,r);(!o||p>o.records)&&(o={objectApiName:s.objectApiName,records:p})}return o}function _e(e){return`${e} record${e===1?"":"s"}`}function qe(e){let{template:r,personObjects:t,budget:n,room:o}=e,s=e.ask?.caps,p=e.ask?.share===!0||s===void 0,g=d=>{let S=Be(r,d,s),E=De(r,{objects:r.objects.map(k=>({objectApiName:k.objectApiName,before:k.recordCount,after:S.get(k.objectApiName)??k.recordCount}))}),j=fe(o,k=>S.get(k)??0);return{counts:S,bytes:Se(E,t)+j,roomBytes:j,requests:we(E,e.path),records:[...S.values()].reduce((k,T)=>k+T,0)}},y=d=>d.bytes<=n.bytes,R=d=>n.runRequests===void 0||d.requests<=n.runRequests,u=d=>y(d)&&R(d),A=(d,S,E,j)=>({share:d,budget:{...ge(n,S.roomBytes,o),...E==="apiRequests"?{limitedBy:"apiRequests"}:{}},objects:r.objects.map(k=>{let T=M(k,r.relations);return{objectApiName:k.objectApiName,before:k.recordCount,after:S.counts.get(k.objectApiName)??k.recordCount,...T?{keptWhole:T}:{}}}),estimateMB:S.bytes/1048576,...j!==void 0?{cannotFit:j}:{},...o.unread!==void 0?{automationUnread:o.unread}:{}}),f=(d,S,E,j)=>({proposal:A(d,S,E,j),heldBy:E,records:S.records,requests:S.requests}),a=d=>{if(y(d))return`about ${d.requests} API requests, past the ${n.runRequests??0} that leave the org a tenth of its daily requests`;let S=pe(d.bytes/1048576,n.bytes/1048576);return`${S.over} MB`+(d.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${S.bound} MB that fit`},c=d=>y(d)?"apiRequests":n.terms.limitedBy,h=r.objects.filter(d=>M(d,r.relations)).reduce((d,S)=>d+S.recordCount,0),b=g(1);if(u(b)){let d=r.objects.some(S=>(b.counts.get(S.objectApiName)??0)<S.recordCount);return f(1,b,d?"caps":"whole")}if(!p)return f(1,b,c(b),`with these caps the seed takes ${a(b)}: lower them, or fit by share`);let l=Le(r,s);if(!l)return f(1,b,c(b),`the ${h} rows the template gives take ${a(b)}, and rows are kept whole`);let w=d=>g(d/l.records),i=D(l.records,d=>u(w(d)));if(i===0){let d=w(1);return f(1/l.records,d,c(d),`the least it can be cut to \u2014 one ${l.objectApiName} and what follows it`+(h>0?`, with the ${h} rows the template gives kept whole`:"")+`, ${_e(d.records)} \u2014 takes ${a(d)}`)}let m=D(l.records,d=>y(w(d)));return f(i/l.records,w(i),m>i?"apiRequests":n.terms.limitedBy)}function wt(e,r,t,n,o){if(!("unread"in e))return qe({template:r,personObjects:t,budget:e,room:n,path:o}).proposal}function St(e,r){if(!(!e||e.before<r))return{module:"seed",share:e.share,...e.withinMB!==void 0?{withinMB:e.withinMB}:{},kept:r,inSource:e.before}}var Fe=(e,r)=>r==="insert";function je(e){return typeof e.unread=="string"}function We(e){return(K(e).find(t=>t.write==="insert")?.fired??[]).map(t=>{let n=t.flow,o=n?.messages??[];return{kind:t.kind,name:t.name,when:t.when,emails:o.filter(s=>s.kind==="email").length,messages:[...new Set(o.flatMap(s=>s.kind==="email"?[]:[s.kind]))],creates:[...n?.creates??[]],afterCommit:(n?.paths?.length??0)>0,bypasses:(n?.permissions??[]).filter(s=>s.bypass).map(({name:s,held:p})=>p===void 0?{name:s}:{name:s,held:p}),keptQuiet:t.keptQuiet===!0,unread:n!==void 0&&n.condition!=="read"}})}function $(e){return[...new Set(e)].sort((r,t)=>r.localeCompare(t))}function Te(e,r,t,n,o=Fe){let s=e.objects.flatMap(l=>{let w=We(l);return w.length>0?[{objectApiName:l.objectApiName,entries:w}]:[]}),p=je(t)?void 0:t,g=p!==void 0&&ce(p),y=p!==void 0&&le(p),R=N(P(e),g,y),u=s.flatMap(l=>l.entries.flatMap(w=>w.bypasses)),A=$(u.filter(l=>l.held===!0).map(l=>l.name)),f=$(u.map(l=>l.name)).filter(l=>!A.includes(l)),a=V(e,f),c=f.map(l=>{let w=a.find(i=>i.permission.toLowerCase()===l.toLowerCase())?.permissionSet;return w?{permission:l,permissionSet:w.name}:{permission:l}}),h=X(e,o),b=h.assign.length>0;return{org:r,objectsRead:[...e.objectsRead],objects:s,emailsPerRecord:R,...p&&R.length>0?{limits:{...p}}:{},...je(t)?{limitsUnread:t.unread}:{},alertsAsSingle:g,bypasses:c,bypassesHeld:A,...b?{mute:h,emailsPerRecordMuted:N(P(Y(e,J(h))),g,y)}:{},unread:e.unread.map(({part:l,reason:w})=>({part:l,reason:w})),blinded:Q(e.unread),conditionsNotRead:e.conditionsNotRead,...n?{deliverability:n}:{}}}async function Ft(e){let r=e.writes??q(e.objects),t;try{t=await e.readAutomation(e.objects)}catch(s){return{error:v(s)}}let n=e.deliverability??(e.readDeliverability?(await oe({read:t,writes:Fe,readDeliverability:e.readDeliverability,accepted:!1,target:e.org,run:"seed"})).gate.deliverability:void 0);if(P(t).length===0)return{preview:Te(t,e.org,{},n,r)};let o=await e.readLimits().catch(s=>({unread:v(s)}));return{preview:Te(t,e.org,o,n,r)}}function I(e,r="and"){return e.length<=1?e.join(""):e.length===2?`${e[0]} ${r} ${e[1]}`:`${e.slice(0,-1).join(", ")}, ${r} ${e[e.length-1]}`}var It="SEED_EMAILS_EXCEEDED";function $t(e,r,t){if("error"in e)return{checks:[],unknown:[`what ${t} runs as these records are created could not be read (${e.error}): the emails they make it send are not known`]};let{preview:n}=e,o={objects:r.map(i=>({objectApiName:i.objectApiName,rows:i.recordCount,storageBytes:0}))},s=n.limitsUnread!==void 0?{unread:n.limitsUnread}:n.limits??{},p=me(o,n.emailsPerRecord,s),g=new Set(r.filter(i=>i.recordCount>0).map(i=>i.objectApiName)),y=n.objects.flatMap(i=>g.has(i.objectApiName)?i.entries.filter(m=>m.unread&&!m.keptQuiet&&m.when!=="before").map(m=>`"${m.name}" on ${i.objectApiName}`):[]),R=[...p.filter(i=>i.verdict==="unread").map(i=>`about ${B(i.emails,i.limit)}, but what ${t} has left today could not be read (${i.unread??"not said"})`),...n.blinded?[`part of what ${t} runs could not be read: emails it sends may not be counted`]:[],...y.length>0?[`the emails of ${I(y)} are not counted: what ${y.length===1?"it does":"they do"} was not read`]:n.conditionsNotRead>0?[`${n.conditionsNotRead} start condition(s) of ${t} not read: the emails of those flows are not counted`]:[]],u=p.find(i=>i.verdict==="exceeds");if(!u)return R.length>0?{checks:p,unknown:R}:{checks:p};let A=p.filter(i=>i.verdict==="exceeds"),f=$(A.flatMap(i=>i.objects.map(m=>m.objectApiName))),a=$(A.flatMap(i=>i.objects.flatMap(m=>m.sentBy))),c=new Map;for(let i of n.objects.flatMap(m=>m.entries))if(!(i.emails===0||!a.includes(i.name)))for(let{name:m}of i.bypasses)c.set(m,(c.get(m)??new Set).add(i.name));let h=n.bypasses.flatMap(i=>{let m=c.get(i.permission);return m?[{...i,quiets:$([...m])}]:[]}),b=A.map(i=>`about ${B(i.emails,i.limit)} (`+i.objects.map(m=>`${m.perRecord} per ${m.objectApiName}`).join(", ")+`), ${i.remaining??0} of ${i.max??0} left today`).join("; "),l=["lower the record counts",`set ${I(f)} to 0`,`turn off ${I(a.map(i=>`"${i}"`))}`,...h.map(i=>"give the user the seed writes as "+(i.permissionSet?`the permission set ${i.permissionSet}, whose ${i.permission}`:`a permission set holding ${i.permission}, which`)+` keeps ${I(i.quiets.map(m=>`"${m}"`))} quiet`)],w=`The seed was refused before it wrote anything: its records would make ${t} send ${b}. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To seed it, ${I(l,"or")}. Nothing was written.`;return{checks:p,refusal:w,figures:{org:t,limit:u.limit,emails:u.emails,remaining:u.remaining??0,max:u.max??0,objects:f,senders:a,bypasses:h},...R.length>0?{unknown:R}:{}}}var Ue={flow:e=>`flow "${e}"`,trigger:e=>`Apex trigger ${e}`,process:e=>`process "${e}"`,workflowRule:e=>`workflow rule "${e}"`},Ge={before:"before save",after:"after save",beforeAndAfter:"before and after save"},He={notification:"custom notifications",outbound:"outbound messages",sms:"text messages"};function Ke(e){let r=n=>n.held===!0?" (held)":n.held===!1?" (not held)":"",t=[Ge[e.when],...e.emails>0?[`${e.emails} email(s) a record`]:[],...e.messages.map(n=>`sends ${He[n]}`),...e.creates.length>0?[`creates ${e.creates.join(", ")}`]:[],...e.afterCommit?["then after commit"]:[],...e.bypasses.length>0?[`not for a user with ${e.bypasses.map(n=>n.name+r(n)).join(", ")}`]:[],...e.keptQuiet?["quiet for this seed"]:[],...e.unread?["what it does was not read"]:[]];return`${Ue[e.kind](e.name)} (${t.join("; ")})`}function Ot(e,r){if("error"in e)return[`target automation: what ${r} runs as these records are created could not be read (${e.error}): the emails they make it send are not known`];let{preview:t}=e,n=[`target automation: what ${r} runs as these records are created`];for(let o of t.objects)n.push(` ${o.objectApiName}: ${o.entries.map(Ke).join(", ")}`);t.objects.length===0&&n.push(t.blinded?" nothing found in what could be read":" nothing runs on them: no flow, Apex trigger, process or workflow rule"),t.bypassesHeld.length>0&&n.push(` bypass held: the user the seed writes as holds ${t.bypassesHeld.join(", ")}, and what names it stays quiet`);for(let o of t.bypasses)n.push(o.permissionSet?` bypass: ${o.permission} keeps quiet what names it; permission set ${o.permissionSet} holds it`:` bypass: ${o.permission} keeps quiet what names it; no permission set of ${r} was found to hold it`);t.alertsAsSingle&&t.emailsPerRecord.some(o=>o.alertsAmong)&&n.push(` ${r} counts its email alerts against its single emails too, as a Developer Edition does`);for(let{part:o,reason:s}of t.unread)n.push(` ${o} could not be read: ${s}`);return t.conditionsNotRead>0&&n.push(` ${t.conditionsNotRead} start condition(s) not read`),n}export{ze as a,rt as b,ot as c,st as d,at as e,ft as f,gt as g,ht as h,q as i,bt as j,yt as k,De as l,qe as m,wt as n,St as o,Ft as p,It as q,$t as r,Ot as s};
7
+ import{a as Re}from"./chunk-A65ADTCR.mjs";import{K as we,Q as Se,b as ye}from"./chunk-A7JJWOLT.mjs";import{Ga as he,Ia as be,h as x,i as fe,j as ge,k as D}from"./chunk-P55MKIZX.mjs";import{o as se,p as ie,q as ae,r as de,s as ue}from"./chunk-WSUKC2U3.mjs";import{g as oe}from"./chunk-JQZTMFO7.mjs";import{$b as B,Rb as ce,Sb as le,Tb as N,Ub as me,nc as pe}from"./chunk-JFNLKHY6.mjs";import{h as re}from"./chunk-HFUDCNU5.mjs";import{b as z}from"./chunk-HFSBDM7B.mjs";import{q as F}from"./chunk-KIMQQ6JQ.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{c as ee,d as te,g as ne}from"./chunk-ZUTUYBNW.mjs";import{Ad as Q,Cd as P,Nd as V,Qd as X,Rd as J,Sd as Y,Td as Z,Xc as H,h as W,i as O,ic as G,k as U,xd as K}from"./chunk-ZQO5PDX5.mjs";var L=1e4,$e=U.REST_API_BATCH_SIZE;function Oe(e){return e.id===void 0&&e.error!==void 0&&(e.errorDetails?.length??0)>0&&se([e.error],e.errorDetails)}function Pe(e,r){return e.error===void 0?e:{...e,error:ae(e.error,r)}}function C(e){return{successIds:e.flatMap(r=>r.id===void 0?[]:[r.id]),errors:e.flatMap(r=>r.error===void 0?[]:[r.error])}}function Ae(e,r){if(e.aborted||e.outcomes.length!==r||(e.unmatchedIds?.length??0)>0||(e.failures??[]).some(n=>n.recordIndex<0))return;let t=new Array(r);for(let n of e.outcomes){if(n.recordIndex<0||n.recordIndex>=r)return;if(n.success){if(!n.id)return;t[n.recordIndex]={id:n.id}}else{let o=n.error??"Unknown error",s=te(o);t[n.recordIndex]={error:o,...s?{errorDetails:[s]}:{}}}}return t.every(n=>n!==void 0)?t:void 0}function ze(e){let{conn:r,bulkManager:t,retry:n,signal:o,label:s}=e,p=new re(e.bulkThreshold),g,y=async(f,a,c)=>{g??=be(r).then(l=>(l||e.log(`[WARN] ${s}: the org's duplicate rules could not be read: an object of more than the Bulk API threshold goes as a Bulk API job, which a duplicate rule may refuse`),l));let h=await g;if(h===void 0)return he.has(f)?(e.log(`[INFO] ${s}: ${f} goes through REST: the duplicate rules could not be read, and a standard rule watches it`),!0):!1;let b=h.has(f);return b&&e.log(`[INFO] ${s}: ${f} goes through REST: an active duplicate rule watches it, which a Bulk API job cannot waive`+(a>L?` \u2014 ${a} records in ${Math.ceil(a/Math.max(1,c))} calls, slower than one job`:"")),b},R=async(f,a,c)=>{let h=[];for(let b=0;b<a.length;b+=c){if(o.aborted)return{rows:h,stopped:!0};let l=a.slice(b,b+c);e.calls?.sending(f,l.length);let w=await n.execute(async()=>r.sobject(f).create(l,{headers:G()}));if(w.cancelled)return e.calls?.answered(f,[]),{rows:h,stopped:!0};if(w.success&&w.result){let i=[];for(let m of w.result)if(m.success&&m.id)i.push(m.id),h.push({id:m.id});else{let d=ne(m.errors);h.push({error:d,errorDetails:(m.errors??[]).map(ee)})}e.calls?.answered(f,i)}else{let i=w.error?.message??"Insert failed after retries";for(let m=0;m<l.length;m++)h.push({error:i});e.calls?.answered(f,[])}}return{rows:h}},u=e.wait??(f=>ie(f,o)),A=async(f,a,c,h)=>{let b=Math.min(Math.max(1,h),$e),l=await de({outcomes:c,locked:Oe,written:i=>i.id!==void 0,send:async i=>(await R(f,i.map(m=>a[m]),b)).rows,note:Pe,wait:u,stopped:()=>o.aborted}),w=ue("record(s)",l);return{rows:l.outcomes,notes:w===void 0?[]:[`${f}: ${w}.`]}};return async(f,a,c,h)=>{let b=(c.length>L||p.shouldUseBulkApi(c.length))&&await y(a,c.length,h),l=b&&await g===void 0?[`The org's duplicate rules could not be read (the user SandForge connects as needs View Setup and Configuration): ${a}, which a standard duplicate rule watches, was sent through REST, whose header lets its matches be saved, rather than as a Bulk API job.`]:[];if(c.length>L&&!b){if(o.aborted)return{successIds:[],errors:[],stopped:!0};let d=new ye({signal:o}),S={connection:r,bulkManager:t,onProgress:(T,Ie)=>{e.onProgress(T,Ie,`Streaming insert ${a}`)},onOpened:T=>e.calls?.sending(a,c.length,{job:T})};e.calls?.sending(a,c.length);let E=await d.executeChunked(S,a,"insert",d.createChunkGenerator(c),c.length);e.calls?.answered(a,E.aborted?[]:E.successIds);let j=E.aborted?void 0:Ae({outcomes:E.outcomes??[],unmatchedIds:E.unmatchedIds},c.length),k=j&&await A(a,c,j,h);return k&&k.notes.length>0?{...C(k.rows),notes:k.notes}:{successIds:E.successIds,errors:E.errors,...E.aborted?{stopped:!0}:{}}}if(p.shouldUseBulkApi(c.length)&&!b){if(o.aborted)return{successIds:[],errors:[],stopped:!0};let d={connection:r,bulkManager:t,onProgress:(k,T)=>{e.onProgress(k,T,`Bulk insert ${a}`)},signal:o,onOpened:k=>e.calls?.sending(a,c.length,{job:k})};e.calls?.sending(a,c.length);let S=await p.executeBulk(d,a,"insert",c);e.calls?.answered(a,S.aborted?[]:S.successIds);let E=Ae(S,c.length),j=E&&await A(a,c,E,h);return j&&j.notes.length>0?{...C(j.rows),rows:j.rows,notes:j.notes}:{successIds:S.successIds,errors:S.failures.map(k=>k.error),...E?{rows:E}:{},...S.aborted?{stopped:!0}:{}}}let w=await R(a,c,h);if(w.stopped)return{...C(w.rows),rows:w.rows,stopped:!0};let i=await A(a,c,w.rows,h),m=[...l,...i.notes];return{...C(i.rows),rows:i.rows,...m.length>0?{notes:m}:{}}}}var xe="SELECT Id, DeveloperName FROM RecordType WHERE SobjectType = 'Account' AND IsPersonType = true";async function rt(e){try{return(await e.query(xe)).records.flatMap(t=>typeof t.Id=="string"&&typeof t.DeveloperName=="string"?[{id:t.Id,developerName:t.DeveloperName}]:[])}catch{return[]}}function ot(e,r,t){let n=new Set(e===F?t.map(o=>o.id.slice(0,15)):[]);return z(r).filter(o=>!o.master&&o.active&&o.available).map(o=>({recordTypeId:o.recordTypeId,developerName:o.developerName,label:o.name,person:n.has(o.recordTypeId.slice(0,15)),isDefault:o.defaultRecordTypeMapping}))}function Ce(e){let{staticValue:r,picklistValues:t}=e.config;return e.ruleType==="static"&&typeof r=="string"?[r]:e.ruleType==="picklist_random"?[...t??[]]:[]}function st(e,r){if(r.length===0)return{template:e,personObjects:[]};let t=new Map(r.map(s=>[s.id.slice(0,15),s.developerName])),n=[],o=[];for(let s of e.objects){if(s.objectApiName!==F){o.push(s);continue}let p=s.fieldRules.find(u=>u.fieldApiName==="RecordTypeId"),g=p?Ce(p):[],y=g.filter(u=>t.has(u.slice(0,15)));if(y.length>0&&y.length<g.length){let u=y.map(A=>t.get(A.slice(0,15))).join(", ");return{refusal:`${F}: ${u} ${y.length===1?"is a person account record type":"are person account record types"} and the other record types chosen are not: a person account and a business account take different fields. Seed one kind in a run.`}}let R=y.length>0?"person":"business";R==="person"&&n.push(s.objectApiName),o.push({...s,fieldRules:s.fieldRules.filter(u=>!H(F,u.fieldApiName,R))})}return{template:{...e,objects:o},personObjects:n}}var Me=/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/;async function ve(e){try{let t=(await e.query("SELECT DefaultLocaleSidKey FROM Organization LIMIT 1")).records[0]?.DefaultLocaleSidKey;return typeof t=="string"&&Me.test(t)?t:void 0}catch{return}}async function at(e,r){return e??await ve(r)??"en_US"}var ft="SEED_FIT_STORAGE_UNREAD",gt="SEED_CANNOT_FIT";function ht(e,r=!1){return q(e.objects.filter(t=>t.recordCount>0).map(t=>t.objectApiName),r)}function q(e,r=!1){let t=new Set(e);return(n,o)=>t.has(n)&&(o==="insert"||o==="update"&&r&&n===Re)}function bt(e,r,t,n){if(typeof e.unread=="string")return{room:{perRecord:[],notCounted:[],unread:e.unread},unread:e.unread};let o=Z(e,r,t);if(!n)return{running:o,room:x(o,t)};let s=[],p=new Set,g=[];for(let u of o.firing){let A=u.flow,f=A?.requiresFilled??[];if(u.write!=="insert"||A?.condition!=="read"||!A.creates?.length)continue;let a=f.filter(b=>n(u.objectApiName,b)==="every"),c=f.filter(b=>n(u.objectApiName,b)==="some"),h={objectApiName:u.objectApiName,name:u.name};a.length>0&&!Ne(o.firing,u)?(p.add(u),s.push({...h,fields:a,why:"leftEmpty"})):(a.length>0||c.length>0)&&(g.push(u),s.push({...h,fields:a.length>0?a:c,why:a.length>0?"automationMayFill":"mayBeLeftEmpty"}))}let y=x({firing:o.firing.filter(u=>!p.has(u))},t),R=x({firing:g},t).perRecord;return{running:o,room:{...y,...R.length>0?{atMost:R}:{},...s.length>0?{starts:s}:{}}}}function Ne(e,r){return e.some(t=>t!==r&&t.objectApiName===r.objectApiName&&t.write==="insert"&&(t.kind==="trigger"||t.kind==="process"||t.kind==="workflowRule"||t.flow?.timing==="beforeSave"))}async function yt(e,r,t){let n=new Set("objects"in r?r.objects.filter(s=>s.flows.some(p=>(p.requiresFilled??[]).length>0)).map(s=>s.objectApiName):[]),o=new Map;for(let s of e.objects)s.recordCount<=0||!n.has(s.objectApiName)||o.set(s.objectApiName,await t(s.objectApiName).catch(()=>{}));return(s,p)=>{let g=e.objects.find(a=>a.objectApiName===s);if(!g)return"none";let y=a=>a.toLowerCase()===p.toLowerCase();if(g.fieldRules.some(a=>y(a.fieldApiName)))return"none";let R=O(s,e.relations);if(R&&y(R.lookupField))return"none";let u=g.rows??[],A=u.filter(a=>Object.entries(a.values).some(([c,h])=>y(c)&&h!==null&&h!=="")).length;if(u.length>0&&A===u.length)return"none";let f=o.get(s);return f?[...f.filled].some(y)?"none":A>0?"some":[...f.empty].some(y)?"every":"some":"some"}}function M(e,r){return O(e.objectApiName,r)?.distribution.mode==="byKey"?"byKey":e.rows!==void 0?"rows":void 0}function ke(e,r){let t=O(e,r.relations);if(!(!t||t.parents.kind!=="generated"||t.distribution.mode==="byKey"||t.parentObject===e||!r.objects.some(n=>n.objectApiName===t.parentObject)))return t}function Ee(e,r){let t=r?.objects?.[e.objectApiName]??r?.all;return t!==void 0?Math.min(e.recordCount,Math.max(1,Math.floor(t))):e.recordCount}function Be(e,r,t){let n=new Map(e.objects.map(g=>[g.objectApiName,g])),o=new Map,s=new Set,p=g=>{let y=o.get(g);if(y!==void 0)return y;let R=n.get(g);if(M(R,e.relations))return o.set(g,R.recordCount),R.recordCount;s.add(g);let u=Math.round(r*Ee(R,t)),A=ke(g,e),f=A&&!s.has(A.parentObject)?Math.max(1,Math.min(u,W(A.distribution,p(A.parentObject)))):Math.max(1,u);return s.delete(g),o.set(g,f),f};return new Map(e.objects.map(g=>[g.objectApiName,p(g.objectApiName)]))}function De(e,r){if(r.cannotFit!==void 0)return e;let t=new Map(r.objects.map(n=>[n.objectApiName,n.after]));return{...e,objects:e.objects.map(n=>{let o=t.get(n.objectApiName);return o!==void 0&&o<n.recordCount?{...n,recordCount:o}:n})}}function Le(e,r){let t=e.objects.filter(s=>!M(s,e.relations)),n=t.filter(s=>!ke(s.objectApiName,e)),o;for(let s of n.length>0?n:t){let p=Ee(s,r);(!o||p>o.records)&&(o={objectApiName:s.objectApiName,records:p})}return o}function _e(e){return`${e} record${e===1?"":"s"}`}function qe(e){let{template:r,personObjects:t,budget:n,room:o}=e,s=e.ask?.caps,p=e.ask?.share===!0||s===void 0,g=d=>{let S=Be(r,d,s),E=De(r,{objects:r.objects.map(k=>({objectApiName:k.objectApiName,before:k.recordCount,after:S.get(k.objectApiName)??k.recordCount}))}),j=fe(o,k=>S.get(k)??0);return{counts:S,bytes:Se(E,t)+j,roomBytes:j,requests:we(E,e.path),records:[...S.values()].reduce((k,T)=>k+T,0)}},y=d=>d.bytes<=n.bytes,R=d=>n.runRequests===void 0||d.requests<=n.runRequests,u=d=>y(d)&&R(d),A=(d,S,E,j)=>({share:d,budget:{...ge(n,S.roomBytes,o),...E==="apiRequests"?{limitedBy:"apiRequests"}:{}},objects:r.objects.map(k=>{let T=M(k,r.relations);return{objectApiName:k.objectApiName,before:k.recordCount,after:S.counts.get(k.objectApiName)??k.recordCount,...T?{keptWhole:T}:{}}}),estimateMB:S.bytes/1048576,...j!==void 0?{cannotFit:j}:{},...o.unread!==void 0?{automationUnread:o.unread}:{}}),f=(d,S,E,j)=>({proposal:A(d,S,E,j),heldBy:E,records:S.records,requests:S.requests}),a=d=>{if(y(d))return`about ${d.requests} API requests, past the ${n.runRequests??0} that leave the org a tenth of its daily requests`;let S=pe(d.bytes/1048576,n.bytes/1048576);return`${S.over} MB`+(d.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${S.bound} MB that fit`},c=d=>y(d)?"apiRequests":n.terms.limitedBy,h=r.objects.filter(d=>M(d,r.relations)).reduce((d,S)=>d+S.recordCount,0),b=g(1);if(u(b)){let d=r.objects.some(S=>(b.counts.get(S.objectApiName)??0)<S.recordCount);return f(1,b,d?"caps":"whole")}if(!p)return f(1,b,c(b),`with these caps the seed takes ${a(b)}: lower them, or fit by share`);let l=Le(r,s);if(!l)return f(1,b,c(b),`the ${h} rows the template gives take ${a(b)}, and rows are kept whole`);let w=d=>g(d/l.records),i=D(l.records,d=>u(w(d)));if(i===0){let d=w(1);return f(1/l.records,d,c(d),`the least it can be cut to \u2014 one ${l.objectApiName} and what follows it`+(h>0?`, with the ${h} rows the template gives kept whole`:"")+`, ${_e(d.records)} \u2014 takes ${a(d)}`)}let m=D(l.records,d=>y(w(d)));return f(i/l.records,w(i),m>i?"apiRequests":n.terms.limitedBy)}function wt(e,r,t,n,o){if(!("unread"in e))return qe({template:r,personObjects:t,budget:e,room:n,path:o}).proposal}function St(e,r){if(!(!e||e.before<r))return{module:"seed",share:e.share,...e.withinMB!==void 0?{withinMB:e.withinMB}:{},kept:r,inSource:e.before}}var Fe=(e,r)=>r==="insert";function je(e){return typeof e.unread=="string"}function We(e){return(K(e).find(t=>t.write==="insert")?.fired??[]).map(t=>{let n=t.flow,o=n?.messages??[];return{kind:t.kind,name:t.name,when:t.when,emails:o.filter(s=>s.kind==="email").length,messages:[...new Set(o.flatMap(s=>s.kind==="email"?[]:[s.kind]))],creates:[...n?.creates??[]],afterCommit:(n?.paths?.length??0)>0,bypasses:(n?.permissions??[]).filter(s=>s.bypass).map(({name:s,held:p})=>p===void 0?{name:s}:{name:s,held:p}),keptQuiet:t.keptQuiet===!0,unread:n!==void 0&&n.condition!=="read"}})}function $(e){return[...new Set(e)].sort((r,t)=>r.localeCompare(t))}function Te(e,r,t,n,o=Fe){let s=e.objects.flatMap(l=>{let w=We(l);return w.length>0?[{objectApiName:l.objectApiName,entries:w}]:[]}),p=je(t)?void 0:t,g=p!==void 0&&ce(p),y=p!==void 0&&le(p),R=N(P(e),g,y),u=s.flatMap(l=>l.entries.flatMap(w=>w.bypasses)),A=$(u.filter(l=>l.held===!0).map(l=>l.name)),f=$(u.map(l=>l.name)).filter(l=>!A.includes(l)),a=V(e,f),c=f.map(l=>{let w=a.find(i=>i.permission.toLowerCase()===l.toLowerCase())?.permissionSet;return w?{permission:l,permissionSet:w.name}:{permission:l}}),h=X(e,o),b=h.assign.length>0;return{org:r,objectsRead:[...e.objectsRead],objects:s,emailsPerRecord:R,...p&&R.length>0?{limits:{...p}}:{},...je(t)?{limitsUnread:t.unread}:{},alertsAsSingle:g,bypasses:c,bypassesHeld:A,...b?{mute:h,emailsPerRecordMuted:N(P(Y(e,J(h))),g,y)}:{},unread:e.unread.map(({part:l,reason:w})=>({part:l,reason:w})),blinded:Q(e.unread),conditionsNotRead:e.conditionsNotRead,...n?{deliverability:n}:{}}}async function Ft(e){let r=e.writes??q(e.objects),t;try{t=await e.readAutomation(e.objects)}catch(s){return{error:v(s)}}let n=e.deliverability??(e.readDeliverability?(await oe({read:t,writes:Fe,readDeliverability:e.readDeliverability,accepted:!1,target:e.org,run:"seed"})).gate.deliverability:void 0);if(P(t).length===0)return{preview:Te(t,e.org,{},n,r)};let o=await e.readLimits().catch(s=>({unread:v(s)}));return{preview:Te(t,e.org,o,n,r)}}function I(e,r="and"){return e.length<=1?e.join(""):e.length===2?`${e[0]} ${r} ${e[1]}`:`${e.slice(0,-1).join(", ")}, ${r} ${e[e.length-1]}`}var It="SEED_EMAILS_EXCEEDED";function $t(e,r,t){if("error"in e)return{checks:[],unknown:[`what ${t} runs as these records are created could not be read (${e.error}): the emails they make it send are not known`]};let{preview:n}=e,o={objects:r.map(i=>({objectApiName:i.objectApiName,rows:i.recordCount,storageBytes:0}))},s=n.limitsUnread!==void 0?{unread:n.limitsUnread}:n.limits??{},p=me(o,n.emailsPerRecord,s),g=new Set(r.filter(i=>i.recordCount>0).map(i=>i.objectApiName)),y=n.objects.flatMap(i=>g.has(i.objectApiName)?i.entries.filter(m=>m.unread&&!m.keptQuiet&&m.when!=="before").map(m=>`"${m.name}" on ${i.objectApiName}`):[]),R=[...p.filter(i=>i.verdict==="unread").map(i=>`about ${B(i.emails,i.limit)}, but what ${t} has left today could not be read (${i.unread??"not said"})`),...n.blinded?[`part of what ${t} runs could not be read: emails it sends may not be counted`]:[],...y.length>0?[`the emails of ${I(y)} are not counted: what ${y.length===1?"it does":"they do"} was not read`]:n.conditionsNotRead>0?[`${n.conditionsNotRead} start condition(s) of ${t} not read: the emails of those flows are not counted`]:[]],u=p.find(i=>i.verdict==="exceeds");if(!u)return R.length>0?{checks:p,unknown:R}:{checks:p};let A=p.filter(i=>i.verdict==="exceeds"),f=$(A.flatMap(i=>i.objects.map(m=>m.objectApiName))),a=$(A.flatMap(i=>i.objects.flatMap(m=>m.sentBy))),c=new Map;for(let i of n.objects.flatMap(m=>m.entries))if(!(i.emails===0||!a.includes(i.name)))for(let{name:m}of i.bypasses)c.set(m,(c.get(m)??new Set).add(i.name));let h=n.bypasses.flatMap(i=>{let m=c.get(i.permission);return m?[{...i,quiets:$([...m])}]:[]}),b=A.map(i=>`about ${B(i.emails,i.limit)} (`+i.objects.map(m=>`${m.perRecord} per ${m.objectApiName}`).join(", ")+`), ${i.remaining??0} of ${i.max??0} left today`).join("; "),l=["lower the record counts",`set ${I(f)} to 0`,`turn off ${I(a.map(i=>`"${i}"`))}`,...h.map(i=>"give the user the seed writes as "+(i.permissionSet?`the permission set ${i.permissionSet}, whose ${i.permission}`:`a permission set holding ${i.permission}, which`)+` keeps ${I(i.quiets.map(m=>`"${m}"`))} quiet`)],w=`The seed was refused before it wrote anything: its records would make ${t} send ${b}. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To seed it, ${I(l,"or")}. Nothing was written.`;return{checks:p,refusal:w,figures:{org:t,limit:u.limit,emails:u.emails,remaining:u.remaining??0,max:u.max??0,objects:f,senders:a,bypasses:h},...R.length>0?{unknown:R}:{}}}var Ue={flow:e=>`flow "${e}"`,trigger:e=>`Apex trigger ${e}`,process:e=>`process "${e}"`,workflowRule:e=>`workflow rule "${e}"`},Ge={before:"before save",after:"after save",beforeAndAfter:"before and after save"},He={notification:"custom notifications",outbound:"outbound messages",sms:"text messages"};function Ke(e){let r=n=>n.held===!0?" (held)":n.held===!1?" (not held)":"",t=[Ge[e.when],...e.emails>0?[`${e.emails} email(s) a record`]:[],...e.messages.map(n=>`sends ${He[n]}`),...e.creates.length>0?[`creates ${e.creates.join(", ")}`]:[],...e.afterCommit?["then after commit"]:[],...e.bypasses.length>0?[`not for a user with ${e.bypasses.map(n=>n.name+r(n)).join(", ")}`]:[],...e.keptQuiet?["quiet for this seed"]:[],...e.unread?["what it does was not read"]:[]];return`${Ue[e.kind](e.name)} (${t.join("; ")})`}function Ot(e,r){if("error"in e)return[`target automation: what ${r} runs as these records are created could not be read (${e.error}): the emails they make it send are not known`];let{preview:t}=e,n=[`target automation: what ${r} runs as these records are created`];for(let o of t.objects)n.push(` ${o.objectApiName}: ${o.entries.map(Ke).join(", ")}`);t.objects.length===0&&n.push(t.blinded?" nothing found in what could be read":" nothing runs on them: no flow, Apex trigger, process or workflow rule"),t.bypassesHeld.length>0&&n.push(` bypass held: the user the seed writes as holds ${t.bypassesHeld.join(", ")}, and what names it stays quiet`);for(let o of t.bypasses)n.push(o.permissionSet?` bypass: ${o.permission} keeps quiet what names it; permission set ${o.permissionSet} holds it`:` bypass: ${o.permission} keeps quiet what names it; no permission set of ${r} was found to hold it`);t.alertsAsSingle&&t.emailsPerRecord.some(o=>o.alertsAmong)&&n.push(` ${r} counts its email alerts against its single emails too, as a Developer Edition does`);for(let{part:o,reason:s}of t.unread)n.push(` ${o} could not be read: ${s}`);return t.conditionsNotRead>0&&n.push(` ${t.conditionsNotRead} start condition(s) not read`),n}export{ze as a,rt as b,ot as c,st as d,at as e,ft as f,gt as g,ht as h,q as i,bt as j,yt as k,De as l,qe as m,wt as n,St as o,Ft as p,It as q,$t as r,Ot as s};