1use std::path::{Path, PathBuf};
8
9use serde_json::json;
10use standard_plugin_manifest::manifest::is_identifier;
11
12use standard_plugin::sources::examples;
13
14const UI_TEMPLATE: &str = examples::CLOCK_CARD;
15const PANE_TEMPLATE: &str = examples::SCROLL_LIST;
16const DAEMON_TEMPLATE: &str = examples::HEARTBEAT_DAEMON;
17const COMPANION_UI_TEMPLATE: &str = examples::TOGETHER_UI;
18const COMPANION_TEMPLATE: &str = examples::TOGETHER_COMPANION;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
22pub enum NewKind {
23 Ui,
25 Pane,
27 Daemon,
29 Companion,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum SdkSource {
36 Path(PathBuf),
37 Version(String),
38}
39
40impl SdkSource {
41 pub fn default_for_this_build() -> Self {
45 let beside = Path::new(env!("CARGO_MANIFEST_DIR")).join("../standard-plugin-sdk");
46 match beside.canonicalize() {
47 Ok(path) if path.join("Cargo.toml").is_file() => Self::Path(path),
48 _ => Self::Version(release_line(env!("CARGO_PKG_VERSION"))),
49 }
50 }
51
52 fn dependency(&self) -> String {
53 match self {
54 Self::Path(path) => format!("{{ path = {:?} }}", path.display().to_string()),
55 Self::Version(version) => format!("{version:?}"),
56 }
57 }
58}
59
60fn release_line(version: &str) -> String {
63 version.splitn(3, '.').take(2).collect::<Vec<_>>().join(".")
64}
65
66#[derive(Debug, thiserror::Error)]
67pub enum ScaffoldError {
68 #[error("{0:?} is not a plugin id: use lowercase letters, digits and dashes")]
69 Name(String),
70 #[error("{0} already exists")]
71 Exists(PathBuf),
72 #[error("{0}")]
73 Io(#[from] std::io::Error),
74}
75
76const PROFILES: &str = r#"
77# Small components: plugins ship as bytes to every viewer.
78[profile.release]
79opt-level = "s"
80lto = true
81codegen-units = 1
82panic = "abort"
83strip = true
84
85[profile.dev]
86panic = "abort"
87"#;
88
89const GITIGNORE: &str = "target/\nbundle/*.wasm\nbundle/browser/\n";
90
91const AGENTS_MD: &str = "# Notes for coding agents
95
96This is a Standard Code plugin, written in Rust with `standard-plugin-sdk`.
97Read the SDK's guides before you change it. They come from the SDK version
98in this project's `Cargo.lock`:
99
100- `standard-plugin guide` lists them, and `standard-plugin guide <name>`
101 prints one. Start with `standard-plugin guide agent-guide`.
102- The same files are the `docs/` directory of the `standard-plugin-sdk`
103 crate that `cargo metadata` names.
104- `cargo doc --open -p standard-plugin-sdk` shows the API, with the guides
105 under `standard_plugin::guide`.
106";
107
108const CLAUDE_MD: &str = "@AGENTS.md\n";
110
111fn module_name(crate_name: &str) -> String {
112 format!("{}.wasm", crate_name.replace('-', "_"))
113}
114
115fn cargo_toml(crate_name: &str, sdk: &SdkSource, standalone: bool) -> String {
116 let mut toml = format!(
117 r#"[package]
118name = "{crate_name}"
119version = "0.1.0"
120edition = "2024"
121publish = false
122
123[lib]
124# cdylib: the component; rlib: the plugin's own `cargo test` links it.
125crate-type = ["cdylib", "rlib"]
126
127[dependencies]
128serde = {{ version = "1", default-features = false, features = ["derive"] }}
129standard-plugin-sdk = {}
130"#,
131 sdk.dependency()
132 );
133 if standalone {
134 toml.push_str("\n# Its own workspace, even inside another project.\n[workspace]\n");
135 toml.push_str(PROFILES);
136 }
137 toml
138}
139
140fn manifest(
141 id: &str,
142 kind: &str,
143 module: &str,
144 surfaces: serde_json::Value,
145 grants: serde_json::Value,
146) -> String {
147 let mut manifest = json!({
148 "apiVersion": 2,
149 "kind": kind,
150 "id": id,
151 "version": "0.1.0",
152 "module": module,
153 });
154 if !surfaces.is_null() {
155 manifest["surfaces"] = surfaces;
156 }
157 manifest["grants"] = grants;
158 let mut text = serde_json::to_string_pretty(&manifest).expect("a JSON value serializes");
159 text.push('\n');
160 text
161}
162
163fn scroll_test(id: &str, plugin: &str, surface: &str) -> String {
166 format!(
167 r#"
168 #[test]
169 fn the_viewer_scrolls_it_and_a_key_reveals_the_selection() {{
170 let host = MockHost::new("{id}").surface("{surface}", Model::Cells);
171 let mut harness = Harness::<{plugin}>::activate(host, "{{}}");
172 assert!(harness.host(|host| host.scrolls.contains_key("{surface}")));
173 harness.key("{surface}", KeyCode::Down);
174 let revealed = harness.host(|host| host.reveals.last().cloned());
175 assert_eq!(revealed, Some(("{surface}".to_string(), 2, 2)));
176 }}
177"#
178 )
179}
180
181fn testable_ui(
185 source: &str,
186 id: &str,
187 plugin: &str,
188 surface: &str,
189 rows: u32,
190 extra_tests: &str,
191) -> String {
192 let source = source.replacen("#![no_std]", "#![cfg_attr(not(test), no_std)]", 1);
193 format!(
194 r#"{source}
195#[cfg(test)]
196mod tests {{
197 use super::*;
198 use standard_plugin::Power;
199 use standard_plugin::surface::Model;
200 use standard_plugin::testing::{{Harness, MockHost}};
201
202 #[test]
203 fn it_paints_once_the_viewer_lays_it_out() {{
204 let host = MockHost::new("{id}").surface("{surface}", Model::Cells);
205 let mut harness = Harness::<{plugin}>::activate(host, "{{}}");
206 harness.resize("{surface}", Geometry::cells(24, {rows}, (0, 0)));
207 harness.show("{surface}", true);
208 harness.frame(1_000, 16, Power::Mains);
209 assert!(!harness.commits("{surface}").is_empty());
210 }}
211{extra_tests}}}
212"#
213 )
214}
215
216fn personalise(
218 template: &str,
219 example_id: &str,
220 id: &str,
221 example_module: &str,
222 module: &str,
223) -> String {
224 template
225 .replace(&format!("\"{example_id}.",), &format!("\"{id}."))
226 .replace(&format!("`{example_id}."), &format!("`{id}."))
227 .replace(
228 &format!("\"id\": \"{example_id}\""),
229 &format!("\"id\": \"{id}\""),
230 )
231 .replace(&format!("call:{example_id}"), &format!("call:{id}"))
232 .replace(example_module, module)
233}
234
235fn write_crate(
236 dir: &Path,
237 crate_name: &str,
238 sdk: &SdkSource,
239 standalone: bool,
240 source: &str,
241 manifest: &str,
242) -> Result<(), ScaffoldError> {
243 std::fs::create_dir_all(dir.join("src"))?;
244 std::fs::create_dir_all(dir.join("bundle"))?;
245 std::fs::write(
246 dir.join("Cargo.toml"),
247 cargo_toml(crate_name, sdk, standalone),
248 )?;
249 std::fs::write(dir.join("src/lib.rs"), source)?;
250 std::fs::write(dir.join("bundle/standard-plugin.json"), manifest)?;
251 if standalone {
252 std::fs::write(dir.join(".gitignore"), GITIGNORE)?;
253 }
254 Ok(())
255}
256
257pub fn scaffold(
259 parent: &Path,
260 name: &str,
261 kind: NewKind,
262 sdk: &SdkSource,
263) -> Result<PathBuf, ScaffoldError> {
264 if !is_identifier(name) {
265 return Err(ScaffoldError::Name(name.into()));
266 }
267 let root = parent.join(name);
268 if root.exists() {
269 return Err(ScaffoldError::Exists(root));
270 }
271 match kind {
272 NewKind::Ui => {
273 let module = module_name(name);
274 let source = testable_ui(
275 &personalise(UI_TEMPLATE, "clock-card", name, "clock_card.wasm", &module),
276 name,
277 "ClockCard",
278 "card",
279 2,
280 "",
281 );
282 let manifest = manifest(
283 name,
284 "ui",
285 &module,
286 json!([{ "id": "card", "anchor": "sidebar.card", "model": "cells", "height": 2 }]),
287 json!({}),
288 );
289 write_crate(&root, name, sdk, true, &source, &manifest)?;
290 }
291 NewKind::Pane => {
292 let module = module_name(name);
293 let source = testable_ui(
294 &personalise(
295 PANE_TEMPLATE,
296 "scroll-list",
297 name,
298 "scroll_list.wasm",
299 &module,
300 ),
301 name,
302 "ScrollList",
303 "list",
304 202,
305 &scroll_test(name, "ScrollList", "list"),
306 );
307 let mut manifest = serde_json::from_str::<serde_json::Value>(&manifest(
308 name,
309 "ui",
310 &module,
311 json!([{ "id": "list", "anchor": "pane", "title": "List", "model": "cells" }]),
312 json!({}),
313 ))
314 .expect("the manifest is JSON");
315 manifest["commands"] =
316 json!([{ "id": "open", "title": "Open the list", "opens": "list" }]);
317 let mut manifest =
318 serde_json::to_string_pretty(&manifest).expect("a JSON value serializes");
319 manifest.push('\n');
320 write_crate(&root, name, sdk, true, &source, &manifest)?;
321 }
322 NewKind::Daemon => {
323 let module = module_name(name);
324 let source = personalise(
325 DAEMON_TEMPLATE,
326 "heartbeat",
327 name,
328 "heartbeat_daemon.wasm",
329 &module,
330 );
331 let manifest = manifest(name, "daemon", &module, serde_json::Value::Null, json!({}));
332 write_crate(&root, name, sdk, true, &source, &manifest)?;
333 }
334 NewKind::Companion => {
335 std::fs::create_dir_all(&root)?;
336 std::fs::write(
337 root.join("Cargo.toml"),
338 format!(
339 "# A UI plugin and its companion daemon: one plugin id, two components.\n\
340 [workspace]\nmembers = [\"ui\", \"companion\"]\nresolver = \"2\"\n{PROFILES}"
341 ),
342 )?;
343 std::fs::write(
344 root.join(".gitignore"),
345 GITIGNORE.replace("bundle", "*/bundle"),
346 )?;
347 let ui_crate = format!("{name}-ui");
348 let ui_module = module_name(&ui_crate);
349 let ui_source = testable_ui(
350 &personalise(
351 COMPANION_UI_TEMPLATE,
352 "together",
353 name,
354 "together_ui.wasm",
355 &ui_module,
356 ),
357 name,
358 "Together",
359 "card",
360 1,
361 "",
362 );
363 let ui_manifest = manifest(
364 name,
365 "ui",
366 &ui_module,
367 json!([{ "id": "card", "anchor": "sidebar.card", "model": "cells", "height": 1 }]),
368 json!({
369 format!("call:{name}"): "Asks the companion on your machine to start a build"
370 }),
371 );
372 write_crate(
373 &root.join("ui"),
374 &ui_crate,
375 sdk,
376 false,
377 &ui_source,
378 &ui_manifest,
379 )?;
380 let companion_crate = format!("{name}-companion");
381 let companion_module = module_name(&companion_crate);
382 let companion_source = personalise(
383 COMPANION_TEMPLATE,
384 "together",
385 name,
386 "together_companion.wasm",
387 &companion_module,
388 );
389 let companion_manifest = manifest(
390 name,
391 "companion",
392 &companion_module,
393 serde_json::Value::Null,
394 json!({
395 "process.exec:make": "Runs make in your project when you ask for a build"
396 }),
397 );
398 write_crate(
399 &root.join("companion"),
400 &companion_crate,
401 sdk,
402 false,
403 &companion_source,
404 &companion_manifest,
405 )?;
406 }
407 }
408 std::fs::write(root.join("AGENTS.md"), AGENTS_MD)?;
409 std::fs::write(root.join("CLAUDE.md"), CLAUDE_MD)?;
410 Ok(root)
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 #[test]
418 fn scaffolds_pass_check_and_carry_the_new_id() {
419 let temp = tempfile::tempdir().unwrap();
420 let sdk = SdkSource::Version("0.1.0".into());
421 let ui = scaffold(temp.path(), "my-card", NewKind::Ui, &sdk).unwrap();
422 let pane = scaffold(temp.path(), "my-list", NewKind::Pane, &sdk).unwrap();
423 let pair = scaffold(temp.path(), "builds", NewKind::Companion, &sdk).unwrap();
424 let daemon = scaffold(temp.path(), "beat", NewKind::Daemon, &sdk).unwrap();
425 for root in [&ui, &pane, &pair, &daemon] {
426 assert!(root.join("AGENTS.md").is_file() && root.join("CLAUDE.md").is_file());
427 }
428 for dir in [
429 ui,
430 pane.clone(),
431 pair.join("ui"),
432 pair.join("companion"),
433 daemon,
434 ] {
435 let manifest = std::fs::read(dir.join("bundle/standard-plugin.json")).unwrap();
436 let report = crate::check::check(&manifest, None);
437 assert!(report.is_ok(), "{dir:?}: {report}");
438 assert!(report.warnings.is_empty(), "{dir:?}: {report}");
439 }
440 let source = std::fs::read_to_string(pane.join("src/lib.rs")).unwrap();
441 assert!(source.contains(".set_scroll(") && source.contains(".reveal("));
442 assert!(source.contains("\"id\": \"my-list\"") && !source.contains("scroll_list.wasm"));
443 let source = std::fs::read_to_string(pair.join("ui/src/lib.rs")).unwrap();
444 assert!(source.contains("\"builds.status\""));
445 assert!(source.contains("#![cfg_attr(not(test), no_std)]"));
446 let toml = std::fs::read_to_string(pair.join("ui/Cargo.toml")).unwrap();
447 assert!(toml.contains(r#"crate-type = ["cdylib", "rlib"]"#));
448 assert!(!source.contains("\"together."));
449 assert!(matches!(
450 scaffold(temp.path(), "Bad Name", NewKind::Ui, &sdk),
451 Err(ScaffoldError::Name(_))
452 ));
453 assert!(matches!(
454 scaffold(temp.path(), "my-card", NewKind::Ui, &sdk),
455 Err(ScaffoldError::Exists(_))
456 ));
457 }
458}