diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index e890c2b65f..10899074d9 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1468,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result { // A heavy plug-in is installed once a person agrees. if plugin.manifest().budget == Budget::Heavy && !allow_heavy { let (minutes, times) = vectorcraft_plugins::heavy_terms(); + let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME); return Err(bad( C, format!( - "“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants", - plugin.manifest().name + "“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants" ), )); } @@ -1615,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result { if !refused.is_empty() { v["refusedCommands"] = json!(refused); } + let translations = &plugin.manifest().translations; + if !translations.is_empty() { + v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null); + } v }) } @@ -2447,7 +2451,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)", always, inspect ), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 194df59e51..6ad6c51d8f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -18,7 +18,7 @@ use crate::script; pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"]; /// The extensions of the scripts `script.run` takes as a file, in any case. -pub const RUN_EXTS: &[&str] = &["js", "jsx"]; +pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"]; /// Does `path` name a file `script.run` takes? pub fn runs(path: &str) -> bool { @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | 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), 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 handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{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 handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "List Installed Scripts", [], None, - "{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", + "{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", always, list_installed ), @@ -198,6 +198,7 @@ fn prepare(s: &Session, p: &Value) -> Result { let actions = script::actions::parse(p.get("actions")).map_err(param)?; let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; + let module = switch_or(p, "module", script::include::module_script(path), "script.run")?; let mut checked_real = None; let text = match (path, source) { (Some(""), None) => return Err(param("`path` is empty")), @@ -213,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result { return Err(EngineError::Other(COMPILED.to_string())); } if !runs(path) { - return Err(param("`path` must name a .js or .jsx file")); + return Err(param("`path` must name a .js, .mjs or .jsx file")); } // One byte more than a script may have shows that the file is too large. let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?; @@ -242,6 +243,7 @@ fn prepare(s: &Session, p: &Value) -> Result { fuel, locale, answers, + module, actions, }) } @@ -444,6 +446,7 @@ impl Session { fuel, locale, answers: vec![], + module: script::include::module_script(path.to_str()), actions: vec![], }; let runs = self.script_runs; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index abff443d46..d5641d9606 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -715,6 +715,15 @@ impl ScriptScope { /// The real path of the file at `path` and its first `max` bytes, at most. pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { + match self.read_unless(path, max, |_| false)? { + (real, Some(bytes)) => Ok((real, bytes)), + (_, None) => Err(ScriptRead::Failed("the file was not read".to_string())), + } + } + + /// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened: + /// → its real path and no bytes. + pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option>), ScriptRead> { use std::io::Read; if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { return Err(ScriptRead::Refused); @@ -730,6 +739,9 @@ impl ScriptScope { if !self.allows(&real) { return Err(ScriptRead::Refused); } + if known(&real) { + return Ok((real, None)); + } let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?; if !meta.is_file() { @@ -747,7 +759,7 @@ impl ScriptScope { if std::fs::canonicalize(path).ok().as_ref() != Some(&real) { return Err(ScriptRead::Refused); } - Ok((real, bytes)) + Ok((real, Some(bytes))) } /// The first granted folder, as people read it (`None` for a script given as text). @@ -966,6 +978,21 @@ mod tests { p.to_string_lossy().into_owned() } + /// A file the caller already has is not opened: its size is not checked and no byte is read. + #[test] + fn a_known_script_file_is_not_read_again() { + let (base, _) = folders("known"); + std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap(); + let scope = ScriptScope::of_folder(&base.join("in")); + let path = base.join("in/big.js"); + assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge)); + let real = std::fs::canonicalize(&path).unwrap(); + assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None))); + assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64))); + assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused)); + let _ = std::fs::remove_dir_all(base); + } + /// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind /// only one grants is not granted. #[test] diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 791143f53b..03a7619e61 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -127,6 +127,12 @@ impl HistoryEntry { self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) } + /// A number no other step takes ([`History::step`]). Undo and Redo make the step they move + /// with a new number, and so does an edit merged into the newest step. + pub fn serial(&self) -> u64 { + self.serial + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7c50925bf0..a5bcbe015f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -44,6 +44,9 @@ //! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. //! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. //! - `app.activeDocument` with no document open throws `No active document`. +//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run +//! made; with no such step they change nothing, and with no document open they throw +//! `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. `undefined` throws. //! - `controlBounds` is the visible bounds, widened to take in the direction points of every path @@ -827,6 +830,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach +/// only the steps the run made. With no step to undo or redo they change nothing. +fn app_history(h: &Host, id: &str, redo: bool) -> Answer { + let has_step = { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() } + }; + if has_step { + command(h, id, &json!({}))?; + } + Ok(Data::Undefined) +} + +fn app_undo(h: &Host, _: &[Data]) -> Answer { + app_history(h, "edit.undo", false) +} + +fn app_redo(h: &Host, _: &[Data]) -> Answer { + app_history(h, "edit.redo", true) +} + fn app_selection(h: &Host, _: &[Data]) -> Answer { let uid = h.session.borrow().active().map(|st| st.uid); match uid { @@ -1746,6 +1771,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + // The ids listed so far; `ids` keeps them in the order they were first listed. let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); @@ -2677,6 +2703,8 @@ fn classes(link: &Link) -> Vec { ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ("redraw", method(l, app_redraw), returns("undefined", &[])), + ("undo", method(l, app_undo), returns("undefined", &[])), + ("redo", method(l, app_redo), returns("undefined", &[])), ("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])), ("toString", class_text("Application"), returns("string", &[])), ]); diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index f9e6c49be5..1b2212c44d 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -1,4 +1,4 @@ -//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a +//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a //! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]). //! //! A listing reads names and file types only, never a script's text. It follows no link: a symbolic @@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } -/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most +/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most /// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there /// and none is a link, and neither the file nor a folder below `root` is marked hidden or system? pub fn holds(root: &Path, path: &Path) -> bool { diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index ae6b41b1a1..acaee51910 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -37,11 +37,21 @@ //! //! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of //! the file it is in. +//! +//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules +//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing +//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL +//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would +//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`], +//! so a link that leads out of the script's folder is refused as well. Module files count against +//! the same limits as included files, and the paths of one file (two spellings, a link, or names +//! that differ only in letter case on Windows) give one module. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; -use vectorcraft_js::{DirectiveName, Options}; +use vectorcraft_js::{DirectiveName, LoadError, Options}; use crate::file_access::{ScriptRead, ScriptScope}; @@ -219,13 +229,65 @@ pub(crate) struct Files { frames: Vec, /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. es2015: bool, + /// The modules a module run has read, by key ([`module_key`]): the names of the folders each + /// is in, below the script's folder. + module_dirs: HashMap>, + /// The key of each module path read, below the script's folder. + module_paths: HashMap, + /// The key [`Files::module_entry`] gave the script, in a module run. + entry_key: Option, } /// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in -/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as -/// ECMAScript 5.1 with the ExtendScript extensions. +/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text +/// run as ECMAScript 5.1 with the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { - path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs")) +} + +/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case). +pub(crate) fn module_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs")) +} + +/// What names the file at the real path `real` among a run's modules: on Unix its device and file +/// number, so two paths to one file give one module; elsewhere its real path, which on Windows +/// spells each name in the letter case the folder stores it in, so two spellings of one file in a +/// folder that ignores case give one module and two files in a folder that does not stay two. +fn module_key(real: &Path) -> String { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let Ok(m) = std::fs::metadata(real) { + return format!("{}:{}", m.dev(), m.ino()); + } + } + display(real).to_string() +} + +/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is +/// not `root` or below it, or has a name that is not Unicode. +fn names_below(root: &Path, dir: &Path) -> Option> { + dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect() +} + +/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between +/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error. +fn specifier_names(specifier: &str) -> Result, LoadError> { + let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}"))); + if !(specifier.starts_with("./") || specifier.starts_with("../")) { + return wrong("must start with './' or '../'"); + } + if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) { + return wrong("must not contain \\, : or control characters"); + } + let names: Vec<&str> = specifier.split('/').collect(); + let file = names.last().copied().unwrap_or_default(); + let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default(); + if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) { + return wrong("must name a .mjs or .js file"); + } + Ok(names) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -321,9 +383,91 @@ impl Files { levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], es2015: es2015_script(path), + module_dirs: HashMap::new(), + module_paths: HashMap::new(), + entry_key: None, } } + /// Makes the run's files read ECMAScript 2015, as a module run given as text does. + pub(crate) fn read_es2015(&mut self) { + self.es2015 = true; + } + + /// The module `text`, the script's own, as a source of one file. → its key and the source. + pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> { + self.bytes = self.bytes.saturating_add(text.len()); + let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); + let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default(); + self.module_dirs.insert(key.clone(), Vec::new()); + self.entry_key = Some(key.clone()); + let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; + Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None })) + } + + /// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or + /// this function gave). → the module's key, with its text and source map the first time the + /// run reads it. + pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> { + let names = specifier_names(specifier)?; + let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?; + for name in names { + match name { + "" | "." => {} + ".." => { + if path.pop().is_none() { + return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'"))); + } + } + name => path.push(name.to_string()), + } + } + let relative = path.join("/"); + if let Some(key) = self.module_paths.get(&relative) { + return Ok((key.clone(), None)); + } + let root = + self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?; + self.probes += 1; + if self.probes > MAX_PROBES { + return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached"))); + } + let candidate = path.iter().fold(root.clone(), |p, name| p.join(name)); + // Another path to a module already read gives that module: the file is not read again, and + // its text is not counted again. + let loaded = &self.module_dirs; + let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real))); + let (real, bytes) = match read { + Ok(found) => found, + Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))), + Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))), + Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))), + Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))), + }; + let key = module_key(&real); + let Some(bytes) = bytes else { + self.module_paths.insert(relative, key.clone()); + return Ok((key, None)); + }; + if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { + return Err(LoadError::Range("script source limit reached (32 MiB)".to_string())); + } + if self.files >= MAX_FILES { + return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); + } + let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + self.bytes += bytes.len(); + self.files += 1; + self.module_paths.insert(relative, key.clone()); + // The module's relative imports start from the folder the file is in, whichever path to it + // was read first; the path as written stands in when that folder is not below the script's. + path.pop(); + let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path); + self.module_dirs.insert(key.clone(), dir); + let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; + Ok((key, Some((text, map)))) + } + /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() } @@ -362,12 +506,26 @@ impl Files { self.expand(shown, dir, text, true) } - /// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its - /// preprocessor lines read. It becomes the file being run until [`Files::end_eval`]. - pub(crate) fn eval_file(&mut self, path: &str) -> Result { + /// The folder of the module `key` ([`Files::module`] gave it), from the script's folder. + pub(crate) fn module_dir(&self, key: &str) -> Option { + let names = self.module_dirs.get(key)?; + let root = self.frames.first().and_then(|f| f.dir.clone())?; + Some(names.iter().fold(root, |p, name| p.join(name))) + } + + /// The script's folder when the run is a module run ([`Files::module_entry`] read the script), + /// or `None` for a script run. + pub(crate) fn entry_module_dir(&self) -> Option { + self.module_dir(self.entry_key.as_deref()?) + } + + /// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder + /// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It + /// becomes the file being run until [`Files::end_eval`]. + pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option) -> Result { let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 }; - let dir = self.frames.last().and_then(|f| f.dir.clone()); + let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone())); let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?; let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?; let shown = display(&real); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 5fd8e0b88b..615e9f2197 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -66,7 +66,8 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_js::{ - Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind, + Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, + Realm, RunError, RunErrorKind, }; use crate::{ @@ -207,6 +208,8 @@ pub(crate) struct Request { pub locale: String, /// The answers to the dialogs of a run with nobody to ask, in order. pub answers: Vec, + /// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]). + pub module: bool, /// The actions `app.doScript` can play. pub actions: Vec, } @@ -784,6 +787,9 @@ struct Host { script_map: RefCell, /// The same for each source `$.evalFile` gave, in order. eval_maps: RefCell>, + /// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a + /// module's, by its index there. + module_maps: RefCell>, /// The file, line and column of each error `$.evalFile` raised for a file it could not run, in /// order: the error's mark ([`HostError::Marked`]) is its index. eval_failures: RefCell, u32, u32)>>, @@ -979,6 +985,22 @@ impl Host { } } + /// The folder of the module whose source has `tag`, when it is a module of a module run: the + /// script itself or a module it imported (not a file `$.evalFile` gave, or code from another + /// run). + fn module_dir_at(&self, tag: u32) -> Option { + let script = self.script_tag.get(); + if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE { + return None; + } + let n = tag.checked_sub(script)?; + if n == 0 { + return self.files.borrow().entry_module_dir(); + } + let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?; + self.files.borrow().module_dir(&key) + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -1596,6 +1618,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc) -> std::result::Result { +/// run (for a call in a module the script imported, that module's file), with its preprocessor +/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not +/// waited on: the file is read at once. `args` starts with the call's place, as +/// [`HostItem::Evaluator`] gives it with `site`. +fn eval_file(host: &Host, mut args: Vec) -> std::result::Result { + let tag = match args.first() { + Some(Data::Number(n)) if args.len() >= 3 => *n as u32, + _ => vectorcraft_js::UNKNOWN_SOURCE, + }; + args.drain(..3.min(args.len())); + let module_dir = host.module_dir_at(tag); let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else { return Err(HostError::Type(EVAL_NO_PATH.to_string())); }; @@ -1626,7 +1657,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message }; let error = match f.kind { include::FailKind::Limit => HostError::Abort(message), @@ -1736,6 +1767,22 @@ fn explained(e: &RunError) -> String { } } +/// The module `specifier` names for the module `referrer` of the run of `host`, read through the +/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order +/// the modules are read, which is the order of their sources' tags. +fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result { + let (key, read) = host.files.borrow_mut().module(referrer, specifier)?; + let source = read.map(|(text, map)| { + let mut maps = host.eval_maps.borrow_mut(); + host.module_maps.borrow_mut().insert(maps.len(), key.clone()); + maps.push(map); + drop(maps); + host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::>()); + text + }); + Ok(LoadedModule { key, source }) +} + /// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own. fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { let (kind, message) = match f.kind { @@ -2153,7 +2200,19 @@ impl Session { self.script_stop.clear(); self.script_report = None; let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env()); - let expanded = files.expand_script(&request.source); + if request.module { + files.read_es2015(); + } + // A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines; + // `module_key` names it among the modules it imports. + let (expanded, module_key) = if request.module { + match files.module_entry(&request.source) { + Ok((key, expanded)) => (Ok(expanded), Some(key)), + Err(f) => (Err(f), None), + } + } else { + (files.expand_script(&request.source), None) + }; let name = match &expanded { Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(), _ => request.name, @@ -2184,9 +2243,8 @@ impl Session { // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read - // code the way the script does. Its realm has `Promise`: a kept realm gets it at the first - // `.js` run that names it, and keeps it as it keeps its globals. - let es2015 = include::es2015_script(request.file.as_deref()); + // code the way the script does. Its realm has `Promise`; a kept realm retains it. + let es2015 = request.module || include::es2015_script(request.file.as_deref()); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. @@ -2255,6 +2313,7 @@ impl Session { files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), + module_maps: RefCell::default(), eval_failures: RefCell::default(), script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE), report_name: Arc::from(name.as_str()), @@ -2319,7 +2378,13 @@ impl Session { .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { - let r = realm.start(&expanded.source); + let r = match &module_key { + None => realm.start(&expanded.source), + Some(key) => { + let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH }; + realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier)) + } + }; // Source that does not compile defines no code, so its map is not kept. if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) { host.script_tag.set(realm.script_tag()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd5a7634e9..5afe3d9b93 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -184,6 +184,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_modules; mod script_run; mod script_scriptui; mod script_styles; @@ -5171,6 +5172,36 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() { assert!(!s.doc().unwrap().selection.contains(b)); } +/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With +/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that +/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked +/// adds its corner. A Ctrl/Cmd-click (the Selection tool, lent) leaves the picks as they are. +#[test] +fn corner_widgets_pick_corners_across_paths_through_the_session() { + let mut s = session(); + let v = ViewInfo::default(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + let all = json!([[0, 0], [0, 1], [0, 2], [0, 3]]); + let start = json!({"items": [{"id": a.0, "anchors": [[0, 0]]}, {"id": b.0, "anchors": all}]}); + s.select_tool("directSelection", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64, mods: vectorcraft_tools::Mods| { + s.execute("select.anchorsMany", &start).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, x, y).with_mods(mods), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(mods), v).unwrap(); + let sel = &s.doc().unwrap().selection; + assert!(sel.contains(a) && sel.contains(b), "both stay selected"); + (sel.partial(a).cloned(), sel.partial(b).cloned()) + }; + let shift = vectorcraft_tools::Mods { shift: true, ..Default::default() }; + // The top-right widget of b. + assert_eq!(click(&mut s, 390.0, 110.0, shift), (Some([(0, 0)].into()), Some([(0, 0), (0, 2), (0, 3)].into()))); + // The top-right widget of a, not picked. + assert_eq!(click(&mut s, 190.0, 110.0, shift), (Some([(0, 0), (0, 1)].into()), None)); + let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() }; + assert_eq!(click(&mut s, 190.0, 110.0, cmd), (Some([(0, 0)].into()), None), "a Ctrl/Cmd-click leaves the picks"); +} + #[test] fn path_commands_reject_bad_anchors_before_modifying_geometry() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index cc04612a89..6cd51a5a1d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3195,6 +3195,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() { assert!(install(&mut s, DESATURATE).get("budget").is_none()); } +/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its +/// name is escaped, so it can't reorder the message around it. +#[test] +fn a_heavy_filter_refusal_escapes_its_name() { + let mut s = session(); + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#); + let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string(); + assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}"); +} + /// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed /// without any of its code running: its start function traps and its `vc_manifest` export loops. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 94886530c1..e87e5b5c51 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -356,6 +356,37 @@ fn page_item_properties_join_one_undo_step() { } } +/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one +/// undo step. They change nothing past the run's first edit or its last undone one. +#[test] +fn app_undo_and_redo_step_through_the_runs_edits() { + let (mut s, a, b) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\ + app.undo(); app.redo();\ + i.name = 'first'; i.opacity = 40;\ + app.undo(); vc.log([i.name, i.opacity]);\ + app.redo(); vc.log(i.opacity);\ + app.redo(); vc.log(i.opacity);\ + app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\ + vc.log(typeof app.undo());\ + d.pageItems[1].name = 'kept';", + ); + assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let st = s.active().unwrap(); + let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect(); + assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run"); + let mut s = Session::new(); + assert!(failure(&mut s, "app.undo();").contains("No active document")); + assert!(failure(&mut s, "app.redo();").contains("No active document")); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index dc9749fb6c..47eaf52e41 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() { fuel: script::DEFAULT_FUEL, locale: "en_US".into(), answers: Vec::new(), + module: false, actions: Vec::new(), }; s.script_start(request).unwrap(); diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs new file mode 100644 index 0000000000..45d5a22417 --- /dev/null +++ b/crates/engine/src/tests/script_modules.rs @@ -0,0 +1,315 @@ +//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of +//! specifiers and paths, the run's limits, and errors at the file they are in. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + base +} + +fn write(path: &Path, text: &str) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, text).unwrap(); +} + +/// Runs `main/` in `base`, with the text `text`. +fn run_file(base: &Path, file: &str, text: &str) -> (Result, Session) { + let main = base.join("main").join(file); + write(&main, text); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})); + (r, s) +} + +fn run(base: &Path, text: &str) -> Result { + run_file(base, "main.mjs", text).0 +} + +/// The report of the run of `main/main.mjs` that failed. +fn failed(base: &Path, text: &str) -> Value { + let (r, s) = run_file(base, "main.mjs", text); + assert!(r.is_err(), "the run failed: {r:?}"); + s.script_report().unwrap().clone() +} + +fn message(report: &Value) -> &str { + report["message"].as_str().unwrap_or_default() +} + +#[test] +fn script_module_imports_from_its_folder_and_below() { + let base = folder("imports"); + write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';"); + write( + &base.join("main/lib/use.mjs"), + "import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();", + ); + let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);"; + let r = run(&base, text).unwrap(); + // count.mjs ran once: use.mjs and the script share its binding. + assert_eq!(r["log"], json!([[2, "lib", true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_two_modules_import_each_other() { + let base = folder("cycle"); + write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }"); + write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();"); + let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap(); + assert_eq!(r["log"], json!([["ab", "ab"]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_path_above_the_script_folder_is_refused() { + let base = folder("above"); + write(&base.join("outside.mjs"), "export var leaked = 1;"); + let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';"); + assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}"); + assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}"); + // `..` names that stay inside are read by name. + write(&base.join("main/sub/x.mjs"), "export var x = 'x';"); + let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap(); + assert_eq!(r["log"], json!(["x"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_missing_file_is_named() { + let base = folder("missing"); + write(&base.join("main/a.mjs"), "import './nope.mjs';"); + let report = failed(&base, "import './a.mjs';"); + assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}"); + assert_eq!(report["line"], 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() { + let base = folder("specifiers"); + // The specifier as the script writes it, as the error names it, and why it is refused. + for (written, shown, why) in [ + ("lib", "lib", "must start with './' or '../'"), + ("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"), + ("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"), + ("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"), + ("./C:x.mjs", "./C:x.mjs", "must not contain"), + ("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"), + ("./x.txt", "./x.txt", "must name a .mjs or .js file"), + ("./x", "./x", "must name a .mjs or .js file"), + ] { + let report = failed(&base, &format!("import '{written}';")); + let expected = format!("SyntaxError: module specifier '{shown}' {why}"); + assert!(message(&report).starts_with(&expected), "{written}: {report}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_errors_are_at_the_file_they_are_in() { + let base = folder("errors"); + write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;"); + let report = failed(&base, "import { a } from './bad.mjs';"); + assert_eq!(report["kind"], "syntax", "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}"); + assert_eq!(report["line"], 2); + write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');"); + let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);"); + assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}"); + assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}"); + let report = failed(&base, "import { b } from './thrower.mjs';"); + assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_preprocessor_lines_and_scripts_differ_by_extension() { + let base = folder("kinds"); + write(&base.join("main/lib.jsxinc"), "var included = 1;"); + // A module has no preprocessor lines. + let report = failed(&base, "#include \"lib.jsxinc\"\n"); + assert_eq!(report["kind"], "syntax", "{report}"); + // A .js or .jsx script does not read import or export. + for file in ["main.js", "main.jsx"] { + let (r, s) = run_file(&base, file, "import { a } from './a.mjs';"); + assert!(r.is_err(), "{file}"); + assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_files_count_against_the_include_limits() { + let base = folder("limits"); + for i in 0..70 { + write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1)); + } + let report = failed(&base, "import './m0.mjs';"); + assert!(message(&report).contains("limit"), "{report}"); + assert_eq!(report["log"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_paths_of_one_file_give_one_module() { + let base = folder("same"); + write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;"); + let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string(); + // Windows file names ignore letter case. + if cfg!(windows) { + text.push_str("import { v as u } from './ONCE.mjs';\n"); + } + let r = run(&base, &text).unwrap(); + assert_eq!(r["log"], json!(["ran"])); + let _ = std::fs::remove_dir_all(base); +} + +/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere. +/// `false` when the system does not allow it here. +fn link_folder(target: &Path, link: &Path) -> bool { + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok() + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + +#[test] +fn script_module_link_out_of_the_folder_is_refused() { + let base = folder("link"); + write(&base.join("outside/x.mjs"), "export var leaked = 1;"); + if !link_folder(&base.join("outside"), &base.join("main").join("away")) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);"); + assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_is_listed_and_taken_by_path() { + assert!(cmd::scripts::runs("tool.MJS")); + let base = folder("text"); + let root = base.join("Scripts"); + write(&root.join("tool.mjs"), "export var a = 1;"); + let mut s = Session::new(); + s.attach_scripts_dir(root.clone()); + let listed = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}])); + // A script given as text is not a module, whatever its name. + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"})); + assert!(r.is_err()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_is_chosen_by_the_module_param() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap(); + assert_eq!(r["log"], json!([[1, true]])); + // A source run as a module imports no files. + let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true})); + assert!(r.is_err()); + assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report()); + let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); + // `module: false` runs a .mjs file as a script, where `export` is a syntax error. + let base = folder("param"); + let main = base.join("main").join("main.mjs"); + write(&main, "export var a = 1;"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false})); + assert!(r.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "syntax"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_read_again_through_another_path_is_not_counted_again() { + let base = folder("budget"); + // 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run. + let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024)); + write(&base.join("main/lib/big.mjs"), &big); + let mut text = String::new(); + for i in 0..5 { + if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n")); + } + text.push_str("vc.log(v0 + v4);"); + let r = run(&base, &text); + assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2]))); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_imports_are_read_from_the_folder_the_file_is_in() { + let base = folder("realdir"); + write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;"); + write(&base.join("main/real/dep.mjs"), "export const d = 'real';"); + write(&base.join("main/other/dep.mjs"), "export const d = 'other';"); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok(); + #[cfg(windows)] + let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok(); + #[cfg(not(any(unix, windows)))] + let linked = false; + if !linked { + eprintln!("skipped: a file link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap(); + assert_eq!(r["log"], json!(["real"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_eval_file_reads_beside_the_module_that_calls_it() { + let base = folder("evalfile"); + write(&base.join("main/helper.jsx"), "'top'"); + write(&base.join("main/sub/helper.jsx"), "'sub'"); + write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');"); + let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap(); + assert_eq!(r["log"], json!([["sub", "top"]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() { + let base = folder("evalfile-entry"); + write(&base.join("main/helper.jsx"), "'top'"); + write(&base.join("main/sub/helper.jsx"), "'sub'"); + // The file in `sub` calls the script's function while it is the file being run. + write(&base.join("main/sub/caller.jsx"), "$.global.load()"); + let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));"; + let r = run(&base, text).unwrap(); + assert_eq!(r["log"], json!(["top"])); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d7f60e5b2c..1a842e6a86 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -90,8 +90,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ - executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \ - unloadAction unloadAction=", + executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \ + undo unloadAction unloadAction=", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index c2ca9a38f6..9699944e35 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() { let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []})); assert_eq!(r["started"], false); assert_eq!(r["ok"], false); - assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}"); + assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}"); } #[test] diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c23f8c6767..a587c74fbb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -619,6 +619,62 @@ pub struct Program { pub(crate) supers: crate::parser::SuperRules, } +/// The name an import takes from the module it names, or an export from a module it re-exports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ImportName { + /// The export of this name (`default` for a default import). + Name(String), + /// The module's namespace object (`* as ns`). + Namespace, +} + +/// A module a module imports or re-exports from: the specifier as written and where it stands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModuleRequest { + /// The specifier as text, with each unpaired surrogate written as U+FFFD. + pub specifier: String, + /// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16, + /// ModuleRequests). It may hold an unpaired surrogate, which no host path can name. + pub units: Vec, + pub span: Span, +} + +/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImportEntry { + /// The index of the module in [`ModuleInfo::requests`]. + pub request: usize, + pub import: ImportName, + /// The name bound in the importing module. + pub local: Name, +} + +/// One name a module exports (ExportEntry). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExportEntry { + /// `export_name` is the module's own binding `local` (`*default*` for a default export of an + /// expression or an anonymous function). + Local { export_name: String, local: String, span: Span }, + /// `export_name` is the export `import` of the module `request` (`export { a as b } from`, + /// `export * as ns from`, or an exported import). + Indirect { export_name: String, request: usize, import: ImportName, span: Span }, + /// Every export of the module `request` but `default` (`export * from`). + Star { request: usize, span: Span }, +} + +/// What a module imports and exports, read by [`crate::parse_module`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ModuleInfo { + /// The modules it names, each specifier once, in the order they first appear. + pub requests: Vec, + pub imports: Vec, + pub exports: Vec, +} + +/// The binding name of a default export that has no name of its own (ECMA-262 2015 section +/// 15.2.3.5); no identifier can name it. +pub const DEFAULT_BINDING: &str = "*default*"; + impl Program { /// The line and column (both from 1, the column in UTF-16 code units) of a source offset. pub fn line_column(&self, offset: u32) -> (u32, u32) { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 8bf8783adf..5fb963b34d 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -591,7 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) + Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -610,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) + Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 42947c7d7a..af377a213f 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { let k = interp.to_prop_key(&arg(args, 1))?; - match interp.get_own_pk(o, &k)? { + match interp.own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let o = *o; for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; + let Some(prop) = interp.own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } @@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { recursion: u32, /// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own. es2015: bool, + /// The code is a module's ([`compile_module`]), which has no completion value. + module: bool, scopes: Vec, templates: Vec