From 48b5f79bed5eb5727dfd4b26352a82dabe9c07b5 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 10:34:23 +0100 Subject: [PATCH 1/7] refactor(cli-rs): make script plugins JavaScript only psychoscript upstream will not take TypeScript mode, so the carrier stops using it. A script plugin's entry is `init.js` and its modules are `.js`, compiled as plain JavaScript; an `init.ts` entry is refused at load with the rename that fixes it, and a `.ts` module a `.js` plugin imports is refused the same way. Authors type-check the JavaScript against the generated `opencode-plugin.d.ts` and `psychoscript.d.ts`. The carrier's `opencode:plugin` prelude is unchanged and is now `prelude.js`, which is what it always compiled to. --- .../cli-rs/crates/plugin/src/loader/mod.rs | 4 +- .../cli-rs/crates/plugin/src/loader/tests.rs | 21 +-- .../cli-rs/crates/plugin/src/script/bind.rs | 2 +- .../crates/plugin/src/script/measure.rs | 22 +-- .../cli-rs/crates/plugin/src/script/mod.rs | 5 +- .../src/script/{prelude.ts => prelude.js} | 0 .../cli-rs/crates/plugin/src/script/tests.rs | 161 +++++++++--------- .../cli-rs/crates/plugin/src/script/vm.rs | 20 ++- packages/cli-rs/crates/plugin/src/source.rs | 27 ++- 9 files changed, 146 insertions(+), 116 deletions(-) rename packages/cli-rs/crates/plugin/src/script/{prelude.ts => prelude.js} (100%) diff --git a/packages/cli-rs/crates/plugin/src/loader/mod.rs b/packages/cli-rs/crates/plugin/src/loader/mod.rs index 238501db4e08..5ec9e2137426 100644 --- a/packages/cli-rs/crates/plugin/src/loader/mod.rs +++ b/packages/cli-rs/crates/plugin/src/loader/mod.rs @@ -145,7 +145,7 @@ pub struct Loader { /// Cache the resolved entry while the spec remains configured. Installing a newer generation must not move a /// running plugin. packages: RefCell>, - /// A directory with a `plugin.toml` whose entry is `.ts`/`.js` runs as a script plugin ([`crate::script`]). + /// A directory with a `plugin.toml` whose entry is `.js` runs as a script plugin ([`crate::script`]). #[cfg(script)] script: Option, /// A script plugin's sources, read and compiled on threads of their own. @@ -221,7 +221,7 @@ impl Loader { Self { off: true, ..self } } - /// Runs the directories with a `plugin.toml` targeting script (`.ts`/`.js`) and no native build as script plugins. + /// Runs the directories with a `plugin.toml` targeting script (`.js`) and no native build as script plugins. #[cfg(script)] pub fn with_script(self, walked: impl Fn() + Send + Sync + 'static) -> Self { let walked: std::sync::Arc = std::sync::Arc::new(walked); diff --git a/packages/cli-rs/crates/plugin/src/loader/tests.rs b/packages/cli-rs/crates/plugin/src/loader/tests.rs index c892630e7486..aa7d4e72f865 100644 --- a/packages/cli-rs/crates/plugin/src/loader/tests.rs +++ b/packages/cli-rs/crates/plugin/src/loader/tests.rs @@ -1161,7 +1161,7 @@ fn a_native_library_is_skipped_and_never_asked_about() { fn a_build_without_script_says_it_has_no_script_plugin_support() { let project = Project::new(); write(&project.global().join("plugin.toml"), "id = \"hello\"\n"); - write(&project.global().join("init.ts"), "export default () => {}\n"); + write(&project.global().join("init.js"), "export default () => {}\n"); let (host, registry) = (host(), Registry::define(Vec::new(), [])); project.loader(Vec::new()).reconcile(&dynamic(&host), ®istry); let skipped = Status::Skipped(crate::SKIPPED_NO_SCRIPT.to_owned()); @@ -1182,8 +1182,9 @@ fn the_loader_picks_carrier_by_entry_extension_and_script_wins_without_entry() { assert_eq!(carrier(&dir), expected, "{name}"); }; check("empty", &[], None); - check("ts", &[("plugin.toml", "id = \"ts\"\n"), ("init.ts", "")], Some(Carrier::Script)); check("js", &[("plugin.toml", "id = \"js\"\n"), ("init.js", "")], Some(Carrier::Script)); + // A `.ts` entry still picks the script carrier, which then refuses it as JavaScript only. + check("ts", &[("plugin.toml", "id = \"ts\"\n"), ("init.ts", "")], Some(Carrier::Script)); check("luau-only", &[("plugin.toml", "id = \"luau\"\n"), ("init.luau", "")], Some(Carrier::Luau)); check("both", &[("plugin.toml", "id = \"both\"\n"), ("init.luau", ""), ("init.ts", "")], Some(Carrier::Script)); check( @@ -1255,7 +1256,7 @@ pub(crate) mod script_loader_tests { // Save a broken edit: previous version stays active, failure reports syntax error. fs::write( - dir.join("init.ts"), + dir.join("init.js"), "export default define((setup) => { ", ) @@ -1264,14 +1265,14 @@ pub(crate) mod script_loader_tests { let status = entry(®istry.entries(), &target).status.clone(); let Status::Failed(error) = status else { panic!("{status:?}") }; assert!( - error.starts_with("example.script-hello: init.ts:") && error.ends_with("(previous version still active)"), + error.starts_with("example.script-hello: init.js:") && error.ends_with("(previous version still active)"), "{error}" ); assert!(footer_text(&host, ®istry).contains("hello")); // Fix it: new version activates and draws updated text. - let fixed = fs::read_to_string(script_example("hello").join("init.ts")).unwrap().replace("\"hello\"", "\"hi\""); - fs::write(dir.join("init.ts"), fixed).unwrap(); + let fixed = fs::read_to_string(script_example("hello").join("init.js")).unwrap().replace("\"hello\"", "\"hi\""); + fs::write(dir.join("init.js"), fixed).unwrap(); assert!(settle_script(&loader, &host, ®istry)); assert_eq!(entry(®istry.entries(), &target).status, Status::Active); let text = footer_text(&host, ®istry); @@ -1322,7 +1323,7 @@ pub(crate) mod script_loader_tests { assert_eq!(decisions.decision(&tree), None); // Editing after approval holds it back and unloads the running build. - fs::write(dir.join("init.ts"), "throw new Error('not approved')").unwrap(); + fs::write(dir.join("init.js"), "throw new Error('not approved')").unwrap(); assert!(unhashed(&|| settle_script(&loader, &host, ®istry))); assert_eq!(status(), Status::Pending); } @@ -1334,14 +1335,14 @@ pub(crate) mod script_loader_tests { let dir = temp.path().join("plugin"); install_script("hello", &dir); fs::write( - temp.path().join("outside.ts"), + temp.path().join("outside.js"), "export const x = 1 ", ) .unwrap(); - std::os::unix::fs::symlink(dir.join("init.ts"), dir.join("inside.ts")).unwrap(); + std::os::unix::fs::symlink(dir.join("init.js"), dir.join("inside.js")).unwrap(); assert!(crate::script::read(&dir).is_ok(), "a link inside the directory is read"); - std::os::unix::fs::symlink(temp.path().join("outside.ts"), dir.join("outside.ts")).unwrap(); + std::os::unix::fs::symlink(temp.path().join("outside.js"), dir.join("outside.js")).unwrap(); let error = crate::script::read(&dir).unwrap_err(); assert!(error.contains("a link out of the plugin directory"), "{error}"); } diff --git a/packages/cli-rs/crates/plugin/src/script/bind.rs b/packages/cli-rs/crates/plugin/src/script/bind.rs index dcebe62472d3..f8de4ddbd68e 100644 --- a/packages/cli-rs/crates/plugin/src/script/bind.rs +++ b/packages/cli-rs/crates/plugin/src/script/bind.rs @@ -25,7 +25,7 @@ use crate::client; use crate::current::{ChangedSlot, Current, Enter, EnterChanged, Slot}; /// The host-provided `opencode:plugin` module source. -pub(crate) const PRELUDE: &str = include_str!("prelude.ts"); +pub(crate) const PRELUDE: &str = include_str!("prelude.js"); /// The most of one `console.*` line the log keeps, in bytes of the plugin's text. pub(crate) const PRINT: usize = 4 << 10; diff --git a/packages/cli-rs/crates/plugin/src/script/measure.rs b/packages/cli-rs/crates/plugin/src/script/measure.rs index bb4c34fbd176..5a3b4dede582 100644 --- a/packages/cli-rs/crates/plugin/src/script/measure.rs +++ b/packages/cli-rs/crates/plugin/src/script/measure.rs @@ -48,8 +48,8 @@ fn each(rounds: u32, mut f: impl FnMut()) -> Duration { } fn script_registered(init: &str) -> (abi::Registered, std::rc::Rc) { - let srcs = Sources::from_files([("plugin.toml", "id = \"test.measure\""), ("init.ts", init)]); - let compiled = Compiled::new(&srcs, "test.measure", "init.ts", bind::PRELUDE).unwrap(); + let srcs = Sources::from_files([("plugin.toml", "id = \"test.measure\""), ("init.js", init)]); + let compiled = Compiled::new(&srcs, "test.measure", "init.js", bind::PRELUDE).unwrap(); let mut registered = abi::Registered::new("test.measure", None); let plugin = bind::setup(&compiled, &mut registered.setup(), Duration::from_millis(100), MEMORY, None).unwrap(); (registered, plugin) @@ -81,7 +81,7 @@ fn measure_calls_g1_to_g3() { // G1: quick start render + command, under monitor, and KEEP render. let hello_srcs = read(&script_example("hello")).unwrap(); - let hello_compiled = Compiled::new(&hello_srcs, "example.script-hello", "init.ts", bind::PRELUDE).unwrap(); + let hello_compiled = Compiled::new(&hello_srcs, "example.script-hello", "init.js", bind::PRELUDE).unwrap(); let mut hello_reg = abi::Registered::new("example.script-hello", None); let _hello_plugin = bind::setup(&hello_compiled, &mut hello_reg.setup(), Duration::from_millis(100), MEMORY, None).unwrap(); @@ -169,15 +169,15 @@ fn measure_startup_memory_and_runaways_g4_to_g6() { "import {{ define }} from \"opencode:plugin\"\n{}\nexport default define((setup) => {{ setup.command({{ name: \"x\" }}, () => {{}}) }})\n", filler(1200) ); - let medium_srcs = Sources::from_files([("plugin.toml", "id = \"test.medium\""), ("init.ts", &medium_init)]); + let medium_srcs = Sources::from_files([("plugin.toml", "id = \"test.medium\""), ("init.js", &medium_init)]); // G5: idle heap. println!("G5 idle heap hello: {} bytes", idle_memory(&hello_srcs).unwrap()); println!("G5 idle heap 1200-line ({} bytes): {} bytes", medium_init.len(), idle_memory(&medium_srcs).unwrap()); // G4: activation startup + ~1 MiB single-file compile. - let hello_compiled = Compiled::new(&hello_srcs, "example.script-hello", "init.ts", bind::PRELUDE).unwrap(); - let medium_compiled = Compiled::new(&medium_srcs, "test.medium", "init.ts", bind::PRELUDE).unwrap(); + let hello_compiled = Compiled::new(&hello_srcs, "example.script-hello", "init.js", bind::PRELUDE).unwrap(); + let medium_compiled = Compiled::new(&medium_srcs, "test.medium", "init.js", bind::PRELUDE).unwrap(); let act_hello = each(200, || { let mut reg = abi::Registered::new("example.script-hello", None); drop(bind::setup(&hello_compiled, &mut reg.setup(), Duration::from_millis(100), MEMORY, None).unwrap()); @@ -195,12 +195,12 @@ fn measure_startup_memory_and_runaways_g4_to_g6() { big_init.push_str( "0]\nexport default define((setup) => { setup.command({ name: \"b\" }, () => { void big.length }) })\n", ); - let big_srcs = Sources::from_files([("plugin.toml", "id = \"test.big\""), ("init.ts", big_init.as_str())]); + let big_srcs = Sources::from_files([("plugin.toml", "id = \"test.big\""), ("init.js", big_init.as_str())]); let t0 = Instant::now(); - drop(Compiled::new(&big_srcs, "test.big", "init.ts", bind::PRELUDE).unwrap()); + drop(Compiled::new(&big_srcs, "test.big", "init.js", bind::PRELUDE).unwrap()); let big_cold = t0.elapsed(); let big_warm = - each(5, || drop(std::hint::black_box(Compiled::new(&big_srcs, "test.big", "init.ts", bind::PRELUDE).unwrap()))); + each(5, || drop(std::hint::black_box(Compiled::new(&big_srcs, "test.big", "init.js", bind::PRELUDE).unwrap()))); println!("G4 compile ~1 MiB ({} bytes): cold {big_cold:?}, warm {big_warm:?}", big_init.len()); // G6: runaway stops (spin, catastrophic regex, shared DAG). @@ -226,8 +226,8 @@ export default define((setup) => { }) }) "#; - let run_srcs = Sources::from_files([("init.ts", runaway_src)]); - let run_compiled = Compiled::new(&run_srcs, "test.runaway", "init.ts", MINI_PRELUDE).unwrap(); + let run_srcs = Sources::from_files([("init.js", runaway_src)]); + let run_compiled = Compiled::new(&run_srcs, "test.runaway", "init.js", MINI_PRELUDE).unwrap(); for (h, label) in [(0, "spin"), (1, "regex"), (2, "shared-dag")] { let mut act = Activation::start(&run_compiled, MINI_PRELUDE, Duration::from_millis(100), MEMORY, |_| { HostBindings::default() diff --git a/packages/cli-rs/crates/plugin/src/script/mod.rs b/packages/cli-rs/crates/plugin/src/script/mod.rs index 9b9066074bfa..1e466f64f485 100644 --- a/packages/cli-rs/crates/plugin/src/script/mod.rs +++ b/packages/cli-rs/crates/plugin/src/script/mod.rs @@ -45,12 +45,13 @@ pub fn enabled() -> bool { !crate::turned_off(std::env::var_os("OPENCODE_PLUGIN_SCRIPT").as_deref()) } -/// Reads `plugin.toml` and every `.ts` (excluding `.d.ts`) and `.js` file in `dir`. +/// Reads `plugin.toml` and every `.js` file in `dir`, and any `.ts` left so [`parse_manifest`] can refuse it. pub fn read(dir: &Path) -> Result { Sources::read(dir) } -/// Parses `plugin.toml`, defaulting `entry` to `init.ts` (or `init.js` when only `init.js` is present). +/// Parses `plugin.toml`, defaulting `entry` to `init.js`. Script plugins are JavaScript: an `init.ts` entry is +/// refused, naming the `init.js` to rename it to. pub fn parse_manifest(sources: &Sources) -> Result { Manifest::parse(sources) } diff --git a/packages/cli-rs/crates/plugin/src/script/prelude.ts b/packages/cli-rs/crates/plugin/src/script/prelude.js similarity index 100% rename from packages/cli-rs/crates/plugin/src/script/prelude.ts rename to packages/cli-rs/crates/plugin/src/script/prelude.js diff --git a/packages/cli-rs/crates/plugin/src/script/tests.rs b/packages/cli-rs/crates/plugin/src/script/tests.rs index dc7593187c8a..09a6eae4c323 100644 --- a/packages/cli-rs/crates/plugin/src/script/tests.rs +++ b/packages/cli-rs/crates/plugin/src/script/tests.rs @@ -35,7 +35,7 @@ fn echo_start(files: &[(&str, &str)], limit: Duration, memory: usize) -> Result< } fn script_sources(init: &str) -> Sources { - Sources::from_files([("plugin.toml", "id = \"test.script\"\ncontract = \"2.0\""), ("init.ts", init)]) + Sources::from_files([("plugin.toml", "id = \"test.script\"\ncontract = \"2.0\""), ("init.js", init)]) } fn running(host: &Rc, definition: crate::Definition) -> Rc { @@ -121,7 +121,7 @@ fn cpu(f: impl FnOnce() -> R) -> (Duration, R) { (crate::contain::thread_cpu().unwrap().saturating_sub(start), result) } -/// A plugin in `dir` whose `init.ts` holds an array literal of `items` numbers: about `2 * items` bytes. +/// A plugin in `dir` whose `init.js` holds an array literal of `items` numbers: about `2 * items` bytes. fn big_plugin(dir: &Path, items: usize) { fs::create_dir_all(dir).unwrap(); fs::write(dir.join(MANIFEST), "id = \"test.big\"\n").unwrap(); @@ -129,7 +129,7 @@ fn big_plugin(dir: &Path, items: usize) { "import {{ define }} from \"opencode:plugin\"\nconst big = [{}]\nexport default define(() => {{ void big }})\n", "1,".repeat(items) ); - fs::write(dir.join("init.ts"), init).unwrap(); + fs::write(dir.join("init.js"), init).unwrap(); } fn checked(body: &str) -> (Vec, Option) { @@ -137,7 +137,7 @@ fn checked(body: &str) -> (Vec, Option) { let registry = plugin_with( &host, &format!( - " setup.command({{ name: \"check\" }}, (host) => {{\n const say = (message: string) => host.toast({{ variant: \"info\", message }})\n {body}\n }})" + " setup.command({{ name: \"check\" }}, (host) => {{\n const say = (message) => host.toast({{ variant: \"info\", message }})\n {body}\n }})" ), ); run_cmd(&host, "check", None); @@ -150,14 +150,14 @@ fn checked(body: &str) -> (Vec, Option) { fn a_script_error_names_the_plugin_the_file_and_the_line() { let syntax = "import { define } from \"opencode:plugin\"\n\nconst = 1\n"; let err = define(&script_sources(syntax), None).err().unwrap(); - assert!(err.starts_with("test.script: init.ts:3:"), "{err}"); + assert!(err.starts_with("test.script: init.js:3:"), "{err}"); - let util = "export function width(node: { text: string }) {\n return node.text.length\n}\n"; + let util = "export function width(node) {\n return node.text.length\n}\n"; let init = r#"import { define } from "opencode:plugin" -import { width } from "./lib/util.ts" +import { width } from "./lib/util.js" export default define((setup) => { setup.command({ name: "boom" }, () => { - void width(null as unknown as { text: string }) + void width(null) }) setup.command({ name: "raw" }, () => { throw "raw boom" @@ -165,15 +165,15 @@ export default define((setup) => { }) "#; let mut srcs = script_sources(init); - srcs.files.insert("lib/util.ts".into(), util.as_bytes().to_vec()); + srcs.files.insert("lib/util.js".into(), util.as_bytes().to_vec()); let h = host(); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "boom", None); let error = failure(®, "test.script").unwrap(); - assert!(error.starts_with("test.script: lib/util.ts:2:") && error.contains("TypeError:"), "{error}"); + assert!(error.starts_with("test.script: lib/util.js:2:") && error.contains("TypeError:"), "{error}"); let traceback = error.split_once("\nstack traceback:\n").map(|(_, frames)| frames).unwrap_or_default(); - assert!(traceback.contains("lib/util.ts:2:") && traceback.contains("init.ts:5:"), "{error}"); + assert!(traceback.contains("lib/util.js:2:") && traceback.contains("init.js:5:"), "{error}"); for noise in ["opencode:entry", "opencode:plugin", "opencode:host"] { assert!(!error.contains(noise), "{noise}: {error}"); } @@ -199,10 +199,10 @@ export default define((setup) => { run_cmd(&h, "big", None); let error = failure(®, "test.script").unwrap(); assert!(error.len() < 4096 + 200, "{} bytes: {:?}", error.len(), error.get(..200)); - assert!(error.starts_with("test.script: init.ts:4:"), "{:?}", error.get(..200)); + assert!(error.starts_with("test.script: init.js:4:"), "{:?}", error.get(..200)); assert!(error.contains(r"\u{1b}]0;title\u{7}EEE") && !error.contains('\u{1b}')); let (message, frames) = error.split_once("\nstack traceback:\n").unwrap_or((&error, "")); - assert!(message.ends_with(" bytes)") && frames.contains("init.ts:4:"), "{error}"); + assert!(message.ends_with(" bytes)") && frames.contains("init.js:4:"), "{error}"); } #[test] @@ -420,13 +420,13 @@ import { define } from "opencode:plugin" export default define((setup) => { setup.handler(() => ({ text: () => {} })) setup.handler(() => { const s = "a".repeat(1024 * 1024); return Array.from({ length: 40 }, () => s) }) - setup.handler(() => { let d: unknown = "leaf"; for (let i = 0; i < 140; i++) d = [d]; return d }) + setup.handler(() => { let d = "leaf"; for (let i = 0; i < 140; i++) d = [d]; return d }) }) "#; for (idx, expected) in [(0, &["TypeError", "function"][..]), (1, &["RangeError"][..]), (2, &["depth", "TypeError"][..])] { - let mut act = echo_start(&[("init.ts", js)], Duration::from_secs(2), MEMORY).unwrap(); + let mut act = echo_start(&[("init.js", js)], Duration::from_secs(2), MEMORY).unwrap(); let err = act.call(idx, vec![]).unwrap_err(); assert!(expected.iter().any(|needle| err.contains(needle)), "case {idx}: {err}"); } @@ -439,7 +439,7 @@ fn crossing_bounds_stop_shared_dags_sparse_arrays_and_uncatchable_refusals() { let render_built = |build: &str| -> (Option, Duration) { let h = host(); let init = format!( - "import {{ define, show }} from \"opencode:plugin\"\nlet node: unknown\n{build}\nexport default define((setup) => {{\n setup.slot({{ path: \"home.footer\" }}, () => show(node))\n}})\n" + "import {{ define, show }} from \"opencode:plugin\"\nlet node\n{build}\nexport default define((setup) => {{\n setup.slot({{ path: \"home.footer\" }}, () => show(node))\n}})\n" ); let reg = running(&h, define(&script_sources(&init), None).unwrap().0); let (used, _) = cpu(|| footer_text(&h, ®)); @@ -546,7 +546,7 @@ fn a_render_that_asks_for_an_effect_fails() { "read.toast", r#"import { define } from "opencode:plugin" export default define((setup) => { - setup.slot({ path: "home.footer" }, (read) => { (read as any).toast({ variant: "info", message: "from a render" }) }) + setup.slot({ path: "home.footer" }, (read) => { read.toast({ variant: "info", message: "from a render" }) }) })"#, "test.script:", "not a function", @@ -567,7 +567,7 @@ export default define((setup) => { export default define((setup) => { setup.slot({ path: "home.footer" }, async () => show(text("async render"))) })"#, - "test.script: init.ts:3:", + "test.script: init.js:3:", "TypeError: a render cannot wait", ), ( @@ -581,7 +581,7 @@ async function slowRender() { export default define((setup) => { setup.slot({ path: "home.footer" }, slowRender) })"#, - "test.script: init.ts:3:", + "test.script: init.js:3:", "TypeError: a render cannot wait", ), ] { @@ -596,15 +596,15 @@ export default define((setup) => { ( "define async", "import { define } from \"opencode:plugin\"\n\nexport default define(async () => {\n await Promise.resolve()\n})\n", - "test.script: init.ts:3:", + "test.script: init.js:3:", ), ( "bare async default", "export default async function setup() {\n await Promise.resolve()\n}\n", - "test.script: init.ts:1:", + "test.script: init.js:1:", ), ] { - let compiled = vm::Compiled::new(&script_sources(src), "test.script", "init.ts", bind::PRELUDE).unwrap(); + let compiled = vm::Compiled::new(&script_sources(src), "test.script", "init.js", bind::PRELUDE).unwrap(); let mut reg = abi::Registered::new("test.script", None); let err = bind::setup(&compiled, &mut reg.setup(), Duration::from_millis(100), MEMORY, None) .err() @@ -629,7 +629,7 @@ export default define((setup) => { }) }) "#; - let srcs = Sources::from_files([("plugin.toml", "id = \"test.script.print\""), ("init.ts", init)]); + let srcs = Sources::from_files([("plugin.toml", "id = \"test.script.print\""), ("init.js", init)]); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "print", None); assert_eq!(failure(®, "test.script.print"), None); @@ -647,7 +647,7 @@ export default define((setup) => { fn render_arity_and_lazy_changed_deliver_exact_fields() { let init = r#" import { define, show, span, text } from "opencode:plugin" -const line = (s: string) => show(text([span(s)])) +const line = (s) => show(text([span(s)])) export default define((setup) => { setup.slot({ path: "home.footer" }, () => line("zero")) setup.slot({ path: "home.footer" }, (_read, input) => line("two:" + String(input.session_id))) @@ -660,12 +660,12 @@ export default define((setup) => { const m = spread.messages ? spread.messages[0][1] : "none" return line([keys, input.session_id, s1, s2, l, m, changed.local, changed.all].map(String).join("|")) }) - setup.slot({ path: "home.footer" }, (...args: any[]) => line("rest:" + (args[2].sessions ? args[2].sessions.length : 0))) + setup.slot({ path: "home.footer" }, (...args) => line("rest:" + (args[2].sessions ? args[2].sessions.length : 0))) setup.route("r0", () => line("route0")) setup.route("r2", (_read, changed) => line("route2:" + Object.keys(changed).sort().join(",") + ":" + String(changed.all))) }) "#; - let compiled = vm::Compiled::new(&script_sources(init), "test.arity", "init.ts", bind::PRELUDE).unwrap(); + let compiled = vm::Compiled::new(&script_sources(init), "test.arity", "init.js", bind::PRELUDE).unwrap(); let mut reg = abi::Registered::new("test.arity", None); let _plugin = bind::setup(&compiled, &mut reg.setup(), Duration::from_millis(100), MEMORY, None).unwrap(); @@ -890,7 +890,7 @@ fn the_cpu_budget_holds_for_each_stretch_of_a_task() { h.reply(); h.app.advance(Duration::from_millis(1)); let error = failure(®, "test.script").expect("the error failed the plugin"); - assert!(error.contains("init.ts:") && error.contains("after the reply"), "{error}"); + assert!(error.contains("init.js:") && error.contains("after the reply"), "{error}"); } #[test] @@ -965,7 +965,7 @@ export default define((setup) => { }) "#; let mut registered = abi::Registered::new("test.script", None); - let compiled = vm::Compiled::new(&script_sources(init), "test.script", "init.ts", bind::PRELUDE).unwrap(); + let compiled = vm::Compiled::new(&script_sources(init), "test.script", "init.js", bind::PRELUDE).unwrap(); let _plugin = bind::setup(&compiled, &mut registered.setup(), Duration::from_millis(100), MEMORY, None).unwrap(); let handler = registered.layers()[0].1.clone(); let key = |bind: &str| -> abi::interact::Event { @@ -1163,20 +1163,16 @@ fn no_vm_is_made_without_a_script_plugin() { fn a_manifest_reads_its_flat_keys() { let srcs = Sources::from_files([ ("plugin.toml", "# a comment\nid = \"example.hello\"\nname = \"Hello\"\ncontract = \"2.0\"\n"), - ("init.ts", "export default () => {}"), + ("init.js", "export default () => {}"), ]); let manifest = parse_manifest(&srcs).unwrap(); - assert_eq!((manifest.id.as_str(), manifest.entry.as_str()), ("example.hello", "init.ts")); - - let js_only = - Sources::from_files([("plugin.toml", "id = \"example.js\"\n"), ("init.js", "export default () => {}")]); - assert_eq!(parse_manifest(&js_only).unwrap().entry, "init.js"); + assert_eq!((manifest.id.as_str(), manifest.entry.as_str()), ("example.hello", "init.js")); let err = |toml: &str| parse_manifest(&Sources::from_files([("plugin.toml", toml)])).unwrap_err(); for (toml, expected) in [ ("id = \"x\"\ncontract = \"1.0\"", "contract 1.0"), ("id = [\"x\"]", "only `key = \"string\"`"), - ("entry = \"../x.ts\"\nid = \"x\"", "not a .ts or .js file"), + ("entry = \"../x.js\"\nid = \"x\"", "not a .js file"), ("entry = \"types.d.ts\"\nid = \"x\"", "declaration file"), ] { let got = err(toml); @@ -1184,6 +1180,19 @@ fn a_manifest_reads_its_flat_keys() { } } +#[test] +fn typescript_is_refused_as_javascript_only() { + let ts = Sources::from_files([("plugin.toml", "id = \"test.ts\"\n"), ("init.ts", "export default () => {}")]); + let err = define(&ts, None).err().expect("init.ts refused"); + assert_eq!(err, "script plugins are JavaScript: rename init.ts to init.js and remove its types"); + + // A `.js` plugin that imports a `.ts` module hears the same refusal, naming the module. + let mut imported = script_sources("import { x } from \"./lib/x.ts\"\nexport default () => x\n"); + imported.files.insert("lib/x.ts".into(), b"export const x = 1".to_vec()); + let err = define(&imported, None).err().expect("./lib/x.ts refused"); + assert_eq!(err, "script plugins are JavaScript: rename ./lib/x.ts to ./lib/x.js and remove its types"); +} + #[test] fn a_spinning_plugin_is_failed_on_cpu_time_and_the_thread_is_back_at_once() { let init = r#" @@ -1273,7 +1282,7 @@ fn a_plugin_that_allocates_past_its_cap_fails() { ] { let h = host(); let init = format!( - "import {{ define }} from \"opencode:plugin\"\nlet keep: string[] = []\nfunction fill() {{\n for (let i = 0; ; i++) keep.push(\"x\".repeat(1024) + i)\n}}\nexport default define((setup) => {{\n setup.command({{ name: \"hog\" }}, {handler})\n}})\n" + "import {{ define }} from \"opencode:plugin\"\nlet keep = []\nfunction fill() {{\n for (let i = 0; ; i++) keep.push(\"x\".repeat(1024) + i)\n}}\nexport default define((setup) => {{\n setup.command({{ name: \"hog\" }}, {handler})\n}})\n" ); let reg = running(&h, define_with(&script_sources(&init), None, 4 << 20).unwrap().0); run_cmd(&h, "hog", None); @@ -1339,9 +1348,9 @@ fn a_build_holds_the_files_its_key_names() { let temp = opencode_util::temp::tempdir().unwrap(); let dir = temp.path().join("plugin"); install_script("hello", &dir); - let good = fs::read(dir.join("init.ts")).unwrap(); + let good = fs::read(dir.join("init.js")).unwrap(); let key = crate::pipe::tree::light(&dir).unwrap(); - fs::write(dir.join("init.ts"), "export default define((setup) => { const = 1 })").unwrap(); + fs::write(dir.join("init.js"), "export default define((setup) => { const = 1 })").unwrap(); let mut retries = 0; let sources = crate::source::read_wanted_with( &dir, @@ -1350,7 +1359,7 @@ fn a_build_holds_the_files_its_key_names() { || true, || { retries += 1; - fs::write(dir.join("init.ts"), &good).unwrap(); + fs::write(dir.join("init.js"), &good).unwrap(); }, ) .expect("sources") @@ -1383,14 +1392,14 @@ fn a_build_for_a_plugin_that_went_is_dropped() { fn a_plugin_runs_under_small_and_tight_caps() { let init = r#" import { define } from "opencode:plugin" -let keep: unknown[] = [] +let keep = [] export default define((setup) => { setup.handler(() => { for (let i = 0; i < 64; i++) keep.push("x".repeat(512) + keep.length) }) setup.handler(() => "idle") }) "#; for (cap, free) in [(1 << 20, 200 << 10), (4 << 20, 400 << 10)] { - let mut act = echo_start(&[("init.ts", init)], Duration::from_secs(10), cap).unwrap(); + let mut act = echo_start(&[("init.js", init)], Duration::from_secs(10), cap).unwrap(); while (act.heap_bytes().unwrap_or(0) as usize) + free < cap { act.call(0, vec![]).unwrap(); } @@ -1403,23 +1412,23 @@ fn the_sandbox_holds_a_plugin_to_its_own_files() { let h = host(); let init = r#" import { define, KEEP } from "opencode:plugin" -import { value as mine } from "./mine.ts" -function refused(f: () => unknown): string { +import { value as mine } from "./mine.js" +function refused(f) { try { f(); return "allowed" } catch (err) { return String(err) } } export default define((setup) => { setup.command({ name: "probe" }, (host) => { - const seen: Record = { + const seen = { eval: typeof eval, fetch: typeof fetch, setTimeout: typeof setTimeout, setInterval: typeof setInterval, process: typeof process, Intl: typeof Intl, Proxy: typeof Proxy, Reflect: typeof Reflect, - hostGlobal: typeof __opencode_host, setProto: typeof (Object as Record).setPrototypeOf, + hostGlobal: typeof __opencode_host, setProto: typeof Object.setPrototypeOf, funcCtor: refused(() => Function("return 1")), - reqUp: refused(() => require("../escape.ts")), + reqUp: refused(() => require("../escape.js")), reqAbs: refused(() => require("/etc/passwd")), reqFs: refused(() => require("fs")), reqHost: refused(() => require("opencode:host")), - frozenHost: refused(() => { (host as Record).toast = null }), - frozenKeep: refused(() => { (KEEP as Record).type = "x" }), + frozenHost: refused(() => { host.toast = null }), + frozenKeep: refused(() => { KEEP.type = "x" }), mine, } host.toast({ variant: "info", message: Object.keys(seen).sort().map((k) => k + "=" + seen[k]).join("\n") }) @@ -1427,7 +1436,7 @@ export default define((setup) => { }) "#; let mut srcs = script_sources(init); - srcs.files.insert("mine.ts".into(), b"export const value = 'own'".to_vec()); + srcs.files.insert("mine.js".into(), b"export const value = 'own'".to_vec()); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "probe", None); assert_eq!(failure(®, "test.script"), None); @@ -1444,45 +1453,40 @@ export default define((setup) => { } assert_eq!(seen["mine"], "own"); - for bad in ["../escape.ts", "./../escape.ts", "/etc/passwd", "fs", "opencode:host"] { + for bad in ["../escape.js", "./../escape.js", "/etc/passwd", "fs", "opencode:host"] { let escape = format!("import x from {bad:?}\nexport default () => x\n"); assert!(define(&script_sources(&escape), None).is_err(), "{bad} compiled"); } } #[test] -fn imports_resolve_cache_erase_types_and_refuse_cycles() { +fn imports_resolve_and_refuse_cycles() { let temp = opencode_util::temp::tempdir().unwrap(); let dir = temp.path().join("plugin"); let init = r#" import { contract, define } from "opencode:plugin" -import type { Boxed } from "./x.ts" -import { box as one } from "./x.ts" -import { box as two } from "./lib/again.ts" -import { one as libOne } from "./lib/one.ts" -import { sibling } from "./lib/sibling.ts" +import { box as one } from "./x.js" +import { box as two } from "./lib/again.js" +import { one as libOne } from "./lib/one.js" +import { sibling } from "./lib/sibling.js" export default define((setup) => { setup.command({ name: "probe" }, (host) => { - const typed: Boxed = one satisfies Boxed host.toast({ variant: "info", - message: [(one === two) + ":" + typed.loads, libOne, sibling, contract as string].join("|"), + message: [(one === two) + ":" + one.loads, libOne, sibling, contract].join("|"), }) }) }) "#; for (path, text) in [ ("plugin.toml", "id = \"test.script\"\ncontract = \"2.0\""), - ("init.ts", init), - ( - "x.ts", - "export interface Boxed { loads: number }\nlet loads = 0; loads += 1; export const box: Boxed = { loads }", - ), - ("two.ts", "export const two = 'root'"), - ("lib/again.ts", "export { box } from '../x.ts'"), - ("lib/one.ts", "import { two } from './two.ts'\nexport const one = 'lib/one:' + two"), - ("lib/two.ts", "export const two = 'lib/two'"), - ("lib/sibling.ts", "import { box } from '../x.ts'\nexport const sibling = 'sib:' + box.loads"), + ("init.js", init), + ("x.js", "let loads = 0; loads += 1; export const box = { loads }"), + ("two.js", "export const two = 'root'"), + ("lib/again.js", "export { box } from '../x.js'"), + ("lib/one.js", "import { two } from './two.js'\nexport const one = 'lib/one:' + two"), + ("lib/two.js", "export const two = 'lib/two'"), + ("lib/sibling.js", "import { box } from '../x.js'\nexport const sibling = 'sib:' + box.loads"), ] { fs::create_dir_all(dir.join(path).parent().unwrap()).unwrap(); fs::write(dir.join(path), text).unwrap(); @@ -1496,22 +1500,22 @@ export default define((setup) => { assert_eq!((failure(®, "test.script"), said(&h)), (None, vec!["true:1|lib/one:lib/two|sib:1|2.0".into()])); // A cycle fails at build time naming the modules in the cycle. - let mut cyclic = script_sources("import { a } from './a.ts'\nexport default () => a\n"); - cyclic.files.insert("a.ts".into(), b"import { b } from './b.ts'\nexport const a = b".to_vec()); - cyclic.files.insert("b.ts".into(), b"import { a } from './a.ts'\nexport const b = a".to_vec()); + let mut cyclic = script_sources("import { a } from './a.js'\nexport default () => a\n"); + cyclic.files.insert("a.js".into(), b"import { b } from './b.js'\nexport const a = b".to_vec()); + cyclic.files.insert("b.js".into(), b"import { a } from './a.js'\nexport const b = a".to_vec()); let err = define(&cyclic, None).err().expect("cycle refused"); assert!( - (err.contains("Circular") || err.contains("cycle")) && err.contains("a.ts") && err.contains("b.ts"), + (err.contains("Circular") || err.contains("cycle")) && err.contains("a.js") && err.contains("b.js"), "{err}" ); // 40 KB of nesting overflowed the compiler's stack and aborted the client: it fails at build time, naming the file. let deep = format!("export const a = {}{}", "[".repeat(20_000), "]".repeat(20_000)); - let mut nested = script_sources("import { a } from './a.ts'\nexport default () => a\n"); - nested.files.insert("a.ts".into(), deep.clone().into_bytes()); + let mut nested = script_sources("import { a } from './a.js'\nexport default () => a\n"); + nested.files.insert("a.js".into(), deep.clone().into_bytes()); for sources in [script_sources(&deep), nested] { let err = define(&sources, None).err().expect("nesting refused"); - assert!(err.contains("nested too deeply") && err.contains(".ts"), "{err}"); + assert!(err.contains("nested more than 2000 levels deep") && err.contains(".js"), "{err}"); } } @@ -1590,9 +1594,10 @@ fn a_script_command_starts_disabled_and_one_declines() { fn the_guides_script_wait_runs_as_written() { let guide = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/plugins.md")).unwrap(); let body = guide - .split("```ts\n") - .find(|block| block.starts_with("setup.command({ name: \"x.clear\"")) - .and_then(|block| block.split("```").next()) + .split("```") + .filter_map(|block| block.split_once('\n')) + .map(|(_, body)| body) + .find(|body| body.starts_with("setup.command({ name: \"x.clear\"")) .expect("the guide's script wait"); let h = host(); let reg = plugin_with(&h, body); diff --git a/packages/cli-rs/crates/plugin/src/script/vm.rs b/packages/cli-rs/crates/plugin/src/script/vm.rs index 2ef9ddb9727f..57fc72ac7160 100644 --- a/packages/cli-rs/crates/plugin/src/script/vm.rs +++ b/packages/cli-rs/crates/plugin/src/script/vm.rs @@ -59,25 +59,27 @@ pub(crate) struct Compiled { } impl Compiled { - /// Links and compiles all `.ts` (excluding `.d.ts`) and `.js` files in `sources` against `prelude`. + /// Links and compiles all `.js` files in `sources` against `prelude`, as plain JavaScript. pub(crate) fn new(sources: &crate::source::Sources, id: &str, entry: &str, prelude: &str) -> Result { let _ = sources.text(entry)?; let mut list = Vec::new(); let mut files = Vec::new(); for (path, _) in sources.files() { - if !path.ends_with(".js") && !(path.ends_with(".ts") && !path.ends_with(".d.ts")) { + if !path.ends_with(".js") { continue; } let text = sources.text(path)?; - list.push(Source::new(path, text)); + // `Source::new` would pick TypeScript from a `.ts` name; a plugin's sources compile as JavaScript. + list.push(Source { typescript: false, ..Source::new(path, text) }); files.push((path.to_owned(), text.to_owned())); } list.push(Source::host(ENTRY_MODULE, entry_source(entry))); let rt = Runtime::make() .limits(Limits { max_source_bytes: Some(MAX_SOURCE_BYTES), ..Limits::default() }) .modules(modules(prelude)); - let compiled = - rt.compile(&Sources::new(ENTRY_MODULE, list)).map_err(|d| format_diagnostic(id, &d, 0, MEMORY))?; + let compiled = rt + .compile(&Sources::new(ENTRY_MODULE, list)) + .map_err(|d| typescript_refusal(&d).unwrap_or_else(|| format_diagnostic(id, &d, 0, MEMORY)))?; Ok(Self { id: id.to_owned(), files: Arc::new(files), compiled }) } @@ -427,6 +429,14 @@ impl Activation { } } +/// Refuses a `.js` plugin that imports a `.ts` module, as the manifest refuses a `.ts` entry. psychoscript names an +/// import it cannot resolve (`Cannot resolve module "./lib/x.ts" from "init.js".`), and no `.ts` source is linked. +fn typescript_refusal(diag: &Diagnostic) -> Option { + let raw = diag.message_lossy(); + let specifier = raw.strip_prefix("Cannot resolve module \"")?.split_once('"')?.0; + (specifier.ends_with(".ts") && !specifier.ends_with(".d.ts")).then(|| crate::source::javascript_only(specifier)) +} + pub(crate) fn format_diagnostic(id: &str, diag: &Diagnostic, slice_ms: u64, memory: usize) -> String { let raw = diag.message_lossy(); let body = match &diag.kind { diff --git a/packages/cli-rs/crates/plugin/src/source.rs b/packages/cli-rs/crates/plugin/src/source.rs index 999bc0c78d93..67f2a82e1f32 100644 --- a/packages/cli-rs/crates/plugin/src/source.rs +++ b/packages/cli-rs/crates/plugin/src/source.rs @@ -26,7 +26,7 @@ pub enum Carrier { /// Picks the carrier for a directory holding `plugin.toml`: /// - An explicit `entry = "..."` ending in `.luau` selects [`Carrier::Luau`]; anything else selects [`Carrier::Script`]. -/// - Without `entry`, `init.ts` or `init.js` wins over `init.luau`. +/// - Without `entry`, `init.js` or `init.ts` wins over `init.luau`; [`Manifest::parse`] then refuses a `.ts` one. pub fn carrier(dir: &Path) -> Option { let manifest = dir.join(MANIFEST); if !manifest.is_file() { @@ -61,7 +61,8 @@ fn manifest_entry(text: &str) -> Option<&str> { None } -/// A script plugin's files, read once: `plugin.toml` and its `.ts`/`.js` sources, by path with `/`. +/// A script plugin's files, read once: `plugin.toml`, its `.js` sources, and any `.ts` left so the refusal can name +/// it, by path with `/`. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Sources { pub(crate) files: BTreeMap>, @@ -138,6 +139,13 @@ fn read_dir( Ok(()) } +/// What a script plugin is refused with when it names TypeScript: script plugins are JavaScript, so `path` is +/// renamed to the `.js` module the carrier compiles. +pub(crate) fn javascript_only(path: &str) -> String { + let js = path.strip_suffix(".ts").unwrap_or(path); + format!("script plugins are JavaScript: rename {path} to {js}.js and remove its types") +} + /// Flat `key = "string"` manifest parsed from `plugin.toml`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Manifest { @@ -149,7 +157,8 @@ pub struct Manifest { } impl Manifest { - /// Parses `plugin.toml` from `sources`, defaulting `entry` to `init.ts`, else `init.js`. + /// Parses `plugin.toml` from `sources`, defaulting `entry` to `init.js`. Script plugins are JavaScript: a `.ts` entry + /// is refused, naming the `.js` to rename it to. pub fn parse(sources: &Sources) -> Result { let mut fields = BTreeMap::new(); for (number, line) in sources.text(MANIFEST)?.lines().enumerate() { @@ -169,16 +178,20 @@ impl Manifest { if let Some(contract) = fields.get("contract").filter(|c| c.split('.').next() != Some("2")) { return Err(format!("plugin.toml asks for contract {contract}; this opencode-native serves 2.x")); } + // `init.js` is the entry; `init.ts` is only selected so the refusal below can name it. let default = - if sources.text("init.ts").is_ok() || sources.text("init.js").is_err() { "init.ts" } else { "init.js" }; + if sources.text("init.js").is_ok() || sources.text("init.ts").is_err() { "init.js" } else { "init.ts" }; let entry = fields.remove("entry").unwrap_or_else(|| default.to_owned()); if entry.ends_with(".d.ts") { return Err(format!("plugin.toml's entry {entry:?} is a declaration file, not a script entry")); } - if !(entry.ends_with(".ts") || entry.ends_with(".js")) - || entry.split('/').any(|part| part.is_empty() || part == "..") + if entry.split('/').any(|part| part.is_empty() || part == "..") + || !(entry.ends_with(".js") || entry.ends_with(".ts")) { - return Err(format!("plugin.toml's entry {entry:?} is not a .ts or .js file of the plugin")); + return Err(format!("plugin.toml's entry {entry:?} is not a .js file of the plugin")); + } + if entry.ends_with(".ts") { + return Err(javascript_only(&entry)); } Ok(Self { id, From bcbedde90c055a5d0ca84694da08d39b9f75410a Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 10:33:52 +0100 Subject: [PATCH 2/7] refactor(cli-rs): convert the example script plugins to JavaScript Script plugins are JavaScript only (O-229): the examples are init.js and .js modules, checked with checkJs against the generated plugin types. The converted files keep the same code, comments aside, so the counter and hello twins still match their frozen traces. --- .../cli-rs/crates/plugin-abi/tests/sdk.rs | 6 +-- .../script/counter/{init.ts => init.js} | 10 +++-- .../script/counter/{shout.ts => shout.js} | 12 ++++-- .../script/hello/{init.ts => init.js} | 1 + .../crates/tui/tests/all/plugin_script.rs | 2 +- packages/cli-rs/docs/plugins.md | 37 ++++++++++++------- .../parity/plugins/script-hello/tui.tsx | 2 +- 7 files changed, 44 insertions(+), 26 deletions(-) rename packages/cli-rs/crates/plugin/examples/script/counter/{init.ts => init.js} (88%) rename packages/cli-rs/crates/plugin/examples/script/counter/{shout.ts => shout.js} (50%) rename packages/cli-rs/crates/plugin/examples/script/hello/{init.ts => init.js} (98%) diff --git a/packages/cli-rs/crates/plugin-abi/tests/sdk.rs b/packages/cli-rs/crates/plugin-abi/tests/sdk.rs index 50b8085f8714..25d4b7498830 100644 --- a/packages/cli-rs/crates/plugin-abi/tests/sdk.rs +++ b/packages/cli-rs/crates/plugin-abi/tests/sdk.rs @@ -8,10 +8,10 @@ fn the_guide_shows_its_examples_as_they_are() { let guide = std::fs::read_to_string(crate_dir.join("../../docs/plugins.md")).unwrap(); let examples = crate_dir.join("../plugin/examples"); for file in [ - "script/hello/init.ts", + "script/hello/init.js", "script/hello/plugin.toml", - "script/counter/init.ts", - "script/counter/shout.ts", + "script/counter/init.js", + "script/counter/shout.js", "pipe/hello/tui.tsx", ] { let source = std::fs::read_to_string(examples.join(file)).unwrap(); diff --git a/packages/cli-rs/crates/plugin/examples/script/counter/init.ts b/packages/cli-rs/crates/plugin/examples/script/counter/init.js similarity index 88% rename from packages/cli-rs/crates/plugin/examples/script/counter/init.ts rename to packages/cli-rs/crates/plugin/examples/script/counter/init.js index 1da5a71edd82..453c67a6d24a 100644 --- a/packages/cli-rs/crates/plugin/examples/script/counter/init.ts +++ b/packages/cli-rs/crates/plugin/examples/script/counter/init.js @@ -1,13 +1,15 @@ +// @ts-check // A counter in the sidebar that `/count` and a click raise and storage keeps, // `/count-reset` asks before it clears it, a toast on a finished session, and a `shout` fence. import { KEEP, click, column, command, define, show, span, text } from "opencode:plugin" -import type { Read } from "opencode:plugin" -import shout from "./shout.ts" +/** @import { Read } from "opencode:plugin" */ +import shout from "./shout.js" const COUNT = "count" -function stored(read: Read): number { - const value = read.storageGet(COUNT) as { value?: number } | undefined +/** @param {Read} read */ +function stored(read) { + const value = /** @type {{ value?: number } | undefined} */ (read.storageGet(COUNT)) return value && typeof value.value === "number" ? value.value : 0 } diff --git a/packages/cli-rs/crates/plugin/examples/script/counter/shout.ts b/packages/cli-rs/crates/plugin/examples/script/counter/shout.js similarity index 50% rename from packages/cli-rs/crates/plugin/examples/script/counter/shout.ts rename to packages/cli-rs/crates/plugin/examples/script/counter/shout.js index 5c11509cea62..30d27ffa7dd9 100644 --- a/packages/cli-rs/crates/plugin/examples/script/counter/shout.ts +++ b/packages/cli-rs/crates/plugin/examples/script/counter/shout.js @@ -1,7 +1,13 @@ -// The `shout` fence: each line of the block in capitals, bold. A module of its own, which `init.ts` imports. -import type { Fence, Fenced, Read } from "opencode:plugin" +// @ts-check +// The `shout` fence: each line of the block in capitals, bold. A module of its own, which `init.js` imports. +/** @import { Fence, Fenced, Read } from "opencode:plugin" */ -export default function shout(_read: Read, fence: Fence): Fenced { +/** + * @param {Read} _read + * @param {Fence} fence + * @returns {Fenced} + */ +export default function shout(_read, fence) { const lines = fence.code .split("\n") .filter((line) => line.length > 0) diff --git a/packages/cli-rs/crates/plugin/examples/script/hello/init.ts b/packages/cli-rs/crates/plugin/examples/script/hello/init.js similarity index 98% rename from packages/cli-rs/crates/plugin/examples/script/hello/init.ts rename to packages/cli-rs/crates/plugin/examples/script/hello/init.js index bb840877efef..bd1881511c1a 100644 --- a/packages/cli-rs/crates/plugin/examples/script/hello/init.ts +++ b/packages/cli-rs/crates/plugin/examples/script/hello/init.js @@ -1,3 +1,4 @@ +// @ts-check // The quick start: a command in the palette and as `/hello`, and a line in the home footer that runs it. import { click, define, show, span, text } from "opencode:plugin" diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_script.rs b/packages/cli-rs/crates/tui/tests/all/plugin_script.rs index 50d3bf90da5c..b7a80615947d 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_script.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_script.rs @@ -90,7 +90,7 @@ fn a_configured_script_plugin_does_not_load_with_no_plugins() { let dir = config.join("plugins").join("hello"); std::fs::create_dir_all(&dir).unwrap(); let example = Path::new(env!("CARGO_MANIFEST_DIR")).join("../plugin/examples/script/hello"); - for file in ["plugin.toml", "init.ts"] { + for file in ["plugin.toml", "init.js"] { std::fs::copy(example.join(file), dir.join(file)).unwrap(); } let target = dir.to_string_lossy().into_owned(); diff --git a/packages/cli-rs/docs/plugins.md b/packages/cli-rs/docs/plugins.md index 9483fe0acfca..afbaa12b1157 100644 --- a/packages/cli-rs/docs/plugins.md +++ b/packages/cli-rs/docs/plugins.md @@ -71,9 +71,10 @@ runs it. The built-ins are the same contract in Rust (`abi::Plugin { id, setup } ### Script -`crates/plugin/examples/script/hello/init.ts`: +`crates/plugin/examples/script/hello/init.js`: -```ts +```js +// @ts-check // The quick start: a command in the palette and as `/hello`, and a line in the home footer that runs it. import { click, define, show, span, text } from "opencode:plugin" @@ -195,19 +196,21 @@ plugin: it has no JSX, no npm packages and no Bun, and it speaks the contract di `crates/plugin/examples/script/counter` counts in the sidebar. Storage keeps the count, `/count` and a click raise it, `/count-reset` asks before it clears it, a finished session shows a toast, and a `shout` fence draws its lines in -capitals. Its `init.ts`: +capitals. Its `init.js`: -```ts +```js +// @ts-check // A counter in the sidebar that `/count` and a click raise and storage keeps, // `/count-reset` asks before it clears it, a toast on a finished session, and a `shout` fence. import { KEEP, click, column, command, define, show, span, text } from "opencode:plugin" -import type { Read } from "opencode:plugin" -import shout from "./shout.ts" +/** @import { Read } from "opencode:plugin" */ +import shout from "./shout.js" const COUNT = "count" -function stored(read: Read): number { - const value = read.storageGet(COUNT) as { value?: number } | undefined +/** @param {Read} read */ +function stored(read) { + const value = /** @type {{ value?: number } | undefined} */ (read.storageGet(COUNT)) return value && typeof value.value === "number" ? value.value : 0 } @@ -255,13 +258,19 @@ export default define((setup) => { ### Modules -The counter's fence renderer is a module of its own, `shout.ts`, which `init.ts` imports: +The counter's fence renderer is a module of its own, `shout.js`, which `init.js` imports: -```ts -// The `shout` fence: each line of the block in capitals, bold. A module of its own, which `init.ts` imports. -import type { Fence, Fenced, Read } from "opencode:plugin" +```js +// @ts-check +// The `shout` fence: each line of the block in capitals, bold. A module of its own, which `init.js` imports. +/** @import { Fence, Fenced, Read } from "opencode:plugin" */ -export default function shout(_read: Read, fence: Fence): Fenced { +/** + * @param {Read} _read + * @param {Fence} fence + * @returns {Fenced} + */ +export default function shout(_read, fence) { const lines = fence.code .split("\n") .filter((line) => line.length > 0) @@ -270,7 +279,7 @@ export default function shout(_read: Read, fence: Fence): Fenced { } ``` -- **A specifier names a file of the plugin**, relative to the importer and with its extension: `./shout.ts`, +- **A specifier names a file of the plugin**, relative to the importer and with its extension: `./shout.js`, `../lib/util.js`. `opencode:plugin` is the host's module. Anything else is a load error: a package name, an absolute path, a path that leaves the plugin, a path without its extension. - **Modules are linked as the plugin loads**, from the bytes read then. Each runs once, before the modules that diff --git a/packages/cli-rs/parity/plugins/script-hello/tui.tsx b/packages/cli-rs/parity/plugins/script-hello/tui.tsx index cc0758e99d96..51604ea48786 100644 --- a/packages/cli-rs/parity/plugins/script-hello/tui.tsx +++ b/packages/cli-rs/parity/plugins/script-hello/tui.tsx @@ -1,7 +1,7 @@ // The script quick start's TypeScript twin: `/hello` shows a toast, and a muted line closes the home // footer. parity/scenarios/P.script/hello.script-pty.ts installs this file beside the script plugin // (`crates/plugin/examples/script/hello`) in one `plugins` directory: TS loads `tui.tsx`, Rust loads -// `plugin.toml` and `init.ts`. +// `plugin.toml` and `init.js`. import type { Context } from "../../../../plugin/src/tui/plugin" export default { From de725d4fc703517c36e563d5b47c9ac16e05519b Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 10:34:43 +0100 Subject: [PATCH 3/7] refactor(cli-rs): port the parity script plugins to JavaScript Script plugins are JavaScript now: psychoscript takes no TypeScript mode, and the client refuses a `.ts` entry. Convert life, other and title the way the ten ports were, with `// @ts-check` and JSDoc for the checker, and point the life machine, the P.0b fixture and the docs at `init.js`. The code each file emits is the same, so the life state machine and the title twins still reproduce their traces. --- .../crates/tui/tests/all/plugin_machines.rs | 6 ++--- packages/cli-rs/docs/testing.md | 8 +++---- packages/cli-rs/parity/machines/plugins.json | 2 +- .../parity/plugins/life/{init.ts => init.js} | 14 +++++++---- .../cli-rs/parity/plugins/life/plugin.toml | 2 +- packages/cli-rs/parity/plugins/life/tui.tsx | 2 +- .../parity/plugins/other/{init.ts => init.js} | 3 ++- .../cli-rs/parity/plugins/other/plugin.toml | 2 +- packages/cli-rs/parity/plugins/other/tui.tsx | 2 +- .../parity/plugins/title/{init.ts => init.js} | 24 +++++++++++++++---- packages/cli-rs/parity/plugins/title/tui.ts | 2 +- .../cli-rs/parity/scenarios/P.0b/fixture.ts | 4 ++-- packages/cli-rs/tsconfig.json | 4 ++-- 13 files changed, 49 insertions(+), 26 deletions(-) rename packages/cli-rs/parity/plugins/life/{init.ts => init.js} (85%) rename packages/cli-rs/parity/plugins/other/{init.ts => init.js} (77%) rename packages/cli-rs/parity/plugins/title/{init.ts => init.js} (76%) diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_machines.rs b/packages/cli-rs/crates/tui/tests/all/plugin_machines.rs index 916cb06707be..4e7ecf612995 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_machines.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_machines.rs @@ -33,7 +33,7 @@ const MACHINES: &str = include_str!("../../../../parity/machines/plugins.json"); struct Life { harness: Harness, loader: Rc, - /// The plugin's entry (`init.ts`), which a reload rewrites with the next build. + /// The plugin's entry (`init.js`), which a reload rewrites with the next build. init: PathBuf, target: String, builds: Cell, @@ -53,7 +53,7 @@ impl Life { let dir = plugins.join(format!("parity.{name}")); std::fs::create_dir_all(&dir).unwrap(); let twin = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../parity/plugins").join(name); - for file in ["plugin.toml", "init.ts"] { + for file in ["plugin.toml", "init.js"] { std::fs::copy(twin.join(file), dir.join(file)).unwrap(); } dir @@ -72,7 +72,7 @@ impl Life { let loader = Rc::new(Loader::new(config, root.path().to_path_buf(), configured).with_script(|| {})); harness.tui.plugins.set_loader(loader.clone()); let target = dir.to_string_lossy().into_owned(); - let life = Self { harness, loader, init: dir.join("init.ts"), target, builds: Cell::new(1), _root: root }; + let life = Self { harness, loader, init: dir.join("init.js"), target, builds: Cell::new(1), _root: root }; life.reconcile(); life.settle(); life diff --git a/packages/cli-rs/docs/testing.md b/packages/cli-rs/docs/testing.md index 673d57545643..4be6ebdd54ae 100644 --- a/packages/cli-rs/docs/testing.md +++ b/packages/cli-rs/docs/testing.md @@ -284,7 +284,7 @@ normalized transcripts differ. Transcripts are kept in `$TMPDIR/opencode-parity/ `bun run parity:machines` covers each edge once and the seeded walks; `bun run parity:machines:deep` adds every path to the file's depth and the fault trials. The package has no `test` script, so the repository's `turbo test` does not run this suite on every pull request that touches a package it depends on, such as `@opencode/tui`. The Rust side -runs the machine on the plugin's script twin, `parity/plugins/life/init.ts`, beside the TypeScript `tui.tsx`. +runs the machine on the plugin's script twin, `parity/plugins/life/init.js`, beside the TypeScript `tui.tsx`. ## Plugin twins @@ -302,13 +302,13 @@ Run them with `bun run cargo test -p opencode-plugin --lib twin::` and `-p openc The five in-repo script plugins are: - **Frozen traces:** `counter` (`crates/plugin/examples/script/counter`, trace in - `parity/fixtures/script/counter.json`) and `title` (`parity/plugins/title/init.ts`, trace in + `parity/fixtures/script/counter.json`) and `title` (`parity/plugins/title/init.js`, trace in `parity/fixtures/script/title.json`; also paired with `parity/plugins/title/tui.ts` in the `P.0b` PTY scenarios). - **Quick start:** `hello` (`crates/plugin/examples/script/hello`), covered by loader, script, TUI and CLI tests and paired with `parity/plugins/script-hello/tui.tsx` in the opt-in PTY test (`parity/scenarios/P.script/hello.script-pty.ts`, run by path with `bun run parity:pty`). -- **State machines:** `life` (`parity/plugins/life/init.ts`, twin of `parity/plugins/life/tui.tsx`) and `other` - (`parity/plugins/other/init.ts`, the failing distractor beside `parity/plugins/other/tui.tsx`), driven against +- **State machines:** `life` (`parity/plugins/life/init.js`, twin of `parity/plugins/life/tui.tsx`) and `other` + (`parity/plugins/other/init.js`, the failing distractor beside `parity/plugins/other/tui.tsx`), driven against `parity/machines/plugins.json` by `crates/tui/tests/all/plugin_machines.rs`. ### Ports outside the repository diff --git a/packages/cli-rs/parity/machines/plugins.json b/packages/cli-rs/parity/machines/plugins.json index a95f56cf6fb7..91cdd4e08626 100644 --- a/packages/cli-rs/parity/machines/plugins.json +++ b/packages/cli-rs/parity/machines/plugins.json @@ -1,5 +1,5 @@ { - "about": "The life of a plugin as the user sees it, written by hand and never captured. The plugin is parity/plugins/life: tui.tsx for TS, and its script twin init.ts for Rust, which crates/tui/tests/all/plugin_machines.rs loads. An observation is line/palette/row/dialog: the plugin's line in home.footer (A, B or -), whether the palette finds its commands (yes or no), its row in the plugin manager (on, off, failed, pending or declined), and which of its dialogs shows (prompt, confirm, alert or -). While a dialog shows, the readers open neither the palette nor the manager, which would replace it, so the first three are ?. Actions: toggle is enter on its row in the plugin manager; flip, throw, stall, arm, dialog, confirm and alert run its palette commands Life flip, Life throw, Life stall (a call of 150 ms: over Rust's budget of one call, which TS does not have), Life arm (the next setup throws), Life dialog (opens its prompt), Life confirm (asks whether to flip the line) and Life alert (flips the line once it closes); leader presses the leader key (ctrl+x), which starts a key sequence: the plugin reads the pending keys (script read.keymapPending(), TS keymap.pending) and its line shows them, so the observation is the line and its keys, as A+ctrl+x/?/?/-, the rest not read while a key would continue the sequence; enter answers the confirm yes; escape closes a dialog, which answers the confirm no, or ends a pending key sequence; reload puts a new build of the plugin in place. TS is the specification: an enable whose setup throws shows the error in a toast and leaves the row as it was, and a plugin's dialog stays open when it reloads; answered after the reload, it reaches nothing the user sees. A row in xfail is a known difference, [client, deviation file or finding:, 'state action observation'].", + "about": "The life of a plugin as the user sees it, written by hand and never captured. The plugin is parity/plugins/life: tui.tsx for TS, and its script twin init.js for Rust, which crates/tui/tests/all/plugin_machines.rs loads. An observation is line/palette/row/dialog: the plugin's line in home.footer (A, B or -), whether the palette finds its commands (yes or no), its row in the plugin manager (on, off, failed, pending or declined), and which of its dialogs shows (prompt, confirm, alert or -). While a dialog shows, the readers open neither the palette nor the manager, which would replace it, so the first three are ?. Actions: toggle is enter on its row in the plugin manager; flip, throw, stall, arm, dialog, confirm and alert run its palette commands Life flip, Life throw, Life stall (a call of 150 ms: over Rust's budget of one call, which TS does not have), Life arm (the next setup throws), Life dialog (opens its prompt), Life confirm (asks whether to flip the line) and Life alert (flips the line once it closes); leader presses the leader key (ctrl+x), which starts a key sequence: the plugin reads the pending keys (script read.keymapPending(), TS keymap.pending) and its line shows them, so the observation is the line and its keys, as A+ctrl+x/?/?/-, the rest not read while a key would continue the sequence; enter answers the confirm yes; escape closes a dialog, which answers the confirm no, or ends a pending key sequence; reload puts a new build of the plugin in place. TS is the specification: an enable whose setup throws shows the error in a toast and leaves the row as it was, and a plugin's dialog stays open when it reloads; answered after the reload, it reaches nothing the user sees. A row in xfail is a known difference, [client, deviation file or finding:, 'state action observation'].", "depth": 4, "seeds": 8, "steps": 12, diff --git a/packages/cli-rs/parity/plugins/life/init.ts b/packages/cli-rs/parity/plugins/life/init.js similarity index 85% rename from packages/cli-rs/parity/plugins/life/init.ts rename to packages/cli-rs/parity/plugins/life/init.js index 644ddf5d632c..5ab0c6022406 100644 --- a/packages/cli-rs/parity/plugins/life/init.ts +++ b/packages/cli-rs/parity/plugins/life/init.js @@ -1,3 +1,4 @@ +// @ts-check // The plugin of the life machine (parity/machines/plugins.json), opencode-native script side, checked against // the machine fixture and its frozen trace. A line in home.footer shows A or B, its build, // then the pending keys while a sequence is pending. Life flip flips the line, Life throw throws, Life stall spins @@ -6,19 +7,19 @@ // setup throws, for the views machine. crates/tui/tests/all/plugin_machines.rs copies this file and rewrites `BUILD` // to reload it. import { define, show, text } from "opencode:plugin" -import type { CommandSpec } from "opencode:plugin" +/** @import { CommandSpec } from "opencode:plugin" */ const BUILD = 1 export default define((setup) => { // The views machine: the setup fails as the plugin first loads, so its row is failed with an error. - const options = setup.options as { fail?: boolean } | null | undefined + const options = /** @type {{ fail?: boolean } | null | undefined} */ (setup.options) if (options?.fail) { throw new Error("life setup fails as it loads") } // Storage outlives an activation, so an armed setup throws on the next enable, once. setup.storageKey("armed") - const armed = setup.host.storageGet("armed") as { on?: boolean } | null | undefined + const armed = /** @type {{ on?: boolean } | null | undefined} */ (setup.host.storageGet("armed")) if (armed?.on) { setup.host.storageSet("armed", { on: false }) throw new Error("life setup armed to throw") @@ -27,7 +28,12 @@ export default define((setup) => { const flip = () => { side = side === "A" ? "B" : "A" } - const command = (name: string, title: string): CommandSpec => ({ name, title, palette: true }) + /** + * @param {string} name + * @param {string} title + * @returns {CommandSpec} + */ + const command = (name, title) => ({ name, title, palette: true }) setup.command(command("life.flip", "Life flip"), () => { flip() }) diff --git a/packages/cli-rs/parity/plugins/life/plugin.toml b/packages/cli-rs/parity/plugins/life/plugin.toml index 5dbb9545f1e8..57dadb4dce15 100644 --- a/packages/cli-rs/parity/plugins/life/plugin.toml +++ b/packages/cli-rs/parity/plugins/life/plugin.toml @@ -1,4 +1,4 @@ -# The life machine's plugin for opencode-native (`init.ts`), beside its TypeScript side (`tui.tsx`). +# The life machine's plugin for opencode-native (`init.js`), beside its TypeScript side (`tui.tsx`). id = "parity.life" name = "Life" version = "0.1.0" diff --git a/packages/cli-rs/parity/plugins/life/tui.tsx b/packages/cli-rs/parity/plugins/life/tui.tsx index 5558d90a4e91..1227d5c1d3bc 100644 --- a/packages/cli-rs/parity/plugins/life/tui.tsx +++ b/packages/cli-rs/parity/plugins/life/tui.tsx @@ -2,7 +2,7 @@ // or B, then the pending keys while a sequence is pending, and seven palette commands. Life flip flips the line, Life throw throws, Life stall takes 150 ms, Life arm makes the next setup throw, // Life dialog opens a prompt, Life confirm asks whether to flip the line, and Life alert flips it once it closes. With // the option fail its setup throws, for the views machine. The TS reader copies this file and rewrites `build` to reload it. Its opencode-native twin is -// `init.ts` beside it; each is checked against the file, not against the other. +// `init.js` beside it; each is checked against the file, not against the other. import type { Context } from "../../../../plugin/src/tui/plugin" import { createSignal } from "solid-js" diff --git a/packages/cli-rs/parity/plugins/other/init.ts b/packages/cli-rs/parity/plugins/other/init.js similarity index 77% rename from packages/cli-rs/parity/plugins/other/init.ts rename to packages/cli-rs/parity/plugins/other/init.js index 797e8432538a..5222c07ff597 100644 --- a/packages/cli-rs/parity/plugins/other/init.ts +++ b/packages/cli-rs/parity/plugins/other/init.js @@ -1,9 +1,10 @@ +// @ts-check // The distractor of the views machine (parity/machines/plugins.json), opencode-native script side, in // psychoscript, whose setup throws, with its own cause, under the option fail. import { define } from "opencode:plugin" export default define((setup) => { - const options = setup.options as { fail?: boolean } | null | undefined + const options = /** @type {{ fail?: boolean } | null | undefined} */ (setup.options) if (options?.fail) { throw new Error("other setup fails as it loads") } diff --git a/packages/cli-rs/parity/plugins/other/plugin.toml b/packages/cli-rs/parity/plugins/other/plugin.toml index 643556794e59..f117f3e638a0 100644 --- a/packages/cli-rs/parity/plugins/other/plugin.toml +++ b/packages/cli-rs/parity/plugins/other/plugin.toml @@ -1,4 +1,4 @@ -# The views machine's distractor for opencode-native (`init.ts`), beside its TypeScript side (`tui.tsx`). +# The views machine's distractor for opencode-native (`init.js`), beside its TypeScript side (`tui.tsx`). id = "parity.other" name = "Other" version = "0.1.0" diff --git a/packages/cli-rs/parity/plugins/other/tui.tsx b/packages/cli-rs/parity/plugins/other/tui.tsx index f2219fa623a5..8a9db191f400 100644 --- a/packages/cli-rs/parity/plugins/other/tui.tsx +++ b/packages/cli-rs/parity/plugins/other/tui.tsx @@ -1,5 +1,5 @@ // The distractor of the views machine (parity/machines/plugins.json): a second plugin beside life whose setup throws, -// with its own cause, under the option fail. Its opencode-native twin is init.ts beside it. +// with its own cause, under the option fail. Its opencode-native twin is init.js beside it. import type { Context } from "../../../../plugin/src/tui/plugin" export default { diff --git a/packages/cli-rs/parity/plugins/title/init.ts b/packages/cli-rs/parity/plugins/title/init.js similarity index 76% rename from packages/cli-rs/parity/plugins/title/init.ts rename to packages/cli-rs/parity/plugins/title/init.js index 94e220952333..f0f0658b6af5 100644 --- a/packages/cli-rs/parity/plugins/title/init.ts +++ b/packages/cli-rs/parity/plugins/title/init.js @@ -1,11 +1,19 @@ +// @ts-check // The P0b title plugin for opencode-native, script side: `/p0btitle` and `/p0blong` set the terminal title, and // `/p0brun` and `/p0btwice` run their input with `sh -c`, once or twice at once. How each program ended becomes the // title, which a terminal's title log keeps where a later toast replaces an earlier one, and a toast. import { define, spawn } from "opencode:plugin" -import type { CommandSpec, Host } from "opencode:plugin" +/** @import { CommandSpec, Host } from "opencode:plugin" */ export default define((setup) => { - const command = (name: string, title: string, slash: string, args?: boolean): CommandSpec => ({ + /** + * @param {string} name + * @param {string} title + * @param {string} slash + * @param {boolean} [args] + * @returns {CommandSpec} + */ + const command = (name, title, slash, args) => ({ name, title, group: "Sample", @@ -13,7 +21,11 @@ export default define((setup) => { palette: true, arguments: args, }) - const report = (host: Host, message: string) => { + /** + * @param {Host} host + * @param {string} message + */ + const report = (host, message) => { host.setTitle(message) host.toast({ variant: "info", message }) } @@ -24,7 +36,11 @@ export default define((setup) => { host.setTitle("p0b long " + "é".repeat(3000)) }) // Each run is a task of its own, so the second of `/p0btwice` asks while the first program runs. - const run = (name: string, times: number) => { + /** + * @param {string} name + * @param {number} times + */ + const run = (name, times) => { setup.command(command("p0b." + name, "Run a program", name, true), (host, input) => { for (let i = 0; i < times; i++) { spawn(async () => { diff --git a/packages/cli-rs/parity/plugins/title/tui.ts b/packages/cli-rs/parity/plugins/title/tui.ts index 772aec4f10a9..7f16255fbc17 100644 --- a/packages/cli-rs/parity/plugins/title/tui.ts +++ b/packages/cli-rs/parity/plugins/title/tui.ts @@ -1,6 +1,6 @@ // The P0b title plugin, TypeScript side: `/p0btitle` sets the terminal title, as an npm plugin does with // `renderer.setTerminalTitle`. parity/scenarios/P.0b/fixture.ts installs this file and its opencode-native twin, the -// script plugin beside it (`host.setTitle`), in one `plugins` directory: TS loads `tui.ts`, Rust loads `init.ts`. +// script plugin beside it (`host.setTitle`), in one `plugins` directory: TS loads `tui.ts`, Rust loads `init.js`. import type { Context } from "../../../../plugin/src/tui/plugin" export default { diff --git a/packages/cli-rs/parity/scenarios/P.0b/fixture.ts b/packages/cli-rs/parity/scenarios/P.0b/fixture.ts index 9911f2f47062..5f59bd882dd6 100644 --- a/packages/cli-rs/parity/scenarios/P.0b/fixture.ts +++ b/packages/cli-rs/parity/scenarios/P.0b/fixture.ts @@ -1,6 +1,6 @@ // The P-PTY fixture of P0b's plugin verbs that need a real terminal: one directory under the sandbox's global // `plugins` directory holds the TS plugin (`parity/plugins/title/tui.ts`) and its opencode-native twin, a script -// plugin (`plugin.toml` and `init.ts`). TS loads the first, Rust the second; each client ignores the other's files. +// plugin (`plugin.toml` and `init.js`). TS loads the first, Rust the second; each client ignores the other's files. import { copyFile, mkdir, writeFile } from "node:fs/promises" import path from "node:path" import type { PtyStep } from "../../pty/run" @@ -10,7 +10,7 @@ import { parityRoot } from "../../cli/client" export async function install(root: string, config?: object) { const directory = path.join(root, "home/.config/opencode/plugins/title") await mkdir(directory, { recursive: true }) - for (const file of ["tui.ts", "plugin.toml", "init.ts"]) { + for (const file of ["tui.ts", "plugin.toml", "init.js"]) { await copyFile(path.join(parityRoot, "plugins/title", file), path.join(directory, file)) } const configured = { ...config, plugins: ["./plugins/title"] } diff --git a/packages/cli-rs/tsconfig.json b/packages/cli-rs/tsconfig.json index 281dd61136c3..cf799c4687e2 100644 --- a/packages/cli-rs/tsconfig.json +++ b/packages/cli-rs/tsconfig.json @@ -11,6 +11,6 @@ }, "include": ["script", "parity"], // Oracle harnesses that import TUI sources need the TUI's Solid JSX settings; they run from packages/tui. - // Psychoscript plugins (`init.ts`) and expected refusals are checked by `check:plugin-types` against `opencode:plugin`. - "exclude": ["parity/oracle/*/", "parity/plugins/*/init.ts", "script/script-expect"] + // Psychoscript plugins (`init.js`) and expected refusals are checked by `check:plugin-types` against `opencode:plugin`. + "exclude": ["parity/oracle/*/", "parity/plugins/*/init.js", "script/script-expect"] } From 8203ab836a379db1e50c907ddd4e3352a04e79b5 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 10:35:20 +0100 Subject: [PATCH 4/7] refactor(cli-rs): check script plugins as JavaScript --- .../cli-rs/crates/cli/src/commands/plugin.rs | 41 ++++++++++++++--- packages/cli-rs/crates/cli/tests/plugin.rs | 41 ++++++++++------- packages/cli-rs/script/check-plugin-types.ts | 45 +++++++++++-------- 3 files changed, 86 insertions(+), 41 deletions(-) diff --git a/packages/cli-rs/crates/cli/src/commands/plugin.rs b/packages/cli-rs/crates/cli/src/commands/plugin.rs index 038d177e88f7..5593bb081528 100644 --- a/packages/cli-rs/crates/cli/src/commands/plugin.rs +++ b/packages/cli-rs/crates/cli/src/commands/plugin.rs @@ -78,7 +78,8 @@ fn types(dir: Option<&str>) -> error::Result<()> { crate::output::print(&format!("wrote {}\nwrote {}\n", stub.display(), globals.display())) } -/// Validates a script plugin directory's manifest and sources, type-checks its entry with `tsc`, and compiles it. +/// Validates a script plugin directory's manifest and sources, type-checks its JavaScript entry with `tsc`, and +/// compiles it. #[cfg(script)] fn check(dir: &Path) -> error::Result<()> { if !dir.is_dir() { @@ -89,16 +90,45 @@ fn check(dir: &Path) -> error::Result<()> { } let sources = opencode_plugin::script::read(dir).map_err(error::Error::msg)?; let manifest = opencode_plugin::script::parse_manifest(&sources).map_err(error::Error::msg)?; - let _ = sources.text(&manifest.entry).map_err(error::Error::msg)?; + let entry = script_entry(dir, &sources, &manifest)?; let root = std::fs::canonicalize(dir)?; - typecheck(&root, &root.join(&manifest.entry))?; + typecheck(&root, &root.join(entry))?; opencode_plugin::script::Built::new(&sources).map_err(error::Error::msg)?; let count = sources.files().filter(|(path, _)| *path != opencode_plugin::source::MANIFEST).count(); crate::output::print(&format!("ok: {} ({count} file(s))\n", manifest.id)) } +/// The plugin's entry, refusing TypeScript: script plugins are JavaScript. An `init.ts` entry with no such file is +/// a loader's default for a plugin with no entry file, which has no `init.js` either. +#[cfg(script)] +fn script_entry<'a>( + dir: &Path, + sources: &opencode_plugin::script::Sources, + manifest: &'a opencode_plugin::script::Manifest, +) -> error::Result<&'a str> { + if manifest.entry.ends_with(".ts") { + if manifest.entry == "init.ts" && sources.text("init.ts").is_err() { + return Err(error::Error::msg("the plugin has no init.js")); + } + return Err(not_javascript(&manifest.entry)); + } + if dir.join("init.ts").is_file() { + return Err(not_javascript("init.ts")); + } + sources.text(&manifest.entry).map_err(error::Error::msg)?; + Ok(&manifest.entry) +} + +#[cfg(script)] +fn not_javascript(entry: &str) -> error::Error { + error::Error::msg(format!( + "script plugins are JavaScript: rename {entry} to {}.js and remove its types", + entry.strip_suffix(".ts").unwrap_or(entry) + )) +} + #[cfg(script)] fn typecheck(root: &Path, entry: &Path) -> error::Result<()> { use std::io::{ErrorKind, Write}; @@ -120,10 +150,7 @@ fn typecheck(root: &Path, entry: &Path) -> error::Result<()> { "target": "es2023", "types": [], "module": "preserve", - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "erasableSyntaxOnly": true, - "verbatimModuleSyntax": true + "moduleResolution": "bundler" }, "files": [globals, stub, entry] }); diff --git a/packages/cli-rs/crates/cli/tests/plugin.rs b/packages/cli-rs/crates/cli/tests/plugin.rs index 8d989e13b6b5..07b6fb97ed99 100644 --- a/packages/cli-rs/crates/cli/tests/plugin.rs +++ b/packages/cli-rs/crates/cli/tests/plugin.rs @@ -71,22 +71,25 @@ fn plugin_check_reports_errors_with_relative_paths() { let dir = opencode_util::temp::tempdir().unwrap(); std::fs::create_dir_all(dir.path().join("sub")).unwrap(); std::fs::write(dir.path().join("plugin.toml"), "id = \"test.paths\"\ncontract = \"2.0\"\n").unwrap(); - std::fs::write(dir.path().join("sub").join("helper.ts"), "export const bad: number = \"not a number\"\n").unwrap(); std::fs::write( - dir.path().join("init.ts"), + dir.path().join("sub").join("helper.js"), + "/** @type {number} */\nexport const bad = \"not a number\"\n", + ) + .unwrap(); + std::fs::write( + dir.path().join("init.js"), "import { client, define } from \"opencode:plugin\"\n\ - import { bad } from \"./sub/helper.ts\"\n\ - enum Nope { A }\n\ + import { bad } from \"./sub/helper.js\"\n\ export default define((setup) => {\n\ setup.command({ name: \"bad.run\" }, async () => {\n\ - void bad; void Nope.A; void new Intl.NumberFormat(\"en-US\")\n\ + void bad; void new Intl.NumberFormat(\"en-US\")\n\ await client.session.inbox.list({ sesionID: \"abc\" })\n\ })\n\ })\n", ) .unwrap(); - // Run from an unrelated directory so `tsc` would otherwise print `../../../../tmp/.../init.ts`. + // Run from an unrelated directory so `tsc` would otherwise print `../../../../tmp/.../init.js`. let caller = opencode_util::temp::tempdir().unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_opencode-native")) .current_dir(caller.path()) @@ -96,7 +99,7 @@ fn plugin_check_reports_errors_with_relative_paths() { .unwrap(); assert_eq!(output.status.code(), Some(1)); let stderr = String::from_utf8_lossy(&output.stderr); - for expected in ["init.ts(3,6): error TS1294", "sub/helper.ts(1,14): error TS2322", "'Intl'", "sesionID"] { + for expected in ["sub/helper.js(2,14): error TS2322", "init.js(6,35): error TS2561", "'Intl'", "sesionID"] { assert!(stderr.contains(expected), "missing {expected} in:\n{stderr}"); } assert!(!stderr.contains("../"), "unexpected relative traversal in diagnostic:\n{stderr}"); @@ -108,12 +111,20 @@ fn plugin_check_reports_errors_with_relative_paths() { fn plugin_check_reports_manifest_and_entry_errors() { let dir = opencode_util::temp::tempdir().unwrap(); let target = dir.path().to_str().unwrap(); - for (manifest, expected) in [ - ("id = \"test.noentry\"\ncontract = \"2.0\"\n", "the plugin has no init.ts"), - ("contract = \"2.0\"\n", "plugin.toml names no id"), - ("id = \"test.dts\"\ncontract = \"2.0\"\nentry = \"types.d.ts\"\n", "declaration file"), + for (manifest, init_ts, expected) in [ + ("id = \"test.noentry\"\ncontract = \"2.0\"\n", false, "the plugin has no init.js"), + ("contract = \"2.0\"\n", false, "plugin.toml names no id"), + ("id = \"test.dts\"\ncontract = \"2.0\"\nentry = \"types.d.ts\"\n", false, "declaration file"), + ( + "id = \"test.ts\"\ncontract = \"2.0\"\n", + true, + "script plugins are JavaScript: rename init.ts to init.js and remove its types", + ), ] { std::fs::write(dir.path().join("plugin.toml"), manifest).unwrap(); + if init_ts { + std::fs::write(dir.path().join("init.ts"), "export default () => {}\n").unwrap(); + } let output = run_cli(&["plugin", "check", target]); assert!(!output.status.success()); let stderr = String::from_utf8_lossy(&output.stderr); @@ -143,14 +154,14 @@ fn plugin_check_accepts_init_js_and_custom_entry() { let custom = opencode_util::temp::tempdir().unwrap(); std::fs::write( custom.path().join("plugin.toml"), - "id = \"test.custom\"\ncontract = \"2.0\"\nentry = \"main.ts\"\n", + "id = \"test.custom\"\ncontract = \"2.0\"\nentry = \"main.js\"\n", ) .unwrap(); - std::fs::write(custom.path().join("helper.ts"), "export const greeting = \"hi\"\n").unwrap(); + std::fs::write(custom.path().join("helper.js"), "export const greeting = \"hi\"\n").unwrap(); std::fs::write( - custom.path().join("main.ts"), + custom.path().join("main.js"), "import { define } from \"opencode:plugin\"\n\ - import { greeting } from \"./helper.ts\"\n\ + import { greeting } from \"./helper.js\"\n\ export default define((setup) => {\n\ setup.command({ name: \"custom.hi\" }, (host) => {\n\ host.toast({ variant: \"info\", message: greeting })\n\ diff --git a/packages/cli-rs/script/check-plugin-types.ts b/packages/cli-rs/script/check-plugin-types.ts index ab157d7a5595..76ad36b291d1 100644 --- a/packages/cli-rs/script/check-plugin-types.ts +++ b/packages/cli-rs/script/check-plugin-types.ts @@ -1,6 +1,9 @@ // Type-checks every script plugin in packages/cli-rs with `tsc` (@typescript/native) against `opencode-plugin.d.ts` // and psychoscript's `GLOBALS_DTS` (written by `opencode-native plugin types`), and checks `script/script-expect/*.ts`. // +// Script plugins are JavaScript: each plugin is checked at its `init.js` (or an `entry` ending in `.js`) with +// `allowJs` and `checkJs`. The refusal fixtures stay TypeScript on purpose; `erasableSyntaxOnly` is theirs alone. +// // Usage: bun run script/check-plugin-types.ts import { mkdtemp, rm } from "node:fs/promises" import { tmpdir } from "node:os" @@ -19,11 +22,11 @@ const compilerOptions = { types: [], module: "preserve", moduleResolution: "bundler", - allowImportingTsExtensions: true, - erasableSyntaxOnly: true, - verbatimModuleSyntax: true, } +// The refusal fixtures are TypeScript, so they can name the non-erasable syntax a script plugin may not use. +const refusalOptions = { ...compilerOptions, erasableSyntaxOnly: true } + let work: string | undefined let failed = false try { @@ -45,10 +48,8 @@ try { let checked = 0 let errors = 0 for (const dir of plugins) { - const count = await check(dir, tsc, config, globals) - if (count < 0) continue checked++ - errors += count + errors += await check(dir, tsc, config, globals) } let unmet = 0 @@ -99,7 +100,7 @@ function writeGlobals(dir: string) { async function refused(file: string, tsc: string, config: string, globals: string) { const wants = Array.from((await Bun.file(file).text()).matchAll(/^\/\/ expect: (.+)$/gm), (match) => match[1]) if (wants.length === 0) throw new Error(`${path.relative(root, file)} names no "// expect: " line`) - const result = await runTsc(tsc, config, [globals, stub, file]) + const result = await runTsc(tsc, config, [globals, stub, file], refusalOptions) const missing = wants.filter((want) => !result.output.includes(want)) if (result.exitCode === 0 || missing.length > 0) { console.error( @@ -110,28 +111,34 @@ async function refused(file: string, tsc: string, config: string, globals: strin return true } -async function entryOf(dir: string): Promise { +// The entry a plugin names, else `init.js`: script plugins are JavaScript. +async function entryOf(dir: string) { const manifest = await Bun.file(path.join(dir, "plugin.toml")).text() - const explicit = manifest.match(/^\s*entry\s*=\s*"([^"]+)"\s*$/m)?.[1] - if (explicit) return explicit.endsWith(".ts") || explicit.endsWith(".js") ? path.join(dir, explicit) : null - for (const name of ["init.ts", "init.js"]) { - const candidate = path.join(dir, name) - if (await Bun.file(candidate).exists()) return candidate - } - return null + return manifest.match(/^\s*entry\s*=\s*"([^"]+)"\s*$/m)?.[1] ?? "init.js" } async function check(dir: string, tsc: string, config: string, globals: string) { - const entry = await entryOf(dir) - if (!entry) return -1 + const name = await entryOf(dir) + const entry = path.join(dir, name) + if (!name.endsWith(".js")) { + const renamed = name.replace(/\.ts$/, ".js") + console.error( + `${path.relative(root, dir)}: script plugins are JavaScript: rename ${name} to ${renamed} and remove its types`, + ) + return 1 + } + if (!(await Bun.file(entry).exists())) { + console.error(`${path.relative(root, dir)}: the plugin has no ${name}; script plugins are JavaScript`) + return 1 + } const result = await runTsc(tsc, config, [globals, stub, entry]) if (result.output.trim()) console.error(result.output.trimEnd()) const count = result.output.split("\n").filter((line) => /error TS\d+:/.test(line)).length return result.exitCode === 0 ? count : Math.max(count, 1) } -async function runTsc(tsc: string, config: string, files: string[]) { - await Bun.write(config, JSON.stringify({ compilerOptions, files }, null, 2)) +async function runTsc(tsc: string, config: string, files: string[], options = compilerOptions) { + await Bun.write(config, JSON.stringify({ compilerOptions: options, files }, null, 2)) const proc = Bun.spawnSync([tsc, "-p", config], { stdout: "pipe", stderr: "pipe" }) return { exitCode: proc.exitCode, output: proc.stdout.toString() + proc.stderr.toString() } } From 4386a20c4bbfb1b951cee2fe03895c30104a2ef3 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 10:32:16 +0100 Subject: [PATCH 5/7] docs(cli-rs): document script plugins as JavaScript --- packages/cli-rs/README.md | 2 +- packages/cli-rs/docs/plugin-abi.md | 6 ++-- packages/cli-rs/docs/plugins.md | 58 ++++++++++++++++-------------- 3 files changed, 35 insertions(+), 31 deletions(-) diff --git a/packages/cli-rs/README.md b/packages/cli-rs/README.md index baa6d31f3849..5679016da332 100644 --- a/packages/cli-rs/README.md +++ b/packages/cli-rs/README.md @@ -28,7 +28,7 @@ rust-analyzer finds no project at the repository root. Open `packages/cli-rs`, o ## Plugins The client runs the TypeScript TUI plugins on its own Bun process. It also runs script plugins in its own process: -a directory with a `plugin.toml` and an `init.ts`, in a confined JavaScript. +a directory with a `plugin.toml` and an `init.js`, in a confined JavaScript. - [`docs/plugins.md`](docs/plugins.md): how plugins work and how to write one. - [`docs/plugin-abi.md`](docs/plugin-abi.md): the full plugin contract. diff --git a/packages/cli-rs/docs/plugin-abi.md b/packages/cli-rs/docs/plugin-abi.md index 6a19b6bc54ec..c7710e5d503c 100644 --- a/packages/cli-rs/docs/plugin-abi.md +++ b/packages/cli-rs/docs/plugin-abi.md @@ -664,7 +664,7 @@ read/effect tables and the typed client. - **One run per activation (`vm.rs`).** Because psychoscript has no host-to-JS call, the entry module runs `setup` and then awaits an inbox host function in a loop; `Activation::call` pushes one call and polls until the VM parks on the inbox again. -- **Handlers cross as integer IDs (`prelude.ts`).** `opencode:plugin` stores plugin closures in a table, registers +- **Handlers cross as integer IDs (`prelude.js`).** `opencode:plugin` stores plugin closures in a table, registers their IDs with the host, and returns results via a sync host function. Sync-only callbacks (renders, views, fences, `onDispose`) fail if they return a pending promise. - **Waits are module promises.** `host.fetch` / `foreground` / timers return a promise keyed by request ID and settled @@ -674,9 +674,9 @@ read/effect tables and the typed client. - **Direct serde crossing (`value.rs`).** Contract types convert directly to/from VM values under [Limits](plugins.md#limits) (`None` → `undefined`, JSON `null` → `null`, unpaired UTF-16 surrogates → U+FFFD). `Changed` crosses as flags and fetches its ID lists lazily on property read. -- **`view.memo` replay.** Because host functions cannot call back into JS, `prelude.ts` checks `View::memo_same`, +- **`view.memo` replay.** Because host functions cannot call back into JS, `prelude.js` checks `View::memo_same`, builds on a miss, and emits a placeholder that the carrier replays through `View::memo`. -- **Compile-time linking and limits.** A `script-compile` thread links all `.ts`/`.js` sources; the entry and +- **Compile-time linking and limits.** A `script-compile` thread links all `.js` sources; the entry and `opencode:plugin` are marked host frames (hidden from tracebacks) and are the only importers of `opencode:host`. CPU slice (`Limits::overrun`), heap cap and crossing bounds are enforced per run ([What stops a script plugin](plugins.md#what-stops-a-script-plugin), [`script-gates.md`](script-gates.md)); an ended diff --git a/packages/cli-rs/docs/plugins.md b/packages/cli-rs/docs/plugins.md index afbaa12b1157..933ebe43d398 100644 --- a/packages/cli-rs/docs/plugins.md +++ b/packages/cli-rs/docs/plugins.md @@ -15,7 +15,7 @@ Schema, `crates/plugin-abi/schema/v2.json`. A *carrier* runs a plugin against it | Carrier | A plugin is | A call crosses as | Host code | | --- | --- | --- | --- | | Linked Rust | an `abi::Plugin { id, setup }` compiled into the client | Rust values | `Builtin` in `crates/plugin/src/lib.rs` | -| Script | a directory with `plugin.toml` and `init.ts` | copies of plain values, into and out of a confined JavaScript VM for each activation | `crates/plugin/src/script` | +| Script | a directory with `plugin.toml` and `init.js` | copies of plain values, into and out of a confined JavaScript VM for each activation | `crates/plugin/src/script` | | Pipe | a TypeScript TUI plugin, unmodified | framed messages to one Bun process for all TS plugins, the *JS host* | `crates/plugin/src/pipe`, and `loader/requests.rs` | - **Every built-in is a linked plugin on the public contract** (`crates/tui/src/plugins`, `crates/latex`, @@ -161,20 +161,21 @@ tool results, with a tick that runs only while the sidebar shows). ## Script plugins -A script plugin is a set of ES modules written against the host's module `opencode:plugin`. Its language is -psychoscript, a confined JavaScript that also reads TypeScript's type syntax. The carrier is -`crates/plugin/src/script`, and `prelude.ts` there is `opencode:plugin`. A script plugin is not a TypeScript TUI -plugin: it has no JSX, no npm packages and no Bun, and it speaks the contract directly. +A script plugin is a set of JavaScript ES modules written against the host's module `opencode:plugin`. Its +language is psychoscript, a confined JavaScript. The carrier is `crates/plugin/src/script`, and `prelude.js` there +is `opencode:plugin`. A script plugin is not a TypeScript TUI plugin: it has no JSX, no npm packages and no Bun, +and it speaks the contract directly. ### The files -- **The entry** is `init.ts`, else `init.js`; `entry = "lib/main.ts"` in `plugin.toml` names another file of the - plugin. +- **The entry** is `init.js`; `entry = "lib/main.js"` in `plugin.toml` names another file of the plugin. - **`plugin.toml`** is flat `key = "string"` lines: `id`, which it must have, and `name`, `version`, `description`, `contract` (a 2.x) and `entry`. -- **What loads** is `plugin.toml` and every `.ts` and `.js` file of the directory, at most 1 MiB in all and 8 - directories deep. Declaration files (`.d.ts`) and hidden entries are skipped, and a link out of the directory is - refused. The files are read once for each build; nothing is read from the disk after that. +- **What loads** is `plugin.toml` and every `.js` file of the directory, at most 1 MiB in all and 8 directories + deep. Declaration files (`.d.ts`) and hidden entries are skipped, and a link out of the directory is refused. The + files are read once for each build; nothing is read from the disk after that. +- **A `.ts` entry, or an import of a `.ts` module, is refused:** + `script plugins are JavaScript: rename init.ts to init.js and remove its types`, naming the file to rename. - **The entry's default export is `define(setup)`.** `setup` runs once for each activation, registers everything, and cannot wait. A registration after `setup` returned throws. @@ -185,9 +186,8 @@ plugin: it has no JSX, no npm packages and no Bun, and it speaks the contract di `read`, `host`, `sleep` and `every`). - **Omitted JS features:** `Intl`, `Proxy`, `Reflect`, `WeakRef`, `Symbol()`, typed arrays other than `Uint8Array`, private `#x` members, static blocks, and `new` on a plain function. Missing syntax fails at load with its line. -- **Erasable TypeScript only:** in `.ts` files, type annotations, interfaces, aliases, `as`, `satisfies`, generics - and `import type` are stripped on load; `enum`, value `namespace`, parameter properties and decorators fail at - load. `.js` files run as written. +- **No TypeScript:** a `.ts` entry or import is refused ([The files](#the-files)); types are JSDoc comments, checked + by `tsc` and not compiled ([Types](#types)). - **Contract names & copy crossing:** camelCase methods (`setup.command`, `read.storageGet`), schema field names (`on_click`, `session_id`), omitted fields as `undefined`, JSON `null` as `null`. Values cross by copy; functions throw `TypeError`. `console.{log,info,warn,error,debug}` write one escaped line (≤ 4 KiB) to the client log. @@ -284,10 +284,13 @@ export default function shout(_read, fence) { absolute path, a path that leaves the plugin, a path without its extension. - **Modules are linked as the plugin loads**, from the bytes read then. Each runs once, before the modules that import it, and a cycle is a load error that names its files. -- **`.ts` and `.js` files mix** in one plugin. +- **Only `.js` modules:** an import of a `.ts` file is refused ([The files](#the-files)). ### Types +Types are checked, not compiled: `// @ts-check` at the top of a file makes `tsc` check it, and JSDoc gives a type +where the checker needs one (`/** @param {Read} read */`). + The client embeds both declaration files: `opencode-plugin.d.ts` (generated into `crates/plugin/src/script/opencode-plugin.d.ts` from `v2.json`, `openapi.json` and `operations.json`) and `psychoscript.d.ts` (`psychoscript::GLOBALS_DTS`, replacing TypeScript's default libs under `noLib`). @@ -305,15 +308,15 @@ The client embeds both declaration files: `opencode-plugin.d.ts` (generated into "compilerOptions": { "strict": true, "noEmit": true, "noLib": true, "allowJs": true, "checkJs": true, "target": "es2023", "types": [], - "module": "preserve", "moduleResolution": "bundler", "allowImportingTsExtensions": true, - "erasableSyntaxOnly": true, "verbatimModuleSyntax": true + "module": "preserve", "moduleResolution": "bundler" }, - "files": ["psychoscript.d.ts", "opencode-plugin.d.ts", "init.ts"] + "files": ["psychoscript.d.ts", "opencode-plugin.d.ts", "init.js"] } ``` This rejects misspelled contract/API/`client` fields, omitted globals (`setTimeout`, `Intl`, `Proxy`, `WeakRef`), -and non-erasable TypeScript (`enum`). Unsupported JS syntax (`#x`) is caught by the compile step of `plugin check`. +and JSDoc types that do not match the value. Unsupported JS syntax (`#x`) is caught by the compile step of +`plugin check`. ### Errors and locations @@ -321,13 +324,14 @@ Errors name the plugin, file, line, column and plugin frames (host frames in `op are one escaped line ≤ 4 KiB; tracebacks over 20 frames keep the first 10 and last 10): ```text -example.report: lib/util.ts:4:11: TypeError: Cannot read properties of null (reading 'spans'). +example.report: lib/util.js:4:11: TypeError: Cannot read properties of null (reading 'spans'). stack traceback: - lib/util.ts:4:11: in function 'width' - init.ts:11:51: in function '' + lib/util.js:4:11: in function 'width' + init.js:11:51: in function '' ``` -- **Build errors** (syntax, non-erasable TS, bad import, cycle) fail before `setup`; on reload the prior build stays. +- **Build errors** (syntax, a `.ts` entry or import, bad import, cycle) fail before `setup`; on reload the prior + build stays. - **Runtime errors** (thrown `Error`, `TypeError`, effect in a render, wait outside a task) fail the plugin and show in `/plugins` and the log ([Failures](#failures)). Throw `new Error(..)` for a location. - **Uncaught `HostError` / `AbortError`** in a task ends only that task and logs it; the plugin keeps running. @@ -335,7 +339,7 @@ stack traceback: ## Waiting: tasks, `await` and timers A handler often waits: for a dialog's answer, a server reply or a timer. A *task* lets it wait in a straight line, -as `async` code does in TypeScript, while every stretch of it still runs inside a host call on the UI thread. +as `async` code does in JavaScript, while every stretch of it still runs inside a host call on the UI thread. - **A task has no thread.** When it waits it returns to the host, and the answer (a reply, a dialog's answer or close, a timer, a wake) is another call into the plugin that resumes it. @@ -367,19 +371,19 @@ async fn clear(cx: Cx) { } ``` -**Script** (`crates/plugin/src/script/prelude.ts`). A handler called with a `host` may be `async`, and is then a +**Script** (`crates/plugin/src/script/prelude.js`). A handler called with a `host` may be `async`, and is then a task. A waiting call returns a promise: a request resolves to its value or rejects, and a dialog resolves to its answer, or to `undefined` when it closed without one. `spawn(f)` starts another task and `all([f, ..])` waits for several. The same handler, which `the_guides_script_wait_runs_as_written` runs from this file: -```ts +```js setup.command({ name: "x.clear", palette: true }, async (host) => { if (!(await host.confirm({ title: "Clear?", message: "Clear the list?" }))) return try { await host.fetch({ method: "DELETE", path: "/api/x" }) host.toast({ variant: "success", message: "Cleared" }) } catch (error) { - await host.alert({ title: "Clear failed", message: (error as Error).message }) + await host.alert({ title: "Clear failed", message: /** @type {Error} */ (error).message }) } }) ``` @@ -505,7 +509,7 @@ In the places the TypeScript client looks, in this order: Targets merge by local path; a later entry replaces an earlier one in its place. The target decides the carrier: - a shared library, or a directory with `plugin.so` (`plugin.dylib`, `plugin.dll`): none, it is listed as skipped; -- a directory with `plugin.toml`: a script plugin (`init.ts` or `init.js`, or `entry` in `plugin.toml`); +- a directory with `plugin.toml`: a script plugin (`init.js`, or `entry` in `plugin.toml`); - any other directory, and an npm package: the JS host. An npm spec (`name`, `name@1.2.3`, a range, a tag, `@scope/name`, a git spec) resolves to the package the TypeScript From 36c65f6fa0bd8bd03aa51766f50661eba25c26b4 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 10:50:05 +0100 Subject: [PATCH 6/7] refactor(cli-rs): finish the JavaScript-only script plugins The five worker branches left a few places on the TypeScript entry: the ports twin's fixture plugin wrote script/init.ts, the TUI script fixtures built their plugins from init.ts (two with type annotations in their source), and the F16 deviation still described stripped types. plugin check now compiles before it runs tsc, so a .js plugin importing a .ts module is refused with the loader's own wording instead of tsc's import-extension error. --- .../cli-rs/crates/cli/src/commands/plugin.rs | 37 +++---------------- packages/cli-rs/crates/cli/tests/plugin.rs | 14 +++++++ packages/cli-rs/crates/plugin/src/twin.rs | 2 +- .../crates/tui/tests/all/plugin_ownership.rs | 6 +-- .../tui/tests/all/plugin_pending_focus.rs | 6 +-- .../crates/tui/tests/all/plugin_script.rs | 6 +-- .../crates/tui/tests/all/plugin_surface.rs | 6 +-- .../crates/tui/tests/all/plugin_timers.rs | 4 +- .../parity/deviations/F16-script-plugins.md | 11 +++--- 9 files changed, 40 insertions(+), 52 deletions(-) diff --git a/packages/cli-rs/crates/cli/src/commands/plugin.rs b/packages/cli-rs/crates/cli/src/commands/plugin.rs index 5593bb081528..d947b63b90e7 100644 --- a/packages/cli-rs/crates/cli/src/commands/plugin.rs +++ b/packages/cli-rs/crates/cli/src/commands/plugin.rs @@ -90,45 +90,18 @@ fn check(dir: &Path) -> error::Result<()> { } let sources = opencode_plugin::script::read(dir).map_err(error::Error::msg)?; let manifest = opencode_plugin::script::parse_manifest(&sources).map_err(error::Error::msg)?; - let entry = script_entry(dir, &sources, &manifest)?; + sources.text(&manifest.entry).map_err(error::Error::msg)?; + // The build first: its refusals (a .ts import) are the loader's, worded the same, where tsc would report them its + // own way. + opencode_plugin::script::Built::new(&sources).map_err(error::Error::msg)?; let root = std::fs::canonicalize(dir)?; - typecheck(&root, &root.join(entry))?; - opencode_plugin::script::Built::new(&sources).map_err(error::Error::msg)?; + typecheck(&root, &root.join(&manifest.entry))?; let count = sources.files().filter(|(path, _)| *path != opencode_plugin::source::MANIFEST).count(); crate::output::print(&format!("ok: {} ({count} file(s))\n", manifest.id)) } -/// The plugin's entry, refusing TypeScript: script plugins are JavaScript. An `init.ts` entry with no such file is -/// a loader's default for a plugin with no entry file, which has no `init.js` either. -#[cfg(script)] -fn script_entry<'a>( - dir: &Path, - sources: &opencode_plugin::script::Sources, - manifest: &'a opencode_plugin::script::Manifest, -) -> error::Result<&'a str> { - if manifest.entry.ends_with(".ts") { - if manifest.entry == "init.ts" && sources.text("init.ts").is_err() { - return Err(error::Error::msg("the plugin has no init.js")); - } - return Err(not_javascript(&manifest.entry)); - } - if dir.join("init.ts").is_file() { - return Err(not_javascript("init.ts")); - } - sources.text(&manifest.entry).map_err(error::Error::msg)?; - Ok(&manifest.entry) -} - -#[cfg(script)] -fn not_javascript(entry: &str) -> error::Error { - error::Error::msg(format!( - "script plugins are JavaScript: rename {entry} to {}.js and remove its types", - entry.strip_suffix(".ts").unwrap_or(entry) - )) -} - #[cfg(script)] fn typecheck(root: &Path, entry: &Path) -> error::Result<()> { use std::io::{ErrorKind, Write}; diff --git a/packages/cli-rs/crates/cli/tests/plugin.rs b/packages/cli-rs/crates/cli/tests/plugin.rs index 07b6fb97ed99..247e636a15cc 100644 --- a/packages/cli-rs/crates/cli/tests/plugin.rs +++ b/packages/cli-rs/crates/cli/tests/plugin.rs @@ -132,6 +132,20 @@ fn plugin_check_reports_manifest_and_entry_errors() { } } +#[test] +fn plugin_check_refuses_a_typescript_import_as_the_loader_does() { + let dir = opencode_util::temp::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("lib")).unwrap(); + std::fs::write(dir.path().join("plugin.toml"), "id = \"test.tsimport\"\ncontract = \"2.0\"\n").unwrap(); + std::fs::write(dir.path().join("lib").join("x.ts"), "export const x = 1\n").unwrap(); + std::fs::write(dir.path().join("init.js"), "import { x } from \"./lib/x.ts\"\nexport default () => x\n").unwrap(); + let output = run_cli(&["plugin", "check", dir.path().to_str().unwrap()]); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + let expected = "script plugins are JavaScript: rename ./lib/x.ts to ./lib/x.js and remove its types"; + assert!(stderr.contains(expected), "missing {expected:?} in:\n{stderr}"); +} + #[test] fn plugin_check_accepts_init_js_and_custom_entry() { let dir = opencode_util::temp::tempdir().unwrap(); diff --git a/packages/cli-rs/crates/plugin/src/twin.rs b/packages/cli-rs/crates/plugin/src/twin.rs index 4a29cab7b179..34fa3783f707 100644 --- a/packages/cli-rs/crates/plugin/src/twin.rs +++ b/packages/cli-rs/crates/plugin/src/twin.rs @@ -1128,7 +1128,7 @@ mod tests { let toml = "id = \"test.mini\"\nname = \"Mini\"\nversion = \"0.1.0\"\ncontract = \"2.0\"\n"; std::fs::write(plugin.join("script/plugin.toml"), toml).unwrap(); std::fs::write( - plugin.join("script/init.ts"), + plugin.join("script/init.js"), r#"import { define } from "opencode:plugin" export default define((setup) => { setup.command({ name: "mini.ping" }, (host) => { diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_ownership.rs b/packages/cli-rs/crates/tui/tests/all/plugin_ownership.rs index db1d33753d0f..442afcb8251e 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_ownership.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_ownership.rs @@ -238,7 +238,7 @@ fn parked(carrier: Carrier) { Carrier::Script => { let sources = opencode_plugin::script::Sources::from_files([ ("plugin.toml", "id = \"test.parked\""), - ("init.ts", &parked_script_ts()), + ("init.js", &parked_script()), ]); opencode_plugin::script::define(&sources, None).unwrap().0 } @@ -749,7 +749,7 @@ impl Probe { let init = script_probe(row, mark); let sources = opencode_plugin::script::Sources::from_files([ ("plugin.toml", "id = \"test.probe\""), - ("init.ts", &init), + ("init.js", &init), ]); let definition = opencode_plugin::script::define(&sources, None).unwrap().0; opencode_tui::plugins::host::add(&harness.tui, definition); @@ -1075,7 +1075,7 @@ fn storage_seen(harness: &Harness, field: &str) -> Vec { } #[cfg(script)] -fn parked_script_ts() -> String { +fn parked_script() -> String { let page = serde_json::to_string(&page()).unwrap(); format!( r#"import {{ define }} from "opencode:plugin" diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_pending_focus.rs b/packages/cli-rs/crates/tui/tests/all/plugin_pending_focus.rs index 6958d0fc856b..f23e57b33207 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_pending_focus.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_pending_focus.rs @@ -71,7 +71,7 @@ fn open(carrier: Carrier) -> Harness { Carrier::Script => { let sources = opencode_plugin::script::Sources::from_files([ ("plugin.toml", "id = \"test.focus\""), - ("init.ts", SCRIPT), + ("init.js", SCRIPT), ]); opencode_plugin::script::define(&sources, None).unwrap().0 } @@ -127,7 +127,7 @@ fn page(wide: bool, show: bool) -> v2::Node { #[cfg(script)] const SCRIPT: &str = r#"import { define } from "opencode:plugin" let show = false -const text = (text: string) => ({ type: "text", spans: [{ text }] }) +const text = (text) => ({ type: "text", spans: [{ text }] }) export default define((setup) => { setup.command({ name: "pf.later", scope: { route: "pf" } }, (host) => host.focus("later")) setup.command({ name: "pf.show", scope: { route: "pf" } }, (host) => { @@ -137,7 +137,7 @@ export default define((setup) => { setup.surface({ name: "pf", place: { type: "route", name: "pf" }, mounts: true }, (view) => { const wide = (view.input.width ?? 0) >= 100 return view.memo("page", wide + " " + show, () => { - const children: unknown[] = [text(wide ? "focus page, wide page" : "focus page")] + const children = [text(wide ? "focus page, wide page" : "focus page")] if (wide) children.push({ type: "input", id: "later" }) if (show) { children.push(text("field shown")) diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_script.rs b/packages/cli-rs/crates/tui/tests/all/plugin_script.rs index b7a80615947d..ef8429a4c5c0 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_script.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_script.rs @@ -45,7 +45,7 @@ export default define((setup) => { }) }) "#; - let sources = Sources::from_files([("plugin.toml", "id = \"test.page\""), ("init.ts", init)]); + let sources = Sources::from_files([("plugin.toml", "id = \"test.page\""), ("init.js", init)]); let h = home(define(&sources, None).unwrap().0); h.tui.navigate(Route::Plugin { id: "test.page".into(), name: "page".into() }); h.wait_for_all(&["cards built", "builds 1"]); @@ -67,7 +67,7 @@ export default define((setup) => { setup.slot({ path: "home.footer" }, () => show(text("spinner claim"))) }) "#; - let sources = Sources::from_files([("plugin.toml", "id = \"test.spin\""), ("init.ts", init)]); + let sources = Sources::from_files([("plugin.toml", "id = \"test.spin\""), ("init.js", init)]); let h = home(define(&sources, None).unwrap().0); h.wait_for("spinner claim"); _ = h.tui.keymap.dispatch("spin", None); @@ -133,7 +133,7 @@ export default define((setup) => { }) }) "#; - let sources = Sources::from_files([("plugin.toml", "id = \"test.ask\""), ("init.ts", init)]); + let sources = Sources::from_files([("plugin.toml", "id = \"test.ask\""), ("init.js", init)]); let h = home(define(&sources, None).unwrap().0); frames(&h); let options = opencode_ui::dialog::DialogOptions::new(opencode_ui::dialog::DialogSize::Medium).key("host.approval"); diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_surface.rs b/packages/cli-rs/crates/tui/tests/all/plugin_surface.rs index 22b8c54f1b17..b6cb15d6c5fb 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_surface.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_surface.rs @@ -1432,8 +1432,8 @@ fn dialog_probe(setup: &mut abi::Setup) -> Result<(), String> { /// [`dialog_probe`] in psychoscript, which records in its storage. #[cfg(script)] const DIALOG_SCRIPT: &str = r#"import { define } from "opencode:plugin" -const text = (text: string) => ({ type: "text", spans: [{ text }] }) -function record(host: { storageGet(k: string): string[] | undefined; storageSet(k: string, v: string[]): void }, line: string) { +const text = (text) => ({ type: "text", spans: [{ text }] }) +function record(host, line) { const seen = host.storageGet("seen") ?? [] seen.push(line) host.storageSet("seen", seen) @@ -1476,7 +1476,7 @@ fn dialog_open(carrier: DialogCarrier) -> Harness { DialogCarrier::Script => { let sources = opencode_plugin::script::Sources::from_files([ ("plugin.toml", "id = \"test.dlg\""), - ("init.ts", DIALOG_SCRIPT), + ("init.js", DIALOG_SCRIPT), ]); opencode_plugin::script::define(&sources, None).unwrap().0 } diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_timers.rs b/packages/cli-rs/crates/tui/tests/all/plugin_timers.rs index 51126d6a2a3c..5b3679944be4 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_timers.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_timers.rs @@ -71,7 +71,7 @@ fn ticks_without_frames(carrier: Carrier) { Carrier::Script => { let sources = opencode_plugin::script::Sources::from_files([ ("plugin.toml", "id = \"test.tick\""), - ("init.ts", SCRIPT_TICKING), + ("init.js", SCRIPT_TICKING), ]); opencode_plugin::script::define(&sources, None).unwrap().0 } @@ -198,7 +198,7 @@ fn an_every_a_mount_started_ends_with_that_mount() { let definition = match carrier { #[cfg(script)] Carrier::Script => { - let files = [("plugin.toml", "id = \"test.tick\""), ("init.ts", SCRIPT_EVERY_OF_A_MOUNT)]; + let files = [("plugin.toml", "id = \"test.tick\""), ("init.js", SCRIPT_EVERY_OF_A_MOUNT)]; opencode_plugin::script::define(&opencode_plugin::script::Sources::from_files(files), None).unwrap().0 } Carrier::InProcess => abi::Plugin { id: "test.tick", setup: every_of_a_mount }.into(), diff --git a/packages/cli-rs/parity/deviations/F16-script-plugins.md b/packages/cli-rs/parity/deviations/F16-script-plugins.md index c05cfb040dec..80bf27a44d8f 100644 --- a/packages/cli-rs/parity/deviations/F16-script-plugins.md +++ b/packages/cli-rs/parity/deviations/F16-script-plugins.md @@ -7,13 +7,13 @@ into the TUI's own process (`packages/tui/src/plugin/context.tsx`). The plugin d imports npm packages, and has Bun's whole runtime: files, the network, processes, timers. Nothing bounds its time or its memory, and nothing is asked before a project's plugin runs. -It reads no `plugin.toml`. A directory under `plugins` that holds only a `plugin.toml` and an `init.ts` has no TUI +It reads no `plugin.toml`. A directory under `plugins` that holds only a `plugin.toml` and an `init.js` has no TUI module, so it is left out and nothing is said (`resolve` answers `unsupported`, and a discovered directory is optional). Its CLI has no `plugin types`, and its `plugin check` checks installed packages for updates. ## Rust -A directory with a `plugin.toml` whose entry is a `.ts` or `.js` file is a script plugin (`docs/plugins.md`, "Script +A directory with a `plugin.toml` whose entry is a `.js` file is a script plugin (`docs/plugins.md`, "Script plugins"; `crates/plugin/src/script`). It runs inside the client, on the UI thread, in a VM of its own for each activation. Script plugins replaced the former Luau carrier. @@ -27,9 +27,10 @@ activation. Script plugins replaced the former Luau carrier. - **The API is the contract, not the TS plugin API.** The plugin imports `opencode:plugin`, registers data in `setup`, returns trees of nodes and asks for effects. It has no JSX, no components and no `context`. - **The language is psychoscript, not Bun's JavaScript.** There are no npm packages, and no `fetch`, timers, file - system, process, `eval`, `Intl`, `Proxy` or `WeakRef`. A `.ts` file's type syntax is stripped, and TypeScript that - needs compiling, such as an `enum`, is a load error. `import` reaches the plugin's own files and `opencode:plugin` - only. + system, process, `eval`, `Intl`, `Proxy` or `WeakRef`. It is JavaScript only: a `.ts` entry, or an import of a `.ts` + module, is refused (`script plugins are JavaScript: rename init.ts to init.js and remove its types`), and types are + JSDoc comments checked with `tsc` against the generated declarations. `import` reaches the plugin's own files and + `opencode:plugin` only. - **It is bounded.** A stretch of it between two waits may use 100 ms of CPU time, a VM may hold 32 MiB of live values, a value that crosses to the host holds at most 320,000 keys and values, and its sources are 1 MiB. Past one of the first three the plugin fails, and `try` does not keep it alive (`F16-plugin-budget-and-restart`, From 430b636ca0ebfeefb41701ec5e5ba6ffd18c9eab Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Thu, 3 Dec 2026 11:20:07 +0100 Subject: [PATCH 7/7] fix(cli-rs): skip non-script plugins in check:plugin-types The checker treated every plugin.toml as a script plugin, so a legacy Luau directory (an init.luau, or an entry ending in .luau) counted as an error and was told to rename init.luau to itself. It now mirrors the loader's source::carrier and skips a directory routed to the Luau carrier. A directory routed to Script keeps its refusal, and an init.ts with no init.js is now named in that refusal rather than reported as a missing init.js, as the loader's default entry does. script/script-expect/luau is the row that holds this: it is scanned and must be skipped, so a regression fails the check. --- packages/cli-rs/script/check-plugin-types.ts | 48 +++++++++++++++---- .../script/script-expect/luau/init.luau | 2 + .../script/script-expect/luau/plugin.toml | 4 ++ 3 files changed, 46 insertions(+), 8 deletions(-) create mode 100644 packages/cli-rs/script/script-expect/luau/init.luau create mode 100644 packages/cli-rs/script/script-expect/luau/plugin.toml diff --git a/packages/cli-rs/script/check-plugin-types.ts b/packages/cli-rs/script/check-plugin-types.ts index 76ad36b291d1..dadfe90350b0 100644 --- a/packages/cli-rs/script/check-plugin-types.ts +++ b/packages/cli-rs/script/check-plugin-types.ts @@ -2,7 +2,8 @@ // and psychoscript's `GLOBALS_DTS` (written by `opencode-native plugin types`), and checks `script/script-expect/*.ts`. // // Script plugins are JavaScript: each plugin is checked at its `init.js` (or an `entry` ending in `.js`) with -// `allowJs` and `checkJs`. The refusal fixtures stay TypeScript on purpose; `erasableSyntaxOnly` is theirs alone. +// `allowJs` and `checkJs`. A directory the loader routes to its Luau carrier is skipped, not refused, and the +// refusal fixtures stay TypeScript on purpose; `erasableSyntaxOnly` is theirs alone. // // Usage: bun run script/check-plugin-types.ts import { mkdtemp, rm } from "node:fs/promises" @@ -48,8 +49,10 @@ try { let checked = 0 let errors = 0 for (const dir of plugins) { + const manifest = await Bun.file(path.join(dir, "plugin.toml")).text() + if ((await carrierOf(dir, manifest)) !== "script") continue checked++ - errors += await check(dir, tsc, config, globals) + errors += await check(dir, manifest, tsc, config, globals) } let unmet = 0 @@ -111,14 +114,43 @@ async function refused(file: string, tsc: string, config: string, globals: strin return true } -// The entry a plugin names, else `init.js`: script plugins are JavaScript. -async function entryOf(dir: string) { - const manifest = await Bun.file(path.join(dir, "plugin.toml")).text() - return manifest.match(/^\s*entry\s*=\s*"([^"]+)"\s*$/m)?.[1] ?? "init.js" +// The loader's `source::carrier`: an explicit entry ending in `.luau` is the Luau carrier; without an entry, +// `init.js` or `init.ts` wins over `init.luau`; anything else is a script plugin. +async function carrierOf(dir: string, manifest: string) { + const entry = manifestEntry(manifest) + if (entry !== undefined) return entry.endsWith(".luau") ? "luau" : "script" + if ((await Bun.file(path.join(dir, "init.ts")).exists()) || (await Bun.file(path.join(dir, "init.js")).exists())) + return "script" + if (await Bun.file(path.join(dir, "init.luau")).exists()) return "luau" + return "script" } -async function check(dir: string, tsc: string, config: string, globals: string) { - const name = await entryOf(dir) +// The loader's `source::manifest_entry`: the first `entry = "..."` line, as the manifest reads it. +function manifestEntry(text: string): string | undefined { + for (const line of text.split("\n")) { + const trimmed = line.trim() + if (trimmed === "" || trimmed.startsWith("#")) continue + const at = trimmed.indexOf("=") + if (at < 0) continue + if (trimmed.slice(0, at).trim() !== "entry") continue + const value = trimmed.slice(at + 1).trim() + return value.length >= 2 && value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : undefined + } + return undefined +} + +// The entry a plugin names, else `init.js`, or the `init.ts` left for the refusal: the loader's defaults, so a +// directory it refuses is refused here with the same message. +async function entryOf(dir: string, manifest: string) { + const named = manifestEntry(manifest) + if (named) return named + if (await Bun.file(path.join(dir, "init.js")).exists()) return "init.js" + if (await Bun.file(path.join(dir, "init.ts")).exists()) return "init.ts" + return "init.js" +} + +async function check(dir: string, manifest: string, tsc: string, config: string, globals: string) { + const name = await entryOf(dir, manifest) const entry = path.join(dir, name) if (!name.endsWith(".js")) { const renamed = name.replace(/\.ts$/, ".js") diff --git a/packages/cli-rs/script/script-expect/luau/init.luau b/packages/cli-rs/script/script-expect/luau/init.luau new file mode 100644 index 000000000000..232c29585911 --- /dev/null +++ b/packages/cli-rs/script/script-expect/luau/init.luau @@ -0,0 +1,2 @@ +-- Not a script plugin: the loader's source::carrier picks the Luau carrier for a directory with only an init.luau. +return {} diff --git a/packages/cli-rs/script/script-expect/luau/plugin.toml b/packages/cli-rs/script/script-expect/luau/plugin.toml new file mode 100644 index 000000000000..f3139adb0ae2 --- /dev/null +++ b/packages/cli-rs/script/script-expect/luau/plugin.toml @@ -0,0 +1,4 @@ +# A legacy Luau plugin: the loader routes this directory to its Luau carrier, so check:plugin-types skips it +# rather than refusing a script entry it will never load. +id = "test.script.luau" +contract = "2.0"