Plug-ins: a JavaScript plug-in's parameters keep their declaration order

Loading a JavaScript plug-in read its JSON into a map that sorts its keys and
wrote it out again before parsing the manifest, so `params` and each command's
`params` reached dialogs in alphabetical order. The manifest is now parsed from
the plug-in's own JSON (`Manifest::parse_text`), with its size still counted
without `script` and `source`, and a `.vcplugin` read from a folder has
`source` added to its own text instead of being written out again.
This commit is contained in:
dotCooCoo committed 2026-11-24 23:52:00 -08:00
1 parent 717b1e1670
commit 468b434c09
3 files changed
+66 -6

No files matched your search

+25 -3
View File
@@ -30,7 +30,7 @@ use serde_json::{Map, Value};
use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind};
use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run};
use crate::manifest::{Manifest, Runtime};
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime};
use crate::permissions::{self, Permission};
use crate::runtime::SELECTION_TOO_LARGE;
use crate::{Error, Limits, Result};
@@ -134,8 +134,14 @@ pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> {
if source.len() > MAX_SCRIPT_BYTES {
return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES)));
}
let manifest = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?;
let manifest = Manifest::parse(&manifest)?;
// The manifest is read from `bytes`, so `params` keep their order; its size is counted
// without `script` and `source`.
let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len();
if size > MAX_MANIFEST_BYTES {
return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})")));
}
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
let manifest = Manifest::parse_text(text)?;
if let Err(e) = vectorcraft_js::parse(&source, &options()) {
let named = Named { id: &manifest.id, script: &name };
return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column)))));
@@ -481,6 +487,22 @@ mod tests {
assert_ne!(a.hash(), b.hash());
}
/// The parameters, and a command's, keep the order the plug-in's JSON declares them in.
#[test]
fn params_keep_their_declaration_order() {
let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#;
let text = format!(
r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js",
"params": {{"z": {num}, "a": {num}, "m": {num}}},
"commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}],
"source": "function run(i) {{ return i; }}"}}"#
);
let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap();
let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
assert_eq!(names(&manifest.params), ["z", "a", "m"]);
assert_eq!(names(&manifest.commands[0].params), ["y", "b"]);
}
#[test]
fn script_names_stay_in_the_manifest_s_folder() {
for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] {
+7
View File
@@ -477,6 +477,13 @@ impl Manifest {
return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len())));
}
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
Manifest::parse_text(text)
}
/// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the
/// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys
/// the manifest doesn't declare are ignored, and `params` keep the order the text gives them.
pub(crate) fn parse_text(text: &str) -> Result<Manifest> {
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
return Err(Error::Manifest("`paintOutput` may only be true".into()));
}
+34 -3
View File
@@ -219,7 +219,7 @@ fn read_js_package_with(
use serde_json::Value;
let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() };
let bytes = read_module(path, &manifest_limits, || {})?;
let mut map: serde_json::Map<String, Value> = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?;
let map: serde_json::Map<String, Value> = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?;
if !crate::js::is_js(&map) {
return Err(Error::Manifest(crate::js::NOT_JS.into()));
}
@@ -232,8 +232,17 @@ fn read_js_package_with(
let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() };
let source = read_module(&file, &script_limits, opening)?;
let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?;
map.insert("source".into(), Value::String(source));
serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))
// `source` is added to the manifest's own text, so its keys keep their order. The text parsed as
// an object that has `runtime`, so its last character other than white space is its closing `}`.
let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}');
let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?;
let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?;
let mut out = Vec::with_capacity(bytes.len() + source.len() + 12);
out.extend_from_slice(&bytes[..end]);
out.extend_from_slice(b",\"source\":");
out.extend_from_slice(&source);
out.push(b'}');
Ok(out)
}
/// The bytes of the module file at `path`. A path that doesn't name a regular file is refused
@@ -704,6 +713,28 @@ mod tests {
assert!(!opened.get(), "the script was opened");
}
/// A manifest file's parameters keep their declaration order through the package it is read
/// into, which is its own text with `source` added.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_javascript_package_keeps_the_manifest_s_order() {
let dir = test_dir("js-order");
let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#;
let text = format!(
"{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n"
);
let path = dir.join("order.vcplugin");
std::fs::write(&path, &text).unwrap();
std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap();
let bytes = read_js_package(&path, &|_| Ok(()));
std::fs::remove_dir_all(&dir).unwrap();
let bytes = bytes.unwrap();
let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap());
assert_eq!(String::from_utf8_lossy(&bytes), expected);
let (manifest, _) = crate::js::read_bundle(&bytes).unwrap();
assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["z", "a"]);
}
/// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm`
/// names as not files, and goes on.
#[cfg(unix)]