Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/cli-rs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 7 additions & 7 deletions packages/cli-rs/crates/cli/src/commands/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -89,11 +90,13 @@ 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)?;
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(&manifest.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))
Expand All @@ -120,10 +123,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]
});
Expand Down
55 changes: 40 additions & 15 deletions packages/cli-rs/crates/cli/tests/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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}");
Expand All @@ -108,19 +111,41 @@ 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);
assert!(stderr.contains(expected), "missing {expected:?} in:\n{stderr}");
}
}

#[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();
Expand All @@ -143,14 +168,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\
Expand Down
6 changes: 3 additions & 3 deletions packages/cli-rs/crates/plugin-abi/tests/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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"

Expand Down
4 changes: 2 additions & 2 deletions packages/cli-rs/crates/plugin/src/loader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HashMap<String, npm::Package>>,
/// 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<crate::pipe::tree::Trees>,
/// A script plugin's sources, read and compiled on threads of their own.
Expand Down Expand Up @@ -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<dyn Fn() + Send + Sync> = std::sync::Arc::new(walked);
Expand Down
21 changes: 11 additions & 10 deletions packages/cli-rs/crates/plugin/src/loader/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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), &registry);
let skipped = Status::Skipped(crate::SKIPPED_NO_SCRIPT.to_owned());
Expand All @@ -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(
Expand Down Expand Up @@ -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) => {
",
)
Expand All @@ -1264,14 +1265,14 @@ pub(crate) mod script_loader_tests {
let status = entry(&registry.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, &registry).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, &registry));
assert_eq!(entry(&registry.entries(), &target).status, Status::Active);
let text = footer_text(&host, &registry);
Expand Down Expand Up @@ -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, &registry)));
assert_eq!(status(), Status::Pending);
}
Expand All @@ -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}");
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli-rs/crates/plugin/src/script/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading