mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 04:25:52 -05:00
Merge pull request #10483 from dotCooCoo/fix/windows-evalfile-uri
Scripts: $.evalFile reads the URI paths File.parent gives, on Windows too
This commit is contained in:
6 files changed
+85
-8
No files matched your search
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, contai
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
|
||||
@@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8.
|
||||
fn decode(s: &str) -> String {
|
||||
pub(crate) fn decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
|
||||
@@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool {
|
||||
p.split(['/', '\\']).any(|name| name == "..")
|
||||
}
|
||||
|
||||
/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give
|
||||
/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…`
|
||||
/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a
|
||||
/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written
|
||||
/// misses. A `//host/share` path, and a form with a `..` name, is left out.
|
||||
pub fn uri_forms(value: &str, windows: bool) -> Vec<String> {
|
||||
if !value.starts_with('/') || value.starts_with("//") {
|
||||
return Vec::new();
|
||||
}
|
||||
let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| {
|
||||
let (first, after) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
let letter = first.as_bytes();
|
||||
(letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char))
|
||||
});
|
||||
let mut forms = Vec::new();
|
||||
for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) {
|
||||
let decoded = crate::script::files::decode(form);
|
||||
for f in [decoded.as_str(), form] {
|
||||
if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) {
|
||||
forms.push(f.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// A real path as people read it.
|
||||
fn display(path: &Path) -> Arc<str> {
|
||||
Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref())
|
||||
@@ -575,13 +601,18 @@ impl Files {
|
||||
let refused = || (FailKind::Error, format!("script file read refused: {value}"));
|
||||
// A script given as text has no folder, and so no file it may read.
|
||||
let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) };
|
||||
// Each candidate, and whether the scope's refusal passes it over.
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), false)];
|
||||
// Each candidate, and whether the scope's refusal passes it over. The path as written comes
|
||||
// first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in
|
||||
// URI notation are tried, and when none of them is read either, the error of the path as written stands.
|
||||
let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) };
|
||||
let mut literal_error = None;
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())];
|
||||
candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true)));
|
||||
if search && !path.is_absolute() {
|
||||
candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false)));
|
||||
candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true)));
|
||||
}
|
||||
for (candidate, passed_over_when_refused) in candidates {
|
||||
for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() {
|
||||
let Some(candidate) = candidate else { return Err(refused()) };
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
@@ -590,12 +621,22 @@ impl Files {
|
||||
match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
|
||||
Ok(found) => return Ok(found),
|
||||
Err(ScriptRead::Missing) => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {
|
||||
if i == 0 {
|
||||
literal_error = Some(refused());
|
||||
}
|
||||
}
|
||||
Err(ScriptRead::Refused) => return Err(refused()),
|
||||
Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))),
|
||||
Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => {
|
||||
literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}")));
|
||||
}
|
||||
Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))),
|
||||
}
|
||||
}
|
||||
if let Some(error) = literal_error {
|
||||
return Err(error);
|
||||
}
|
||||
Err((FailKind::Error, format!("include file not found: {value}")))
|
||||
}
|
||||
|
||||
|
||||
@@ -301,6 +301,40 @@ fn files_are_checked_before_they_are_read() {
|
||||
assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err());
|
||||
}
|
||||
|
||||
/// `$.evalFile` also tries a path in a `File`'s URI notation, as `File.parent` gives
|
||||
/// it: on Windows `/c/…` as the drive path `C:/…`, and on every platform with its escapes decoded,
|
||||
/// after the path as written misses. Relative, share, device and `..` forms are not tried.
|
||||
#[test]
|
||||
fn include_paths_in_uri_notation_name_a_windows_drive() {
|
||||
use crate::script::include::uri_forms;
|
||||
assert_eq!(uri_forms("/c/Users/Test/more.jsx", true), ["C:/Users/Test/more.jsx"]);
|
||||
assert_eq!(uri_forms("/d", true), ["D:/"]);
|
||||
assert_eq!(uri_forms("/c/My%20Scripts/more.jsx", true), ["C:/My Scripts/more.jsx", "C:/My%20Scripts/more.jsx"]);
|
||||
assert_eq!(uri_forms("/home/My%20Scripts/more.jsx", false), ["/home/My Scripts/more.jsx"]);
|
||||
assert!(uri_forms("/c/Users/Test/more.jsx", false).is_empty());
|
||||
for kept in
|
||||
["//host/share/more.jsx", "//?/c/more.jsx", "/c/x/../more.jsx", "/Users/more.jsx", "more.jsx", "my%20file.jsx", "C:/more.jsx", "/1/more.jsx"]
|
||||
{
|
||||
assert!(uri_forms(kept, true).is_empty(), "{kept}: {:?}", uri_forms(kept, true));
|
||||
}
|
||||
assert_eq!(uri_forms("/c/%2E%2E/more.jsx", true), ["C:/%2E%2E/more.jsx"], "an escaped `..` is not decoded into a parent name");
|
||||
// From a folder whose name has a space, `File.parent` gives `%20`, and the sibling is read.
|
||||
let dir = fresh_folder("uri forms");
|
||||
std::fs::write(dir.join("more.jsx"), "'more';").unwrap();
|
||||
let main = dir.join("main.jsx");
|
||||
std::fs::write(&main, "vc.log(File($.fileName).parent + '');\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n").unwrap();
|
||||
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert!(r["log"][0].as_str().is_some_and(|p| p.contains("uri%20forms")), "{r}");
|
||||
assert_eq!(r["log"][1], "more", "{r}");
|
||||
// A file whose name holds `%20` as written is read before the decoded name.
|
||||
std::fs::write(dir.join("part%20one.jsx"), "'literal';").unwrap();
|
||||
std::fs::write(dir.join("part one.jsx"), "'decoded';").unwrap();
|
||||
let literal = dir.join("part%20one.jsx").to_string_lossy().replace('\\', "/");
|
||||
std::fs::write(&main, format!("vc.log($.evalFile({literal:?}));\n")).unwrap();
|
||||
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["log"], json!(["literal"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2015");
|
||||
|
||||
+3
-1
@@ -3558,7 +3558,9 @@ through `$`:
|
||||
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
|
||||
- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global
|
||||
environment, so its functions and variables stay defined, and returns its last value (`undefined` for an empty
|
||||
file). Its preprocessor lines are read as the script's are. `timeout` is a number of milliseconds from 0; the file
|
||||
file). Its preprocessor lines are read as the script's are. An absolute path in a `File`'s URI notation, as
|
||||
`File.parent` gives it, is read too: when the path as written names no file it may read, `%20` and the other
|
||||
escapes are decoded, and on Windows `/c/…` names the drive `C:`. `timeout` is a number of milliseconds from 0; the file
|
||||
is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a
|
||||
missing file and a refused path throw errors the script can catch.
|
||||
- `$.fileName` is the file of the code that reads it: the script, a file it included with `#include`, or a file
|
||||
|
||||
@@ -1142,7 +1142,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`.
|
||||
- Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`.
|
||||
- Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`.
|
||||
- Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`).
|
||||
- Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` tries the path as written first; only when that file is missing, fails to read (a file over the size limit stops the lookup) or is refused does it read an absolute path in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`).
|
||||
- Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`.
|
||||
- Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`.
|
||||
- Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`.
|
||||
|
||||
Reference in new issue
Block a user