From 3237057ec8e6072df37847d74391345c6bd207e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:04:29 -0800 Subject: [PATCH 01/17] Plug-ins: names and labels show in the UI language from the manifest's translations A plug-in manifest may give `translations`, keyed by language code, with the plug-in's name, its commands' labels, its parameters' labels, help and choice labels, and its group headings. Menus, plug-in dialogs, the Appearance panel, Keyboard Shortcuts, the command palette and Last Effect show the text for the UI language, then for the language without its region (pt-br, then pt), then the manifest's own text. Command ids, parameter names, choice values, plugin.list and errors keep the manifest's own text. The install approval asks with the name in the UI language and shows the manifest's own name under the ID when they differ. Installing refuses malformed or repeated language codes, more than 16 languages, empty or over-long text, control, direction and line-separator characters, keys the manifest does not declare, and two choices with the same label after fallback, with an error that names the key. The 64 KiB manifest limit covers the translations. Filter and importer menu items, plug-in dialog text and the heavy-filter refusal now escape bidirectional characters, and Keyboard Shortcuts and the palette no longer put a plug-in's own name or command label through the app's catalogs. --- crates/engine/src/cmd/plugin.rs | 10 +- crates/engine/src/tests/plugins.rs | 13 + crates/plugins/src/lib.rs | 4 +- crates/plugins/src/manifest.rs | 14 +- crates/plugins/src/permissions.rs | 2 +- crates/plugins/src/translations.rs | 539 ++++++++++++++++++++++++ crates/ui-egui/src/dialogs/effect.rs | 12 +- crates/ui-egui/src/dialogs/form.rs | 78 +++- crates/ui-egui/src/dialogs/plugin.rs | 106 +++-- crates/ui-egui/src/dialogs/tests.rs | 70 +++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/io/open.rs | 27 +- crates/ui-egui/src/menus/labels.rs | 13 +- crates/ui-egui/src/palette.rs | 69 ++- crates/ui-egui/src/panels/appearance.rs | 20 +- crates/ui-egui/src/shortcut_editor.rs | 49 ++- crates/ui-egui/src/tests/plugins.rs | 167 ++++++++ docs/mcp.md | 3 + docs/plugins.md | 48 +++ docs/target-app-parity.md | 1 + 47 files changed, 1301 insertions(+), 97 deletions(-) create mode 100644 crates/plugins/src/translations.rs diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..6ff023d4de 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -808,11 +808,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" ), )); } @@ -955,6 +955,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 }) } @@ -1306,7 +1310,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → 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 (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → 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/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..32d96f5df9 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2017,6 +2017,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}"); +} + #[test] fn invalid_install_flags_are_refused() { let mut s = session(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..1e053354c6 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -31,7 +31,8 @@ //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host -//! runs through `vc_run` with the command's id in `_context`. +//! runs through `vc_run` with the command's id in `_context`. Its name, command labels and +//! parameter text may come in other languages too ([`translations`]). #![forbid(unsafe_code)] pub mod deferred; @@ -48,6 +49,7 @@ pub mod registry; mod runtime; pub mod safe_mode; pub mod storage; +pub mod translations; pub mod wat; pub use dialog::ParamUi; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..4efef7cd9e 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -6,6 +6,7 @@ use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; +use crate::translations::Translations; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -348,6 +349,10 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// Its name, command labels and parameter text in other languages, shown in place of the + /// manifest's own when the UI is in one of them ([`crate::translations`]). + #[serde(default, skip_serializing_if = "Translations::is_empty")] + pub translations: Translations, } impl Manifest { @@ -383,13 +388,15 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + translations: Translations::default(), } } /// The manifest command `c` runs with: this one with `c`'s label as its name and `c`'s - /// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them. + /// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them, + /// and with `c`'s text in each language as its translations. pub fn for_command(&self, c: &Command) -> Manifest { - Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), ..self.clone() } + Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), translations: self.command_translations(c), ..self.clone() } } /// The command with id `id`. @@ -440,7 +447,8 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_translations() } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..88641f03bf 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -211,7 +211,7 @@ pub fn names(permissions: &[Permission]) -> Vec<&'static str> { /// Is `c` a character that changes the direction text is laid out in, or a line or paragraph /// separator, which a prompt must not let a manifest string use to disguise itself? -fn is_bidi_or_separator(c: char) -> bool { +pub(crate) fn is_bidi_or_separator(c: char) -> bool { matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{2028}' | '\u{2029}') } diff --git a/crates/plugins/src/translations.rs b/crates/plugins/src/translations.rs new file mode 100644 index 0000000000..f940a635cd --- /dev/null +++ b/crates/plugins/src/translations.rs @@ -0,0 +1,539 @@ +//! Text a plug-in gives in other languages: its manifest's `translations` (docs/plugins.md › +//! Translations). +//! +//! `translations` maps language codes (`de`, `pt-br`, `zh-hant`, compared without regard to case) +//! to the text shown in that language: the plug-in's `name`, its commands' labels, its parameters' +//! labels, help and choice labels, and its group headings. Every entry is optional; text a language +//! leaves out comes from the language without its last part (`pt-br`, then `pt`) and then from the +//! manifest's own text. The text is shown only: command ids, parameter names, the values a choice +//! passes, `plugin.list` and the install approval keep the manifest's own text. + +use std::collections::HashSet; + +use serde::{Deserialize, Serialize}; + +use crate::dialog::{MAX_HELP, MAX_LABEL}; +use crate::manifest::{Command, Manifest, ParamSpec}; +use crate::permissions::{self, MAX_SHOWN_FIELD, MAX_SHOWN_NAME}; +use crate::{Error, Result}; + +/// Most languages a manifest's `translations` gives text in. +pub const MAX_LANGUAGES: usize = 16; +/// Longest language code, in bytes. +pub const MAX_LANGUAGE_CODE: usize = 35; +/// Longest translated plug-in name, command label or choice label, in characters. +pub const MAX_NAME: usize = 64; + +/// Named entries in the order the manifest gives them; each name at most once. +#[derive(Clone, Debug, PartialEq)] +pub struct Entries(pub Vec<(String, T)>); + +impl Default for Entries { + fn default() -> Self { + Entries(Vec::new()) + } +} + +impl Entries { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The entry named `name`. + pub fn get(&self, name: &str) -> Option<&T> { + self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v) + } +} + +impl Serialize for Entries { + fn serialize(&self, s: S) -> std::result::Result { + use serde::ser::SerializeMap; + let mut m = s.serialize_map(Some(self.0.len()))?; + for (k, v) in &self.0 { + m.serialize_entry(k, v)?; + } + m.end() + } +} + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries { + fn deserialize>(d: D) -> std::result::Result { + struct V(std::marker::PhantomData); + impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for V { + type Value = Entries; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("an object") + } + fn visit_unit(self) -> std::result::Result { + Ok(Entries::default()) + } + fn visit_map>(self, mut map: A) -> std::result::Result { + let mut seen = HashSet::new(); + let mut out = Vec::new(); + while let Some(k) = map.next_key::()? { + if !seen.insert(k.clone()) { + let shown = permissions::display_text(&k, MAX_SHOWN_FIELD); + return Err(serde::de::Error::custom(format!("`{shown}` is given twice"))); + } + out.push((k, map.next_value()?)); + } + Ok(Entries(out)) + } + } + d.deserialize_any(V(std::marker::PhantomData)) + } +} + +/// A parameter's text in one language. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ParamText { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub help: Option, + /// A choice's labels, by the value each option passes. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub options: Entries, +} + +/// A command's text in one language. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CommandText { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub params: Entries, +} + +/// A plug-in's text in one language. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Catalog { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// By parameter name. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub params: Entries, + /// Group headings, by the `group` the parameters give. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub groups: Entries, + /// By command id. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub commands: Entries, +} + +/// A manifest's `translations`, by language code. +pub type Translations = Entries; + +/// Is `tag` a language code: a language of 2 or 3 letters, then parts of 2 to 8 letters and +/// digits, each after a `-`, at most [`MAX_LANGUAGE_CODE`] bytes in all (`de`, `pt-BR`, +/// `zh-Hant-TW`)? +pub fn valid_language_code(tag: &str) -> bool { + let mut parts = tag.split('-'); + tag.len() <= MAX_LANGUAGE_CODE + && parts.next().is_some_and(|l| (2..=3).contains(&l.len()) && l.bytes().all(|b| b.is_ascii_alphabetic())) + && parts.all(|p| (2..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric())) +} + +/// The codes text for language `lang` is looked up under, most specific first: `lang`, then +/// `lang` without its last part, down to the language alone (`zh-hant-tw`, `zh-hant`, `zh`). +fn lookup_codes(lang: &str) -> impl Iterator { + std::iter::successors(Some(lang), |l| l.rfind('-').map(|i| &l[..i])) +} + +impl Translations { + /// The first text `f` finds for language `lang` ([`lookup_codes`]). + fn find<'a, T>(&'a self, lang: &str, f: impl Fn(&'a Catalog) -> Option) -> Option { + lookup_codes(lang).find_map(|code| self.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case(code)).find_map(|(_, c)| f(c))) + } + + /// The plug-in's name these translations give for language `lang` (`None`: they give none). + pub fn name_in(&self, lang: &str) -> Option<&str> { + self.find(lang, |c| c.name.as_deref()) + } +} + +/// Is `s` text a translation may give: 1 to `max` characters, not all spaces, without control +/// characters (`\n` too, unless `lines`) or characters that change the direction text is laid out +/// in or separate lines? +fn fits(s: &str, max: usize, lines: bool) -> bool { + !s.trim().is_empty() + && s.chars().count() <= max + && s.chars().all(|c| (!c.is_control() || (lines && c == '\n')) && !permissions::is_bidi_or_separator(c)) +} + +/// `translations.` as an error names it, each part escaped as prompts show text. +fn key(path: &[&str]) -> String { + let parts: Vec = path.iter().map(|p| permissions::display_text(p, MAX_SHOWN_FIELD)).collect(); + format!("`translations.{}`", parts.join(".")) +} + +/// Checks text `s` at `path` against `max` characters (`lines`: `\n` allowed). +fn check_text(s: &str, max: usize, lines: bool, path: &[&str]) -> Result<()> { + if fits(s, max, lines) { + return Ok(()); + } + let at = key(path); + Err(Error::Manifest(format!("{at} must be 1-{max} printable characters, without direction or line-separator characters"))) +} + +/// The error for the key at `path`, which names a parameter, choice value, group or command the +/// manifest doesn't declare, or translates a field the manifest doesn't give (`options` of a +/// parameter that isn't a choice, `help` of a parameter without one). +fn undeclared(path: &[&str]) -> Error { + let at = key(path); + Error::Manifest(format!("{at} names or translates something the manifest doesn't declare")) +} + +/// Checks the text of parameters `texts` against the parameters `params` they name, at `path`. +fn check_params(texts: &Entries, params: &[(String, crate::Param)], path: &[&str]) -> Result<()> { + for (k, t) in &texts.0 { + let here = [path, &[k.as_str()]].concat(); + let Some((_, p)) = params.iter().find(|(name, _)| name == k) else { + return Err(undeclared(&here)); + }; + if let Some(label) = &t.label { + check_text(label, MAX_LABEL, false, &[here.as_slice(), &["label"]].concat())?; + } + if let Some(help) = &t.help { + let at = [here.as_slice(), &["help"]].concat(); + if p.ui.help.is_none() { + return Err(undeclared(&at)); + } + check_text(help, MAX_HELP, true, &at)?; + } + if t.options.is_empty() { + continue; + } + let ParamSpec::Choice { options, .. } = &p.spec else { + return Err(undeclared(&[here.as_slice(), &["options"]].concat())); + }; + for (value, label) in &t.options.0 { + let at = [here.as_slice(), &["options", value.as_str()]].concat(); + if !options.contains(value) { + return Err(undeclared(&at)); + } + check_text(label, MAX_NAME, false, &at)?; + } + } + Ok(()) +} + +impl Manifest { + /// `translations` gives at most [`MAX_LANGUAGES`] languages, each by a distinct language code + /// ([`valid_language_code`]; case doesn't tell codes apart), and names only what the manifest + /// declares: its parameters, their choices' values, its groups and its commands. Each text + /// follows the rules of the text it translates, without direction or line-separator + /// characters, and `help` translates a `help` the parameter gives. The error names the key. + pub(crate) fn validate_translations(&self) -> Result<()> { + let langs = &self.translations.0; + if langs.len() > MAX_LANGUAGES { + return Err(Error::Manifest(format!("`translations` gives at most {MAX_LANGUAGES} languages"))); + } + let groups: HashSet<&str> = + self.params.iter().chain(self.commands.iter().flat_map(|c| c.params.iter())).filter_map(|(_, p)| p.ui.group.as_deref()).collect(); + for (i, (lang, c)) in langs.iter().enumerate() { + let lang = lang.as_str(); + if !valid_language_code(lang) || langs.get(..i).is_some_and(|before| before.iter().any(|(b, _)| b.eq_ignore_ascii_case(lang))) { + let at = key(&[lang]); + return Err(Error::Manifest(format!("{at} is not a language code such as `de` or `pt-BR`, or repeats one given before it"))); + } + if let Some(name) = &c.name { + check_text(name, MAX_NAME, false, &[lang, "name"])?; + } + check_params(&c.params, &self.params, &[lang, "params"])?; + for (g, heading) in &c.groups.0 { + let g = g.as_str(); + if !groups.contains(g) { + return Err(undeclared(&[lang, "groups", g])); + } + check_text(heading, MAX_LABEL, false, &[lang, "groups", g])?; + } + for (id, t) in &c.commands.0 { + let id = id.as_str(); + let Some(command) = self.command(id) else { + return Err(undeclared(&[lang, "commands", id])); + }; + if let Some(label) = &t.label { + check_text(label, MAX_NAME, false, &[lang, "commands", id, "label"])?; + } + check_params(&t.params, &command.params, &[lang, "commands", id, "params"])?; + } + } + // A dropdown tells its options apart by their labels: in each language, with the labels a + // language leaves out taken from the language without its region, no two may be the same. + for (lang, _) in langs { + self.check_option_labels(lang, &[lang, "params"])?; + } + for c in self.commands.iter().filter(|c| c.params.iter().any(|(_, p)| matches!(p.spec, ParamSpec::Choice { .. }))) { + let own = self.for_command(c); + for (lang, _) in langs { + own.check_option_labels(lang, &[lang, "commands", c.id.as_str(), "params"])?; + } + } + Ok(()) + } + + /// Checks that no two options of a choice show the same label in language `lang`, naming the + /// choice's `options` under `path`. + fn check_option_labels(&self, lang: &str, path: &[&str]) -> Result<()> { + for (k, p) in &self.params { + let ParamSpec::Choice { options, .. } = &p.spec else { continue }; + let shown: Vec<&str> = options.iter().map(|o| self.option_label_in(k, o, lang)).collect(); + if shown.iter().enumerate().any(|(i, s)| shown.get(..i).is_some_and(|before| before.contains(s))) { + let at = key(&[path, &[k.as_str(), "options"]].concat()); + return Err(Error::Manifest(format!("{at} gives two options the same label"))); + } + } + Ok(()) + } + + /// The translations command `c`'s manifest ([`Manifest::for_command`]) shows: in each language, + /// `c`'s label as its name, `c`'s parameters' text and the group headings. + pub(crate) fn command_translations(&self, c: &Command) -> Translations { + let langs = self.translations.0.iter().map(|(lang, cat)| { + let own = cat.commands.get(&c.id); + let catalog = Catalog { + name: own.and_then(|t| t.label.clone()), + params: own.map(|t| t.params.clone()).unwrap_or_default(), + groups: cat.groups.clone(), + commands: Entries::default(), + }; + (lang.clone(), catalog) + }); + Entries(langs.collect()) + } + + /// The plug-in's name in language `lang` (an app language code such as `de` or `pt-br`): its + /// translation, else the manifest's `name`. + pub fn name_in(&self, lang: &str) -> &str { + self.translations.name_in(lang).unwrap_or(&self.name) + } + + /// [`Manifest::name_in`] as menus show it: trimmed, control and bidirectional characters + /// escaped, at most [`MAX_SHOWN_NAME`] characters. + pub fn shown_name(&self, lang: &str) -> String { + permissions::display_text(self.name_in(lang).trim(), MAX_SHOWN_NAME) + } + + /// Command `c`'s label in language `lang`, as menus show it ([`Command::shown_label`]). + pub fn shown_command_label(&self, c: &Command, lang: &str) -> String { + let label = self.translations.find(lang, |t| t.commands.get(&c.id).and_then(|t| t.label.as_deref())).unwrap_or(&c.label); + permissions::display_text(label.trim(), MAX_SHOWN_NAME) + } + + /// Parameter `k`'s label in language `lang`: its translation, else its `label` (`None`: it + /// has neither). + pub fn param_label_in(&self, k: &str, lang: &str) -> Option<&str> { + let own = self.param(k).and_then(|p| p.ui.label.as_deref()); + self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.label.as_deref())).or(own) + } + + /// Parameter `k`'s help in language `lang`: its translation, else its `help`. + pub fn param_help_in(&self, k: &str, lang: &str) -> Option<&str> { + let own = self.param(k).and_then(|p| p.ui.help.as_deref()); + self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.help.as_deref())).or(own) + } + + /// The label of value `option` of choice `k` in language `lang`: its translation, else the + /// value itself. + pub fn option_label_in<'a>(&'a self, k: &str, option: &'a str, lang: &str) -> &'a str { + self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.options.get(option)).map(String::as_str)).unwrap_or(option) + } + + /// The heading of group `group` in language `lang`: its translation, else `group`. + pub fn group_in<'a>(&'a self, group: &'a str, lang: &str) -> &'a str { + self.translations.find(lang, |c| c.groups.get(group).map(String::as_str)).unwrap_or(group) + } +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use super::*; + + const TRANSLATED: &str = r#"{"id":"org.example.tidy","name":"Tidy","kind":"filter", + "params":{"mode":{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."}, + "steps":{"type":"int","min":1,"max":9,"group":"Shape"}}, + "commands":[{"id":"grow","label":"Grow","params":{"by":{"type":"number","min":0,"max":10,"default":2,"label":"By","group":"Shape"}}}, + {"id":"shrink","label":"Shrink"}], + "translations":{ + "de":{"name":"Aufräumen","params":{"mode":{"label":"Modus","help":"Wie stark.","options":{"soft":"Weich"}},"steps":{"label":"Schritte"}}, + "groups":{"Shape":"Form"}, + "commands":{"grow":{"label":"Wachsen","params":{"by":{"label":"Um"}}}}}, + "pt":{"name":"Arrumar","commands":{"shrink":{"label":"Encolher"}}}, + "pt-BR":{"name":"Organizar"}}}"#; + + fn translated() -> Manifest { + Manifest::parse(TRANSLATED.as_bytes()).unwrap() + } + + /// A German UI shows the German text; any language without a catalog shows the manifest's own. + #[test] + fn a_language_shows_its_text_and_others_the_manifests_own() { + let m = translated(); + assert_eq!(m.name_in("de"), "Aufräumen"); + assert_eq!(m.shown_name("de"), "Aufräumen"); + assert_eq!(m.name_in("de-at"), "Aufräumen", "a region falls back to its language"); + for other in ["en", "fr", "ja", "zh-hant"] { + assert_eq!(m.name_in(other), "Tidy", "{other}"); + assert_eq!(m.param_label_in("mode", other), Some("Mode"), "{other}"); + assert_eq!(m.param_label_in("steps", other), None, "{other}"); + assert_eq!(m.option_label_in("mode", "soft", other), "soft", "{other}"); + assert_eq!(m.group_in("Shape", other), "Shape", "{other}"); + } + assert_eq!(m.param_label_in("mode", "de"), Some("Modus")); + assert_eq!(m.param_label_in("steps", "de"), Some("Schritte"), "a label for a parameter that gives none"); + assert_eq!(m.param_help_in("mode", "de"), Some("Wie stark.")); + assert_eq!((m.option_label_in("mode", "soft", "de"), m.option_label_in("mode", "hard", "de")), ("Weich", "hard")); + assert_eq!(m.group_in("Shape", "de"), "Form"); + let grow = m.command("grow").unwrap(); + assert_eq!((m.shown_command_label(grow, "de"), m.shown_command_label(grow, "en")), ("Wachsen".into(), "Grow".into())); + // A command's dialog shows its own text in that language. + let run = m.for_command(grow); + assert_eq!((run.name_in("de"), run.param_label_in("by", "de"), run.group_in("Shape", "de")), ("Wachsen", Some("Um"), "Form")); + assert_eq!((run.name_in("en"), run.param_label_in("by", "en")), ("Grow", Some("By"))); + // The text is shown only: what runs and what plugin.list reads keep the manifest's own. + assert_eq!((m.name.as_str(), grow.label.as_str(), grow.id.as_str()), ("Tidy", "Grow", "grow")); + assert_eq!(Value::Object(m.resolve_params(&json!({"mode": "soft"})).unwrap())["mode"], json!("soft")); + } + + /// `pt-br` text comes from `pt-br`, then `pt`, then the manifest, each piece on its own. + #[test] + fn a_region_falls_back_to_its_language_and_then_the_manifest() { + let m = translated(); + assert_eq!(m.name_in("pt-br"), "Organizar", "codes match without regard to case"); + assert_eq!(m.name_in("pt"), "Arrumar"); + assert_eq!(m.name_in("pt-pt"), "Arrumar"); + let shrink = m.command("shrink").unwrap(); + assert_eq!(m.shown_command_label(shrink, "pt-br"), "Encolher", "from pt"); + let grow = m.command("grow").unwrap(); + assert_eq!(m.shown_command_label(grow, "pt-br"), "Grow", "from the manifest"); + } + + #[test] + fn translations_round_trip_and_are_left_out_when_absent() { + let m = translated(); + let written = serde_json::to_value(&m).unwrap(); + assert_eq!(written["translations"]["pt-BR"], json!({"name": "Organizar"})); + assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap(); + assert!(serde_json::to_value(&plain).unwrap().get("translations").is_none()); + assert_eq!(plain.name_in("de"), "x"); + } + + /// A bad code, text a source field couldn't hold, text that changes direction, and a key the + /// manifest doesn't declare are refused with an error naming the key. + #[test] + fn bad_translations_are_refused_naming_the_key() { + let with = |translations: &str| { + format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["a","b"],"group":"G"}}, + "n":{{"type":"number","min":0,"max":1,"default":0}}}},"commands":[{{"id":"c","label":"C"}}],"translations":{translations}}}"# + ) + }; + let long = "x".repeat(MAX_NAME + 1); + let long_label = format!(r#"{{"de":{{"params":{{"n":{{"label":"{}"}}}}}}}}"#, "x".repeat(MAX_LABEL + 1)); + let long_name = format!(r#"{{"de":{{"name":"{long}"}}}}"#); + for (translations, says) in [ + (r#"{"german":{"name":"X"}}"#, "`translations.german` is not a language code"), + (r#"{"d":{"name":"X"}}"#, "`translations.d` is not a language code"), + (r#"{"de-":{"name":"X"}}"#, "`translations.de-` is not a language code"), + (r#"{"de_DE":{"name":"X"}}"#, "`translations.de_DE` is not a language code"), + (r#"{"x-klingon":{"name":"X"}}"#, "`translations.x-klingon` is not a language code"), + (r#"{"":{"name":"X"}}"#, "`translations.` is not a language code"), + (r#"{"de":{"name":"X"},"DE":{"name":"Y"}}"#, "`translations.DE` is not a language code such as `de` or `pt-BR`, or repeats one"), + (r#"{"de":{"name":""}}"#, "`translations.de.name` must be 1-64"), + (r#"{"de":{"name":" "}}"#, "`translations.de.name` must be 1-64"), + (long_name.as_str(), "`translations.de.name` must be 1-64"), + (r#"{"de":{"name":"a\u0007b"}}"#, "`translations.de.name`"), + (r#"{"de":{"commands":{"c":{"label":"a\nb"}}}}"#, "`translations.de.commands.c.label` must be"), + ( + r#"{"de":{"commands":{"nope":{"label":"N"}}}}"#, + "`translations.de.commands.nope` names or translates something the manifest doesn't declare", + ), + (r#"{"de":{"params":{"nope":{"label":"N"}}}}"#, "`translations.de.params.nope` names or translates"), + (long_label.as_str(), "`translations.de.params.n.label` must be 1-64"), + (r#"{"de":{"params":{"n":{"help":"H"}}}}"#, "`translations.de.params.n.help` names or translates"), + (r#"{"de":{"params":{"n":{"options":{"a":"A"}}}}}"#, "`translations.de.params.n.options` names or translates"), + (r#"{"de":{"params":{"mode":{"options":{"c":"C"}}}}}"#, "`translations.de.params.mode.options.c` names or translates"), + (r#"{"de":{"params":{"mode":{"options":{"a":""}}}}}"#, "`translations.de.params.mode.options.a` must be"), + (r#"{"de":{"params":{"mode":{"options":{"a":"b"}}}}}"#, "`translations.de.params.mode.options` gives two options the same label"), + (r#"{"de":{"params":{"mode":{"options":{"a":"X","b":"X"}}}}}"#, "gives two options the same label"), + ( + r#"{"pt":{"params":{"mode":{"options":{"a":"Leve"}}}},"pt-BR":{"params":{"mode":{"options":{"b":"Leve"}}}}}"#, + "`translations.pt-BR.params.mode.options` gives two options the same label", + ), + (r#"{"de":{"groups":{"H":"Ha"}}}"#, "`translations.de.groups.H` names or translates"), + ] { + let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{translations}: {e}"); + } + // Characters that change the direction of the text or separate lines, written as JSON + // escapes: right-to-left and left-to-right overrides, isolates, and a line separator. + let esc = |c: u32| format!("\\u{c:04X}"); + for (translations, says) in [ + (format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x202E)), "`translations.de.name` must be"), + (format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x2067)), "`translations.de.name` must be"), + (format!(r#"{{"de":{{"name":"a{}b"}}}}"#, esc(0x2028)), "`translations.de.name` must be"), + (format!(r#"{{"de":{{"commands":{{"c":{{"label":"{}C"}}}}}}}}"#, esc(0x202E)), "`translations.de.commands.c.label` must be"), + (format!(r#"{{"de":{{"params":{{"n":{{"label":"{}N"}}}}}}}}"#, esc(0x202D)), "`translations.de.params.n.label` must be"), + (format!(r#"{{"de":{{"params":{{"mode":{{"options":{{"a":"{}A"}}}}}}}}}}"#, esc(0x202B)), "`translations.de.params.mode.options.a`"), + (format!(r#"{{"de":{{"groups":{{"G":"{}Ge"}}}}}}"#, esc(0x2066)), "`translations.de.groups.G` must be"), + (format!(r#"{{"de{}":{{"name":"X"}}}}"#, esc(0x202E)), "`translations.de\\u{202E}` is not a language code"), + ] { + let e = Manifest::parse(with(&translations).as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{translations}: {e}"); + } + // Keys and types serde reads: an unknown key, a repeated one, and a value of the wrong type. + for (translations, says) in [ + (r#"{"de":{"title":"X"}}"#, "unknown field `title`"), + (r#"{"de":{"params":{"n":{"unit":"mm"}}}}"#, "unknown field `unit`"), + (r#"{"de":{"name":"X","name":"Y"}}"#, "duplicate field `name`"), + (r#"{"de":{"params":{"n":{"label":"A"},"n":{"label":"B"}}}}"#, "`n` is given twice"), + (r#"{"de":{"name":"X"},"de":{"name":"Y"}}"#, "`de` is given twice"), + (r#"{"de":{"name":7}}"#, "manifest"), + (r#"["de"]"#, "manifest"), + (r#""de""#, "manifest"), + ] { + let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{translations}: {e}"); + } + // Right-to-left text without direction characters is text like any other. + let arabic = Manifest::parse(with(r#"{"ar":{"name":"ترتيب","commands":{"c":{"label":"تكبير"}}}}"#).as_bytes()).unwrap(); + assert_eq!(arabic.name_in("ar"), "ترتيب"); + } + + /// At most 16 languages, and the whole manifest, translations included, stays within the + /// manifest's byte limit. + #[test] + fn languages_and_manifest_size_are_capped() { + const CODES: [&str; 17] = ["de", "fr", "es", "it", "pt", "nl", "sv", "da", "fi", "pl", "cs", "hu", "ro", "tr", "ru", "uk", "ja"]; + let manifest = |n: usize| { + let langs: Vec = CODES.iter().take(n).map(|c| format!(r#""{c}":{{"name":"X"}}"#)).collect(); + format!(r#"{{"id":"a","name":"x","kind":"filter","translations":{{{}}}}}"#, langs.join(",")) + }; + assert_eq!(Manifest::parse(manifest(MAX_LANGUAGES).as_bytes()).unwrap().translations.0.len(), MAX_LANGUAGES); + let e = Manifest::parse(manifest(MAX_LANGUAGES + 1).as_bytes()).unwrap_err().to_string(); + assert!(e.contains("`translations` gives at most 16 languages"), "{e}"); + let help = "h".repeat(crate::manifest::MAX_MANIFEST_BYTES); + let big = format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"n":{{"type":"bool","help":"H"}}}},"translations":{{"de":{{"params":{{"n":{{"help":"{help}"}}}}}}}}}}"# + ); + assert!(Manifest::parse(big.as_bytes()).unwrap_err().to_string().contains("limit"), "the manifest's byte limit applies"); + } + + #[test] + fn language_codes() { + for good in ["de", "DE", "pt-br", "pt-BR", "zh-Hant", "zh-Hant-TW", "es-419", "fil", "sr-Latn-RS"] { + assert!(valid_language_code(good), "{good}"); + } + let long = format!("de-{}", ["abcdefgh"; 4].join("-")); + for bad in ["", "d", "deutsch", "de-", "-de", "de--at", "de_AT", "de-a", "x-test", "i-klingon", "de-abcdefghi", "1d", long.as_str()] { + assert!(!valid_language_code(bad), "{bad}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index df5789e649..143759d0b6 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -68,11 +68,12 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } /// The effect's name (`__label`, English) in the UI language: the catalog may carry it with or -/// without its trailing ellipsis. A plug-in effect's name is shown as it is. +/// without its trailing ellipsis. A plug-in effect's name is the plug-in's in the UI language +/// ([`super::plugin::effect_name`]). fn heading_label(d: &Dialog) -> String { let label = d.str("__label"); if vectorcraft_plugins::effect::plugin_id(&d.str("__effect")).is_some() { - return label; + return super::plugin::effect_name(&d.str("__effect")).unwrap_or(label); } let dotted = format!("{label}…"); let shown = tl!(&dotted); @@ -648,8 +649,11 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option, cmyk: bool) -> Option> { if let Some(plugin) = vectorcraft_plugins::effect::installed(effect) { - return plugin.manifest().param(key).and_then(|p| match &p.spec { - vectorcraft_plugins::ParamSpec::Choice { options, .. } => Some(options.iter().map(|o| (o.clone(), o.clone())).collect()), + let m = plugin.manifest(); + return m.param(key).and_then(|p| match &p.spec { + vectorcraft_plugins::ParamSpec::Choice { options, .. } => { + Some(options.iter().map(|o| (form::plugin_option_label(m, key, o), o.clone())).collect()) + } _ => None, }); } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index f19cd18cda..2e596173f8 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -615,7 +615,8 @@ fn typed_number(x: f64) -> Value { /// page. Parameters outside any group come first, then each group as a section that folds /// ([`Manifest::sections`]); a parameter whose `visibleWhen` the values don't meet is left out /// ([`Manifest::visible`]). Returns true when a value changed. Labels, choices, groups and help are -/// the plug-in's text, shown as they are. A plug-in may declare more parameters +/// the plug-in's text in the UI language ([`vectorcraft_plugins::translations`]), with control and +/// bidirectional characters escaped ([`plugin_text`]). A plug-in may declare more parameters /// ([`MAX_PARAMS`](vectorcraft_plugins::manifest::MAX_PARAMS)) than the window has room for, and /// the rows then scroll ([`super::modal::scrolled_rows`]). pub(super) fn schema_fields(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> bool { @@ -640,7 +641,7 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b // down the dialog; the rows outside groups make up for the indent of a group's rows. let font = egui::TextStyle::Body.resolve(ui.style()); let label_width = (m.params.iter().filter(|(k, _)| visible.contains(k.as_str()))) - .map(|(k, p)| ui.painter().layout_no_wrap(param_label(k, p), font.clone(), egui::Color32::WHITE).size().x) + .map(|(k, _)| ui.painter().layout_no_wrap(param_label(m, k), font.clone(), egui::Color32::WHITE).size().x) .fold(0.0, f32::max); let indent = if sections.iter().any(|(group, _)| group.is_some()) { ui.spacing().indent } else { 0.0 }; super::modal::scrolled_rows(ui, "plugin-fields", |ui| { @@ -653,7 +654,7 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b let grid = egui::Grid::new(("plugin-grid", section)).num_columns(2).spacing([12.0, 8.0]).min_col_width(label_width); grid.show(ui, |ui| { for (k, p) in shown { - let (row_changed, opened) = param_row(ui, d, k, p); + let (row_changed, opened) = param_row(ui, d, m, k, p); changed |= row_changed; help = help.take().or(opened); ui.end_row(); @@ -663,7 +664,9 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b match group { None => rows(ui, label_width + indent), Some(g) => { - egui::CollapsingHeader::new(g).id_salt(("plugin-group", g)).default_open(true).show(ui, |ui| rows(ui, label_width)); + // The section is kept by the manifest's group, whatever language heads it. + let heading = plugin_text(m.group_in(g, plugin_lang())); + egui::CollapsingHeader::new(heading).id_salt(("plugin-group", g)).default_open(true).show(ui, |ui| rows(ui, label_width)); } } } @@ -671,18 +674,56 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b (changed, help) } -/// The label of parameter `k`'s row: its manifest `label`, else its name spaced out. -fn param_label(k: &str, p: &Param) -> String { - p.ui.label.as_ref().map_or_else(|| humanize(k), |l| format!("{l}:")) +/// The UI language's code, which a plug-in's translations are looked up under. +fn plugin_lang() -> &'static str { + crate::i18n::current().code() +} + +/// Plug-in text `s` as a dialog shows it: each line with its control and bidirectional characters +/// escaped ([`vectorcraft_plugins::permissions::display_text`]), so a label or help can't reorder +/// the text around it. +fn plugin_text(s: &str) -> String { + let lines: Vec = + s.split('\n').map(|l| vectorcraft_plugins::permissions::display_text(l, vectorcraft_plugins::dialog::MAX_HELP)).collect(); + lines.join("\n") +} + +/// Parameter `k`'s `label` in manifest `m`, in the UI language as dialogs show it ([`plugin_text`]); +/// `None` when it gives none. +pub(crate) fn plugin_param_label(m: &Manifest, k: &str) -> Option { + m.param_label_in(k, plugin_lang()).map(plugin_text) +} + +/// Parameter `k`'s `help` in manifest `m`, in the UI language as dialogs show it. +pub(crate) fn plugin_param_help(m: &Manifest, k: &str) -> Option { + m.param_help_in(k, plugin_lang()).map(plugin_text) +} + +/// The label of value `option` of choice `k` in manifest `m`, in the UI language as dialogs show it. +pub(crate) fn plugin_option_label(m: &Manifest, k: &str, option: &str) -> String { + plugin_text(m.option_label_in(k, option, plugin_lang())) +} + +/// The label of parameter `k`'s row in manifest `m`: its `label` in the UI language, else its name +/// spaced out. +fn param_label(m: &Manifest, k: &str) -> String { + plugin_param_label(m, k).map_or_else(|| humanize(k), |l| format!("{l}:")) } /// One row of [`schema_fields`]: parameter `k`'s label and value field → whether the value changed, /// and the help page asked for. -fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Option) { +fn param_row(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest, k: &str, p: &Param) -> (bool, Option) { let t = Tokens::get(ui.ctx()); - let label = param_label(k, p); + let label = param_label(m, k); let shown_label = ui.label(egui::RichText::new(&label).color(t.text)); - let shown_label = if let Some(help) = &p.ui.help { shown_label.on_hover_text(help) } else { shown_label }; + let shown_label = match plugin_param_help(m, k) { + Some(help) => shown_label.on_hover_text(help), + None => shown_label, + }; + let choices: Vec = match &p.spec { + ParamSpec::Choice { options, .. } => options.iter().map(|o| plugin_option_label(m, k, o)).collect(), + _ => Vec::new(), + }; let cur = d.fields.get(k).cloned().unwrap_or_else(|| p.spec.default_value()); let unit = p.ui.unit.as_deref().unwrap_or_default(); let suffix = unit_suffix(unit); @@ -691,7 +732,7 @@ fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Op .horizontal(|ui| { // The row's painted label names every input in its value column (egui 0.37's strict // accessibility gate), not only the first one. - let (new, in_field) = ui.label_inputs_by(shown_label.id, |ui| value_field(ui, k, &label, &p.spec, &cur, &suffix)); + let (new, in_field) = ui.label_inputs_by(shown_label.id, |ui| value_field(ui, k, &label, &p.spec, &choices, &cur, &suffix)); if !in_field && !unit.is_empty() { ui.label(egui::RichText::new(unit).color(t.text_dim)); } @@ -707,10 +748,10 @@ fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Op (changed, opened) } -/// The field of parameter `k`'s value `cur` (a checkbox is called by the row's `label`) → the new -/// value when it changed, and whether the field shows `suffix` (numbers do; the other fields leave -/// the unit to a label after them). -fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: &Value, suffix: &str) -> (Option, bool) { +/// The field of parameter `k`'s value `cur` (a checkbox is called by the row's `label`; a choice +/// shows `choices`, the label of each option in order) → the new value when it changed, and whether +/// the field shows `suffix` (numbers do; the other fields leave the unit to a label after them). +fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, choices: &[String], cur: &Value, suffix: &str) -> (Option, bool) { match spec { ParamSpec::Number { min, max, .. } => { let x = cur.as_f64().unwrap_or(*min); @@ -737,9 +778,10 @@ fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: & (crate::widgets::check_box(ui, label, b, true).then(|| json!(!b)), false) } ParamSpec::Choice { options, .. } => { - let labels: Vec<&str> = options.iter().map(String::as_str).collect(); - let chosen = - crate::widgets::dropdown_names_named(ui, ("plugin-choice", k), Some(label), cur.as_str().unwrap_or_default(), &labels, 140.0); + let labels: Vec<&str> = choices.iter().map(String::as_str).collect(); + // The option chosen now, by its label in `choices`. + let shown = options.iter().position(|o| Some(o.as_str()) == cur.as_str()).and_then(|i| labels.get(i).copied()).unwrap_or_default(); + let chosen = crate::widgets::dropdown_names_named(ui, ("plugin-choice", k), Some(label), shown, &labels, 140.0); (chosen.and_then(|i| options.get(i)).map(|o| json!(o)), false) } ParamSpec::Text { max_length, .. } => { diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 706188f6da..c4dfe69d86 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -43,9 +43,57 @@ const CMD: &str = "plugin.run"; /// Object › Plug-ins' header while no filter plug-in is installed. pub const NO_FILTERS: &str = "No filter plug-ins installed"; -/// Headed by the plug-in's name, as it is (plug-in text is never translated). -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |d| d.str("__label"), body, confirm, preview: true, max_width: Some(420.0), ..DialogSpec::FORM }; +/// Headed by the plug-in's name, or the command's label, in the UI language ([`heading`]). +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, preview: true, max_width: Some(420.0), ..DialogSpec::FORM }; + +/// The UI language's code, which a plug-in's translations are looked up under +/// ([`vectorcraft_plugins::translations`]): plug-in text comes from the plug-in, never from the +/// app's catalogs. +fn lang() -> &'static str { + crate::i18n::current().code() +} + +/// Menu path `path` (English, `›`-separated) with each segment put through `tr`, except the +/// segments after Object › Plug-ins or Effect › Plug-ins: those are a plug-in's name and its items, +/// already in the UI language from the plug-in's translations. +pub(crate) fn translate_path<'a>(path: &'a str, tr: impl Fn(&'a str) -> &'a str) -> String { + let parts: Vec<&str> = path.split(" › ").collect(); + let plugin = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", _, ..]); + parts.iter().enumerate().map(|(i, s)| if plugin && i >= 2 { s } else { tr(s) }).collect::>().join(" › ") +} + +/// The heading of plug-in dialog `d`: its command's label (`__command`), else its plug-in's name, +/// in the UI language as menus show it, read each time it is drawn so a change of language shows +/// at once; `__label` once the plug-in is gone. +fn heading(d: &Dialog) -> String { + let command = d.str("__command"); + let shown = match command.is_empty() { + true => shown_name(&d.str("__plugin")), + false => vectorcraft_engine::cmd::plugin::command_of(&command).map(|(plugin, c)| plugin.manifest().shown_command_label(&c, lang())), + }; + shown.unwrap_or_else(|| d.str("__label")) +} + +/// Plug-in `id`'s name in the UI language as menus show it, without a trailing ellipsis (`None` +/// while no such plug-in is installed). +pub(crate) fn shown_name(id: &str) -> Option { + registry::get(id).map(|p| p.manifest().shown_name(lang()).trim_end_matches('…').to_string()) +} + +/// The name of live effect `effect` (an effect id) in the UI language when a plug-in gives it +/// ([`shown_name`]); `None` for a built-in effect. +pub(crate) fn effect_name(effect: &str) -> Option { + vectorcraft_plugins::effect::plugin_id(effect).and_then(shown_name) +} + +/// Effect › Plug-ins' label for live effect `e`: its plug-in's name in the UI language, with an +/// ellipsis when it opens a dialog ([`label`]); the catalog's label once the plug-in is gone. +pub(crate) fn effect_item_label(e: &vectorcraft_effects::EffectInfo) -> &'static str { + match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) { + Some(p) => label(&p.manifest().shown_name(lang()), !p.manifest().params.is_empty()), + None => e.label, + } +} /// A menu label for plug-in `name`: with an ellipsis when it opens a dialog. fn label(name: &str, has_params: bool) -> &'static str { @@ -56,7 +104,7 @@ fn label(name: &str, has_params: bool) -> &'static str { /// A filter or live effect `plugin`'s item `own`, as the menu lists it: alone, or for a plug-in /// with commands of its own, a submenu named after it holding `own` and then its commands. Each /// command runs its command id (`plugin..`), with an ellipsis when it has parameters, -/// whose dialog [`open_command`] opens. +/// whose dialog [`open_command`] opens. Names and labels are in the UI language. fn with_commands(plugin: &Plugin, own: Item) -> Item { let m = plugin.manifest(); if m.commands.is_empty() { @@ -65,18 +113,21 @@ fn with_commands(plugin: &Plugin, own: Item) -> Item { let mut items = vec![own, Item::Sep]; items.extend(m.commands.iter().map(|c| { let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)); - Item::Cmd(label(&c.shown_label(), !c.params.is_empty()), id, Value::Null) + Item::Cmd(label(&m.shown_command_label(c, lang()), !c.params.is_empty()), id, Value::Null) })); - Item::Sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items) + Item::Sub(registry::intern(&m.shown_name(lang())), items) } -/// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then -/// Install Plug-in… and Reload Plug-ins. +/// Object › Plug-ins: the installed object filters by their names in the UI language (each with +/// its commands, if it has any), then Install Plug-in… and Reload Plug-ins. pub fn object_menu() -> Vec { let mut items: Vec = registry::list() .iter() .filter(|p| p.manifest().kind == Kind::Filter) - .map(|p| with_commands(p, Item::Cmd(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))) + .map(|p| { + let m = p.manifest(); + with_commands(p, Item::Cmd(label(&m.shown_name(lang()), !m.params.is_empty()), "plugin.dialog", json!({ "id": p.id() }))) + }) .collect(); if items.is_empty() { items.push(Item::Header(NO_FILTERS)); @@ -92,11 +143,15 @@ pub fn object_menu() -> Vec { /// File › Open With's header while no importer plug-in is installed. pub const NO_IMPORTERS: &str = "No importer plug-ins installed"; -/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name. +/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name in the +/// UI language. pub fn open_with_menu() -> Vec { let items: Vec = vectorcraft_plugins::import::installed() .iter() - .map(|p| Item::Cmd(label(&p.manifest().name, true), "file.openWith", json!({ "importer": vectorcraft_plugins::export::format_id(p.id()) }))) + .map(|p| { + let importer = vectorcraft_plugins::export::format_id(p.id()); + Item::Cmd(label(&p.manifest().shown_name(lang()), true), "file.openWith", json!({ "importer": importer })) + }) .collect(); if items.is_empty() { vec![Item::Header(NO_IMPORTERS)] } else { items } } @@ -107,9 +162,10 @@ pub fn effect_menu() -> Option { let items: Vec = vectorcraft_effects::plugin_effects() .into_iter() .map(|e| { + let label = effect_item_label(&e); let own = match e.defaults.as_object().is_some_and(|o| o.is_empty()) { - true => Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })), - false => Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })), + true => Item::Cmd(label, "effect.apply", json!({ "effect": e.id })), + false => Item::Cmd(label, "effect.dialog", json!({ "effect": e.id })), }; match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) { Some(plugin) => with_commands(&plugin, own), @@ -273,15 +329,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// The dialog kind of an exporter's parameters, after Export As picked the file. pub const EXPORT_KIND: &str = "pluginExport"; -/// Headed by the plug-in's name, as it is; Export writes the file. -pub(super) const EXPORT_SPEC: DialogSpec = DialogSpec { - heading: |d| d.str("__label"), - body: export_body, - confirm: export_confirm, - ok: Some("Export"), - max_width: Some(420.0), - ..DialogSpec::FORM -}; +/// Headed by the plug-in's name in the UI language ([`heading`]); Export writes the file. +pub(super) const EXPORT_SPEC: DialogSpec = + DialogSpec { heading, body: export_body, confirm: export_confirm, ok: Some("Export"), max_width: Some(420.0), ..DialogSpec::FORM }; /// Export As with exporter `plugin`, which has parameters: its fields at their defaults, and /// `export`, the export's own parameters (`format`, `path`, …), kept for Export. @@ -310,15 +360,9 @@ fn export_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result /// The dialog kind of an importer's parameters, after Open With picked the file. pub const IMPORT_KIND: &str = "pluginImport"; -/// Headed by the plug-in's name, as it is; Open opens the file. -pub(super) const IMPORT_SPEC: DialogSpec = DialogSpec { - heading: |d| d.str("__label"), - body: export_body, - confirm: import_confirm, - ok: Some("Open"), - max_width: Some(420.0), - ..DialogSpec::FORM -}; +/// Headed by the plug-in's name in the UI language ([`heading`]); Open opens the file. +pub(super) const IMPORT_SPEC: DialogSpec = + DialogSpec { heading, body: export_body, confirm: import_confirm, ok: Some("Open"), max_width: Some(420.0), ..DialogSpec::FORM }; /// Open With with importer `plugin`, which has parameters: its fields at their defaults, and /// `open`, Open With's own parameters (`path`, `importer`, and `picked` for a file from the diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..16356868d7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -720,6 +720,7 @@ impl PluginIntField { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + translations: Default::default(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { @@ -819,6 +820,75 @@ fn plugin_color_parameter_shows_a_color_button() { } } +/// Every text `shape` draws. +fn drawn_texts(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| drawn_texts(s, out)), + _ => {} + } +} + +/// A plug-in's dialog shows the text its manifest's `translations` give in the UI language (the +/// heading, a label, a group heading and a choice's label) and its own text in any other language; +/// the choice still passes its value. Plug-in text with a right-to-left override is drawn escaped. +#[test] +fn plugin_dialogs_show_the_plugins_text_in_the_ui_language() { + let id = "test.dialogs.translated"; + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + let manifest = format!( + r#"{{"id":"{id}","name":"Tidy","kind":"filter","params":{{ + "mode":{{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."}}, + "flip":{{"type":"bool","label":"Flip{rlo}txt"}}}}, + "commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"number","min":0,"max":10,"default":2,"label":"By"}}}}}}], + "translations":{{"de":{{"name":"Aufräumen","params":{{"mode":{{"label":"Modus","options":{{"soft":"Weich"}}}}}}, + "groups":{{"Shape":"Form"}},"commands":{{"grow":{{"label":"Wachsen","params":{{"by":{{"label":"Um"}}}}}}}}}}}}}}"# + ); + let module = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let installed = vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let drawn = |lang: &str, m: &vectorcraft_plugins::Manifest, fields: serde_json::Value| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered")); + let mut d = Dialog::new(plugin::KIND, fields); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + form::schema_rows(ui, &mut d, m); + }); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|s| drawn_texts(&s.shape, &mut texts)); + crate::i18n::set_current(crate::i18n::Lang::EN); + texts + }; + let m = installed.manifest(); + let de = drawn("de", m, json!({"mode": "soft"})); + for text in ["Modus:", "Weich", "Form", "Flip\\u{202E}txt:"] { + assert!(de.iter().any(|t| t == text), "{text} in German: {de:?}"); + } + assert!(!de.iter().any(|t| t == "Mode:" || t == "soft" || t == "Shape"), "{de:?}"); + let en = drawn("en", m, json!({"mode": "soft"})); + for text in ["Mode:", "soft", "Shape"] { + assert!(en.iter().any(|t| t == text), "{text} in English: {en:?}"); + } + assert!(!en.iter().chain(&de).any(|t| t.contains('\u{202E}')), "the override is never drawn as one"); + // The heading follows the language it is drawn in, for the filter and for its command. + let own = Dialog::new(plugin::KIND, json!({"__plugin": id, "__label": "Tidy"})); + let command = Dialog::new(plugin::KIND, json!({"__plugin": id, "__label": "Grow", "__command": format!("plugin.{id}.grow")})); + let heading = |lang: &str, d: &Dialog| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let shown = (plugin::SPEC.heading)(d); + crate::i18n::set_current(crate::i18n::Lang::EN); + shown + }; + assert_eq!((heading("de", &own), heading("en", &own)), ("Aufräumen".to_string(), "Tidy".to_string())); + assert_eq!((heading("de", &command), heading("fr", &command)), ("Wachsen".to_string(), "Grow".to_string())); + let grow = m.for_command(m.command("grow").unwrap()); + assert!(drawn("de", &grow, json!({})).iter().any(|t| t == "Um:")); + vectorcraft_plugins::registry::remove(id); +} + #[test] fn a_dialog_opens_with_its_first_field_focused_so_typing_and_enter_apply() { let mut app = app(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..436e92c147 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6677,6 +6677,7 @@ axis Y Axis Y ос # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Да се инсталира ли „{name}“, който иска тези права? ID: {id} ID: {id} + Manifest name: {name} Име в манифеста: {name} Version: {version} Версия: {version} Install “{name}” in place of the plug-in with the same ID? Да се инсталира ли „{name}“ на мястото на приставката със същия ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Този файл не е приставката, инсталирана преди с този ID. Той получава настройките и кеша, пазени за този ID. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..e55b59f674 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6703,6 +6703,7 @@ axis Y Axis Y osa # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instalirati „{name}”, koji traži ove dozvole? ID: {id} ID: {id} + Manifest name: {name} Naziv u manifestu: {name} Version: {version} Verzija: {version} Install “{name}” in place of the plug-in with the same ID? Instalirati „{name}” umjesto dodatka s istim ID-om? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ova datoteka nije dodatak ranije instaliran s ovim ID-om. Dobija postavke i predmemoriju sačuvane za taj ID. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a50e9c56ed 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7827,6 +7827,7 @@ variable-list-end {0}, {1} {0} i {1} # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instal·la «{name}», que demana aquests permisos? ID: {id} ID: {id} + Manifest name: {name} Nom al manifest: {name} Version: {version} Versió: {version} Install “{name}” in place of the plug-in with the same ID? Instal·la «{name}» en lloc del complement amb el mateix ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Aquest fitxer no és el complement instal·lat abans amb aquest ID. Rep la configuració i la memòria cau desades per a aquest ID. @@ -7890,6 +7891,11 @@ variable-list-end {0}, {1} {0} i {1} @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a «{name}» no se li ha concedit `{p}`, que la seva sortida necessita: no s’ha canviat res @msg a heavy filter runs in the background, so it can't declare `commands` un filtre pesat s’executa en segon pla, de manera que no pot declarar `commands` @msg at most {MAX_COMMANDS} `commands` com a màxim {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dona com a màxim {MAX_LANGUAGES} idiomes +@msg {at} gives two options the same label {at} dona la mateixa etiqueta a dues opcions +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no és un codi d’idioma com `de` o `pt-BR`, o en repeteix un de donat abans +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} ha de tenir 1-{max} caràcters imprimibles, sense caràcters de direcció ni separadors de línia +@msg {at} names or translates something the manifest doesn't declare {at} anomena o tradueix alguna cosa que el manifest no declara @msg command {name} is declared twice l’ordre {name} està declarada dues vegades @msg command {name}: `label` must be 1-64 printable characters ordre {name}: `label` ha de tenir 1-64 caràcters imprimibles @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ordre {name}: fes servir un id d’1-{MAX_COMMAND_ID} caràcters d’a-z 0-9 _ que comenci per una lletra diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..9331658a1d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7437,6 +7437,7 @@ axis Y Axis osa Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Nainstalovat „{name}“, který žádá o tato oprávnění? ID: {id} ID: {id} + Manifest name: {name} Název v manifestu: {name} Version: {version} Verze: {version} Install “{name}” in place of the plug-in with the same ID? Nainstalovat „{name}“ místo zásuvného modulu se stejným ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tento soubor není zásuvný modul dříve nainstalovaný s tímto ID. Získá nastavení a mezipaměť uchovávané pro toto ID. @@ -7500,6 +7501,11 @@ axis Y Axis osa Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ nedostal `{p}`, které jeho výstup potřebuje: nic se nezměnilo @msg a heavy filter runs in the background, so it can't declare `commands` těžký filtr běží na pozadí, takže nemůže deklarovat `commands` @msg at most {MAX_COMMANDS} `commands` nejvýše {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` uvádí nejvýše {MAX_LANGUAGES} jazyků +@msg {at} gives two options the same label {at} dává dvěma možnostem stejný popisek +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} není kód jazyka jako `de` nebo `pt-BR`, nebo opakuje kód uvedený dříve +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musí mít 1-{max} tisknutelných znaků, bez znaků směru textu a oddělovačů řádků +@msg {at} names or translates something the manifest doesn't declare {at} pojmenovává nebo překládá něco, co manifest nedeklaruje @msg command {name} is declared twice příkaz {name} je deklarován dvakrát @msg command {name}: `label` must be 1-64 printable characters příkaz {name}: `label` musí mít 1-64 tisknutelných znaků @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter příkaz {name}: použijte id o 1-{MAX_COMMAND_ID} znacích z a-z 0-9 _, které začíná písmenem diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..9e950f43af 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -712,6 +712,11 @@ liquify-list-end {0}, {1} {0} og {1} @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed »{name}« fik ikke tildelt `{p}`, som dets output kræver: intet blev ændret @msg a heavy filter runs in the background, so it can't declare `commands` et tungt filter kører i baggrunden, så det kan ikke angive `commands` @msg at most {MAX_COMMANDS} `commands` højst {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` angiver højst {MAX_LANGUAGES} sprog +@msg {at} gives two options the same label {at} giver to valgmuligheder samme etiket +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} er ikke en sprogkode som `de` eller `pt-BR`, eller gentager en, der er angivet før +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} skal være 1-{max} tegn, der kan udskrives, uden retnings- eller linjeskilletegn +@msg {at} names or translates something the manifest doesn't declare {at} navngiver eller oversætter noget, som manifestet ikke erklærer @msg command {name} is declared twice kommandoen {name} er erklæret to gange @msg command {name}: `label` must be 1-64 printable characters kommandoen {name}: `label` skal være 1-64 tegn, der kan udskrives @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommandoen {name}: brug et id på 1-{MAX_COMMAND_ID} tegn fra a-z 0-9 _, der starter med et bogstav @@ -9596,6 +9601,7 @@ axis Y Axis Y-akse # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installér »{name}«, som beder om disse rettigheder? ID: {id} ID: {id} + Manifest name: {name} Navn i manifestet: {name} Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? Installér »{name}« i stedet for det plug-in, der har samme id? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Denne fil er ikke det plug-in, der før var installeret med dette id. Den får de indstillinger og den cache, der er gemt for dette id. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..1be15dae35 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7020,6 +7020,7 @@ axis Y Axis Y-Achse # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? „{name}“ installieren, das diese Berechtigungen verlangt? ID: {id} ID: {id} + Manifest name: {name} Name im Manifest: {name} Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? „{name}“ anstelle des Plug-ins mit derselben ID installieren? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Diese Datei ist nicht das Plug-in, das vorher mit dieser ID installiert war. Sie erhält die Einstellungen und den Cache, die für diese ID gespeichert sind. @@ -7083,6 +7084,11 @@ axis Y Axis Y-Achse @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ wurde `{p}` nicht gewährt, das seine Ausgabe braucht: Es wurde nichts geändert @msg a heavy filter runs in the background, so it can't declare `commands` ein schwerer Filter läuft im Hintergrund und kann daher keine `commands` deklarieren @msg at most {MAX_COMMANDS} `commands` höchstens {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` gibt höchstens {MAX_LANGUAGES} Sprachen an +@msg {at} gives two options the same label {at} gibt zwei Optionen dieselbe Beschriftung +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ist kein Sprachcode wie `de` oder `pt-BR` oder wiederholt einen zuvor angegebenen +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} muss 1-{max} druckbare Zeichen lang sein, ohne Schreibrichtungs- oder Zeilentrennzeichen +@msg {at} names or translates something the manifest doesn't declare {at} benennt oder übersetzt etwas, das das Manifest nicht deklariert @msg command {name} is declared twice der Befehl {name} ist doppelt deklariert @msg command {name}: `label` must be 1-64 printable characters Befehl {name}: `label` muss 1-64 druckbare Zeichen haben @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter Befehl {name}: Verwenden Sie eine ID aus 1-{MAX_COMMAND_ID} Zeichen aus a-z 0-9 _, die mit einem Buchstaben beginnt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..03fa786075 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7427,6 +7427,7 @@ axis Y Axis Άξονας Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Να εγκατασταθεί το «{name}», που ζητά αυτά τα δικαιώματα; ID: {id} Αναγνωριστικό: {id} + Manifest name: {name} Όνομα στο manifest: {name} Version: {version} Έκδοση: {version} Install “{name}” in place of the plug-in with the same ID? Να εγκατασταθεί το «{name}» στη θέση του πρόσθετου με το ίδιο αναγνωριστικό; This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Αυτό το αρχείο δεν είναι το πρόσθετο που ήταν εγκατεστημένο πριν με αυτό το αναγνωριστικό. Παίρνει τις ρυθμίσεις και την κρυφή μνήμη που διατηρούνται για αυτό το αναγνωριστικό. @@ -7490,6 +7491,11 @@ axis Y Axis Άξονας Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed στο «{name}» δεν παραχωρήθηκε το `{p}`, που χρειάζεται η έξοδός του: δεν άλλαξε τίποτα @msg a heavy filter runs in the background, so it can't declare `commands` ένα βαρύ φίλτρο εκτελείται στο παρασκήνιο, οπότε δεν μπορεί να δηλώνει `commands` @msg at most {MAX_COMMANDS} `commands` το πολύ {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages το `translations` δίνει το πολύ {MAX_LANGUAGES} γλώσσες +@msg {at} gives two options the same label το {at} δίνει την ίδια ετικέτα σε δύο επιλογές +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it το {at} δεν είναι κωδικός γλώσσας όπως `de` ή `pt-BR`, ή επαναλαμβάνει έναν που δόθηκε πριν +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters το {at} πρέπει να έχει 1-{max} εκτυπώσιμους χαρακτήρες, χωρίς χαρακτήρες κατεύθυνσης ή διαχωρισμού γραμμών +@msg {at} names or translates something the manifest doesn't declare το {at} ονομάζει ή μεταφράζει κάτι που το manifest δεν δηλώνει @msg command {name} is declared twice η εντολή {name} δηλώνεται δύο φορές @msg command {name}: `label` must be 1-64 printable characters εντολή {name}: το `label` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter εντολή {name}: χρησιμοποιήστε αναγνωριστικό 1-{MAX_COMMAND_ID} χαρακτήρων από a-z 0-9 _ που αρχίζει με γράμμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..413e456910 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7413,6 +7413,7 @@ axis Y Axis Eje Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? ¿Instalar “{name}”, que pide estos permisos? ID: {id} ID: {id} + Manifest name: {name} Nombre en el manifiesto: {name} Version: {version} Versión: {version} Install “{name}” in place of the plug-in with the same ID? ¿Instalar “{name}” en lugar del plugin con el mismo ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este archivo no es el plugin instalado antes con este ID. Recibe la configuración y la caché guardadas para ese ID. @@ -7476,6 +7477,11 @@ axis Y Axis Eje Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” no se le concedió `{p}`, que su resultado necesita: no se cambió nada @msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesado se ejecuta en segundo plano, así que no puede declarar `commands` @msg at most {MAX_COMMANDS} `commands` como máximo {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` da como máximo {MAX_LANGUAGES} idiomas +@msg {at} gives two options the same label {at} da la misma etiqueta a dos opciones +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no es un código de idioma como `de` o `pt-BR`, o repite uno dado antes +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} debe tener 1-{max} caracteres imprimibles, sin caracteres de dirección ni separadores de línea +@msg {at} names or translates something the manifest doesn't declare {at} nombra o traduce algo que el manifiesto no declara @msg command {name} is declared twice el comando {name} está declarado dos veces @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` debe tener 1-64 caracteres imprimibles @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que empiece por una letra diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..4e424a2741 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7504,6 +7504,7 @@ axis Y Axis Y-akseli # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Asennetaanko ”{name}”, joka pyytää näitä käyttöoikeuksia? ID: {id} Tunnus: {id} + Manifest name: {name} Nimi manifestissa: {name} Version: {version} Versio: {version} Install “{name}” in place of the plug-in with the same ID? Asennetaanko ”{name}” samaa tunnusta käyttävän laajennuksen tilalle? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tämä tiedosto ei ole laajennus, joka oli aiemmin asennettu tällä tunnuksella. Se saa tälle tunnukselle säilytetyt asetukset ja välimuistin. @@ -7567,6 +7568,11 @@ axis Y Axis Y-akseli @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” ei saanut käyttöoikeutta `{p}`, jota sen tulos tarvitsee: mitään ei muutettu @msg a heavy filter runs in the background, so it can't declare `commands` raskas suodin suoritetaan taustalla, joten se ei voi määritellä `commands`-kohtaa @msg at most {MAX_COMMANDS} `commands` enintään {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` antaa enintään {MAX_LANGUAGES} kieltä +@msg {at} gives two options the same label {at} antaa kahdelle vaihtoehdolle saman nimen +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ei ole kielikoodi kuten `de` tai `pt-BR`, tai toistaa aiemmin annetun koodin +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} saa olla 1-{max} tulostettavaa merkkiä ilman suunta- tai rivinerotinmerkkejä +@msg {at} names or translates something the manifest doesn't declare {at} nimeää tai kääntää jotain, mitä manifesti ei määrittele @msg command {name} is declared twice komento {name} on määritelty kahdesti @msg command {name}: `label` must be 1-64 printable characters komento {name}: `label`-kentässä on oltava 1-64 tulostettavaa merkkiä @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter komento {name}: käytä 1-{MAX_COMMAND_ID} merkin tunnusta merkeistä a-z 0-9 _, joka alkaa kirjaimella diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..4fc64305db 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7433,6 +7433,7 @@ axis Y Axis Axe Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installer « {name} », qui demande ces autorisations ? ID: {id} ID : {id} + Manifest name: {name} Le manifeste le nomme {name} Version: {version} Version : {version} Install “{name}” in place of the plug-in with the same ID? Installer « {name} » à la place du module externe qui a le même ID ? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ce fichier n’est pas le module externe installé auparavant avec cet ID. Il reçoit les réglages et le cache conservés pour cet ID. @@ -7496,6 +7497,11 @@ axis Y Axis Axe Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed « {name} » n’a pas reçu `{p}`, dont sa sortie a besoin : rien n’a été modifié @msg a heavy filter runs in the background, so it can't declare `commands` un filtre lourd s’exécute en arrière-plan, il ne peut donc pas déclarer `commands` @msg at most {MAX_COMMANDS} `commands` au plus {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` donne au plus {MAX_LANGUAGES} langues +@msg {at} gives two options the same label {at} donne le même libellé à deux options +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} n’est pas un code de langue comme `de` ou `pt-BR`, ou répète un code donné avant +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} doit compter 1-{max} caractères imprimables, sans caractères de direction ni séparateurs de ligne +@msg {at} names or translates something the manifest doesn't declare {at} nomme ou traduit quelque chose que le manifeste ne déclare pas @msg command {name} is declared twice la commande {name} est déclarée deux fois @msg command {name}: `label` must be 1-64 printable characters commande {name} : `label` doit compter 1-64 caractères imprimables @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter commande {name} : utilisez un id de 1-{MAX_COMMAND_ID} caractères parmi a-z 0-9 _ commençant par une lettre diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..5eadc075d0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1876,6 +1876,7 @@ Max Ascender મહત્તમ એસેન્ડર ICF Top/Right ICF ઉપર/જમણે ID: {id} ID: {id} + Manifest name: {name} મેનિફેસ્ટમાં નામ: {name} Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. જો ડ્રોઇંગ ટેબ્લેટની પેન દોરતી ન હોય, તો X11 (XWayland) વિકલ્પ પસંદ કરો. Ignore અવગણો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..45d53ee202 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6621,6 +6621,7 @@ arrowhead Feather पंख # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? "{name}" स्थापित करें, जो ये अनुमतियां मांगता है? ID: {id} ID: {id} + Manifest name: {name} मैनिफ़ेस्ट में नाम: {name} Version: {version} संस्करण: {version} Install “{name}” in place of the plug-in with the same ID? समान ID वाले प्लग-इन की जगह “{name}” इंस्टॉल करें? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. यह फ़ाइल इस ID के साथ पहले इंस्टॉल किया गया प्लग-इन नहीं है। इसे उस ID के लिए रखी गई सेटिंग्स और कैश मिलते हैं। @@ -6680,6 +6681,11 @@ arrowhead Feather पंख @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” को `{p}` नहीं दी गई, जो उसके आउटपुट को चाहिए: कुछ नहीं बदला @msg a heavy filter runs in the background, so it can't declare `commands` भारी फ़िल्टर पृष्ठभूमि में चलता है, इसलिए वह `commands` घोषित नहीं कर सकता @msg at most {MAX_COMMANDS} `commands` अधिकतम {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` अधिकतम {MAX_LANGUAGES} भाषाएँ देता है +@msg {at} gives two options the same label {at} दो विकल्पों को एक ही लेबल देता है +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} `de` या `pt-BR` जैसा भाषा कोड नहीं है, या पहले दिए गए कोड को दोहराता है +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} में 1-{max} मुद्रण योग्य वर्ण होने चाहिए, दिशा या पंक्ति-विभाजक वर्णों के बिना +@msg {at} names or translates something the manifest doesn't declare {at} ऐसी चीज़ का नाम लेता है या अनुवाद करता है जिसे मैनिफ़ेस्ट घोषित नहीं करता @msg command {name} is declared twice कमांड {name} दो बार घोषित है @msg command {name}: `label` must be 1-64 printable characters कमांड {name}: `label` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter कमांड {name}: a-z 0-9 _ के 1-{MAX_COMMAND_ID} वर्णों वाली ऐसी id इस्तेमाल करें जो अक्षर से शुरू हो diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..8059e3c8f7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7422,6 +7422,7 @@ axis Y Axis Y tengely # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Telepíted a(z) „{name}” bővítményt, amely ezeket az engedélyeket kéri? ID: {id} Azonosító: {id} + Manifest name: {name} Név a manifestben: {name} Version: {version} Verzió: {version} Install “{name}” in place of the plug-in with the same ID? Telepíted a(z) „{name}” bővítményt az azonos azonosítójú bővítmény helyére? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ez a fájl nem az a bővítmény, amely korábban ezzel az azonosítóval volt telepítve. Megkapja az ehhez az azonosítóhoz tárolt beállításokat és gyorsítótárat. @@ -7485,6 +7486,11 @@ axis Y Axis Y tengely @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a(z) „{name}” nem kapta meg a(z) `{p}` engedélyt, amelyre a kimenetének szüksége van: semmi sem változott @msg a heavy filter runs in the background, so it can't declare `commands` a nehéz szűrő a háttérben fut, ezért nem deklarálhat `commands` értéket @msg at most {MAX_COMMANDS} `commands` legfeljebb {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages a `translations` legfeljebb {MAX_LANGUAGES} nyelvet adhat meg +@msg {at} gives two options the same label {at} két lehetőségnek ugyanazt a címkét adja +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nem olyan nyelvkód, mint a `de` vagy a `pt-BR`, vagy egy korábban megadottat ismétel +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 1-{max} nyomtatható karakter lehet, irány- és sorelválasztó karakterek nélkül +@msg {at} names or translates something the manifest doesn't declare {at} olyasmit nevez meg vagy fordít, amit a manifest nem deklarál @msg command {name} is declared twice a(z) {name} parancs kétszer van deklarálva @msg command {name}: `label` must be 1-64 printable characters {name} parancs: a `label` 1-64 nyomtatható karakter legyen @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} parancs: használj 1-{MAX_COMMAND_ID} karakteres, a-z 0-9 _ karakterekből álló, betűvel kezdődő azonosítót diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b7227a3c2a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -594,6 +594,11 @@ @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” tidak diberi `{p}`, yang diperlukan keluarannya: tidak ada yang diubah @msg a heavy filter runs in the background, so it can't declare `commands` filter berat berjalan di latar belakang, sehingga tidak dapat mendeklarasikan `commands` @msg at most {MAX_COMMANDS} `commands` paling banyak {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` memberikan paling banyak {MAX_LANGUAGES} bahasa +@msg {at} gives two options the same label {at} memberikan label yang sama untuk dua opsi +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} bukan kode bahasa seperti `de` atau `pt-BR`, atau mengulang kode yang diberikan sebelumnya +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} harus berisi 1-{max} karakter yang dapat dicetak, tanpa karakter arah atau pemisah baris +@msg {at} names or translates something the manifest doesn't declare {at} menamai atau menerjemahkan sesuatu yang tidak dideklarasikan manifes @msg command {name} is declared twice perintah {name} dideklarasikan dua kali @msg command {name}: `label` must be 1-64 printable characters perintah {name}: `label` harus berupa 1-64 karakter yang dapat dicetak @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter perintah {name}: gunakan id sepanjang 1-{MAX_COMMAND_ID} karakter dari a-z 0-9 _ yang diawali huruf @@ -7381,6 +7386,7 @@ axis Y Axis Sumbu Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instal “{name}”, yang meminta izin berikut? ID: {id} ID: {id} + Manifest name: {name} Nama di manifes: {name} Version: {version} Versi: {version} Install “{name}” in place of the plug-in with the same ID? Instal “{name}” sebagai pengganti plug-in dengan ID yang sama? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. File ini bukan plug-in yang sebelumnya diinstal dengan ID ini. File ini mendapatkan pengaturan dan cache yang disimpan untuk ID tersebut. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..e3748e5199 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7059,6 +7059,7 @@ axis Y Axis Asse Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installare “{name}”, che chiede queste autorizzazioni? ID: {id} ID: {id} + Manifest name: {name} Nome nel manifest: {name} Version: {version} Versione: {version} Install “{name}” in place of the plug-in with the same ID? Installare “{name}” al posto del plug-in con lo stesso ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Questo file non è il plug-in installato prima con questo ID. Riceve le impostazioni e la cache conservate per quell’ID. @@ -7122,6 +7123,11 @@ axis Y Axis Asse Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” non è stata concessa `{p}`, che serve al suo risultato: non è stato modificato nulla @msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesante viene eseguito in background, quindi non può dichiarare `commands` @msg at most {MAX_COMMANDS} `commands` al massimo {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` indica al massimo {MAX_LANGUAGES} lingue +@msg {at} gives two options the same label {at} dà la stessa etichetta a due opzioni +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} non è un codice di lingua come `de` o `pt-BR`, o ripete uno indicato prima +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve avere 1-{max} caratteri stampabili, senza caratteri di direzione o separatori di riga +@msg {at} names or translates something the manifest doesn't declare {at} nomina o traduce qualcosa che il manifest non dichiara @msg command {name} is declared twice il comando {name} è dichiarato due volte @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve avere 1-64 caratteri stampabili @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id di 1-{MAX_COMMAND_ID} caratteri tra a-z 0-9 _ che inizi con una lettera diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..35d55b2518 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7134,6 +7134,7 @@ axis Y Axis Y 軸 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? これらの権限を求める「{name}」をインストールしますか? ID: {id} ID: {id} + Manifest name: {name} マニフェストの名前: {name} Version: {version} バージョン: {version} Install “{name}” in place of the plug-in with the same ID? 同じ ID のプラグインの代わりに「{name}」をインストールしますか? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. このファイルは、以前にこの ID でインストールされていたプラグインではありません。この ID 用に保持されている設定とキャッシュを引き継ぎます。 @@ -7197,6 +7198,11 @@ axis Y Axis Y 軸 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」には出力に必要な `{p}` が付与されていません。何も変更されませんでした @msg a heavy filter runs in the background, so it can't declare `commands` 重いフィルターはバックグラウンドで実行されるため、`commands` を宣言できません @msg at most {MAX_COMMANDS} `commands` `commands` は最大 {MAX_COMMANDS} 個です +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` に指定できる言語は最大 {MAX_LANGUAGES} 個です +@msg {at} gives two options the same label {at} で 2 つの選択肢に同じラベルが付いています +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} は `de` や `pt-BR` のような言語コードではないか、前に指定したコードの繰り返しです +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} は方向制御文字や行区切り文字を含まない 1-{max} 文字の印字可能な文字にしてください +@msg {at} names or translates something the manifest doesn't declare {at} はマニフェストで宣言されていないものを指定または翻訳しています @msg command {name} is declared twice コマンド {name} が 2 回宣言されています @msg command {name}: `label` must be 1-64 printable characters コマンド {name}: `label` は印刷可能な 1-64 文字にしてください @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter コマンド {name}: a-z 0-9 _ からなり英字で始まる 1-{MAX_COMMAND_ID} 文字の ID を使用してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..3e78f5a722 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9540,6 +9540,7 @@ axis Y Axis Y ღერძი # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? დავაყენოთ „{name}“, რომელიც ამ ნებართვებს ითხოვს? ID: {id} ID: {id} + Manifest name: {name} სახელი მანიფესტში: {name} Version: {version} ვერსია: {version} Install “{name}” in place of the plug-in with the same ID? დავაყენოთ „{name}“ იმავე ID-ის მქონე პლაგინის ნაცვლად? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. ეს ფაილი არ არის ამ ID-ით ადრე დაყენებული პლაგინი. ის მიიღებს ამ ID-სთვის შენახულ პარამეტრებს და ქეშს. @@ -9603,6 +9604,11 @@ axis Y Axis Y ღერძი @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“-ს არ მიეცა `{p}`, რომელიც მის შედეგს სჭირდება: არაფერი შეცვლილა @msg a heavy filter runs in the background, so it can't declare `commands` მძიმე ფილტრი ფონურ რეჟიმში მუშაობს, ამიტომ მას არ შეუძლია `commands`-ის გამოცხადება @msg at most {MAX_COMMANDS} `commands` მაქსიმუმ {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` იძლევა მაქსიმუმ {MAX_LANGUAGES} ენას +@msg {at} gives two options the same label {at} ორ ვარიანტს ერთსა და იმავე წარწერას აძლევს +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} არ არის ენის კოდი, როგორიცაა `de` ან `pt-BR`, ან იმეორებს ადრე მოცემულ კოდს +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} უნდა იყოს 1-{max} დასაბეჭდი სიმბოლო, მიმართულების და ხაზის გამყოფი სიმბოლოების გარეშე +@msg {at} names or translates something the manifest doesn't declare {at} ასახელებს ან თარგმნის რაღაცას, რასაც მანიფესტი არ აცხადებს @msg command {name} is declared twice ბრძანება {name} ორჯერაა გამოცხადებული @msg command {name}: `label` must be 1-64 printable characters ბრძანება {name}: `label` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ბრძანება {name}: გამოიყენეთ 1-{MAX_COMMAND_ID} სიმბოლოიანი id a-z 0-9 _ სიმბოლოებიდან, რომელიც ასოთი იწყება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..ff523d1e27 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7031,6 +7031,7 @@ axis Y Axis Y축 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 이 권한을 요청하는 “{name}”을(를) 설치하시겠습니까? ID: {id} ID: {id} + Manifest name: {name} 매니페스트의 이름: {name} Version: {version} 버전: {version} Install “{name}” in place of the plug-in with the same ID? 같은 ID의 플러그인 대신 “{name}”을(를) 설치하시겠습니까? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 이 파일은 이전에 이 ID로 설치된 플러그인이 아닙니다. 이 ID에 보관된 설정과 캐시를 받습니다. @@ -7094,6 +7095,11 @@ axis Y Axis Y축 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”에 출력에 필요한 `{p}` 권한이 부여되지 않았습니다. 아무것도 변경되지 않았습니다 @msg a heavy filter runs in the background, so it can't declare `commands` 무거운 필터는 백그라운드에서 실행되므로 `commands`를 선언할 수 없습니다 @msg at most {MAX_COMMANDS} `commands` `commands`는 최대 {MAX_COMMANDS}개입니다 +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations`에는 언어를 최대 {MAX_LANGUAGES}개까지 지정할 수 있습니다 +@msg {at} gives two options the same label {at}에서 두 옵션에 같은 레이블을 지정했습니다 +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}은(는) `de`나 `pt-BR` 같은 언어 코드가 아니거나 앞에서 지정한 코드를 반복합니다 +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}은(는) 방향 문자나 줄 구분 문자 없이 인쇄 가능한 문자 1-{max}자여야 합니다 +@msg {at} names or translates something the manifest doesn't declare {at}은(는) 매니페스트가 선언하지 않은 항목을 지정하거나 번역합니다 @msg command {name} is declared twice 명령 {name}이(가) 두 번 선언되었습니다 @msg command {name}: `label` must be 1-64 printable characters 명령 {name}: `label`은 인쇄 가능한 문자 1-64자여야 합니다 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 명령 {name}: a-z 0-9 _로 이루어지고 문자로 시작하는 1-{MAX_COMMAND_ID}자 ID를 사용하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..647178e610 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -558,6 +558,11 @@ liquify-list-end {0}, {1} {0} en {1} @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” heeft `{p}` niet gekregen, wat de uitvoer ervan nodig heeft: er is niets gewijzigd @msg a heavy filter runs in the background, so it can't declare `commands` een zwaar filter wordt op de achtergrond uitgevoerd, dus kan het geen `commands` declareren @msg at most {MAX_COMMANDS} `commands` maximaal {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` geeft maximaal {MAX_LANGUAGES} talen +@msg {at} gives two options the same label {at} geeft twee opties hetzelfde label +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} is geen taalcode zoals `de` of `pt-BR`, of herhaalt een eerder gegeven code +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} moet 1-{max} afdrukbare tekens zijn, zonder richtings- of regelscheidingstekens +@msg {at} names or translates something the manifest doesn't declare {at} noemt of vertaalt iets wat het manifest niet declareert @msg command {name} is declared twice opdracht {name} is twee keer gedeclareerd @msg command {name}: `label` must be 1-64 printable characters opdracht {name}: `label` moet uit 1-64 afdrukbare tekens bestaan @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter opdracht {name}: gebruik een id van 1-{MAX_COMMAND_ID} tekens uit a-z 0-9 _ die met een letter begint @@ -9434,6 +9439,7 @@ axis Y Axis Y-as # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? „{name}” installeren, dat om deze machtigingen vraagt? ID: {id} ID: {id} + Manifest name: {name} Naam in het manifest: {name} Version: {version} Versie: {version} Install “{name}” in place of the plug-in with the same ID? „{name}” installeren in plaats van de plug-in met dezelfde ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Dit bestand is niet de plug-in die eerder met deze ID was geïnstalleerd. Het krijgt de instellingen en cache die voor die ID bewaard zijn. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..0c6e487cfa 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7292,6 +7292,7 @@ axis Y Axis Oś Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Zainstalować „{name}”, wtyczkę, która prosi o te uprawnienia? ID: {id} ID: {id} + Manifest name: {name} Nazwa w manifeście: {name} Version: {version} Wersja: {version} Install “{name}” in place of the plug-in with the same ID? Zainstalować „{name}” zamiast wtyczki o tym samym ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ten plik nie jest wtyczką zainstalowaną wcześniej z tym ID. Otrzyma ustawienia i pamięć podręczną przechowywane dla tego ID. @@ -7355,6 +7356,11 @@ axis Y Axis Oś Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” nie otrzymała `{p}`, którego potrzebuje jej wynik: nic nie zmieniono @msg a heavy filter runs in the background, so it can't declare `commands` ciężki filtr działa w tle, więc nie może deklarować `commands` @msg at most {MAX_COMMANDS} `commands` najwyżej {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` podaje najwyżej {MAX_LANGUAGES} języków +@msg {at} gives two options the same label {at} nadaje dwóm opcjom tę samą etykietę +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nie jest kodem języka takim jak `de` czy `pt-BR` albo powtarza kod podany wcześniej +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musi mieć 1-{max} drukowalnych znaków, bez znaków kierunku tekstu i separatorów wierszy +@msg {at} names or translates something the manifest doesn't declare {at} nazywa lub tłumaczy coś, czego manifest nie deklaruje @msg command {name} is declared twice polecenie {name} jest zadeklarowane dwa razy @msg command {name}: `label` must be 1-64 printable characters polecenie {name}: `label` musi mieć 1-64 drukowalnych znaków @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter polecenie {name}: użyj id z 1-{MAX_COMMAND_ID} znaków spośród a-z 0-9 _, zaczynającego się od litery diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..59a2544240 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7336,6 +7336,7 @@ axis Y Axis Eixo Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instalar “{name}”, que pede estas permissões? ID: {id} ID: {id} + Manifest name: {name} Nome no manifesto: {name} Version: {version} Versão: {version} Install “{name}” in place of the plug-in with the same ID? Instalar “{name}” no lugar do plug-in com o mesmo ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este arquivo não é o plug-in instalado antes com este ID. Ele recebe as configurações e o cache guardados para esse ID. @@ -7399,6 +7400,11 @@ axis Y Axis Eixo Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” não recebeu `{p}`, de que sua saída precisa: nada foi alterado @msg a heavy filter runs in the background, so it can't declare `commands` um filtro pesado é executado em segundo plano, então não pode declarar `commands` @msg at most {MAX_COMMANDS} `commands` no máximo {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dá no máximo {MAX_LANGUAGES} idiomas +@msg {at} gives two options the same label {at} dá o mesmo rótulo a duas opções +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} não é um código de idioma como `de` ou `pt-BR`, ou repete um dado antes +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve ter 1-{max} caracteres imprimíveis, sem caracteres de direção ou separadores de linha +@msg {at} names or translates something the manifest doesn't declare {at} nomeia ou traduz algo que o manifesto não declara @msg command {name} is declared twice o comando {name} está declarado duas vezes @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve ter 1-64 caracteres imprimíveis @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: use um id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que comece com uma letra diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..bd75d9b29d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7059,6 +7059,7 @@ axis Y Axis Ось Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Установить «{name}», которому нужны эти разрешения? ID: {id} ID: {id} + Manifest name: {name} Имя в манифесте: {name} Version: {version} Версия: {version} Install “{name}” in place of the plug-in with the same ID? Установить «{name}» вместо модуля с тем же ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Этот файл не является модулем, установленным ранее с этим ID. Он получит настройки и кэш, сохранённые для этого ID. @@ -7122,6 +7123,11 @@ axis Y Axis Ось Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не получил разрешение `{p}`, нужное для его результата: ничего не изменено @msg a heavy filter runs in the background, so it can't declare `commands` тяжёлый фильтр выполняется в фоне, поэтому не может объявлять `commands` @msg at most {MAX_COMMANDS} `commands` не более {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задаёт не более {MAX_LANGUAGES} языков +@msg {at} gives two options the same label {at} даёт двум вариантам одинаковую подпись +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не является кодом языка вроде `de` или `pt-BR` или повторяет код, заданный ранее +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} должен содержать 1-{max} печатных символов без символов направления текста и разделителей строк +@msg {at} names or translates something the manifest doesn't declare {at} называет или переводит то, что манифест не объявляет @msg command {name} is declared twice команда {name} объявлена дважды @msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` должен содержать 1-64 печатаемых символа @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: используйте id из 1-{MAX_COMMAND_ID} символов a-z 0-9 _, начинающийся с буквы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..7a6a004d29 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7449,6 +7449,7 @@ axis Y Axis Y-axel # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installera ”{name}”, som begär dessa behörigheter? ID: {id} ID: {id} + Manifest name: {name} Namn i manifestet: {name} Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? Installera ”{name}” i stället för det plugin som har samma id? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Den här filen är inte det plugin som tidigare installerades med detta id. Den får de inställningar och den cache som sparats för detta id. @@ -7508,6 +7509,11 @@ axis Y Axis Y-axel @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” beviljades inte `{p}`, som dess utdata behöver: ingenting ändrades @msg a heavy filter runs in the background, so it can't declare `commands` ett tungt filter körs i bakgrunden, så det kan inte deklarera `commands` @msg at most {MAX_COMMANDS} `commands` högst {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` anger högst {MAX_LANGUAGES} språk +@msg {at} gives two options the same label {at} ger två alternativ samma etikett +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} är inte en språkkod som `de` eller `pt-BR`, eller upprepar en som angetts tidigare +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} måste vara 1-{max} utskrivbara tecken, utan riktnings- eller radavgränsartecken +@msg {at} names or translates something the manifest doesn't declare {at} namnger eller översätter något som manifestet inte deklarerar @msg command {name} is declared twice kommandot {name} deklareras två gånger @msg command {name}: `label` must be 1-64 printable characters kommando {name}: `label` måste ha 1-64 utskrivbara tecken @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommando {name}: använd ett id med 1-{MAX_COMMAND_ID} tecken av a-z 0-9 _ som börjar med en bokstav diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..e256c8ee68 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7509,6 +7509,7 @@ axis Y Axis Y ekseni # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Bu izinleri isteyen “{name}” yüklensin mi? ID: {id} Kimlik: {id} + Manifest name: {name} Manifestteki ad: {name} Version: {version} Sürüm: {version} Install “{name}” in place of the plug-in with the same ID? Aynı kimliğe sahip eklentinin yerine “{name}” yüklensin mi? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Bu dosya, daha önce bu kimlikle yüklenen eklenti değil. O kimlik için saklanan ayarları ve önbelleği alır. @@ -7572,6 +7573,11 @@ axis Y Axis Y ekseni @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” öğesine çıktısının ihtiyaç duyduğu `{p}` izni verilmedi: hiçbir şey değiştirilmedi @msg a heavy filter runs in the background, so it can't declare `commands` ağır bir filtre arka planda çalışır, bu yüzden `commands` bildiremez @msg at most {MAX_COMMANDS} `commands` en fazla {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` en fazla {MAX_LANGUAGES} dil verir +@msg {at} gives two options the same label {at} iki seçeneğe aynı etiketi veriyor +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}, `de` veya `pt-BR` gibi bir dil kodu değil ya da daha önce verilmiş bir kodu yineliyor +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}, yön veya satır ayırıcı karakterleri olmadan 1-{max} yazdırılabilir karakter olmalıdır +@msg {at} names or translates something the manifest doesn't declare {at}, manifestin bildirmediği bir şeyi adlandırıyor veya çeviriyor @msg command {name} is declared twice {name} komutu iki kez bildirilmiş @msg command {name}: `label` must be 1-64 printable characters {name} komutu: `label` 1-64 yazdırılabilir karakter olmalıdır @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} komutu: a-z 0-9 _ karakterlerinden oluşan ve harfle başlayan 1-{MAX_COMMAND_ID} karakterlik bir kimlik kullanın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..fdcf7c5894 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7041,6 +7041,7 @@ axis Y Axis Вісь Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Встановити «{name}», якому потрібні ці дозволи? ID: {id} ID: {id} + Manifest name: {name} Назва в маніфесті: {name} Version: {version} Версія: {version} Install “{name}” in place of the plug-in with the same ID? Встановити «{name}» замість модуля з тим самим ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Цей файл не є модулем, установленим раніше з цим ID. Він отримає налаштування й кеш, збережені для цього ID. @@ -7104,6 +7105,11 @@ axis Y Axis Вісь Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не отримав дозволу `{p}`, потрібного для його результату: нічого не змінено @msg a heavy filter runs in the background, so it can't declare `commands` важкий фільтр виконується у фоні, тому не може оголошувати `commands` @msg at most {MAX_COMMANDS} `commands` щонайбільше {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задає щонайбільше {MAX_LANGUAGES} мов +@msg {at} gives two options the same label {at} дає двом варіантам однаковий підпис +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не є кодом мови на кшталт `de` чи `pt-BR` або повторює код, заданий раніше +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} має містити 1-{max} друкованих символів без символів напрямку тексту й розділювачів рядків +@msg {at} names or translates something the manifest doesn't declare {at} називає або перекладає те, чого маніфест не оголошує @msg command {name} is declared twice команду {name} оголошено двічі @msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` має містити 1-64 друковані символи @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: використайте id з 1-{MAX_COMMAND_ID} символів a-z 0-9 _, що починається з літери diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..72dd7e49a2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7088,6 +7088,7 @@ axis Y Axis Trục Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Cài đặt “{name}”, plug-in yêu cầu các quyền này? ID: {id} ID: {id} + Manifest name: {name} Tên trong manifest: {name} Version: {version} Phiên bản: {version} Install “{name}” in place of the plug-in with the same ID? Cài đặt “{name}” thay cho plug-in có cùng ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tệp này không phải là plug-in đã cài đặt trước đây với ID này. Tệp sẽ nhận cài đặt và bộ nhớ đệm được lưu cho ID đó. @@ -7151,6 +7152,11 @@ axis Y Axis Trục Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” chưa được cấp `{p}`, quyền mà đầu ra của nó cần: không có gì thay đổi @msg a heavy filter runs in the background, so it can't declare `commands` bộ lọc nặng chạy ở chế độ nền nên không thể khai báo `commands` @msg at most {MAX_COMMANDS} `commands` tối đa {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` chỉ định tối đa {MAX_LANGUAGES} ngôn ngữ +@msg {at} gives two options the same label {at} đặt cùng một nhãn cho hai tùy chọn +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} không phải mã ngôn ngữ như `de` hoặc `pt-BR`, hoặc lặp lại mã đã cho trước đó +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} phải có 1-{max} ký tự in được, không có ký tự định hướng hoặc ký tự phân cách dòng +@msg {at} names or translates something the manifest doesn't declare {at} đặt tên hoặc dịch một thứ mà manifest không khai báo @msg command {name} is declared twice lệnh {name} được khai báo hai lần @msg command {name}: `label` must be 1-64 printable characters lệnh {name}: `label` phải có 1-64 ký tự in được @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter lệnh {name}: hãy dùng id gồm 1-{MAX_COMMAND_ID} ký tự từ a-z 0-9 _ và bắt đầu bằng một chữ cái diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..c563337d66 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7269,6 +7269,7 @@ axis Y Axis Y 轴 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 要安装需要这些权限的“{name}”吗? ID: {id} ID:{id} + Manifest name: {name} 清单中的名称:{name} Version: {version} 版本:{version} Install “{name}” in place of the plug-in with the same ID? 要安装“{name}”来替换具有相同 ID 的插件吗? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此文件不是之前以此 ID 安装的插件。它将获得为该 ID 保存的设置和缓存。 @@ -7332,6 +7333,11 @@ axis Y Axis Y 轴 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”未获授予其输出所需的 `{p}`:未作任何更改 @msg a heavy filter runs in the background, so it can't declare `commands` 重型滤镜在后台运行,因此不能声明 `commands` @msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 个 `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多给出 {MAX_LANGUAGES} 种语言 +@msg {at} gives two options the same label {at} 为两个选项给出了相同的标签 +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 这样的语言代码,或重复了前面给出的代码 +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必须为 1-{max} 个可打印字符,且不含方向字符或行分隔符 +@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻译了清单未声明的内容 @msg command {name} is declared twice 命令 {name} 声明了两次 @msg command {name}: `label` must be 1-64 printable characters 命令 {name}:`label` 必须是 1-64 个可打印字符 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 命令 {name}:请使用由 a-z 0-9 _ 组成、以字母开头的 1-{MAX_COMMAND_ID} 个字符的 ID diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..5b9ce67800 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7090,6 +7090,7 @@ axis Y Axis Y 軸 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 要安裝需要這些權限的「{name}」嗎? ID: {id} ID:{id} + Manifest name: {name} 資訊清單中的名稱:{name} Version: {version} 版本:{version} Install “{name}” in place of the plug-in with the same ID? 要安裝「{name}」來取代具有相同 ID 的增效模組嗎? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此檔案不是先前以此 ID 安裝的增效模組。它會取得為該 ID 保存的設定和快取。 @@ -7153,6 +7154,11 @@ axis Y Axis Y 軸 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」未獲授予其輸出所需的 `{p}`:未做任何變更 @msg a heavy filter runs in the background, so it can't declare `commands` 重型濾鏡在背景執行,因此不能宣告 `commands` @msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 個 `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多提供 {MAX_LANGUAGES} 種語言 +@msg {at} gives two options the same label {at} 為兩個選項提供了相同的標籤 +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 這類語言代碼,或重複了前面提供的代碼 +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必須為 1-{max} 個可列印字元,且不含方向字元或行分隔字元 +@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻譯了資訊清單未宣告的內容 @msg command {name} is declared twice 指令 {name} 宣告了兩次 @msg command {name}: `label` must be 1-64 printable characters 指令 {name}:`label` 必須是 1-64 個可列印字元 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 指令 {name}:請使用由 a-z 0-9 _ 組成、以字母開頭的 1-{MAX_COMMAND_ID} 個字元的 ID diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..63c2e82b15 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -279,12 +279,25 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result Result Option { Some(text) } +/// The name Last Effect gives effect `e`: its Effect menu label, a plug-in's name in the UI language +/// as Effect › Plug-ins shows it ([`crate::dialogs::plugin::effect_item_label`]). +fn last_effect_name(e: &str) -> &str { + vectorcraft_effects::effect_info(e).map(|i| crate::dialogs::plugin::effect_item_label(&i)).unwrap_or(e) +} + /// The labels that follow the last effect, the envelope being edited, the history and the perspective grid. fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option { let text: String = match id { "effect.last" => match &app.last_effect { - Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), + Some((e, _)) => format!("Last Effect: {}", last_effect_name(e)), None => label.into(), }, // Edit Contents reads Edit Envelope while an envelope's contents are being edited. @@ -151,7 +157,8 @@ pub(crate) fn shows_a_name(id: &str, label: &str) -> bool { ) || vectorcraft_engine::cmd::plugin::is_command_id(id) || (id == "window.workspace" && !crate::workspaces::is_builtin(label)) - || (matches!(id, "effect.apply" | "effect.dialog") && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label)) + || (matches!(id, "effect.apply" | "effect.dialog") + && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label || crate::dialogs::plugin::effect_item_label(e) == label)) } /// Does the menu item `id` with `params` list an installed plug-in (an Object › Plug-ins filter, an @@ -187,7 +194,7 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } "effect.last" => match &app.last_effect { Some((e, _)) => { - let name = vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str()); + let name = last_effect_name(e); fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) } None => crate::i18n::tr_id(lang, id, label).to_string(), diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..eabb023ad4 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -106,6 +106,9 @@ struct Draft { label: String, /// Does the label translate? An installed filter plug-in's name does not. translates: bool, + /// Is this a plug-in command, whose label and plug-in name come from the plug-in's own + /// translations? + plugin_command: bool, id: String, shortcut: String, /// Has [`distinct_names`] given the result its [`context`]? @@ -120,6 +123,7 @@ impl Draft { path: path.to_string(), label: label.to_string(), translates: true, + plugin_command: false, id, shortcut: shortcut.to_string(), in_context: false, @@ -130,6 +134,20 @@ impl Draft { /// The name in `lang`: the path's segments and the label translate on their own, and the id /// follows in parentheses when the result shows it. fn name(&self, lang: crate::i18n::Lang) -> String { + // A plug-in command shows its label and its plug-in's name as its menu item does. + if self.plugin_command + && let Some((plugin, command)) = vectorcraft_engine::cmd::plugin::command_of(&self.id) + { + let m = plugin.manifest(); + let path = if self.in_context { + shown_label(lang, &self.path) + } else { + let top = self.path.rsplit_once(" › ").map_or("", |(top, _)| top); + format!("{} › {}", shown_label(lang, top), m.shown_name(lang.code())) + }; + let name = format!("{path} › {}", m.shown_command_label(&command, lang.code())); + return if self.keyed { format!("{name} ({})", self.id) } else { name }; + } // A built-in effect's label translates by its effect id first, as the Effect menu's does. let label = match self.id.strip_prefix("effect:") { _ if !self.translates => self.label.as_str(), @@ -158,9 +176,13 @@ fn drafts() -> Vec { && !ui_ids.contains(c.id) && (!crate::shortcut_editor::needs_a_value(c.id) || PICK_RUNS.contains(&c.id)) }; - for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c)).chain(plugin_commands) { + for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c)) { out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or(""))); } + for c in plugin_commands { + let draft = Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or("")); + out.push(Draft { plugin_command: true, ..draft }); + } // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of // the Scripts folder runs from File › Scripts, by its path. A UI command that wraps an engine // command, or has an engine command's id, takes that command's menu path, so a search for the @@ -266,9 +288,10 @@ fn distinct_names(drafts: &mut [Draft], langs: &[crate::i18n::Lang]) { } /// A palette label in `lang`: each `›`-separated menu segment and the command label translate on -/// their own. +/// their own, except a plug-in's name and items after Object › Plug-ins or Effect › Plug-ins +/// ([`crate::dialogs::plugin::translate_path`]). fn shown_label(lang: crate::i18n::Lang, label: &str) -> String { - label.split(" › ").map(|s| crate::i18n::tr(lang, s)).collect::>().join(" › ") + crate::dialogs::plugin::translate_path(label, |s| crate::i18n::tr(lang, s)) } /// The label of the item of the menu bar that runs `e`, in `lang`, as the menu bar draws it @@ -3259,6 +3282,46 @@ mod tests { vectorcraft_plugins::registry::remove(two); } + /// A plug-in command's result shows its label and its plug-in's name in the language the + /// plug-in translates them into, and the manifest's own text in a language it doesn't. + #[test] + fn a_plugin_command_result_shows_the_plugins_translation() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_translated"; + let manifest = format!( + r#"{{"id":"{id}","name":"Tidy","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Grow"}}], + "translations":{{"de":{{"name":"Aufräumen","commands":{{"grow":{{"label":"Wachsen"}}}}}}}}}}"# + ); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let key = format!("plugin.{id}.grow"); + let shown = |code: &str| { + let lang = Lang::from_code(code).unwrap(); + build(lang).into_iter().find(|e| e.id == key).map(|e| (e.shown, crate::i18n::tr(lang, "Object"), crate::i18n::tr(lang, "Plug-ins"))) + }; + let (de, fr) = (shown("de"), shown("fr")); + vectorcraft_plugins::registry::remove(id); + let (de, object, plugins) = de.expect("the command is a result"); + assert_eq!(de, format!("{object} › {plugins} › Aufräumen › Wachsen")); + let (fr, object, plugins) = fr.expect("the command is a result"); + assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); + } + + /// A plug-in's name in the path of its own item, in the submenu a plug-in with commands gets, + /// stays as the plug-in gives it where it matches text the app translates ("Open" in German). + #[test] + fn a_plugin_submenu_name_is_not_translated_by_the_app() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_submenu_name"; + let manifest = format!(r#"{{"id":"{id}","name":"Open","version":"1","kind":"filter","commands":[{{"id":"go","label":"Go"}}]}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let de = Lang::from_code("de").unwrap(); + let shown = build(de).into_iter().find(|e| e.id == format!("plugin:{id}")).map(|e| e.shown); + vectorcraft_plugins::registry::remove(id); + assert_ne!(crate::i18n::tr(de, "Open"), "Open", "German translates the app's Open"); + let path = format!("{} › {}", crate::i18n::tr(de, "Object"), crate::i18n::tr(de, "Plug-ins")); + assert_eq!(shown, Some(format!("{path} › Open › Open"))); + } + /// Of the engine commands the palette listed before, it leaves out only the ones /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 52b36b4535..4c7b0a345a 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -243,11 +243,12 @@ fn built_in_effect(id: &str) -> bool { } /// [`effect_label`] as shown: a built-in effect's in the UI language (an `@id` row for the -/// effect's id wins over the plain row of its English label), a plug-in's as it is. +/// effect's id wins over the plain row of its English label), a plug-in's by the name the plug-in +/// gives in the UI language ([`crate::dialogs::plugin::effect_name`]). pub(crate) fn shown_effect_label(id: &str) -> String { match catalog().iter().find(|c| c.0 == id) { Some(c) => crate::i18n::t_id(id, &c.1).to_string(), - None => effect_label(id), + None => crate::dialogs::plugin::effect_name(id).unwrap_or_else(|| effect_label(id)), } } @@ -1396,10 +1397,14 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } let ui_keys = manifest.and_then(|m| m.param(key)).map(|p| &p.ui); ui.horizontal(|ui| { - let label = ui_keys.and_then(|u| u.label.clone()).unwrap_or_else(|| param_label(key, built_in)); + // A plug-in's label and help in the UI language, escaped as its dialog shows them. + let label = manifest.and_then(|m| crate::dialogs::form::plugin_param_label(m, key)).unwrap_or_else(|| param_label(key, built_in)); let label_node = ui.add_sized(vec2(84.0, 22.0), egui::Label::new(egui::RichText::new(label.as_str()).size(11.5).color(t.text)).truncate()); - let label_node = if let Some(help) = ui_keys.and_then(|u| u.help.as_deref()) { label_node.on_hover_text(help) } else { label_node }; + let label_node = match manifest.and_then(|m| crate::dialogs::form::plugin_param_help(m, key)) { + Some(help) => label_node.on_hover_text(help), + None => label_node, + }; // The row's actual label node names its fields, including a plug-in's plain text // and number fields (egui 0.37's strict a11y gate). ui.label_inputs_by(label_node.id, |ui| { @@ -1815,8 +1820,11 @@ fn delete_selected(app: &mut VectorcraftApp, ui: &Ui, node: Option<&Node>, sel: /// opens the effect dialog. pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut groups: Vec<(String, Vec<(String, String)>)> = vec![]; - let plugins: Vec<_> = vectorcraft_effects::plugin_effects().into_iter().map(catalog_entry).collect(); - // Built-in effects in the UI language; a plug-in's by the name it gives. + let plugins: Vec<_> = vectorcraft_effects::plugin_effects() + .into_iter() + .map(|e| (e.id.to_string(), crate::dialogs::plugin::effect_item_label(&e).trim_end_matches('…').to_string(), catalog_entry(e).2)) + .collect(); + // Built-in effects in the UI language; a plug-in's by the name it gives in it. let built_in = catalog().iter().map(|(id, label, menu)| (id, tl!(label), menu)); for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.as_str(), menu))) { let g = menu.get(1).cloned().unwrap_or_else(|| "Other".into()); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a9d7b022a7..bf1471df25 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -385,15 +385,20 @@ pub struct Entry { pub(crate) struct Snapshot { /// The plug-in revision read before the menus were walked. pub revision: u64, + /// The UI language the menus were walked in, which names plug-in items in a plug-in's own + /// translations. + pub lang: &'static str, pub effects: Arc<[EffectItem]>, pub filters: Arc<[FilterItem]>, pub entries: Arc<[Entry]>, } /// The entries for the plug-ins installed now: rebuilt when a plug-in is installed or removed, so -/// a live-effect or filter plug-in installed later has its row, and one removed has none. +/// a live-effect or filter plug-in installed later has its row, and one removed has none, and when +/// the UI language changes, so plug-in items show the plug-in's text in it. pub(crate) fn snapshot() -> Arc { static LAST: Mutex>> = Mutex::new(None); + let lang = crate::i18n::current().code(); let mut revision = menus::plugin_revision(); let last = LAST.lock().unwrap_or_else(|e| e.into_inner()).clone(); // A test's walk hook runs even when a snapshot of this revision is already stored. @@ -406,13 +411,13 @@ pub(crate) fn snapshot() -> Arc { }; #[cfg(not(test))] let hooked = false; - if let Some(s) = last.filter(|s| s.revision == revision && !hooked) { + if let Some(s) = last.filter(|s| s.revision == revision && s.lang == lang && !hooked) { return s; } // When a plug-in is installed or removed during the walk, the entries may not match // `revision`, and the keymap cached for it would lack rows or hold extra ones. The menus are // walked again at the new revision, and a snapshot that still doesn't match is not cached. - let mut s = build_snapshot(revision); + let mut s = build_snapshot(revision, lang); for _ in 0..8 { let now = menus::plugin_revision(); if now == revision { @@ -424,13 +429,14 @@ pub(crate) fn snapshot() -> Arc { return s; } revision = now; - s = build_snapshot(revision); + s = build_snapshot(revision, lang); } s } -/// The snapshot of the menus as they are now, under plug-in revision `revision`. -fn build_snapshot(revision: u64) -> Arc { +/// The snapshot of the menus as they are now, under plug-in revision `revision`, walked in UI +/// language `lang`. +fn build_snapshot(revision: u64, lang: &'static str) -> Arc { // Built without the lock held: the Effect menu is walked anew. #[cfg(test)] if let Some(f) = tests::WHILE_WALKING.take() { @@ -456,17 +462,22 @@ fn build_snapshot(revision: u64) -> Arc { is_tool: false, shows_key: false, })) - .chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| Entry { - key: c.id.into(), - label: c.label.into(), - group: c.menu.join(" › "), - is_tool: false, - shows_key: false, + .chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| { + // A plug-in command's label and its plug-in's name in `lang`, as its menu shows them. + let (label, group) = match vectorcraft_engine::cmd::plugin::command_of(c.id) { + Some((plugin, command)) => { + let m = plugin.manifest(); + let path: Vec = c.menu.iter().take(2).map(|s| s.to_string()).chain([m.shown_name(lang)]).collect(); + (m.shown_command_label(&command, lang), path.join(" › ")) + } + None => (c.label.to_string(), c.menu.join(" › ")), + }; + Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false } })) .chain(tail.iter().cloned()) .collect(); distinct_names(&mut entries); - Arc::new(Snapshot { revision, effects, filters, entries: entries.into() }) + Arc::new(Snapshot { revision, lang, effects, filters, entries: entries.into() }) } /// Every tool, command and panel the editor can give a shortcut; [`listed`] says which it lists. @@ -647,15 +658,19 @@ pub fn filter_shortcut(id: &str) -> Option<&'static str> { effective(&format!("plugin:{id}")) } -/// Entry `e`'s label in the UI language. A plug-in's own name is not translated. +/// Entry `e`'s label in the UI language. A plug-in's own name and its commands' labels, already in +/// the UI language from the plug-in's translations, are not translated again. pub(crate) fn shown_label(e: &Entry) -> &str { - let plugin = e.key.starts_with("plugin:") || e.key.strip_prefix("effect:").and_then(vectorcraft_plugins::effect::plugin_id).is_some(); + let plugin = e.key.starts_with("plugin:") + || vectorcraft_engine::cmd::plugin::is_command_id(&e.key) + || e.key.strip_prefix("effect:").and_then(vectorcraft_plugins::effect::plugin_id).is_some(); if plugin { &e.label } else { tl!(&e.label) } } -/// A menu path in the UI language, one segment at a time. +/// A menu path in the UI language, one segment at a time; a plug-in's name after Object › Plug-ins +/// or Effect › Plug-ins stays as the plug-in gives it ([`crate::dialogs::plugin::translate_path`]). pub(crate) fn shown_group(group: &str) -> String { - group.split(" › ").map(|s| tl!(s)).collect::>().join(" › ") + crate::dialogs::plugin::translate_path(group, |s| tl!(s)) } /// How Keyboard Shortcuts names entry `e`: a tool by its label, the others after their menu, and diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..81046387f3 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -279,6 +279,41 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// The approval names a plug-in whose manifest translates its name in the UI language and also +/// gives the manifest's own name, both escaped; a language without a translation shows the +/// manifest's name alone. What OK installs stays bound to the id and hash shown. +#[test] +fn the_install_approval_shows_the_translated_and_the_manifests_own_name() { + let mut app = app(); + let id = "test.ui.translated_approval"; + let manifest = json!({"id": id, "name": "Tidy", "version": "1", "kind": "filter", "permissions": ["doc.read"], + "translations": {"de": {"name": "Aufräumen"}}}) + .to_string(); + let bytes = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes); + let data = vectorcraft_format::base64_encode(&bytes); + let ask = |app: &mut VectorcraftApp, lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let r = app.run("ui.installPlugin", json!({ "dataBase64": data })); + let pending = app.pending_plugin_install.as_ref().map(|p| (p.message.clone(), p.detail.clone(), p.params["hash"].clone())); + crate::i18n::set_current(crate::i18n::Lang::EN); + dialogs::cancel(app); + assert_eq!(r.unwrap()["pending"], dialogs::plugin::INSTALL_KIND); + pending.unwrap() + }; + let (message, detail, shown_hash) = ask(&mut app, "de"); + assert!(message.contains("Aufräumen") && !message.contains("Tidy"), "{message}"); + assert!(detail.contains("ID: test.ui.translated_approval"), "{detail}"); + assert!(detail.contains("Tidy"), "the manifest's own name: {detail}"); + assert!(!detail.contains("Aufräumen"), "{detail}"); + assert_eq!(shown_hash, json!(hash)); + let (message, detail, _) = ask(&mut app, "en"); + assert_eq!(message, "Install “Tidy”, which asks for these permissions?"); + assert_eq!(detail.lines().next(), Some("ID: test.ui.translated_approval")); + assert_eq!(detail.lines().nth(1), Some("Version: 1"), "no second name line: {detail}"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); +} + /// The approval's OK takes no click, Enter or Space, and a confirm installs nothing, until its /// question has been on screen for [`dialogs::plugin::APPROVAL_DELAY`]; then a click installs it. /// Cancel works on the first frame. @@ -720,3 +755,135 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// The label of each item of `items`, a submenu's as `name ›` followed by its items'. +fn menu_labels(items: &[menus::Item]) -> Vec { + items + .iter() + .flat_map(|it| match it { + menus::Item::Cmd(label, ..) | menus::Item::Header(label) => vec![label.to_string()], + menus::Item::Sub(name, children) => std::iter::once(format!("{name} ›")).chain(menu_labels(children)).collect(), + _ => Vec::new(), + }) + .collect() +} + +/// Object › Plug-ins, Effect › Plug-ins and File › Open With name a plug-in and its commands in the +/// UI language when its manifest's `translations` give them: German text in German, `pt` text for +/// Brazilian Portuguese without its own, and the manifest's own text in any other language. +#[test] +fn plugin_menus_show_the_plugins_names_in_the_ui_language() { + let mut app = app(); + let (filter, effect, importer) = ("test.ui.translated.filter", "test.ui.translated.effect", "test.ui.translated.importer"); + let translations = r#""translations":{"de":{"name":"Aufräumen","commands":{"grow":{"label":"Wachsen"}}},"pt":{"name":"Arrumar"}}"#; + let filter_manifest = format!( + r#"{{"id":"{filter}","name":"Tidy","kind":"filter","commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"bool"}}}}}}],{translations}}}"# + ); + let effect_manifest = format!( + r#"{{"id":"{effect}","name":"Wobble","kind":"effect","params":{{"on":{{"type":"bool"}}}},"translations":{{"de":{{"name":"Wackeln"}}}}}}"# + ); + let importer_manifest = + format!(r#"{{"id":"{importer}","name":"Plotter","kind":"importer","extensions":["tpx"],"translations":{{"de":{{"name":"Zeichner"}}}}}}"#); + for manifest in [filter_manifest, effect_manifest, importer_manifest] { + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + } + let shown = |lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered")); + let effects = dialogs::plugin::effect_menu().map(|m| menu_labels(&[m])).unwrap_or_default(); + let all = [menu_labels(&dialogs::plugin::object_menu()), effects, menu_labels(&dialogs::plugin::open_with_menu())].concat(); + crate::i18n::set_current(crate::i18n::Lang::EN); + all + }; + let de = shown("de"); + for label in ["Aufräumen ›", "Aufräumen", "Wachsen…", "Wackeln…", "Zeichner…"] { + assert!(de.contains(&label.to_string()), "{label} in German: {de:?}"); + } + // Other tests' plug-ins may be installed meanwhile: only this test's names are checked. + for label in ["Tidy ›", "Tidy", "Grow…", "Wobble…", "Plotter…"] { + assert!(!de.contains(&label.to_string()), "{label} in German: {de:?}"); + } + let pt_br = shown("pt-br"); + assert!(pt_br.contains(&"Arrumar ›".to_string()) && pt_br.contains(&"Grow…".to_string()), "pt, then the manifest: {pt_br:?}"); + for lang in ["en", "fr"] { + let other = shown(lang); + for label in ["Tidy ›", "Grow…", "Wobble…", "Plotter…"] { + assert!(other.contains(&label.to_string()), "{label} in {lang}: {other:?}"); + } + } + // A German item is still the plug-in's own name, not text a catalog translates, and Keyboard + // Shortcuts lists the filter and its command as the menu does, in the language it is shown in. + let grow = format!("plugin.{filter}.grow"); + let rows = |lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let names = menus::shows_a_name("effect.dialog", "Wackeln…"); + let row = |key: &str| crate::shortcut_editor::entry(key).map(|e| (e.label.clone(), e.group.clone())); + let rows = (names, row(&grow), row(&format!("plugin:{filter}"))); + crate::i18n::set_current(crate::i18n::Lang::EN); + rows + }; + let (names, command, own) = rows("de"); + assert!(names); + assert_eq!(command, Some(("Wachsen".to_string(), "Object › Plug-ins › Aufräumen".to_string()))); + assert_eq!(own.map(|r| r.0), Some("Aufräumen".to_string())); + let (_, command, _) = rows("en"); + assert_eq!(command, Some(("Grow".to_string(), "Object › Plug-ins › Tidy".to_string()))); + // Last Effect names the effect as Effect › Plug-ins does. + app.last_effect = Some((vectorcraft_plugins::effect::effect_id(effect), json!({}))); + let last = |lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let shown = (menus::display_label(&app, "effect.last", "Last Effect…"), menus::dynamic_label(&app, "effect.last", "Last Effect…")); + crate::i18n::set_current(crate::i18n::Lang::EN); + shown + }; + let (de, de_dynamic) = last("de"); + assert!(de.contains("Wackeln…") && de_dynamic == "Last Effect: Wackeln…", "{de} / {de_dynamic}"); + assert_eq!(last("en"), ("Last Effect: Wobble…".to_string(), "Last Effect: Wobble…".to_string())); + app.last_effect = None; + for id in [filter, effect, importer] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// Keyboard Shortcuts shows a plug-in command's label and its plug-in's name as the plug-in gives +/// them, even where they match text the app translates: in German, a command labeled "Open" of a +/// plug-in named "Close" keeps both, as in its menu. +#[test] +fn keyboard_shortcuts_leave_a_plugin_commands_text_as_the_plugin_gives_it() { + let mut app = app(); + let id = "test.ui.untranslated.command"; + let manifest = format!(r#"{{"id":"{id}","name":"Close","kind":"filter","commands":[{{"id":"go","label":"Open"}}]}}"#); + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let shown = crate::shortcut_editor::entry(&format!("plugin.{id}.go")).map(|e| crate::shortcut_editor::shown_name(&e)); + let expected = format!("{} › {} › Close › Open", crate::i18n::t("Object"), crate::i18n::t("Plug-ins")); + assert_ne!((crate::i18n::t("Open"), crate::i18n::t("Close")), ("Open", "Close"), "German translates both as app text"); + crate::i18n::set_current(crate::i18n::Lang::EN); + app.run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(shown, Some(expected)); +} + +/// A filter's and an importer's menu item show their names as prompts do, a right-to-left override +/// escaped, as a filter with commands already showed its submenu. +#[test] +fn plugin_menu_items_escape_bidirectional_characters() { + let mut app = app(); + let (filter, importer) = ("test.ui.bidi.filter", "test.ui.bidi.importer"); + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + for manifest in [ + format!(r#"{{"id":"{filter}","name":"Flip{rlo}txt.exe","kind":"filter"}}"#), + format!(r#"{{"id":"{importer}","name":"Read{rlo}fdp.exe","kind":"importer","extensions":["rdx"]}}"#), + ] { + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + } + let labels = [menu_labels(&dialogs::plugin::object_menu()), menu_labels(&dialogs::plugin::open_with_menu())].concat(); + assert!(labels.contains(&"Flip\\u{202E}txt.exe".to_string()), "{labels:?}"); + assert!(labels.contains(&"Read\\u{202E}fdp.exe…".to_string()), "{labels:?}"); + assert!(!labels.iter().any(|l| l.contains('\u{202E}')), "{labels:?}"); + for id in [filter, importer] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..fccfc2d5d2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13312,6 +13312,9 @@ The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `pr sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M, plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)). +A manifest's `translations` ([plug-ins](plugins.md#translations)) change only the text the app shows: `plugin.list`, +`plugin.info` and plug-in command entries keep the manifest's own names and labels, and `plugin.inspect` and +`plugin.info`'s `manifest` give `translations` as declared. A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..42a20023c5 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -574,6 +574,7 @@ the module's start function, in a run that isn't a filter's run on a document, o it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. +- `translations`: the plug-in's text in other languages ([Translations](#translations)). - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped @@ -604,6 +605,53 @@ declares them still installs there: A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons. +Dialogs and menus show plug-in text with control and bidirectional characters escaped (`\u{202E}`). + +#### Translations + +`translations` gives the plug-in's text in other languages, keyed by language code. The app shows the text for its +interface language (Preferences › User Interface). Text a language leaves out comes from the same code without its +last part (`pt-BR`, then `pt`; `zh-Hant-TW`, then `zh-Hant`, then `zh`) and then from the manifest's own text. Codes +match without regard to case. + +```json +"translations": { + "de": { + "name": "Pfade aufräumen", + "params": {"mode": {"label": "Modus", "help": "Weich rundet die Ecken.", "options": {"soft": "Weich", "hard": "Hart"}}}, + "groups": {"Shape": "Form"}, + "commands": {"grow": {"label": "Vergrößern", "params": {"by": {"label": "Um"}}}} + }, + "pt": {"name": "Arrumar caminhos"}, + "pt-BR": {"name": "Organizar caminhos"} +} +``` + +| Key | What it translates | +|---|---| +| `name` | The plug-in's name in Object › Plug-ins, Effect › Plug-ins, File › Open With, Edit › Keyboard Shortcuts, the command palette, the Appearance panel and dialog headings (1–64 characters). | +| `params` | By parameter name: its `label` (also for a parameter that gives none), `help` (only where the parameter gives one; line breaks allowed) and `options`, the label of each choice by the value it passes (1–64 characters each). | +| `groups` | By the `group` the parameters give: the section's heading. The section stays the same section in every language. | +| `commands` | By command id: its `label` and its parameters' text, as `params` gives it. | + +The text is only shown. Command ids, parameter names and choice values are the same in every language, the plug-in +is given the values it declared, and `plugin.list`, `plugin.info` and errors use the manifest's own `name` and labels; +`plugin.inspect` and `plugin.info` give `translations` as declared. The install approval names the plug-in in the UI +language and, when that name is a translation, also shows the manifest's own name under its ID; what the approval +grants is still bound to the ID and file hash it shows. + +A manifest gives at most 16 languages, inside its 64 KiB limit. Installing refuses the following, with an error that +names the key (such as `translations.de.params.mode.label`): + +- a code that is not a language of 2 or 3 letters followed by parts of 2–8 letters and digits after a `-` (at most 35 + characters), or a language given twice; +- text longer than the field it translates allows, empty text, or text with a control character (a line break + outside `help`), a character that changes the direction text runs in (`U+202A`–`U+202E`, `U+2066`–`U+2069`, + `U+200E`, `U+200F`, `U+061C`) or a line or paragraph separator; +- a parameter, choice value, group or command the manifest doesn't declare, `options` on a parameter that isn't a + choice, two options of a choice with the same label, or a key not listed above. + +Hosts from before `translations` ignore it and show the manifest's own text. ### Input diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..b56fc9013c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2647,6 +2647,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. +- **Plug-in text in the UI language:** a manifest's `translations` give the plug-in's name, its commands' labels, its parameters' labels, help and choice labels, and its group headings in up to 16 languages, by language code (`de`, `pt-BR`). Object › Plug-ins, Effect › Plug-ins, File › Open With, Edit › Keyboard Shortcuts, the command palette, the plug-in dialogs and the Appearance panel show the text for the UI language, then for the language without its region (`pt-br`, then `pt`), then the manifest's own; command ids, parameter names, choice values and `plugin.list` keep the manifest's own text, and the install approval shows the manifest's own name under the ID when the name it asks with is a translation. An unknown code, a repeated language, text a source field couldn't hold, a control, direction or line-separator character, or a key the manifest doesn't declare is refused at install with an error naming the key, inside the 64 KiB manifest limit. Filter and importer menu items and plug-in dialog labels, help, groups and choices now escape bidirectional characters as command labels already did, and so does the refusal of a heavy filter. Regressions: `crates/plugins/src/translations.rs`, `crates/ui-egui/src/tests/plugins.rs`, `crates/ui-egui/src/dialogs/tests.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. - **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged. - **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. From ece34c6ba732f797b4ed46f597679b8793479d7b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:51:53 -0800 Subject: [PATCH 02/17] Plug-ins: translated names keep their English text in messages and the heavy-budget prompt - A choice's options are compared for repeats as dialogs show them, with control and bidirectional characters escaped, so a translation can no longer give one option the text another option's value shows as. - Installing a heavy filter that asks for nothing else now shows its ID and file SHA-256, and the manifest's own name when the prompt names it by a translation. - Shortcut conflict messages name a plug-in's filter and commands by the manifest's own text, as they name every other entry in English, while Keyboard Shortcuts still lists them in the UI language. - Keyboard Shortcuts builds its list again when the UI language changed since it was last open. Docs: docs/plugins.md, ui.installPlugin params. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/plugins/src/translations.rs | 22 +++++- crates/ui-egui/src/io/open.rs | 13 ++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 101 ++++++++++++++++++++---- crates/ui-egui/src/shortcuts/tests.rs | 1 + crates/ui-egui/src/tests/plugin_runs.rs | 31 ++++++++ crates/ui-egui/src/tests/plugins.rs | 29 +++++++ docs/plugins.md | 4 +- 9 files changed, 181 insertions(+), 24 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..d06ba12484 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1999,7 +1999,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.installPlugin", "Install Plug-in…", "", - "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, showing its id and file SHA-256, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), ( "plugin.cancelRuns", diff --git a/crates/plugins/src/translations.rs b/crates/plugins/src/translations.rs index f940a635cd..76c8f65046 100644 --- a/crates/plugins/src/translations.rs +++ b/crates/plugins/src/translations.rs @@ -170,6 +170,13 @@ fn key(path: &[&str]) -> String { format!("`translations.{}`", parts.join(".")) } +/// Text `s` as a dialog shows it: each line with its control and bidirectional characters escaped +/// and cut at [`MAX_HELP`] characters. +fn shown_text(s: &str) -> String { + let lines: Vec = s.split('\n').map(|l| permissions::display_text(l, MAX_HELP)).collect(); + lines.join("\n") +} + /// Checks text `s` at `path` against `max` characters (`lines`: `\n` allowed). fn check_text(s: &str, max: usize, lines: bool, path: &[&str]) -> Result<()> { if fits(s, max, lines) { @@ -277,11 +284,13 @@ impl Manifest { } /// Checks that no two options of a choice show the same label in language `lang`, naming the - /// choice's `options` under `path`. + /// choice's `options` under `path`. Labels are compared as dialogs show them, with control and + /// bidirectional characters escaped, so an option value holding U+202E and a translation + /// giving the text `\u{202E}` count as the same label. fn check_option_labels(&self, lang: &str, path: &[&str]) -> Result<()> { for (k, p) in &self.params { let ParamSpec::Choice { options, .. } = &p.spec else { continue }; - let shown: Vec<&str> = options.iter().map(|o| self.option_label_in(k, o, lang)).collect(); + let shown: Vec = options.iter().map(|o| shown_text(self.option_label_in(k, o, lang))).collect(); if shown.iter().enumerate().any(|(i, s)| shown.get(..i).is_some_and(|before| before.contains(s))) { let at = key(&[path, &[k.as_str(), "options"]].concat()); return Err(Error::Manifest(format!("{at} gives two options the same label"))); @@ -488,6 +497,15 @@ mod tests { let e = Manifest::parse(with(&translations).as_bytes()).unwrap_err().to_string(); assert!(e.contains(says), "{translations}: {e}"); } + // An option value holding U+202E shows as the text `\u{202E}`, so a translation giving + // that text for another option shows the same label. + let escaped = format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["soft","{}"]}}}}, + "translations":{{"de":{{"params":{{"mode":{{"options":{{"soft":"\\u{{202E}}"}}}}}}}}}}}}"#, + esc(0x202E) + ); + let e = Manifest::parse(escaped.as_bytes()).unwrap_err().to_string(); + assert!(e.contains("`translations.de.params.mode.options` gives two options the same label"), "{e}"); // Keys and types serde reads: an unknown key, a repeated one, and a value of the wrong type. for (translations, says) in [ (r#"{"de":{"title":"X"}}"#, "unknown field `title`"), diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 63c2e82b15..5ccf65a813 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -247,10 +247,11 @@ fn permission_words(name: &str, commands: &[String]) -> String { /// Installs the plug-in module that `module` names (`plugin.install`'s `path`, or `dataBase64` /// with `name`) → `plugin.install`'s result. A plug-in that lists permissions no person has granted /// it yet asks first, showing its name, id, version, file hash and what each permission lets it -/// do, so does a filter that asks for a heavy budget, and so does a module that would take the -/// place of another one with its id and get its settings and cache (`replace`); OK installs it if -/// the module still has the hash the prompt showed, Cancel installs nothing → `{pending}` while it -/// asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves. +/// do, so does a filter that asks for a heavy budget, showing its id and file hash, and so does a +/// module that would take the place of another one with its id and get its settings and cache +/// (`replace`). When the name shown is a translation, the id lines also give the manifest's own +/// name. OK installs it if the module still has the hash the prompt showed, Cancel installs +/// nothing → `{pending}` while it asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves. /// Every question opens the approval dialog ([`dialogs::plugin::ask_install`]). When automation /// asked ([`VectorcraftApp::automation_asked`]), the question has no OK that installs, its /// `replace: true` doesn't skip asking about replacing, and the answer while it asks adds @@ -323,6 +324,10 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result, } /// The editor's entries, the Effect menu's effect items and Object › Plug-ins' filter items while @@ -454,6 +458,7 @@ fn build_snapshot(revision: u64, lang: &'static str) -> Arc { group: e.group.clone(), is_tool: false, shows_key: false, + english: vectorcraft_plugins::effect::plugin_id(&e.effect).and_then(|id| own_plugin_text(id, lang, &e.group, &e.label)), })) .chain(filters.iter().map(|f| Entry { key: format!("plugin:{}", f.id), @@ -461,18 +466,21 @@ fn build_snapshot(revision: u64, lang: &'static str) -> Arc { group: f.group.clone(), is_tool: false, shows_key: false, + english: own_plugin_text(&f.id, lang, &f.group, &f.label), })) .chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| { // A plug-in command's label and its plug-in's name in `lang`, as its menu shows them. + let own = (c.menu.join(" › "), c.label.to_string()); let (label, group) = match vectorcraft_engine::cmd::plugin::command_of(c.id) { Some((plugin, command)) => { let m = plugin.manifest(); let path: Vec = c.menu.iter().take(2).map(|s| s.to_string()).chain([m.shown_name(lang)]).collect(); (m.shown_command_label(&command, lang), path.join(" › ")) } - None => (c.label.to_string(), c.menu.join(" › ")), + None => (own.1.clone(), own.0.clone()), }; - Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false } + let english = (own != (group.clone(), label.clone())).then_some(own); + Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false, english } })) .chain(tail.iter().cloned()) .collect(); @@ -480,6 +488,29 @@ fn build_snapshot(revision: u64, lang: &'static str) -> Arc { Arc::new(Snapshot { revision, lang, effects, filters, entries: entries.into() }) } +/// The group and label of plug-in `id`'s menu item, shown as `group` and `label` in UI language +/// `lang`, with the manifest's own name in place of the name its translations give there +/// ([`Entry::english`]); `None` when no such plug-in is installed or `lang` shows its own name. +fn own_plugin_text(id: &str, lang: &str, group: &str, label: &str) -> Option<(String, String)> { + use vectorcraft_plugins::permissions; + let plugin = vectorcraft_plugins::registry::get(id)?; + let m = plugin.manifest(); + let (shown, own) = (m.shown_name(lang), permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)); + if shown == own { + return None; + } + // A plug-in with commands of its own has a submenu named after it. + let parts: Vec<&str> = group.split(" › ").collect(); + let submenu = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", name, ..] if *name == shown); + let group = parts.iter().enumerate().map(|(i, s)| if submenu && i == 2 { own.as_str() } else { *s }).collect::>().join(" › "); + let label = match label.strip_prefix(shown.as_str()) { + Some(rest) if own.ends_with('…') => format!("{own}{}", rest.trim_start_matches('…')), + Some(rest) => format!("{own}{rest}"), + None => label.to_string(), + }; + Some((group, label)) +} + /// Every tool, command and panel the editor can give a shortcut; [`listed`] says which it lists. pub fn entries() -> Arc<[Entry]> { snapshot().entries.clone() @@ -491,7 +522,14 @@ fn fixed_entries() -> &'static (Vec, Vec) { static E: OnceLock<(Vec, Vec)> = OnceLock::new(); E.get_or_init(|| { let mut v: Vec = vectorcraft_tools::catalog::all_tools() - .map(|t| Entry { key: format!("tool:{}", t.id), label: t.label.to_string(), group: "Tools".into(), is_tool: true, shows_key: false }) + .map(|t| Entry { + key: format!("tool:{}", t.id), + label: t.label.to_string(), + group: "Tools".into(), + is_tool: true, + shows_key: false, + english: None, + }) .collect(); let mut seen = HashSet::new(); // The commands listed only because an item of the menu bar runs them as a key press would @@ -506,7 +544,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { by_the_menu_bar.insert(c.id); } let group = if c.menu.is_empty() { id_group(c.id) } else { c.menu.join(" › ") }; - v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false }); + v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false, english: None }); } v.extend(crate::state::all_panels().map(|(id, label)| Entry { key: format!("panel:{id}"), @@ -514,6 +552,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { group: "Window".into(), is_tool: false, shows_key: false, + english: None, })); // Each effect of the Effect menu comes next, by its own key (#3296): see [`snapshot`]. let mut tail = vec![]; @@ -525,7 +564,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(id); } - tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false }); + tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false, english: None }); } // A command listed only because an item of the menu bar runs it can have the group and // label of another entry. When that entry is an engine command that no item of the menu bar @@ -679,9 +718,13 @@ pub(crate) fn shown_name(e: &Entry) -> String { name_of(e, &shown_group(&e.group), shown_label(e)) } -/// [`shown_name`] in English, for a status or error message, which is translated when shown. +/// [`shown_name`] in English, for a status or error message, which is translated when shown; a +/// plug-in item by its manifest's own text ([`Entry::english`]). fn english_name(e: &Entry) -> String { - name_of(e, &e.group, &e.label) + match &e.english { + Some((group, label)) => name_of(e, group, label), + None => name_of(e, &e.group, &e.label), + } } /// Entry `e`'s name with its group and label as `group` and `label`. @@ -713,8 +756,13 @@ fn distinct_names(entries: &mut [Entry]) { // The entries of each name that more than one entry has. fn shared(entries: &[Entry]) -> Vec> { let mut by_name: HashMap> = HashMap::new(); + // A plug-in item counts under the name it shows and under its manifest's own name. for (i, e) in entries.iter().enumerate() { - by_name.entry(english_name(e)).or_default().push(i); + let (shown, english) = (name_of(e, &e.group, &e.label), english_name(e)); + if english != shown { + by_name.entry(english).or_default().push(i); + } + by_name.entry(shown).or_default().push(i); } by_name.into_values().filter(|list| list.len() > 1).collect() } @@ -1872,8 +1920,8 @@ pub fn is_recording(app: &VectorcraftApp) -> bool { // ---------- dialog ---------- /// The dialog's working set as a keymap, with the entries it lists, each entry's shortcut text (in -/// their order) and the number of conflicts, kept between frames while the set and the installed -/// plug-ins are unchanged. +/// their order) and the number of conflicts, kept between frames while the set, the installed +/// plug-ins and the UI language are unchanged. struct DialogView { /// The dialog's `overrides` field this was built from. source: Value, @@ -1881,6 +1929,8 @@ struct DialogView { backtick: Option, /// The plug-in revision of `entries`. revision: u64, + /// The UI language `entries` name plug-in items in ([`Snapshot::lang`]). + lang: &'static str, entries: Arc<[Entry]>, keymap: Keymap, texts: Vec>, @@ -1898,6 +1948,7 @@ impl DialogView { source: stored::to_value(&crate::keymap::effect_keys_in(&overrides, &snapshot.effects)), backtick, revision: snapshot.revision, + lang: snapshot.lang, entries: snapshot.entries.clone(), keymap, texts, @@ -1905,15 +1956,18 @@ impl DialogView { } } - /// The view of `d`'s working set, from the cache unless the set, the backtick key's character - /// or the installed plug-ins changed. The dialog's `overrides` field is left in its stored form. + /// The view of `d`'s working set, from the cache unless the set, the backtick key's character, + /// the installed plug-ins or the UI language changed. The dialog's `overrides` field is left in + /// its stored form. fn of(ctx: &egui::Context, d: &mut Dialog) -> Arc { let id = egui::Id::unique("dialog-shortcuts-view"); let source = d.fields.get("overrides").unwrap_or(&Value::Null); let backtick = backtick_text(); let revision = menus::plugin_revision(); - if let Some(v) = - ctx.data(|m| m.get_temp::>(id)).filter(|v| v.source == *source && v.backtick == backtick && v.revision == revision) + let lang = crate::i18n::current().code(); + if let Some(v) = ctx + .data(|m| m.get_temp::>(id)) + .filter(|v| v.source == *source && v.backtick == backtick && v.revision == revision && v.lang == lang) { return v; } @@ -3600,6 +3654,7 @@ mod tests { group: group.into(), is_tool: false, shows_key: false, + english: None, }; let menu = "Object › Plug-ins"; let mut rows = vec![ @@ -3625,6 +3680,24 @@ mod tests { ); } + /// The dialog's view is built again when the UI language changes, so reopening Keyboard + /// Shortcuts after a change of language lists plug-in items in the new language. + #[test] + fn the_dialog_view_is_built_again_when_the_language_changes() { + let ctx = egui::Context::default(); + let mut d = Dialog::new("shortcuts", json!({})); + let (en, again, de) = with_steady_plugins(|| { + let en = DialogView::of(&ctx, &mut d); + let again = DialogView::of(&ctx, &mut d); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let de = DialogView::of(&ctx, &mut d); + crate::i18n::set_current(crate::i18n::Lang::EN); + (en, again, de) + }); + assert!(Arc::ptr_eq(&en, &again), "kept while nothing changes"); + assert_eq!((en.lang, de.lang), ("en", "de")); + } + /// A command with items in more than one menu is shown under the path of its first item with /// no params, or else of its first item: Recolor Artwork… under Edit › Edit Colors, not Edit › /// Edit Colors › Recolor with Preset. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 063d63bb14..1d8e0ad34b 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -3548,6 +3548,7 @@ fn a_filter_plugin_row_translates_its_path_and_not_its_name() { group: "Object › Plug-ins".into(), is_tool: false, shows_key: false, + english: None, }; let path = format!("{} › {}", crate::i18n::tr(zh, "Object"), crate::i18n::tr(zh, "Plug-ins")); let (filter, command) = (crate::shortcut_editor::shown_name(&entry("plugin:a.b")), crate::shortcut_editor::shown_name(&entry("object.group"))); diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index 32cc241027..930eb41fc4 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -90,6 +90,37 @@ fn installing_a_heavy_filter_asks_first() { assert!(registry::get(id).is_none()); } +/// The heavy-budget question gives the filter's ID and file SHA-256, and also the manifest's own +/// name when the name it asks with is a translation. +#[test] +fn the_heavy_budget_question_shows_the_id_hash_and_manifest_name() { + let mut app = app(); + let id = "test.ui.heavy.translated"; + let manifest = + format!(r#"{{"id":"{id}","name":"Route","version":"1","kind":"filter","budget":"heavy","translations":{{"de":{{"name":"Fräsen"}}}}}}"#); + let bytes = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes); + let data = vectorcraft_format::base64_encode(&bytes); + let ask = |app: &mut VectorcraftApp, lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let r = app.run("ui.installPlugin", json!({ "dataBase64": data })); + let pending = app.pending_plugin_install.as_ref().map(|p| (p.message.clone(), p.detail.clone())); + crate::i18n::set_current(crate::i18n::Lang::EN); + dialogs::cancel(app); + assert_eq!(r.unwrap()["pending"], dialogs::plugin::INSTALL_KIND); + pending.unwrap() + }; + let (message, detail) = ask(&mut app, "de"); + assert!(message.contains("Fräsen") && !message.contains("Route"), "{message}"); + for shown in [id, "Route", hash.as_str()] { + assert!(detail.contains(shown), "{shown}: {detail}"); + } + let (message, detail) = ask(&mut app, "en"); + assert_eq!(message, "Install “Route”, which asks for a heavy budget?"); + assert!(detail.starts_with(&format!("ID: {id}\nFile SHA-256: {hash}\n\n")), "no second name line: {detail}"); + assert!(registry::get(id).is_none()); +} + /// The dialog has no Preview; OK closes it and the filter runs in the background, the status bar /// saying so, and its result is one undo step named after it, selected. #[test] diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 81046387f3..030b6bfb55 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -864,6 +864,35 @@ fn keyboard_shortcuts_leave_a_plugin_commands_text_as_the_plugin_gives_it() { assert_eq!(shown, Some(expected)); } +/// A shortcut conflict names a translated plug-in's filter and command by the manifest's own text, +/// as status and error messages name every entry in English, while Keyboard Shortcuts lists them in +/// the UI language. +#[test] +fn a_shortcut_conflict_names_a_translated_plugin_by_its_own_text() { + let mut app = app(); + let id = "test.ui.translated.conflict"; + // Names no other test's plug-in has, since tests running beside this one share the registry. + let manifest = format!( + r#"{{"id":"{id}","name":"Neaten","kind":"filter","commands":[{{"id":"grow","label":"Grow Rim"}}],"translations":{{"de":{{"name":"Ordnen","commands":{{"grow":{{"label":"Rand wachsen"}}}}}}}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + let (grow, own) = (format!("plugin.{id}.grow"), format!("plugin:{id}")); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let conflict = |first: &str, second: &str| { + let mut ov = craft_keymap::Overrides::new(); + crate::shortcut_editor::assign(&mut ov, first, Some("Cmd+Alt+Shift+F10"), false).unwrap(); + crate::shortcut_editor::assign(&mut ov, second, Some("Cmd+Alt+Shift+F10"), false).unwrap_err() + }; + let (by_command, by_filter) = (conflict(&grow, &own), conflict(&own, &grow)); + let label = crate::shortcut_editor::entry(&grow).map(|e| e.label); + crate::i18n::set_current(crate::i18n::Lang::EN); + app.run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(label.as_deref(), Some("Rand wachsen"), "the row is in German"); + assert!(by_command.ends_with("is already used by Object › Plug-ins › Neaten › Grow Rim"), "{by_command}"); + assert!(by_filter.ends_with("is already used by Object › Plug-ins › Neaten › Neaten"), "{by_filter}"); +} + /// A filter's and an importer's menu item show their names as prompts do, a right-to-left override /// escaped, as a filter with commands already showed its submenu. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 42a20023c5..7a3f5b3665 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -177,8 +177,8 @@ an importer an import's). Each of its runs gets 1 G instructions (20 times a lig and 300 s (`vectorcraft_plugins::{HEAVY_FUEL, HEAVY_WALL_TIME_MS}`). Its output can't add to the budget: the host learns how much there is only once the run has ended. -- **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, and install it once the - user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`, +- **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, with its ID and file + SHA-256, and install it once the user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`, and refuses `allowHeavy` from a request except in a session started with `vectorcraft-cli --allow-plugin-grants` (`plugin.inspect` shows the budget beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed again at startup. The Additional Plug-ins Folder skips heavy filters with a note in its report, since loading a folder From 8e093c9e148b592929f682e30167402dc5cab4b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:35:16 -0800 Subject: [PATCH 03/17] Command palette: a translated plug-in is still found by its manifest name A filter or live-effect plug-in whose name the UI language translates shows the translation in the palette, and a search for the manifest's own name finds it too. Export Text's test compares its rows with the names the dialog shows, which for a plug-in with an English translation differ from the manifest text that messages use. --- crates/ui-egui/src/palette.rs | 59 ++++++++++++++++++++++++--- crates/ui-egui/src/shortcut_editor.rs | 12 +++++- 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index eabb023ad4..644952aaee 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -109,6 +109,10 @@ struct Draft { /// Is this a plug-in command, whose label and plug-in name come from the plug-in's own /// translations? plugin_command: bool, + /// For a filter or live-effect plug-in item whose path and label give the plug-in's name in the + /// UI language from its translations: the path and label with the manifest's own text, which a + /// query also matches ([`Draft::plain`]). + own: Option<(String, String)>, id: String, shortcut: String, /// Has [`distinct_names`] given the result its [`context`]? @@ -124,6 +128,7 @@ impl Draft { label: label.to_string(), translates: true, plugin_command: false, + own: None, id, shortcut: shortcut.to_string(), in_context: false, @@ -157,6 +162,16 @@ impl Draft { let name = if self.path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &self.path)) }; if self.keyed { format!("{name} ({})", self.id) } else { name } } + + /// The English name a query matches before [`distinct_names`] runs: a plug-in item that shows + /// a translated name by the manifest's own text ([`Draft::own`]). + fn plain(&self) -> String { + match &self.own { + Some((path, label)) if path.is_empty() => label.clone(), + Some((path, label)) => format!("{path} › {label}"), + None => self.name(crate::i18n::Lang::EN), + } + } } /// The palette's results before their names are made distinct: every listed engine command and @@ -203,9 +218,12 @@ fn drafts() -> Vec { } // An Effect menu item runs what its item runs; a live-effect plug-in's name does not translate. for e in crate::shortcut_editor::effect_items().iter() { + let plugin = vectorcraft_plugins::effect::plugin_id(&e.effect).is_some(); + let id = format!("effect:{}", e.effect); out.push(Draft { - translates: vectorcraft_plugins::effect::plugin_id(&e.effect).is_none(), - ..Draft::new(&e.group, &e.label, format!("effect:{}", e.effect), crate::shortcut_editor::effect_shortcut(&e.effect).unwrap_or("")) + translates: !plugin, + own: if plugin { crate::shortcut_editor::own_plugin_text_of(&id) } else { None }, + ..Draft::new(&e.group, &e.label, id, crate::shortcut_editor::effect_shortcut(&e.effect).unwrap_or("")) }); } out @@ -429,11 +447,15 @@ fn build(lang: crate::i18n::Lang) -> Vec { fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { let homes = search::menu_homes(native); let mut drafts = drafts(); - drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| Draft { - translates: false, - ..Draft::new(&f.group, &f.label, format!("plugin:{}", f.id), crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("")) + drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| { + let id = format!("plugin:{}", f.id); + Draft { + translates: false, + own: crate::shortcut_editor::own_plugin_text_of(&id), + ..Draft::new(&f.group, &f.label, id, crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("")) + } })); - let plain: Vec = drafts.iter().map(|d| d.name(crate::i18n::Lang::EN)).collect(); + let plain: Vec = drafts.iter().map(Draft::plain).collect(); distinct_names(&mut drafts, &[crate::i18n::Lang::EN, lang]); drafts .into_iter() @@ -3306,6 +3328,31 @@ mod tests { assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); } + /// A filter whose name the UI language translates shows the translation, English included, and + /// a search for the manifest's own name still finds it. + #[test] + fn a_translated_filter_is_found_by_its_manifest_name() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_translated_filter"; + let manifest = format!( + r#"{{"id":"{id}","name":"Polish Edges","version":"1","kind":"filter","translations":{{"de":{{"name":"Kanten polieren"}},"en":{{"name":"Smooth Edges"}}}}}}"# + ); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let found = |lang: Lang| { + crate::i18n::set_current(lang); + let found = build(lang).into_iter().find(|e| e.id == format!("plugin:{id}")).map(|e| (e.shown, e.haystack)); + crate::i18n::set_current(Lang::EN); + found + }; + let (de, en) = (found(Lang::from_code("de").unwrap()), found(Lang::EN)); + vectorcraft_plugins::registry::remove(id); + for (found, name) in [(de, "Kanten polieren"), (en, "Smooth Edges")] { + let (shown, haystack) = found.expect("the filter is a result"); + assert!(shown.ends_with(name), "{shown}"); + assert!(haystack.contains("polish edges"), "{haystack}"); + } + } + /// A plug-in's name in the path of its own item, in the submenu a plug-in with commands gets, /// stays as the plug-in gives it where it matches text the app translates ("Open" in German). #[test] diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 7c1d4fc044..96b87827b0 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1151,6 +1151,16 @@ pub fn entry(key: &str) -> Option { entries().iter().find(|e| e.key == key).cloned() } +/// The group and label of plug-in item `key` (`plugin:` or `effect:`) with the manifest's +/// own text, when the item shows the plug-in's name in the UI language from its translations +/// ([`Entry::english`]); `None` for every other entry. +pub(crate) fn own_plugin_text_of(key: &str) -> Option<(String, String)> { + if !key.starts_with("plugin:") && !key.starts_with("effect:") { + return None; + } + entries().iter().find(|e| e.key == key).and_then(|e| e.english.clone()) +} + /// Entries (other than `except`) whose effective shortcut equals `chord`. pub fn conflicts_with(overrides: &Overrides, chord: &str, except: &str) -> Vec { let Some(c) = vc_chord(chord) else { return vec![] }; @@ -2788,7 +2798,7 @@ mod tests { let text = export_text("VectorCraft Defaults", &ov); let km = keymap_with(&ov); let names = |tools: bool| -> Vec { - entries().iter().filter(|e| e.is_tool == tools && listed(km.overrides(), e)).map(|e| format!("{}\t", english_name(e))).collect() + entries().iter().filter(|e| e.is_tool == tools && listed(km.overrides(), e)).map(|e| format!("{}\t", shown_name(e))).collect() }; let rows = (names(true), names(false)); (text, km, rows.0, rows.1) From 64ba4f59d1a3f05e7c01b0249c2ce584e56d39a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:51:40 -0800 Subject: [PATCH 04/17] Last Effect: a plug-in's translated name is not translated again Last Effect shows a live-effect plug-in's name in the UI language as the plug-in's translations give it, even where it matches text the app translates ("Open" in German stays "Open"). --- crates/ui-egui/src/menus/labels.rs | 4 +++- crates/ui-egui/src/tests/plugins.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 365315facb..c1a06ea48a 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -194,8 +194,10 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } "effect.last" => match &app.last_effect { Some((e, _)) => { + // A plug-in's name is already in the UI language from its translations. let name = last_effect_name(e); - fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) + let name = if vectorcraft_plugins::effect::plugin_id(e).is_some() { name } else { crate::i18n::tr_id(lang, e, name) }; + fmt(tl!("Last Effect: {name}"), &[("name", name)]) } None => crate::i18n::tr_id(lang, id, label).to_string(), }, diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 030b6bfb55..dec0b39419 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -845,6 +845,26 @@ fn plugin_menus_show_the_plugins_names_in_the_ui_language() { } } +/// Last Effect shows a live-effect plug-in's translated name as the plug-in gives it, even where it +/// matches text the app translates: "Open" in German stays "Open". +#[test] +fn last_effect_leaves_a_plugins_translated_name_as_it_gives_it() { + let mut app = app(); + let effect = "test.ui.translated.last_effect"; + let manifest = format!(r#"{{"id":"{effect}","name":"Unseal","kind":"effect","translations":{{"de":{{"name":"Open"}}}}}}"#); + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + app.last_effect = Some((vectorcraft_plugins::effect::effect_id(effect), json!({}))); + let de = crate::i18n::Lang::from_code("de").unwrap(); + crate::i18n::set_current(de); + let shown = menus::display_label(&app, "effect.last", "Last Effect…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + app.last_effect = None; + app.run("plugin.remove", json!({"id": effect})).unwrap(); + assert_ne!(crate::i18n::tr(de, "Open"), "Open", "German translates the app's Open"); + assert_eq!(shown, crate::i18n::fmt(crate::i18n::tr(de, "Last Effect: {name}"), &[("name", "Open")])); +} + /// Keyboard Shortcuts shows a plug-in command's label and its plug-in's name as the plug-in gives /// them, even where they match text the app translates: in German, a command labeled "Open" of a /// plug-in named "Close" keeps both, as in its menu. From e84336a5c7ad04e93f17a16498023fed5c59146e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:05:42 -0800 Subject: [PATCH 05/17] Command palette: a plug-in command is found by its manifest's own text A plug-in command whose plug-in translates its name and label into English shows the translation, and a search for the manifest's own name and label still finds it. --- crates/ui-egui/src/palette.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 644952aaee..852c0ddeb3 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -164,8 +164,17 @@ impl Draft { } /// The English name a query matches before [`distinct_names`] runs: a plug-in item that shows - /// a translated name by the manifest's own text ([`Draft::own`]). + /// a translated name by the manifest's own text ([`Draft::own`]), and a plug-in command by its + /// plug-in's own name and its own label. fn plain(&self) -> String { + if self.plugin_command + && let Some((plugin, command)) = vectorcraft_engine::cmd::plugin::command_of(&self.id) + { + use vectorcraft_plugins::permissions; + let own = permissions::display_text(plugin.manifest().name.trim(), permissions::MAX_SHOWN_NAME); + let top = self.path.rsplit_once(" › ").map_or("", |(top, _)| top); + return format!("{top} › {own} › {}", command.shown_label()); + } match &self.own { Some((path, label)) if path.is_empty() => label.clone(), Some((path, label)) => format!("{path} › {label}"), @@ -3328,6 +3337,25 @@ mod tests { assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); } + /// A plug-in command whose plug-in translates its name and label into English shows the + /// translation, and a search for the manifest's own text still finds it. + #[test] + fn a_plugin_command_with_english_translations_is_found_by_its_own_text() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_english_command"; + let manifest = format!( + r#"{{"id":"{id}","name":"Trim Pack","version":"1","kind":"filter","commands":[{{"id":"shave","label":"Shave Ends"}}], + "translations":{{"en":{{"name":"Trimmer","commands":{{"shave":{{"label":"Cut Tips"}}}}}}}}}}"# + ); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let key = format!("plugin.{id}.shave"); + let found = build(Lang::EN).into_iter().find(|e| e.id == key).map(|e| (e.shown, e.haystack)); + vectorcraft_plugins::registry::remove(id); + let (shown, haystack) = found.expect("the command is a result"); + assert!(shown.ends_with("Trimmer › Cut Tips"), "{shown}"); + assert!(haystack.contains("trim pack › shave ends"), "{haystack}"); + } + /// A filter whose name the UI language translates shows the translation, English included, and /// a search for the manifest's own name still finds it. #[test] From 7615aed3ee6b719c299f2c29c0c5fa5829e46aa2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:16:11 -0800 Subject: [PATCH 06/17] JavaScript: a .mjs script runs as an ECMAScript 2015 module script.run, File > Scripts and Other Script... run a file ending in .mjs as a module: strict code with import and export declarations at its top level. parse_module reads the module grammar and its early errors, and Realm::start_module and Realm::run_module load the module graph through the host, link every import before any module runs, and run each module once, after the modules it imports. Imports read the exporting binding each time; a read before initialization is a ReferenceError and an assignment is a TypeError. import * as ns gives a namespace object that is not extensible, and Object.isSealed and Object.isFrozen on it throw a ReferenceError for an export its module has not initialized. Specifiers are ./ and ../ paths to .mjs and .js files, resolved against the importing file and read only through the script's file scope, so a module can import only from the script's folder and the folders below it. Bare names, URLs and absolute paths are a SyntaxError that names the specifier. Module files count against the #include limits: 64 files besides the script, 16 imports deep. import and export stay syntax errors in .js and .jsx scripts; import() is not read. script.listInstalled lists .mjs files. The test262 runner also runs the module tests under language/module-code, import and export, reading the fixture files they import from the suite. --- crates/engine/src/cmd/scripts.rs | 8 +- crates/engine/src/script/folder.rs | 4 +- crates/engine/src/script/include.rs | 129 ++++++- crates/engine/src/script/mod.rs | 35 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_modules.rs | 227 +++++++++++ crates/engine/tests/script_corpus.rs | 2 +- crates/js/src/ast.rs | 52 +++ crates/js/src/builtins.rs | 4 +- crates/js/src/builtins/object.rs | 6 +- crates/js/src/compiler.rs | 14 + crates/js/src/heap.rs | 55 ++- crates/js/src/interp.rs | 200 +++++++++- crates/js/src/lib.rs | 47 ++- crates/js/src/module.rs | 448 ++++++++++++++++++++++ crates/js/src/module_tests.rs | 419 ++++++++++++++++++++ crates/js/src/parser.rs | 8 + crates/js/src/parser/module.rs | 299 +++++++++++++++ crates/js/src/realm.rs | 89 ++++- crates/js/tests/test262.rs | 172 ++++++++- crates/mcp/src/ui_catalog.rs | 4 +- crates/ui-egui/src/dialogs/script_run.rs | 4 +- crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tests.rs | 4 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/menus/ui_commands.rs | 4 +- crates/ui-egui/src/tests/script_run.rs | 2 +- docs/mcp.md | 38 +- docs/target-app-parity.md | 5 +- 52 files changed, 2270 insertions(+), 110 deletions(-) create mode 100644 crates/engine/src/tests/script_modules.rs create mode 100644 crates/js/src/module.rs create mode 100644 crates/js/src/module_tests.rs create mode 100644 crates/js/src/parser/module.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..67d6556bbe 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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (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), 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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. 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, and 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 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (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 ), @@ -188,7 +188,7 @@ fn run(s: &mut 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)?; diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..8226fa0711 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 @@ -256,7 +256,7 @@ 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 a024949a35..8de325cb70 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,57 @@ 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, } /// 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 path, in lowercase on Windows, +/// whose file names ignore letter case. +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()); + } + } + let shown = display(real).to_string(); + if cfg!(windows) { shown.to_lowercase() } else { shown } +} + +/// 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 +375,76 @@ 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(), } } + /// 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()); + 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, |p, name| p.join(name)); + let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + 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}"))), + }; + if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { + return Err(LoadError::Range("script source limit reached (32 MiB)".to_string())); + } + self.bytes += bytes.len(); + let key = module_key(&real); + self.module_paths.insert(relative, key.clone()); + if self.module_dirs.contains_key(&key) { + return Ok((key, None)); + } + if self.files >= MAX_FILES { + return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); + } + self.files += 1; + let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + path.pop(); + self.module_dirs.insert(key.clone(), path); + 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, ..Options::default() } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a01453a627..e318c0abb6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -62,7 +62,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::{ @@ -1575,6 +1576,19 @@ 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)| { + host.eval_maps.borrow_mut().push(map); + 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 { @@ -1937,7 +1951,16 @@ 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); + // A `.mjs` script is a module, with no preprocessor lines; `module_key` names it among the + // modules it imports. + let (expanded, module_key) = if include::module_script(request.file.as_deref()) { + 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, @@ -2083,7 +2106,13 @@ impl Session { .and_then(|()| if fresh { dialogs::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 e524d1c63c..cfaf6649ba 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -176,6 +176,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_modules; mod script_run; mod scripts; mod select_effects; diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs new file mode 100644 index 0000000000..9727abb927 --- /dev/null +++ b/crates/engine/src/tests/script_modules.rs @@ -0,0 +1,227 @@ +//! `.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); +} diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..b4ad5c5a61 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 c015e3fa38..a5d39c0b06 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -471,6 +471,58 @@ pub struct Program { pub(crate) es2015: bool, } +/// 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 { + pub specifier: String, + 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 f2c02bdf4c..b85780cdc5 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -433,7 +433,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_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.own_property(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -452,7 +452,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_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..419fbe57c5 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -130,7 +130,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_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + match interp.own_property(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -265,7 +265,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let o = *o; for k in interp.own_keys(o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.own_property(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } @@ -294,7 +294,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult, kin c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() }) } +/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an +/// environment of its own, as strict eval code does, and returns `undefined`. +pub(crate) fn compile_module(program: &crate::Program, source: &Rc) -> CResult> { + let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0); + c.es2015 = true; + let hoisted = c.hoist(&program.body, &[])?; + let top_scope = c.list_scope(&program.body, false)?; + c.stmts(&program.body)?; + c.emit(Op::Undefined); + c.emit(Op::Return); + let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX); + c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() }) +} + /// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program /// must be that one parenthesized function expression and nothing else. The name `anonymous` is /// not bound inside the function (section 15.3.2.1). diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 0750204403..f158f45a0f 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,9 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the + /// module's exports, read live from the bindings they name. + ModuleNamespace(Box), } /// What an XML value is. @@ -322,6 +325,8 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + // The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1). + Class::ModuleNamespace(_) => "Module", } } } @@ -353,17 +358,49 @@ pub(crate) struct Binding { /// A `let` or `const` binding, or a function declared in a block: a `var` that eval code /// declares cannot take its name. pub(crate) lexical: bool, + /// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5, + /// CreateImportBinding): reading it reads the binding of that name in that environment, and + /// writing it is a `TypeError`. `value` is unused. + pub(crate) import: Option<(EnvId, Key)>, } impl Binding { /// An initialized binding. pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self { - Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false } + Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None } } /// A `let` (or with `constant`, a `const`) binding not yet initialized. pub(crate) fn lexical(constant: bool) -> Self { - Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true } + Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None } + } + + /// An import of the binding `name` of the environment `env`. + pub(crate) fn import(env: EnvId, name: Key) -> Self { + Self { + value: Value::Undefined, + mutable: false, + deletable: false, + uninitialized: false, + constant: true, + lexical: true, + import: Some((env, name)), + } + } +} + +/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in +/// code unit order, with the environment and name of the binding it reads, or `None` for an export +/// whose value is fixed (another module's namespace object), kept in the object's own property. +#[derive(Clone, Debug, Default)] +pub(crate) struct ModuleExports { + pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>, +} + +impl ModuleExports { + /// The binding the export `name` reads, when it reads one. + pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> { + self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref()) } } @@ -674,6 +711,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = BOUND_ARG_BYTES * args.len(); } Class::Arguments(map) => work.push(map.env.0), + Class::ModuleNamespace(exports) => { + for (k, b) in &exports.bindings { + strings.add_key(k); + if let Some((env, name)) = b { + work.push(env.0); + strings.add_key(name); + } + } + extra = PROP_BYTES * exports.bindings.len(); + } Class::String(s) => strings.add(s), Class::RegExp(re) => { if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) { @@ -730,6 +777,10 @@ fn trace_env(e: &Env, work: &mut Vec, strings: &mut StringSizes) -> usize { for (k, b) in bindings.iter() { strings.add_key(k); mark_value(&b.value, work, strings); + if let Some((env, name)) = &b.import { + work.push(env.0); + strings.add_key(name); + } } ENV_BYTES + PROP_BYTES * bindings.len() } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index dc0e678e91..ae755f3aa3 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -24,8 +24,8 @@ use crate::ast::BinaryOp; use crate::bytecode::{Code, CodeKind, Op, Source}; use crate::compiler::{CompileFail, compile_program}; use crate::heap::{ - ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId, - Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, + ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES, + OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; use crate::string_builtins::flat_charged; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; @@ -184,6 +184,10 @@ pub(crate) struct Frame { completion: Value, /// Returning from this frame returns from the Rust call that pushed it. boundary: bool, + /// The frame runs a module that another module of the same run waits under (ECMA-262 2015 + /// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception + /// that leaves it ends the run at the boundary frame without stopping in the frames between. + chained: bool, } /// Where the exception being thrown was raised: the code and the instruction. @@ -949,7 +953,11 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); - if frame.boundary { + if frame.chained { + // The modules under it have not started, so no handler of theirs takes it. + self.abort_to_boundary(); + } + if frame.boundary || frame.chained { self.passing = v.clone(); return Err(Abrupt::Throw(v)); } @@ -983,6 +991,9 @@ impl Interp { if frame.boundary { return Ok(Some(v)); } + if frame.chained { + return Ok(None); + } self.push(v)?; Ok(None) } @@ -1245,6 +1256,15 @@ impl Interp { matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized)) } + /// The binding the binding `name` of the declarative environment `env` imports, when it is a + /// module's import. + fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> { + match self.heap.env(env) { + Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()), + _ => None, + } + } + fn not_initialized(&mut self, name: &[u16]) -> Abrupt { let ident = String::from_utf16_lossy(name); self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized")) @@ -1257,6 +1277,14 @@ impl Interp { /// GetValue of a reference whose base was resolved earlier (section 8.7.1). fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> { + if let Resolved::Decl(e) = r + && let Some((target, target_name)) = self.import_of(e, name) + { + if self.uninitialized(target, &target_name) { + return Err(self.not_initialized(name)); + } + return Ok((self.binding_value(target, &target_name)?, Value::Undefined)); + } match r { Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)), Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)), @@ -1276,6 +1304,12 @@ impl Interp { /// PutValue of a reference whose base was resolved earlier (section 8.7.2). fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> { let strict = self.strict(); + if let Resolved::Decl(e) = r + && self.import_of(e, name).is_some() + { + let ident = String::from_utf16_lossy(name); + return Err(self.type_error(&format!("assignment to the import '{ident}'"))); + } match r { Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)), Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => { @@ -1464,11 +1498,38 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + Class::ModuleNamespace(exports) => { + if let Some((env, name)) = exports.binding(k) + && let Some(Prop::Data { flags, .. }) = o.props.get(k) + { + return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags })); + } + } _ => {} } Ok(o.props.get(k).cloned()) } + /// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like): + /// [`Self::get_own_property`], except that an export of a module namespace object read before + /// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5). + pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + self.check_namespace_export(id, k)?; + self.get_own_property(id, k) + } + + /// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module + /// has not initialized yet. + fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> { + if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class) + && let Some((env, name)) = exports.binding(k) + && self.uninitialized(*env, name) + { + return Err(self.not_initialized(k)); + } + Ok(()) + } + /// [[GetProperty]]: the property found on the object or its prototype chain. pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { let mut cur = Some(id); @@ -1492,6 +1553,9 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // A module's export read before the module ran is in its temporal dead zone (ECMA-262 + // 2015 section 9.4.6.8). + self.check_namespace_export(start, k)?; match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -1600,10 +1664,26 @@ impl Interp { } Ok(true) } + Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw), _ => self.define_ordinary(id, k, desc, throw), } } + /// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.6): only a + /// descriptor that leaves an export as it is (enumerable, writable, not configurable, its + /// current value) succeeds, and it changes nothing. + fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else { + return self.reject_bool(throw, k, "a module namespace object is not extensible"); + }; + let unchanged = desc.configurable != Some(true) + && desc.enumerable != Some(false) + && !desc.is_accessor() + && desc.writable != Some(false) + && desc.value.as_ref().is_none_or(|v| same_value(v, &value)); + if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") } + } + fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { let key = String::from_utf16_lossy(k); @@ -1768,6 +1848,10 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + // A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9). + if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) { + return self.reject(throw, &k, "a module namespace object is read-only"); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -2586,7 +2670,14 @@ impl Interp { // listed or their bytes reserved must not free it. let saved = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); + // Listing a namespace object's exports reads each one (ECMA-262 2015 section 9.4.6.5). let keys = self.enumerable_keys(o).and_then(|keys| { + for k in &keys { + self.check_namespace_export(o, k)?; + } + Ok(keys) + }); + let keys = keys.and_then(|keys| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); @@ -2862,6 +2953,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + chained: false, }); Ok(()) } @@ -3135,6 +3227,22 @@ impl Interp { }) } + /// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the + /// source limit, with [`Self::source_tag`] as its source's tag. + pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc, crate::ModuleInfo), CompileError> { + self.source_units = self.source_units.saturating_add(units.len()); + let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len())); + let options = Options { max_source_units: remaining, ..self.options.clone() }; + let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?; + let writes = self.writes_mode(); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes }); + let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e { + CompileFail::Syntax(s) => CompileError::Syntax(s), + CompileFail::Internal(m) => CompileError::Internal(m), + })?; + Ok((code, info)) + } + /// Turns a compile failure inside a running script into what it throws. pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt { match e { @@ -3316,10 +3424,96 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + chained: false, }); Ok(()) } + /// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4, + /// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global + /// scope holds its variables and functions, and one inside that its `let` and `const` names, + /// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary + /// roots for the caller to remove. + pub(crate) fn instantiate_module(&mut self, code: &Rc) -> JsResult<(EnvId, EnvId)> { + self.charge_code(code, declaration_bytes(code).saturating_add(ENV_BYTES))?; + let scope = self.global_lex; + let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); + self.temp_envs.push(env); + let lex = self.instantiate_global(code, env, env, true)?; + self.temp_envs.push(lex); + Ok((lex, env)) + } + + /// Adds `binding` (an import) to the module environment `env`, which must not have `name`. + pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> { + self.use_fuel()?; + // The binding's value (a namespace object) stays reachable while room is made. + self.temp_roots.push(binding.value.clone()); + let reserved = self.reserve_heap(binding_bytes(name.len())); + self.temp_roots.pop(); + reserved?; + self.env_insert(env, name, binding) + } + + /// The environment that holds `name` of a module whose code runs in `lex` inside `env`. + pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option { + [lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name))) + } + + /// A module namespace object for the exports `exports`, each `(name, binding)` with the + /// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit + /// order and distinct. + pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult { + let bytes = exports.iter().map(|(k, _)| binding_bytes(k.len()).saturating_mul(2)).sum::(); + self.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let mut object = Object::new(Class::ModuleNamespace(Box::default()), None); + object.extensible = false; + for (name, _) in &exports { + self.use_fuel()?; + let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone()); + object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE }); + } + object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports })); + Ok(self.heap.alloc_object(object)) + } + + /// Pushes the frames of a run of modules: `modules` in the order they run, each with its code, + /// the environment it runs in and the outer one. The last is the boundary frame, pushed first; + /// each of the others is pushed above the one that runs after it, so the first to run is on + /// top. + pub(crate) fn push_module_frames(&mut self, modules: &[(Rc, EnvId, EnvId)]) -> JsResult<()> { + for (i, (code, env, var_env)) in modules.iter().enumerate().rev() { + let last = i + 1 == modules.len(); + self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?; + if let Some(frame) = self.frames.last_mut() { + frame.chained = !last; + } + } + Ok(()) + } + + /// Ends module linking: drops the temporary roots from `mark` on. + pub(crate) fn drop_temp_envs(&mut self, mark: usize) { + self.temp_envs.truncate(mark); + } + + pub(crate) fn temp_envs_mark(&self) -> usize { + self.temp_envs.len() + } + + /// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it. + pub(crate) fn hold(&mut self, v: Value) { + self.temp_roots.push(v); + } + + pub(crate) fn temp_roots_mark(&self) -> usize { + self.temp_roots.len() + } + + pub(crate) fn drop_temp_roots(&mut self, mark: usize) { + self.temp_roots.truncate(mark); + } + /// Declaration binding instantiation for global and eval code (section 10.5). The caller has /// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel. /// diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index f1fa58730f..8f99275192 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -55,8 +55,14 @@ //! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and //! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again //! before each element, strings and `String` objects by code point, and objects with a `length` by -//! index; other values are a `TypeError`. Destructuring, `for … of`, classes, -//! generators and modules stay syntax errors. +//! index; other values are a `TypeError`. Destructuring, `for … of`, classes and generators stay +//! syntax errors, and so do `import` and `export` in a script. +//! +//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import` +//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a +//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module +//! once, after the modules it imports, with each import reading the exporting module's binding. +//! Dynamic `import()` is a syntax error. #![forbid(unsafe_code)] pub mod ast; @@ -71,6 +77,7 @@ mod heap; mod host; mod interp; mod lexer; +mod module; mod number; mod number_builtins; mod parser; @@ -86,13 +93,15 @@ mod xml_builtins; mod xpath; pub use ast::{ - AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program, - Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, CatchClause, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, + ImportEntry, ImportName, LexKind, LogicalOp, ModuleInfo, ModuleRequest, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, + SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use lexer::{Goal, Lexer}; +pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; @@ -140,6 +149,34 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result Result<(Program, ModuleInfo), SyntaxError> { + let units = to_utf16(source, options)?; + parse_module_utf16(&units, options) +} + +/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]). +pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> { + check_length(source.len(), options)?; + parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info)) +} + +/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module +/// ([`parse_module`]). The source must be a valid module. +pub fn tokenize_module(source: &str, options: &Options) -> Result, SyntaxError> { + let units = to_utf16(source, options)?; + check_length(units.len(), options)?; + parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens) +} + +/// `options` as a module is read with them. +pub(crate) fn module_options(options: &Options) -> Options { + Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() } +} + /// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and /// each `/` read as division or as the start of a regular expression literal as the grammar /// decides. The source must be a valid script. @@ -227,6 +264,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod module_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs new file mode 100644 index 0000000000..b706c280f5 --- /dev/null +++ b/crates/js/src/module.rs @@ -0,0 +1,448 @@ +//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports, +//! linking their imports to the bindings their exports name, and readying them to run, each once, +//! the modules a module imports before it. +//! +//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17, +//! HostResolveImportedModule): it gives a key that names the module, and its source the first time +//! it gives that key. Every module is parsed and compiled before any runs, and every import is +//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host +//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many +//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each +//! binding made in linking takes a unit. +//! +//! An import reads the exporting module's binding itself, so it sees each later assignment, and a +//! read before that binding is initialized (a module that imports one that imports it back) is a +//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no +//! prototype, takes no writes and has the module's export names, in code unit order, as its +//! properties. `export *` passes on every name but `default`; a name two `export *` give from +//! different bindings is left out of a namespace and is a `SyntaxError` to import. + +use std::collections::HashMap; +use std::rc::Rc; + +use crate::ast::{ExportEntry, ImportName, ModuleInfo}; +use crate::bytecode::Code; +use crate::heap::{Binding, EnvId, ObjId, Prop, key}; +use crate::interp::{Abrupt, CompileError, ErrorType, Interp}; +use crate::value::Value; + +/// What the host gives for a module a run imports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LoadedModule { + /// What names the module: two specifiers that give one key import one module, which runs once. + pub key: String, + /// The module's source, given the first time the host gives its key in a run. `None` for a key + /// the host gave before in the same run. + pub source: Option, +} + +/// Why the host cannot give a module, which ends the run before any module runs: the error the +/// `import` raises, with its message. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LoadError { + /// A specifier the host does not read: a `SyntaxError`. + Syntax(String), + /// A limit of the host's: a `RangeError`. + Range(String), + /// A module that is missing, refused or unreadable: an `Error`. + Other(String), +} + +/// The host's map from a specifier to a module: called with the key of the importing module and +/// the specifier as written. +pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result + 'a; + +/// Bounds on the modules of one run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ModuleLimits { + /// The most modules a run loads, the first included. + pub modules: usize, + /// The most imports from the first module to any other, along the shortest chain. + pub depth: usize, +} + +impl Default for ModuleLimits { + fn default() -> Self { + Self { modules: 64, depth: 16 } + } +} + +/// The most modules a run loads, whatever its limits say: [`resolve_export`] and +/// [`exported_names`] recurse once for each module at most. +const MAX_MODULES: usize = 1024; +/// The most `(module, name)` pairs one export's resolution visits. +const MAX_RESOLVE_STEPS: usize = 1024; + +/// A loaded module. +struct Record { + key: String, + info: ModuleInfo, + code: Rc, + tag: u32, + /// The module each of `info.requests` names, by index. + requested: Vec, + /// The environment its code runs in and the outer one, once instantiated. + envs: Option<(EnvId, EnvId)>, + namespace: Option, +} + +/// Why a module run could not start. +pub(crate) enum LinkFail { + /// A module does not parse; `tag` is its source's. + Syntax { tag: u32, error: crate::SyntaxError }, + /// An exception, raised at `line` and `column` of the module whose source has `tag`. + At { tag: u32, line: u32, column: u32, abrupt: Abrupt }, + /// A limit or an internal error, not at any place. + Run(Abrupt), +} + +/// Where an export resolves to (ResolvedBinding). +#[derive(Clone, PartialEq, Eq)] +enum Resolution { + /// The binding `name` of module `module`. + Binding { module: usize, name: String }, + /// The namespace object of module `module` (`export * as ns from`). + Namespace(usize), +} + +/// An export that two `export *` declarations give from different places. +struct Ambiguous; + +/// The modules of a run, loaded and linked. +struct Graph<'a, 'l> { + interp: &'a mut Interp, + records: Vec, + by_key: HashMap, + load: &'a mut ModuleLoader<'l>, +} + +/// Loads the module `key` with `source` and every module it imports, instantiates and links them, +/// and gives them in the order they run, each with its code, the environment it runs in and the +/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes +/// the next tag. The environments stay in the interpreter's temporary roots for the caller to +/// remove once their frames are pushed. +pub(crate) fn link( + interp: &mut Interp, + key_name: &str, + source: &str, + entry_tag: u32, + limits: ModuleLimits, + load: &mut ModuleLoader<'_>, +) -> Result, EnvId, EnvId)>, LinkFail> { + let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load }; + if limits.modules == 0 { + return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached")); + } + graph.add(key_name.to_string(), source, entry_tag)?; + graph.load_imports(limits)?; + graph.instantiate()?; + graph.link_imports()?; + Ok(graph.evaluation_order()) +} + +impl Graph<'_, '_> { + /// Parses and compiles a module's source under `tag`. + fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result { + let interp = &mut *self.interp; + interp.prepare_source(source.len()).map_err(LinkFail::Run)?; + let saved = std::mem::replace(&mut interp.source_tag, tag); + let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units)); + interp.source_tag = saved; + let (code, info) = match compiled { + Ok(c) => c, + Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }), + Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))), + }; + self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None }); + let index = self.records.len() - 1; + self.by_key.insert(key_name, index); + Ok(index) + } + + /// An exception of type `t` with `message`, at the source offset `offset` of module `m`. + fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail { + let (tag, (line, column)) = match self.records.get(m) { + Some(r) => (r.tag, r.code.source.lines.line_column(offset)), + None => (crate::realm::UNKNOWN_SOURCE, (0, 0)), + }; + LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) } + } + + /// Loads the modules each loaded module imports, breadth first, so a module's depth is the + /// length of the shortest chain of imports to it. + fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> { + let max_modules = limits.modules.min(MAX_MODULES); + let mut depths = vec![0usize]; + let mut i = 0; + while i < self.records.len() { + let requests: Vec<(String, u32)> = self.records[i].info.requests.iter().map(|r| (r.specifier.clone(), r.span.start)).collect(); + let depth = depths.get(i).copied().unwrap_or(0); + for (specifier, offset) in requests { + self.interp.use_fuel().map_err(LinkFail::Run)?; + let referrer = self.records[i].key.clone(); + let loaded = match (self.load)(&referrer, &specifier) { + Ok(loaded) => loaded, + Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)), + Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)), + Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)), + }; + let target = match (self.by_key.get(&loaded.key), loaded.source) { + (Some(&j), _) => j, + (None, None) => { + let message = format!("the module '{specifier}' was given without its source"); + return Err(self.fail_at(i, offset, ErrorType::Error, &message)); + } + (None, Some(source)) => { + if depth >= limits.depth { + let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth); + return Err(self.fail_at(i, offset, ErrorType::Range, &message)); + } + if self.records.len() >= max_modules { + let message = format!("module limit ({max_modules}) reached at '{specifier}'"); + return Err(self.fail_at(i, offset, ErrorType::Range, &message)); + } + let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag)); + self.interp.evaluated = tag; + depths.push(depth + 1); + self.add(loaded.key, &source, tag)? + } + }; + self.records[i].requested.push(target); + } + i += 1; + } + Ok(()) + } + + /// Makes each module's environments, with its variables, functions and `let` and `const` + /// names. + fn instantiate(&mut self) -> Result<(), LinkFail> { + for i in 0..self.records.len() { + let code = self.records[i].code.clone(); + let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?; + self.records[i].envs = Some(envs); + } + Ok(()) + } + + /// The module the request `request` of module `m` names. + fn target(&self, m: usize, request: usize) -> Option { + self.records.get(m).and_then(|r| r.requested.get(request)).copied() + } + + /// The specifier of request `request` of module `m`, as written. + fn specifier(&self, m: usize, request: usize) -> String { + self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default() + } + + /// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from, + /// `None` when the module has no such export (or only through a cycle). + fn resolve_export(&mut self, m: usize, name: &str, seen: &mut Vec<(usize, String)>) -> Result, Ambiguous>, LinkFail> { + if seen.iter().any(|(sm, sn)| *sm == m && sn == name) { + return Ok(Ok(None)); + } + if seen.len() >= MAX_RESOLVE_STEPS { + let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'"); + return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message))); + } + self.interp.use_fuel().map_err(LinkFail::Run)?; + seen.push((m, name.to_string())); + let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); + for e in &exports { + match e { + ExportEntry::Local { export_name, local, .. } if export_name == name => { + return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))); + } + ExportEntry::Indirect { export_name, request, import, .. } if export_name == name => { + let Some(t) = self.target(m, *request) else { return Ok(Ok(None)) }; + return match import { + ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))), + ImportName::Name(n) => self.resolve_export(t, n, seen), + }; + } + _ => {} + } + } + if name == "default" { + return Ok(Ok(None)); + } + let mut star = None; + for e in &exports { + let ExportEntry::Star { request, .. } = e else { continue }; + let Some(t) = self.target(m, *request) else { continue }; + match self.resolve_export(t, name, seen)? { + Err(Ambiguous) => return Ok(Err(Ambiguous)), + Ok(None) => {} + Ok(Some(r)) => match &star { + None => star = Some(r), + Some(s) if *s == r => {} + Some(_) => return Ok(Err(Ambiguous)), + }, + } + } + Ok(Ok(star)) + } + + /// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its + /// `export *` modules but `default` included, each once. + fn exported_names(&mut self, m: usize, star: bool, visited: &mut Vec, names: &mut Vec) -> Result<(), LinkFail> { + if visited.contains(&m) { + return Ok(()); + } + visited.push(m); + let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); + for e in &exports { + self.interp.use_fuel().map_err(LinkFail::Run)?; + match e { + ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { + if !(star && export_name == "default") && !names.contains(export_name) { + names.push(export_name.clone()); + } + } + ExportEntry::Star { request, .. } => { + if let Some(t) = self.target(m, *request) { + self.exported_names(t, true, visited, names)?; + } + } + } + } + Ok(()) + } + + /// The environment and name of the binding `name` of module `m`. + fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> { + let (lex, env) = self.records.get(m)?.envs?; + let k = key(name); + self.interp.module_binding(lex, env, &k).map(|e| (e, k)) + } + + /// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time. + fn namespace(&mut self, m: usize) -> Result { + if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) { + return Ok(ns); + } + let mut names = Vec::new(); + self.exported_names(m, false, &mut Vec::new(), &mut names)?; + let mut resolved = Vec::new(); + for name in names { + if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { + resolved.push((key(&name), r)); + } + } + resolved.sort_by(|(a, _), (b, _)| a.cmp(b)); + let mut exports = Vec::new(); + let mut later = Vec::new(); + for (k, r) in resolved { + match r { + Resolution::Binding { module, name } => match self.binding_of(module, &name) { + Some(b) => exports.push((k, Some(b))), + None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))), + }, + Resolution::Namespace(module) => { + exports.push((k.clone(), None)); + later.push((k, module)); + } + } + } + let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?; + self.interp.hold(Value::Object(ns)); + if let Some(r) = self.records.get_mut(m) { + r.namespace = Some(ns); + } + // A namespace that holds another is made first, so two that hold each other end. + for (k, module) in later { + let inner = self.namespace(module)?; + let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE; + self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?; + } + Ok(ns) + } + + /// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that + /// each re-export resolves. + fn link_imports(&mut self) -> Result<(), LinkFail> { + for m in 0..self.records.len() { + let exports = self.records[m].info.exports.clone(); + for e in &exports { + let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue }; + if self.target(m, *request).is_none() { + continue; + } + match self.resolve_export(m, export_name, &mut Vec::new())? { + Ok(Some(_)) => {} + Ok(None) => { + let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request)); + return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message)); + } + Err(Ambiguous) => { + let message = format!("the export '{export_name}' is ambiguous"); + return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message)); + } + } + } + let imports = self.records[m].info.imports.clone(); + let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) }; + for imp in imports { + let Some(t) = self.target(m, imp.request) else { continue }; + let local = key(&imp.local.name); + let binding = match &imp.import { + ImportName::Namespace => self.namespace_binding(t)?, + ImportName::Name(n) => match self.resolve_export(t, n, &mut Vec::new())? { + Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) { + Some((target_env, target_name)) => Binding::import(target_env, target_name), + None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))), + }, + Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?, + Ok(None) => { + let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request)); + return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message)); + } + Err(Ambiguous) => { + let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request)); + return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message)); + } + }, + }; + self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?; + } + } + Ok(()) + } + + /// An immutable binding of module `m`'s namespace object. + fn namespace_binding(&mut self, m: usize) -> Result { + let ns = self.namespace(m)?; + Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) }) + } + + /// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module + /// after the modules it imports, in the order it imports them, and each once; a module an + /// import cycle reaches again while it waits is not waited for. + fn evaluation_order(&self) -> Vec<(Rc, EnvId, EnvId)> { + let mut state = vec![0u8; self.records.len()]; + let mut order = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + if let Some(s) = state.first_mut() { + *s = 1; + } + while let Some(top) = stack.last_mut() { + let m = top.0; + let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice()); + if let Some(&t) = requested.get(top.1) { + top.1 += 1; + if let Some(s @ 0) = state.get_mut(t) { + *s = 1; + stack.push((t, 0)); + } + continue; + } + stack.pop(); + if let Some(r) = self.records.get(m) + && let Some((lex, env)) = r.envs + { + order.push((r.code.clone(), lex, env)); + } + } + order + } +} diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs new file mode 100644 index 0000000000..26f453b652 --- /dev/null +++ b/crates/js/src/module_tests.rs @@ -0,0 +1,419 @@ +use std::collections::{HashMap, HashSet}; + +use crate::{ + JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module, +}; + +fn es() -> Realm { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()); + // Modules declare no globals, so they report through this array. + assert!(realm.run("var out = [];").is_ok()); + realm +} + +/// A loader over `files`: each specifier is its own key, given with its source the first time. +fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result + use<> { + let map: HashMap = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let mut given = HashSet::new(); + move |_, specifier| { + if !specifier.starts_with('.') && specifier != "main" { + return Err(LoadError::Syntax(format!("bare specifier: {specifier}"))); + } + let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?; + let first = given.insert(specifier.to_string()); + Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) }) + } +} + +/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`. +fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result, String) { + let mut load = loader(files); + let result = realm.run_module("main.mjs", entry, limits, &mut load); + let out = match realm.run("out.join('|')") { + Ok(JsValue::String(s)) => s, + other => panic!("{other:?}"), + }; + (result, out) +} + +fn run(entry: &str, files: &[(&str, &str)]) -> String { + match run_with(&mut es(), entry, files, ModuleLimits::default()) { + (Ok(v), out) => { + assert_eq!(v, JsValue::Undefined); + out + } + (Err(e), _) => panic!("{entry}\n{e:?}"), + } +} + +/// The run ends with an error whose message starts with `start`, and `out` holds `ran`. +fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError { + match run_with(&mut es(), entry, files, ModuleLimits::default()) { + (Err(e), out) => { + assert!(e.message.starts_with(start), "{entry}: {e:?}"); + assert_eq!(out, ran, "{entry}"); + e + } + (Ok(_), out) => panic!("{entry}: completed with {out}"), + } +} + +fn syntax(src: &str) { + assert!(parse_module(src, &Options::default()).is_err(), "{src}"); +} + +#[test] +fn an_import_reads_the_exporting_binding_each_time() { + let counter = "export let count = 0; export function inc() { count++; }"; + let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]); + assert_eq!(out, "0|2"); +} + +#[test] +fn imports_can_be_renamed_and_combined() { + let m = "export default 'd'; export var a = 1; export const b = 2;"; + let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]); + assert_eq!(out, "d|1|2"); + let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]); + assert_eq!(out, "d|1|d"); +} + +#[test] +fn default_exports_of_expressions_and_functions() { + let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]); + assert_eq!(out, "42"); + let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]); + assert_eq!(out, "anon"); + // A named default function is a declaration: hoisted, and its name is bound in the module. + let f = "out.push(typeof g); export default function g() { return 'g'; }"; + let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]); + assert_eq!(out, "function|g"); +} + +#[test] +fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() { + let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;"; + let out = run( + "import * as ns from './m.mjs'; + out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null); + try { ns.alpha = 5; } catch (e) { out.push(e.name); } + try { ns.added = 5; } catch (e) { out.push(e.name); } + try { delete ns.alpha; } catch (e) { out.push(e.name); } + out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);", + &[("./m.mjs", m)], + ); + assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true"); +} + +#[test] +fn a_namespace_takes_only_definitions_that_change_nothing() { + let m = "export var a = 1;"; + let out = run( + "import * as ns from './m.mjs'; + out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns)); + out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns); + var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }]; + for (var i = 0; i < ds.length; i++) { + try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); } + } + try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); } + try { Object.freeze(ns); } catch (e) { out.push(e.name); } + out.push(ns.a);", + &[("./m.mjs", m)], + ); + assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1"); +} + +#[test] +fn a_namespace_reads_live_values() { + let m = "export var n = 1; export function bump() { n = n + 1; }"; + let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]); + assert_eq!(out, "2"); +} + +#[test] +fn assigning_to_an_import_is_a_type_error() { + let m = "export var a = 1;"; + let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]); + assert_eq!(out, "TypeError|1"); + let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]); + assert_eq!(out, "TypeError"); +} + +#[test] +fn a_cycle_of_two_modules_runs_each_once_dependency_first() { + // main imports b, b imports main back: b runs first and sees main's hoisted function. + let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';"; + let mut realm = es(); + let mut load = loader(&[("./b.mjs", b), ("main", "")]); + let mut load = |referrer: &str, specifier: &str| { + if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) } + }; + let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);"; + let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load); + assert_eq!(r, Ok(JsValue::Undefined)); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into()))); +} + +#[test] +fn reading_an_import_before_its_module_ran_is_a_reference_error() { + let b = "import { a } from 'main'; out.push('b'); out.push(a);"; + let mut realm = es(); + let mut inner = loader(&[("./b.mjs", b)]); + let mut load = |referrer: &str, specifier: &str| { + if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) } + }; + let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load); + match r { + Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"), + other => panic!("{other:?}"), + } + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into()))); +} + +#[test] +fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { + let b = "import * as ns from 'main'; + var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'), + () => Object.getOwnPropertyDescriptor(ns, 'a'), () => { for (var k in ns) {} }, () => Object.isSealed(ns), () => Object.isFrozen(ns), + () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns)]; + tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } }); + out.push('a' in ns, Object.getOwnPropertyNames(ns).join());"; + let mut realm = es(); + let mut inner = loader(&[("./b.mjs", b)]); + let mut load = |referrer: &str, specifier: &str| { + if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) } + }; + let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load); + assert_eq!(r, Ok(JsValue::Undefined)); + let errors = "ReferenceError|".repeat(12); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}true|a")))); +} + +#[test] +fn a_module_two_modules_import_runs_once() { + let shared = "out.push('shared'); export var s = 1;"; + let a = "import { s } from './shared.mjs'; out.push('a' + s);"; + let b = "import { s } from './shared.mjs'; out.push('b' + s);"; + let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]); + assert_eq!(out, "shared|a1|b1|main"); +} + +#[test] +fn re_exports_pass_names_on() { + let base = "export var x = 1, y = 2; export default 'base';"; + let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';"; + let out = run( + "import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));", + &[("./base.mjs", base), ("./mid.mjs", mid)], + ); + // `export *` does not pass `default` on. + assert_eq!(out, "1|1|2|base|all,renamed,x,y"); +} + +#[test] +fn an_exported_import_is_a_re_export() { + let base = "export var v = 'v';"; + let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };"; + let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]); + assert_eq!(out, "v|v"); +} + +#[test] +fn a_name_two_stars_give_is_ambiguous() { + let files = + [("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")]; + fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", ""); + // The namespace leaves the name out. + let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files); + assert_eq!(out, "0"); +} + +#[test] +fn a_missing_export_ends_the_run_before_any_module_runs() { + let files = [("./m.mjs", "out.push('m'); export var a = 1;")]; + let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", ""); + assert_eq!((e.line, e.column), (1, 10)); + let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")]; + fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", ""); +} + +#[test] +fn a_module_the_loader_cannot_give_is_named_in_the_error() { + let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", ""); + assert_eq!(e.line, 2); + fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", ""); +} + +#[test] +fn a_syntax_error_in_an_imported_module_names_its_source() { + let mut realm = es(); + let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]); + let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load); + let e = r.err().unwrap_or_else(|| panic!("ran")); + assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2)); + // The entry is source 0, then each module in the order it was loaded. + assert_eq!(realm.error_source(), 2); + assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0))); +} + +#[test] +fn module_code_is_strict_and_its_this_is_undefined() { + let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]); + assert_eq!(out, "true|true|ReferenceError"); + // Its declarations stay in the module. + let mut realm = es(); + let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default()); + assert_eq!(r, Ok(JsValue::Undefined)); + assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into()))); +} + +#[test] +fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() { + let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")]; + fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a"); +} + +#[test] +fn the_module_count_and_import_depth_are_limited() { + let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")]; + let mut realm = es(); + let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 }); + assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}"); + assert_eq!(out, ""); + let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 }); + assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}"); + let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 }); + assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c")); +} + +#[test] +fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() { + let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")]; + let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 }); + assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a")); +} + +#[test] +fn a_module_limit_of_zero_runs_no_module() { + let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 }); + assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}"); + assert_eq!(out, ""); +} + +#[test] +fn a_module_run_is_held_to_the_fuel_limit() { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() }); + let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]); + let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load); + assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel))); +} + +#[test] +fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() { + let mut realm = es(); + let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]); + let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');"; + assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(())); + let mut slices = 0; + loop { + match realm.advance(10) { + Ok(Progress::Paused) => slices += 1, + Ok(Progress::Done(v)) => { + assert_eq!(v, JsValue::Undefined); + break; + } + Err(e) => panic!("{e:?}"), + } + } + assert!(slices > 20, "{slices}"); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into()))); +} + +#[test] +fn an_es5_realm_runs_no_module() { + let mut realm = Realm::new(); + let mut load = loader(&[]); + let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load); + assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax)); +} + +#[test] +fn a_script_does_not_read_import_or_export() { + for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] { + assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}"); + assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}"); + } +} + +#[test] +fn module_early_errors() { + for src in [ + "export var a; export { a };", + "export { undeclared };", + "export default 1; export default 2;", + "import { a } from './x.mjs'; var a;", + "var a; import a from './x.mjs';", + "import { a, a } from './x.mjs';", + "function f() { import a from './x.mjs'; }", + "{ export var a; }", + "import { default } from './x.mjs';", + "export { default };", + "import a from x;", + "import * from './x.mjs';", + "with (a) {}", + "export default class {}", + "import('./x.mjs');", + "#include 'x.js'\n", + // Top-level functions are lexical declarations in a module. + "function f() {} function f() {}", + "var f; function f() {}", + "function f() {} var f;", + "let f; function f() {}", + ] { + syntax(src); + } + for src in [ + "import { default as d, if as i } from './x.mjs'; export { d as default, i as if };", + "import {} from './x.mjs'; export {};", + "export function f() {} export { f as g };", + "var as = 1, from = 2; export { as, from };", + "export * as default from './x.mjs';", + "function f() {} { function f() {} } function g() { var g; function h() {} var h; }", + ] { + assert!(parse_module(src, &Options::default()).is_ok(), "{src}"); + } +} + +#[test] +fn a_module_lists_what_it_imports_and_exports() { + let (_, info) = + match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default()) + { + Ok(p) => p, + Err(e) => panic!("{e:?}"), + }; + let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect(); + assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]); + assert_eq!(info.imports.len(), 2); + assert!( + matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d") + ); +} + +#[test] +fn modules_survive_a_collection_while_they_link() { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() }); + assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok()); + let m = "export var v = 'kept'; export function f() { return v; }"; + let mut load = loader(&[("./m.mjs", m)]); + let r = realm.run_module( + "main.mjs", + "import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());", + ModuleLimits::default(), + &mut load, + ); + assert_eq!(r, Ok(JsValue::Undefined)); + realm.collect_garbage(); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into()))); +} diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index edc6b22c9a..28b7cd5f72 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -7,6 +7,7 @@ //! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long //! runs of them do not nest at all. +mod module; mod xml; use std::collections::{HashMap, HashSet}; @@ -101,6 +102,9 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical + /// declarations (ECMA-262 2015 section 15.2.1.11). + module: bool, } impl<'s> Parser<'s> { @@ -125,6 +129,7 @@ impl<'s> Parser<'s> { e4x: options.e4x, es2015: options.es2015, scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + module: false, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -342,6 +347,9 @@ impl<'s> Parser<'s> { /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + if self.module && self.scopes.len() == 1 { + return self.declare_lexical(&name, true); + } match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs new file mode 100644 index 0000000000..ec39092afb --- /dev/null +++ b/crates/js/src/parser/module.rs @@ -0,0 +1,299 @@ +//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a +//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1). +//! +//! A module is strict mode code throughout. An import binds its names as lexical declarations at +//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name +//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an +//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be +//! exported once, and a name an `export { … }` list exports from the module itself must be one it +//! declares or imports. + +use std::collections::HashSet; + +use super::{Parser, Result, describe}; +use crate::ast::{ + DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId, VarDecl, +}; +use crate::token::{Keyword, Punct, Span, Token, TokenKind}; + +/// A name an `export { … }` list without `from` exports: the module's own binding (or import) +/// `local`, exported as `export_name`. +struct ClauseExport { + export_name: String, + local: String, + span: Span, +} + +impl Parser<'_> { + /// Reads the source as a module: its statements, without its import and export declarations + /// but with the declarations they export, and what it imports and exports. + pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec)> { + self.module = true; + let mut info = ModuleInfo::default(); + let mut clause = Vec::new(); + let mut body = Vec::new(); + while self.tok.kind != TokenKind::Eof { + if self.at_keyword(Keyword::Import) { + self.import_declaration(&mut info)?; + } else if self.at_keyword(Keyword::Export) { + if let Some(stmt) = self.export_declaration(&mut info, &mut clause)? { + body.push(stmt); + } + } else { + body.push(self.parse_statement_item()?); + } + } + self.finish_exports(&mut info, clause)?; + if let Some(tokens) = &mut self.tokens { + tokens.push(self.tok.clone()); + } + let program = Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015 }; + Ok((program, info, self.tokens.unwrap_or_default())) + } + + /// The current token is the contextual keyword `word` (`as` or `from`), written without escapes. + fn at_contextual(&self, word: &str) -> bool { + self.tok.ident() == Some(word) && !self.tok.escaped + } + + fn expect_contextual(&mut self, word: &str) -> Result<()> { + if self.at_contextual(word) { + self.bump()?; + return Ok(()); + } + Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok)))) + } + + /// A module specifier: a string literal, added to the module's requests once. → its index. + fn module_specifier(&mut self, info: &mut ModuleInfo) -> Result { + let TokenKind::String(units) = &self.tok.kind else { + return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok)))); + }; + let Ok(specifier) = String::from_utf16(units) else { + return Err(self.error_at_token(&self.tok, "a module specifier must be valid text")); + }; + let span = self.bump()?.span; + if let Some(i) = info.requests.iter().position(|r| r.specifier == specifier) { + return Ok(i); + } + info.requests.push(ModuleRequest { specifier, span }); + Ok(info.requests.len() - 1) + } + + /// A name as an import or export list gives it: any identifier name, keywords included. → the + /// name and whether it was an identifier (not a keyword). + fn list_name(&mut self) -> Result<(Name, bool)> { + let Some(name) = self.tok.identifier_name().map(str::to_string) else { + return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok)))); + }; + let ident = matches!(self.tok.kind, TokenKind::Ident(_)); + let token = self.bump()?; + Ok((Name { name, span: token.span }, ident)) + } + + /// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope. + fn import_declaration(&mut self, info: &mut ModuleInfo) -> Result<()> { + let import = self.bump()?; + if self.at(Punct::LParen) { + return Err(self.error_at_token(&import, "import() is not supported")); + } + if matches!(self.tok.kind, TokenKind::String(_)) { + self.module_specifier(info)?; + return self.semicolon(); + } + let mut bound: Vec<(ImportName, Name)> = Vec::new(); + let mut list = true; + if matches!(self.tok.kind, TokenKind::Ident(_)) { + let local = self.binding_identifier()?; + bound.push((ImportName::Name("default".into()), local)); + list = self.eat(Punct::Comma)?; + } + if list { + if self.eat(Punct::Star)? { + self.expect_contextual("as")?; + let local = self.binding_identifier()?; + bound.push((ImportName::Namespace, local)); + } else { + self.expect(Punct::LBrace)?; + while !self.at(Punct::RBrace) { + if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() { + // A name without `as` binds itself, so it must be one a declaration may bind. + let local = self.binding_identifier()?; + bound.push((ImportName::Name(local.name.clone()), local)); + } else { + let (imported, _) = self.list_name()?; + self.expect_contextual("as")?; + let local = self.binding_identifier()?; + bound.push((ImportName::Name(imported.name), local)); + } + if !self.eat(Punct::Comma)? { + break; + } + } + self.expect(Punct::RBrace)?; + } + } + self.expect_contextual("from")?; + let request = self.module_specifier(info)?; + self.semicolon()?; + for (import, local) in bound { + self.declare_lexical(&local, false)?; + info.imports.push(ImportEntry { request, import, local }); + } + Ok(()) + } + + /// The token after the current one is the contextual keyword `as`. + fn next_is_as(&self) -> bool { + self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as")) + } + + /// `export …` (section 15.2.3). → the declaration it exports, which runs in place. + fn export_declaration(&mut self, info: &mut ModuleInfo, clause: &mut Vec) -> Result> { + let export = self.bump()?; + let span = export.span; + if self.eat(Punct::Star)? { + if self.at_contextual("as") { + self.bump()?; + let (name, _) = self.list_name()?; + self.expect_contextual("from")?; + let request = self.module_specifier(info)?; + self.semicolon()?; + info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span }); + return Ok(None); + } + self.expect_contextual("from")?; + let request = self.module_specifier(info)?; + self.semicolon()?; + info.exports.push(ExportEntry::Star { request, span }); + return Ok(None); + } + if self.at(Punct::LBrace) { + self.bump()?; + // Each name: the name it refers to (and whether that was an identifier) and the name it + // is exported as. + let mut names: Vec<(Name, bool, Name)> = Vec::new(); + while !self.at(Punct::RBrace) { + let (local, ident) = self.list_name()?; + let exported = if self.at_contextual("as") { + self.bump()?; + self.list_name()?.0 + } else { + local.clone() + }; + names.push((local, ident, exported)); + if !self.eat(Punct::Comma)? { + break; + } + } + self.expect(Punct::RBrace)?; + if self.at_contextual("from") { + self.bump()?; + let request = self.module_specifier(info)?; + self.semicolon()?; + for (local, _, exported) in names { + let import = ImportName::Name(local.name); + info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span }); + } + return Ok(None); + } + self.semicolon()?; + for (local, ident, exported) in names { + // Without `from`, each name refers to a binding of the module (section 15.2.3.1). + if !ident || crate::token::strict_reserved(&local.name) { + return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name))); + } + clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span }); + } + return Ok(None); + } + if self.at_keyword(Keyword::Default) { + self.bump()?; + return self.export_default(info, span).map(Some); + } + let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some(); + if !exportable { + return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok)))); + } + let stmt = self.parse_statement_item()?; + let names: Vec = match self.ast.stmt(stmt) { + Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().map(|d| d.name.clone()).collect(), + Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(), + _ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")), + }; + for name in names { + info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span }); + } + Ok(Some(stmt)) + } + + /// `export default …` after `default`: a function declaration (named or not) or an expression. + fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result { + if self.at_keyword(Keyword::Class) { + return Err(self.error_at_token(&self.tok, "classes are not supported")); + } + if self.at_keyword(Keyword::Function) { + self.enter()?; + let result = self.default_function(); + self.leave(); + let (stmt, fid, local) = result?; + self.declare_function(fid)?; + info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span }); + return Ok(stmt); + } + let start = self.tok.span; + let value = self.parse_assignment(false)?; + self.semicolon()?; + let name = Name { name: DEFAULT_BINDING.into(), span: start }; + let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { name, init: Some(value) }]), self.span_from(start)); + info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span }); + Ok(stmt) + } + + /// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of + /// `name`, or of [`DEFAULT_BINDING`] for a function without one. + fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> { + let keyword = self.expect_keyword(Keyword::Function)?; + let start = keyword.span; + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { + self.function_name()? + } else { + (Name { name: DEFAULT_BINDING.into(), span: start }, keyword) + }; + let local = name.0.name.clone(); + let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start)); + Ok((stmt, fid, local)) + } + + /// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and + /// each name an `export { … }` list takes from the module itself declared or imported there. An + /// exported import becomes a re-export of what it imports (section 15.2.1.16.1; a namespace + /// import as ECMA-262 2020 reads `export * as ns from`). + fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec) -> Result<()> { + let top = self.scopes.first(); + for c in clause { + let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local)); + if !declared { + return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local))); + } + let imported = info.imports.iter().find(|i| i.local.name == c.local); + let entry = match imported { + Some(i) => ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }, + None => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span }, + }; + info.exports.push(entry); + } + let mut seen = HashSet::new(); + for e in &info.exports { + let (name, span) = match e { + ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span), + ExportEntry::Star { .. } => continue, + }; + if !seen.insert(name.as_str()) { + return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once"))); + } + } + Ok(()) + } +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 728839949c..1765d6d9d1 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -7,9 +7,14 @@ use std::sync::atomic::{AtomicBool, Ordering}; use crate::bytecode::CodeKind; use crate::heap::{Func, HIDDEN, Object, Prop, key}; use crate::interp::{Abrupt, CompileError, Interp}; +use crate::module::{LinkFail, ModuleLimits, ModuleLoader}; use crate::value::Value; use crate::{Options, SyntaxError}; +fn internal_error(message: &str) -> RunError { + RunError { kind: RunErrorKind::Internal, message: message.to_string(), line: 0, column: 0, authored: false } +} + /// The limits a run is held to. Reaching one ends the run with [`RunErrorKind::Limit`]; scripts /// cannot catch it, and their `finally` blocks do not run. #[derive(Clone, Debug, PartialEq, Eq)] @@ -255,6 +260,75 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.reset_run()?; + let interp = &mut self.interp; + let strict = interp.options.strict; + interp.evaluated = next_tag(interp.evaluated); + self.script_tag = interp.evaluated; + interp.source_tag = self.script_tag; + let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); + interp.source_tag = UNKNOWN_SOURCE; + match code { + Ok(code) => Ok(code), + Err(CompileError::Syntax(e)) => { + interp.error_tag = self.script_tag; + Err(e.into()) + } + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), + } + } + + /// Begins a run of the module `key` with `source` (ECMA-262 2015 section 15.2), which + /// [`Realm::advance`] carries on as it does a script [`Realm::start`] began. `load` gives each + /// module a module imports ([`ModuleLoader`]). Every module is loaded, parsed and linked before + /// any runs, so a syntax error, an import of a missing or ambiguous export, a module `load` + /// cannot give or a module past `limits` ends the run here, with no code run. The first module + /// has [`Realm::script_tag`] as its source's tag, and each module loaded after it the next tag, + /// in the order `load` first gave their sources, as the sources an evaluator gives during a run + /// take theirs. A realm without [`Options::es2015`] runs no module: that is a syntax error. + pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> { + self.reset_run()?; + if !self.interp.options.es2015 { + let message = "modules need ECMAScript 2015; this script runs ECMAScript 5".to_string(); + return Err(RunError { kind: RunErrorKind::Syntax, message, line: 0, column: 0, authored: false }); + } + let interp = &mut self.interp; + interp.evaluated = next_tag(interp.evaluated); + self.script_tag = interp.evaluated; + let marks = (interp.temp_envs_mark(), interp.temp_roots_mark()); + let linked = crate::module::link(interp, key, source, self.script_tag, limits, load); + let pushed = match linked { + Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run), + Err(fail) => Err(fail), + }; + let interp = &mut self.interp; + interp.drop_temp_envs(marks.0); + interp.drop_temp_roots(marks.1); + match pushed { + Ok(()) => Ok(()), + Err(LinkFail::Syntax { tag, error }) => { + self.interp.error_tag = tag; + Err(error.into()) + } + Err(LinkFail::At { tag, line, column, abrupt }) => { + let e = self.outcome(Err(abrupt)).err(); + self.interp.error_tag = tag; + Err(e.map_or_else(|| internal_error("a module failed without an error"), |e| RunError { line, column, ..e })) + } + Err(LinkFail::Run(abrupt)) => self.outcome(Err(abrupt)).map(drop), + } + } + + /// Runs the module `key` with `source` to its end ([`Realm::start_module`]) and returns + /// `undefined`. + pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result { + self.start_module(key, source, limits, load)?; + let result = self.interp.execute(); + self.outcome(result) + } + + /// Readies the realm for a run: its state from the last run cleared and its fuel filled. + fn reset_run(&mut self) -> Result<(), RunError> { self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { @@ -274,20 +348,7 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.error_mark = None; - let strict = interp.options.strict; - interp.evaluated = next_tag(interp.evaluated); - self.script_tag = interp.evaluated; - interp.source_tag = self.script_tag; - let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); - interp.source_tag = UNKNOWN_SOURCE; - match code { - Ok(code) => Ok(code), - Err(CompileError::Syntax(e)) => { - interp.error_tag = self.script_tag; - Err(e.into()) - } - Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), - } + Ok(()) } /// The end of a run: its completion value or error, with the interpreter's stacks emptied. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 32790b3125..3e3472d634 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -30,7 +30,10 @@ //! //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters) without and with that option, and -//! prints both counts; its failures with the option go to `es2015-failures.txt`. +//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs +//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading +//! the fixture files they import from the suite, and as scripts for comparison; its failures as +//! modules go to `module-failures.txt`. //! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset @@ -46,7 +49,9 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; -use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; +use vectorcraft_js::{ + JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, tokenize_module, +}; /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] @@ -427,6 +432,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: Err(_) => return true, } } + uses_missing_builtin(&lists, missing) +} + +/// The tokens `lists` (of a test and the harness files it includes) use a missing built-in, as +/// [`needs_missing_builtin`] counts them. +fn uses_missing_builtin(lists: &[Vec], missing: &HashSet<&str>) -> bool { let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), @@ -793,6 +804,163 @@ fn run_es2015(dir: &Path) { assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); } +/// The folders under `test/language/` whose module tests [`modules_run`] reads. +const MODULE_FOLDERS: &[&str] = &["module-code", "import", "export"]; + +/// The feature tags a module test may carry: those of [`ES2015_FEATURES`] and `export * as ns from`. +const MODULE_FEATURES: &[&str] = + &["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "export-star-as-namespace-from-module"]; + +#[test] +fn modules_run() { + let Some(dir) = suite_dir() else { + println!("test262 modules: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_modules(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// The `/`-separated path, from the suite's folder, of the module `specifier` names for the module +/// at `referrer` (a path from the suite's folder too): only a `./` or `../` path that stays inside +/// `test/`. +fn module_path(referrer: &str, specifier: &str) -> Result { + if !(specifier.starts_with("./") || specifier.starts_with("../")) { + return Err(LoadError::Syntax(format!("the runner reads only relative specifiers: '{specifier}'"))); + } + let mut names: Vec<&str> = referrer.split('/').collect(); + names.pop(); + for name in specifier.split('/') { + match name { + "" | "." => {} + ".." if names.len() > 1 => { + names.pop(); + } + ".." => return Err(LoadError::Other(format!("'{specifier}' leads out of the suite's tests"))), + name => names.push(name), + } + } + Ok(names.join("/")) +} + +/// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with +/// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the +/// suite. `Err` describes a failure. A `negative_type` is the error the run must end with: thrown, +/// or, for a `SyntaxError`, also a module that does not parse. +fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?; + let mut given = HashSet::new(); + let mut load = |referrer: &str, specifier: &str| { + let key = module_path(referrer, specifier)?; + let path = inside(dir, &key).map_err(LoadError::Other)?; + let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None }; + Ok(LoadedModule { key, source }) + }; + match (realm.run_module(rel, source, ModuleLimits::default(), &mut load), negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some("SyntaxError")) if e.kind == RunErrorKind::Syntax => Ok(()), + (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { + realm.bind_last_thrown("__thrown"); + match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { + Ok(JsValue::Bool(true)) => Ok(()), + _ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)), + } + } + (Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)), + } +} + +/// Runs the module tests (`flags: [module]`) under [`MODULE_FOLDERS`] whose feature tags are all in +/// [`MODULE_FEATURES`], leaving out asynchronous tests and those that use a missing built-in: each +/// once as a strict script with [`Options::es2015`], as they could run before modules, and once as +/// a module, and prints both counts. A `negative: phase: parse` test must not parse as a module, +/// and a `phase: resolution` one must end before it runs with the error its `type:` names. +/// Failures as a module go to `module-failures.txt`. +fn run_modules(dir: &Path) { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let missing = missing_builtins(&[TEXT_BUILTINS]); + let options = Options { es2015: true, ..Options::default() }; + let (mut selected, mut skipped) = (0usize, 0usize); + let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize)); + let mut failures = String::new(); + for folder in MODULE_FOLDERS { + let root = or_fail(inside(dir, &format!("test/language/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if !has("module") || !meta.features.iter().all(|f| MODULE_FEATURES.contains(&f.as_str())) { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let phase = meta.negative_phase.as_deref(); + // A module that must not parse has no tokens to look at, and one that does not parse + // runs, to fail. + let missing_builtin = phase != Some("parse") + && match (tokenize_module(&source, &options), tokenize(&includes, &options)) { + (Ok(test), Ok(harness)) => uses_missing_builtin(&[test, harness], &missing), + (Err(_), Ok(_)) => false, + (_, Err(_)) => true, + }; + if has("async") || missing_builtin { + skipped += 1; + continue; + } + selected += 1; + let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution"))); + let as_script = if matches!(phase, Some("parse" | "resolution")) { + parse(&source, &Options { strict: true, ..options.clone() }).is_err() + } else { + run_one(&format!("\"use strict\";\n{prelude}{includes}{source}"), negative_type.as_deref(), &options).is_ok() + }; + if as_script { + before.0 += 1; + } else { + before.1 += 1; + } + let outcome = if phase == Some("parse") { + match vectorcraft_js::parse_module(&source, &options) { + Err(_) => Ok(()), + Ok(_) => Err("parsed; a SyntaxError was expected".to_string()), + } + } else { + let prelude = format!("{prelude}{includes}"); + match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative_type.as_deref(), &options)) { + Ok(r) => r, + Err(_) => Err("PANIC".to_string()), + } + }; + match outcome { + Ok(()) => after.0 += 1, + Err(why) => { + after.1 += 1; + failures.push_str(&format!("{rel}: {why}\n")); + } + } + } + } + assert!(selected > 0, "no module tests under {}", dir.display()); + let report = dir.join("module-failures.txt"); + if let Err(e) = std::fs::write(&report, &failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 modules: {selected} tests. As scripts: {} passed, {} failed. As modules: {} passed, {} failed. Skipped {skipped} \ + asynchronous or missing-built-in tests. Failures: {}", + before.0, + before.1, + after.0, + after.1, + report.display() + ); + assert!(!failures.contains("PANIC"), "the interpreter panicked; see {}", report.display()); +} + #[test] fn annex_b_runs() { let Some(dir) = suite_dir() else { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..ff97bd9a3e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2029,13 +2029,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..f281431dc5 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -3,7 +3,7 @@ //! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`. //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it -//! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › +//! asks for a `.js`, `.mjs` or `.jsx` file (the web opens the browser's file picker). With Preferences › //! General › Show External Script Warning off, the chosen script runs at once. Warning fields: //! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). //! @@ -145,7 +145,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result { let path = params.get("path").and_then(Value::as_str); if path.is_some_and(|path| !runs(path)) { - return Err("Choose a .js or .jsx script".into()); + return Err("Choose a .js, .mjs or .jsx script".into()); } if !app.session.prefs.show_external_script_warning { return app.run("script.run", params); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..0150154359 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6427,7 +6427,7 @@ digits Malayalam Malaiàlam Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet? -@msg Choose a .js or .jsx script Trieu un script .js o .jsx +@msg Choose a .js, .mjs or .jsx script Trieu un script .js, .mjs o .jsx @msg Ran {name} S'ha executat {name} @msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis @msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi @@ -6597,7 +6597,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB @msg `path` is empty `path` és buit @msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source` -@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` ha d’indicar un fitxer .js, .mjs o .jsx @msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source` @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..08fa462557 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5235,7 +5235,7 @@ imageTrace Outline Obrys Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny? -@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx +@msg Choose a .js, .mjs or .jsx script Vyberte skript .js, .mjs nebo .jsx @msg Ran {name} Spuštěno: {name} @msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny @msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení @@ -5382,7 +5382,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `args` is larger than 1 MiB `args` je větší než 1 MiB @msg `path` is empty `path` je prázdný @msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source` -@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` musí označovat soubor .js, .mjs nebo .jsx @msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source` @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..6ea9ba8e12 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -53,7 +53,7 @@ @msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB @msg its editing data is for a different page dens redigeringsdata er til en anden side @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox" -@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script +@msg Choose a .js, .mjs or .jsx script Vælg et .js-, .mjs- eller .jsx-script @msg Ran {name} Kørte {name} @msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt @msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt @@ -241,7 +241,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg `args` is larger than 1 MiB `args` er større end 1 MiB @msg `path` is empty `path` er tom @msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source` -@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil +@msg `path` must name a .js, .mjs or .jsx file `path` skal angive en .js-, .mjs- eller .jsx-fil @msg give exactly one of `path` and `source` angiv præcis én af `path` og `source` @msg Running a script Kører et script @msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..b915221d20 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4820,7 +4820,7 @@ theme Appearance Erscheinungsbild Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen? -@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript +@msg Choose a .js, .mjs or .jsx script Wählen Sie ein .js-, .mjs- oder .jsx-Skript @msg Ran {name} {name} ausgeführt @msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht @msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist @@ -8434,7 +8434,7 @@ breakText Glyphs Glyphen @msg `args` is larger than 1 MiB `args` ist größer als 1 MiB @msg `path` is empty `path` ist leer @msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source` -@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben +@msg `path` must name a .js, .mjs or .jsx file `path` muss eine .js-, .mjs- oder .jsx-Datei angeben @msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an @msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein @msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..3fdba11d4c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2624,7 +2624,7 @@ axis Both Και τα δύο Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε; -@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx +@msg Choose a .js, .mjs or .jsx script Επιλέξτε ένα σενάριο .js, .mjs ή .jsx @msg Ran {name} Εκτελέστηκε: {name} @msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν @msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει @@ -2795,7 +2795,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB @msg `path` is empty το `path` είναι κενό @msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source` -@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx +@msg `path` must name a .js, .mjs or .jsx file το `path` πρέπει να ορίζει αρχείο .js, .mjs ή .jsx @msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source` @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..b2e9ad14bd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4899,7 +4899,7 @@ axis Both Ambos Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo? -@msg Choose a .js or .jsx script Elija un script .js o .jsx +@msg Choose a .js, .mjs or .jsx script Elija un script .js, .mjs o .jsx @msg Ran {name} Se ejecutó {name} @msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron @msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine @@ -5069,7 +5069,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB @msg `path` is empty `path` está vacío @msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source` -@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` debe indicar un archivo .js, .mjs o .jsx @msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source` @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..b715bbc2ec 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5140,7 +5140,7 @@ imageTrace Outline Ääriviiva Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset? -@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja +@msg Choose a .js, .mjs or .jsx script Valitse .js-, .mjs- tai .jsx-komentosarja @msg Ran {name} Suoritettu: {name} @msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin @msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista @@ -5310,7 +5310,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB @msg `path` is empty `path` on tyhjä @msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa -@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto +@msg `path` must name a .js, .mjs or .jsx file `path` on oltava .js-, .mjs- tai .jsx-tiedosto @msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source` @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..ca239421f1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4881,7 +4881,7 @@ axis Both Les deux Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ? -@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx +@msg Choose a .js, .mjs or .jsx script Choisissez un script .js, .mjs ou .jsx @msg Ran {name} {name} exécuté @msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées @msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine @@ -5027,7 +5027,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `args` is larger than 1 MiB `args` dépasse 1 Mio @msg `path` is empty `path` est vide @msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source` -@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` doit désigner un fichier .js, .mjs ou .jsx @msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source` @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue @msg Running a script Exécution d’un script diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..65579ccc22 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7573,7 +7573,7 @@ arrowhead Feather पंख Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें? -@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें +@msg Choose a .js, .mjs or .jsx script .js, .mjs या .jsx स्क्रिप्ट चुनें @msg Ran {name} {name} चलाई गई @msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए @msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें @@ -7744,7 +7744,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है @msg `path` is empty `path` खाली है @msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं -@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए +@msg `path` must name a .js, .mjs or .jsx file `path` में किसी .js, .mjs या .jsx फ़ाइल का नाम होना चाहिए @msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..f1b34e6842 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5752,7 +5752,7 @@ imageTrace Outline Körvonal Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait? -@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt +@msg Choose a .js, .mjs or .jsx script Válasszon .js, .mjs vagy .jsx parancsfájlt @msg Ran {name} Lefutott: {name} @msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva @msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön @@ -5900,7 +5900,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál @msg `path` is empty a `path` üres @msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket -@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia +@msg `path` must name a .js, .mjs or .jsx file a `path` értékének .js, .mjs vagy .jsx fájlt kell megadnia @msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source` @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..cdb530f77c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -53,7 +53,7 @@ @msg it decompresses to more than {_1} MB hasil dekompresinya lebih dari {_1} MB @msg its editing data is for a different page data penyuntingannya untuk halaman lain @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` harus "emBox", "capHeight", "xHeight" atau "icfBox" -@msg Choose a .js or .jsx script Pilih skrip .js atau .jsx +@msg Choose a .js, .mjs or .jsx script Pilih skrip .js, .mjs, atau .jsx @msg Ran {name} {name} dijalankan @msg The script was stopped and its changes were undone Skrip dihentikan dan perubahannya dibatalkan @msg a script is running: stop it or wait for it to finish skrip sedang berjalan: hentikan atau tunggu hingga selesai @@ -148,7 +148,7 @@ @msg `args` is larger than 1 MiB `args` lebih besar dari 1 MiB @msg `path` is empty `path` kosong @msg `installed` takes a `path`, not a `source` `installed` menerima `path`, bukan `source` -@msg `path` must name a .js or .jsx file `path` harus menyebut file .js atau .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` harus menyebut file .js, .mjs, atau .jsx @msg give exactly one of `path` and `source` berikan tepat satu dari `path` dan `source` @msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} @msg `answers[{i}]` {e} `answers[{i}]` {e} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..8362a90183 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4958,7 +4958,7 @@ axis Both Entrambi Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto? -@msg Choose a .js or .jsx script Scegli uno script .js o .jsx +@msg Choose a .js, .mjs or .jsx script Scegli uno script .js, .mjs o .jsx @msg Ran {name} {name} eseguito @msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate @msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca @@ -8475,7 +8475,7 @@ breakText Glyphs Glifi @msg `args` is larger than 1 MiB `args` supera 1 MiB @msg `path` is empty `path` è vuoto @msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source` -@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` deve indicare un file .js, .mjs o .jsx @msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source` @msg `answers` must be a list of answers `answers` deve essere un elenco di risposte @msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..0655c91562 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5784,7 +5784,7 @@ variable-list-end {0}, {1} {0}、{1} Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか? -@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください +@msg Choose a .js, .mjs or .jsx script .js、.mjs または .jsx スクリプトを選択してください @msg Ran {name} {name} を実行しました @msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました @msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください @@ -5931,7 +5931,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg `args` is larger than 1 MiB `args` が 1 MiB を超えています @msg `path` is empty `path` が空です @msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください -@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください +@msg `path` must name a .js, .mjs or .jsx file `path` には .js、.mjs または .jsx ファイルを指定してください @msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ff7f6aa9a0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2135,7 +2135,7 @@ @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` უნდა იყოს მთელი რიცხვი 1-დან {_1}-მდე @msg `max` must be 1 to {MAX_WORDS} `max` უნდა იყოს 1-დან {MAX_WORDS}-მდე @msg `path` is empty `path` ცარიელია -@msg `path` must name a .js or .jsx file `path` უნდა მიუთითებდეს .js ან .jsx ფაილს +@msg `path` must name a .js, .mjs or .jsx file `path` უნდა მიუთითებდეს .js, .mjs ან .jsx ფაილს @msg `reference` must be a whole number from 0 to 8 `reference` უნდა იყოს მთელი რიცხვი 0-დან 8-მდე @msg `ringSeed` must be below 2^53, not {r} `ringSeed` უნდა იყოს 2^53-ზე ნაკლები და არა {r} @msg `source` is the only path, line or label that graph group `target` stands for `source` ერთადერთი ტრაექტორია, ხაზი ან წარწერაა, რომელსაც დიაგრამის ჯგუფი `target` წარმოადგენს @@ -8453,7 +8453,7 @@ imageTrace Outline კონტური Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები? -@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი +@msg Choose a .js, .mjs or .jsx script აირჩიეთ .js, .mjs ან .jsx სკრიპტი @msg Ran {name} გაშვებულია: {name} @msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა @msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..423ade9b5c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5713,7 +5713,7 @@ variable-list-end {0}, {1} {0} 및 {1} Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요? -@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요 +@msg Choose a .js, .mjs or .jsx script .js, .mjs 또는 .jsx 스크립트를 선택하세요 @msg Ran {name} {name} 실행됨 @msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다 @msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요 @@ -5860,7 +5860,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다 @msg `path` is empty `path`이(가) 비어 있습니다 @msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요 -@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다 +@msg `path` must name a .js, .mjs or .jsx file `path`은(는) .js, .mjs 또는 .jsx 파일을 가리켜야 합니다 @msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..982e687887 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -53,7 +53,7 @@ @msg it decompresses to more than {_1} MB gedecomprimeerd is het groter dan {_1} MB @msg its editing data is for a different page zijn bewerkingsgegevens horen bij een andere pagina @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` moet "emBox", "capHeight", "xHeight" of "icfBox" zijn -@msg Choose a .js or .jsx script Kies een .js- of .jsx-script +@msg Choose a .js, .mjs or .jsx script Kies een .js-, .mjs- of .jsx-script @msg Ran {name} {name} uitgevoerd @msg The script was stopped and its changes were undone Het script is gestopt en de wijzigingen ervan zijn ongedaan gemaakt @msg a script is running: stop it or wait for it to finish er wordt een script uitgevoerd: stop het of wacht tot het klaar is @@ -219,7 +219,7 @@ liquify-list-end {0}, {1} {0} en {1} @msg `args` is larger than 1 MiB `args` is groter dan 1 MiB @msg `path` is empty `path` is leeg @msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source` -@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen +@msg `path` must name a .js, .mjs or .jsx file `path` moet een .js-, .mjs- of .jsx-bestand aanwijzen @msg give exactly one of `path` and `source` geef precies een van `path` en `source` @msg Running a script Er wordt een script uitgevoerd @msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..85ecad038e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5063,7 +5063,7 @@ imageTrace Outline Kontur Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany? -@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx +@msg Choose a .js, .mjs or .jsx script Wybierz skrypt .js, .mjs lub .jsx @msg Ran {name} Wykonano: {name} @msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte @msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie @@ -8678,7 +8678,7 @@ breakText Glyphs Glify @msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB @msg `path` is empty `path` jest puste @msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source` -@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` musi wskazywać plik .js, .mjs lub .jsx @msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source` @msg `answers` must be a list of answers `answers` musi być listą odpowiedzi @msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..94b7580994 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6102,7 +6102,7 @@ variable-list-end {0}, {1} {0} e {1} Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez? -@msg Choose a .js or .jsx script Escolha um script .js ou .jsx +@msg Choose a .js, .mjs or .jsx script Escolha um script .js, .mjs ou .jsx @msg Ran {name} {name} executado @msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas @msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine @@ -9047,7 +9047,7 @@ swatch Yellow Green Verde-amarelado @msg `args` is larger than 1 MiB `args` tem mais de 1 MiB @msg `path` is empty `path` está vazio @msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source` -@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` deve indicar um arquivo .js, .mjs ou .jsx @msg give exactly one of `path` and `source` informe exatamente um de `path` e `source` @msg `answers` must be a list of answers `answers` deve ser uma lista de respostas @msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..48468148a6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4934,7 +4934,7 @@ axis Both Оба Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения? -@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx +@msg Choose a .js, .mjs or .jsx script Выберите скрипт .js, .mjs или .jsx @msg Ran {name} Выполнено: {name} @msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены @msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения @@ -5091,7 +5091,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `args` is larger than 1 MiB `args` больше 1 МиБ @msg `path` is empty параметр `path` пуст @msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source` -@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` должен указывать на файл .js, .mjs или .jsx @msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source` @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..556baff641 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4796,7 +4796,7 @@ axis Both Båda Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort? -@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript +@msg Choose a .js, .mjs or .jsx script Välj ett .js-, .mjs- eller .jsx-skript @msg Ran {name} Körde {name} @msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades @msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart @@ -4967,7 +4967,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `args` is larger than 1 MiB `args` är större än 1 MiB @msg `path` is empty `path` är tomt @msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source` -@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil +@msg `path` must name a .js, .mjs or .jsx file `path` måste ange en .js-, .mjs- eller .jsx-fil @msg give exactly one of `path` and `source` ange exakt en av `path` och `source` @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..762714fd4d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5848,7 +5848,7 @@ fn script_run_param_errors_are_translated() { "`args` is larger than 1 MiB", "`path` is empty", "`installed` takes a `path`, not a `source`", - "`path` must name a .js or .jsx file", + "`path` must name a .js, .mjs or .jsx file", "give exactly one of `path` and `source`", ]; let scanned = message_literals(); @@ -5876,7 +5876,7 @@ fn script_run_param_errors_are_translated() { (json!({"source": "1", "args": {"x": "x".repeat(1 << 20)}}), Some("`args` is larger than 1 MiB".into())), (json!({"path": ""}), Some("`path` is empty".into())), (json!({"source": "1", "installed": true}), Some("`installed` takes a `path`, not a `source`".into())), - (json!({"path": "notes.txt"}), Some("`path` must name a .js or .jsx file".into())), + (json!({"path": "notes.txt"}), Some("`path` must name a .js, .mjs or .jsx file".into())), (json!({}), Some("give exactly one of `path` and `source`".into())), (json!({"path": "a.js", "source": "1"}), Some("give exactly one of `path` and `source`".into())), (json!({"path": 1}), Some("`path` must be a string".into())), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..370480f94f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4648,7 +4648,7 @@ axis Both Her İkisi Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın? -@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin +@msg Choose a .js, .mjs or .jsx script Bir .js, .mjs veya .jsx betiği seçin @msg Ran {name} {name} çalıştırıldı @msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı @msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin @@ -4803,7 +4803,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük @msg `path` is empty `path` boş @msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz -@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır +@msg `path` must name a .js, .mjs or .jsx file `path` bir .js, .mjs veya .jsx dosyasını adlandırmalıdır @msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..07182972fa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4942,7 +4942,7 @@ axis Both Обидві Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни? -@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx +@msg Choose a .js, .mjs or .jsx script Виберіть скрипт .js, .mjs або .jsx @msg Ran {name} Виконано: {name} @msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано @msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення @@ -8634,7 +8634,7 @@ breakText Glyphs Гліфи @msg `args` is larger than 1 MiB `args` більший за 1 МіБ @msg `path` is empty параметр `path` порожній @msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source` -@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` має вказувати на файл .js, .mjs або .jsx @msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source` @msg `answers` must be a list of answers `answers` має бути списком відповідей @msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..f24dd20ba4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5420,7 +5420,7 @@ theme Appearance Giao diện Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm? -@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx +@msg Choose a .js, .mjs or .jsx script Chọn một tập lệnh .js, .mjs hoặc .jsx @msg Ran {name} Đã chạy {name} @msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác @msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc @@ -5590,7 +5590,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB @msg `path` is empty `path` trống @msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source` -@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` phải chỉ đến tệp .js, .mjs hoặc .jsx @msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source` @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..fa282f2150 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5449,7 +5449,7 @@ imageTrace Outline 轮廓 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改? -@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本 +@msg Choose a .js, .mjs or .jsx script 请选择 .js、.mjs 或 .jsx 脚本 @msg Ran {name} 已运行 {name} @msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销 @msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成 @@ -8684,7 +8684,7 @@ breakText Glyphs 字形 @msg `args` is larger than 1 MiB `args` 大于 1 MiB @msg `path` is empty `path` 为空 @msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` -@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件 +@msg `path` must name a .js, .mjs or .jsx file `path` 必须指向 .js、.mjs 或 .jsx 文件 @msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个 @msg `answers` must be a list of answers `answers` 必须是回答的列表 @msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..8f2aa2eafb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2795,7 +2795,7 @@ file-filter Templates 範本 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更? -@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼 +@msg Choose a .js, .mjs or .jsx script 請選擇 .js、.mjs 或 .jsx 指令碼 @msg Ran {name} 已執行 {name} @msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原 @msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成 @@ -2942,7 +2942,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `args` is larger than 1 MiB `args` 大於 1 MiB @msg `path` is empty `path` 為空 @msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` -@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案 +@msg `path` must name a .js, .mjs or .jsx file `path` 必須指向 .js、.mjs 或 .jsx 檔案 @msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..33986b055a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2030,13 +2030,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), ( crate::scripts_menu::COMMAND, "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..f8d3d4c39e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -94,7 +94,7 @@ fn only_js_and_jsx_files_are_taken() { let mut app = app(); for name in ["a.txt", "a.jsxbin", "a"] { let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": name })).unwrap().unwrap_err(); - assert!(e.contains(".js or .jsx"), "{name}: {e}"); + assert!(e.contains(".js, .mjs or .jsx"), "{name}: {e}"); } assert!(app.ui.dialog.is_none()); } diff --git a/docs/mcp.md b/docs/mcp.md index ec6f2d7f76..b34a4ebed6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2611,10 +2611,10 @@ vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` `script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. -File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page +File › Scripts › Other Script… (Cmd+F12) picks a `.js`, `.mjs` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html -describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any -case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is +describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in +any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and `ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in `.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and @@ -2625,8 +2625,36 @@ before each element, strings and `String` objects by code point, and objects wit throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. + +A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module +(https://262.ecma-international.org/6.0/#sec-modules): strict mode code with the forms above, and `import` and +`export` declarations at its top level. `import` and `export` are syntax errors in a `.js` or `.jsx` script. + +- A specifier is a path relative to the file that imports it. It starts with `./` or `../`, separates names with + `/` and names a `.mjs` or `.js` file, which is read as a module. A bare name such as `'lib'`, a URL, an absolute + path, and a specifier with `\`, `:` or a control character end the run with a `SyntaxError` that names the + specifier. +- Modules are read through the script's own file scope: only from the script's folder and the folders below it. + A specifier whose `..` names lead above the script's folder, and a link that leads out of it, end the run with an + error that names the specifier. A missing file ends the run with an error that names the specifier. +- Every module is read, parsed and linked before any of them runs. A syntax error, a missing or refused file, an + import of a name the module does not export, and an import of a name that two `export *` declarations give from + different modules end the run with no code run, at the file, line and column of the module they are in. +- Each module runs once in a run, after the modules it imports, in the order it imports them; two paths to one file + (a link, `sub/../x.mjs`, or names that differ only in letter case on Windows) are one module. An import reads + the exporting module's binding each time, so it sees later assignments, and reading it before that module has + initialized it (in a cycle of imports) throws a `ReferenceError`. Assigning to an import throws a `TypeError`. +- `import * as ns` gives a namespace object: not extensible, with no prototype, its export names in code unit order + as properties that cannot be written or deleted, and `[object Module]` from `Object.prototype.toString`. + `export *` passes on every name but `default`, and `export * as ns from` passes on a namespace. +- A module's top-level names stay in the module, `this` is `undefined` at its top, it has no preprocessor lines, + and `import()` is a syntax error. `vc`, `$` and the other globals are there as in a script. +- Module files count against the limits of `#include` files: 8 MiB a file, 32 MiB of source in all, 64 files + besides the script, imports 16 deep and 1,024 paths looked up. These limits are VectorCraft's own. + +The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files +through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144b20bd1c..15745fc595 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,7 +1079,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. @@ -1161,7 +1162,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). + - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js, .mjs or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`). From 5edc81e54873b0dfab9fce13c1d01ab234d5a7a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:31:42 -0800 Subject: [PATCH 07/17] Plug-ins: a null translations map is refused A manifest that gives `null` for `translations` or for one of its maps (`params`, `groups`, `commands`, `options`) is refused with an error instead of being read as empty. The palette test of translated plug-in commands uses names no other test's plug-in has. --- crates/plugins/src/translations.rs | 9 ++++++--- crates/ui-egui/src/palette.rs | 9 +++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/plugins/src/translations.rs b/crates/plugins/src/translations.rs index 76c8f65046..849b6b2905 100644 --- a/crates/plugins/src/translations.rs +++ b/crates/plugins/src/translations.rs @@ -64,9 +64,6 @@ impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries { fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("an object") } - fn visit_unit(self) -> std::result::Result { - Ok(Entries::default()) - } fn visit_map>(self, mut map: A) -> std::result::Result { let mut seen = HashSet::new(); let mut out = Vec::new(); @@ -516,6 +513,12 @@ mod tests { (r#"{"de":{"name":7}}"#, "manifest"), (r#"["de"]"#, "manifest"), (r#""de""#, "manifest"), + ("null", "expected an object"), + (r#"{"de":null}"#, "manifest"), + (r#"{"de":{"params":null}}"#, "expected an object"), + (r#"{"de":{"groups":null}}"#, "expected an object"), + (r#"{"de":{"commands":null}}"#, "expected an object"), + (r#"{"de":{"params":{"mode":{"options":null}}}}"#, "expected an object"), ] { let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string(); assert!(e.contains(says), "{translations}: {e}"); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 852c0ddeb3..c38ba36e0f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -3319,9 +3319,10 @@ mod tests { fn a_plugin_command_result_shows_the_plugins_translation() { use vectorcraft_plugins::wat as tpl; let id = "test.UI.palette_translated"; + // Names no other test's plug-in has, since tests running beside this one share the registry. let manifest = format!( - r#"{{"id":"{id}","name":"Tidy","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Grow"}}], - "translations":{{"de":{{"name":"Aufräumen","commands":{{"grow":{{"label":"Wachsen"}}}}}}}}}}"# + r#"{{"id":"{id}","name":"Groom","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Expand Rim"}}], + "translations":{{"de":{{"name":"Pflegen","commands":{{"grow":{{"label":"Erweitern"}}}}}}}}}}"# ); vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); let key = format!("plugin.{id}.grow"); @@ -3332,9 +3333,9 @@ mod tests { let (de, fr) = (shown("de"), shown("fr")); vectorcraft_plugins::registry::remove(id); let (de, object, plugins) = de.expect("the command is a result"); - assert_eq!(de, format!("{object} › {plugins} › Aufräumen › Wachsen")); + assert_eq!(de, format!("{object} › {plugins} › Pflegen › Erweitern")); let (fr, object, plugins) = fr.expect("the command is a result"); - assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); + assert_eq!(fr, format!("{object} › {plugins} › Groom › Expand Rim")); } /// A plug-in command whose plug-in translates its name and label into English shows the From 4cfa6a8434f66f54d4c839df5f5df3354bd1696d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:54:53 -0800 Subject: [PATCH 08/17] JavaScript: module namespaces, global deletes and module loading follow ES2015 - A read or write that reaches a module namespace through a prototype chain checks the export's temporal dead zone and refuses the write; for-in over a namespace lists its keys without reading the exports. - `delete this.x` and a delete inside `with` remove only the property, so a later `let x` is still a SyntaxError. - An arrow function's `length` is configurable. - `let [` cannot start the body of if, else, while, for or a label. - A specifier with an unpaired surrogate parses; the loader refuses it before reading any file. - Each module's code counts against the heap from when it loads, and export lookups use an index instead of copying export lists. - A module reached again through another path is not read or counted against the 32 MiB source limit again, its relative imports are read from the folder the file is in, and on Windows two files whose names differ only in case in a case-sensitive folder stay two modules. - `$.evalFile` in a module reads beside that module. - `script.run` takes `module`, and a `.mjs` file picked on the web runs as a module. - Without `es2015`, the compiler does not collect the block scopes that only Annex B block functions read. - The test262 runner grades negative module tests by their phase and counts panics on their own. --- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/file_access.rs | 29 +++++- crates/engine/src/script/include.rs | 63 +++++++++---- crates/engine/src/script/mod.rs | 51 +++++++++-- crates/engine/src/tests/script_folder.rs | 1 + crates/engine/src/tests/script_modules.rs | 75 ++++++++++++++++ crates/js/src/ast.rs | 4 + crates/js/src/compiler.rs | 34 ++++--- crates/js/src/es2015_tests.rs | 29 +++++- crates/js/src/heap.rs | 2 +- crates/js/src/host.rs | 19 ++-- crates/js/src/host_tests.rs | 37 ++++++-- crates/js/src/interp.rs | 96 +++++++++++++++----- crates/js/src/lib.rs | 5 +- crates/js/src/module.rs | 90 +++++++++++++------ crates/js/src/module_tests.rs | 103 ++++++++++++++++++++-- crates/js/src/parser.rs | 5 ++ crates/js/src/parser/module.rs | 10 +-- crates/js/src/realm.rs | 3 +- crates/js/tests/test262.rs | 46 ++++++++-- crates/ui-egui/src/dialogs/script_run.rs | 5 +- crates/ui-egui/src/tests/script_run.rs | 12 +++ docs/mcp.md | 13 ++- docs/target-app-parity.md | 2 +- 24 files changed, 604 insertions(+), 134 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 67d6556bbe..fa4d7ea425 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), 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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. 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, and 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 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (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 ), @@ -173,6 +173,7 @@ fn run(s: &mut Session, p: &Value) -> Result { } 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")), @@ -217,6 +218,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, + module, }; let name = s.script_start(request)?; if s.script_frames { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index abc7fa0740..cd45cccaaf 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -640,6 +640,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); @@ -655,6 +664,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() { @@ -672,7 +684,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). @@ -891,6 +903,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/script/include.rs b/crates/engine/src/script/include.rs index 8de325cb70..bc91914f0b 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -249,8 +249,9 @@ pub(crate) fn module_script(path: Option<&str>) -> bool { } /// 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 path, in lowercase on Windows, -/// whose file names ignore letter case. +/// 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)] { @@ -259,8 +260,13 @@ fn module_key(real: &Path) -> String { return format!("{}:{}", m.dev(), m.ino()); } } - let shown = display(real).to_string(); - if cfg!(windows) { shown.to_lowercase() } else { shown } + 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 @@ -380,6 +386,11 @@ impl Files { } } + /// 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()); @@ -417,30 +428,38 @@ impl Files { if self.probes > MAX_PROBES { return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached"))); } - let candidate = path.iter().fold(root, |p, name| p.join(name)); - let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + 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())); } - self.bytes += bytes.len(); - let key = module_key(&real); - self.module_paths.insert(relative, key.clone()); - if self.module_dirs.contains_key(&key) { - return Ok((key, None)); - } if self.files >= MAX_FILES { return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); } - self.files += 1; 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(); - self.module_dirs.insert(key.clone(), path); + 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)))) } @@ -483,12 +502,20 @@ 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 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 e318c0abb6..101cdc2bac 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -202,6 +202,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, } thread_local! { @@ -777,6 +779,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)>>, @@ -932,6 +937,18 @@ impl Host { } } + /// The folder of the module whose source has `tag`, when it is a module the script imported + /// (not the script itself, 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).filter(|n| *n > 0)?; + 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 }; @@ -1436,6 +1453,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())); }; @@ -1466,7 +1492,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), @@ -1582,7 +1608,10 @@ fn explained(e: &RunError) -> String { 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)| { - host.eval_maps.borrow_mut().push(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 }); @@ -1951,9 +1980,12 @@ 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()); - // A `.mjs` script is a module, with no preprocessor lines; `module_key` names it among the - // modules it imports. - let (expanded, module_key) = if include::module_script(request.file.as_deref()) { + 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), @@ -1992,7 +2024,7 @@ impl Session { let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read // code the way the script does. - let es2015 = include::es2015_script(request.file.as_deref()); + 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, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. @@ -2058,6 +2090,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()), diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..e64f7c3ad2 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -359,6 +359,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, }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs index 9727abb927..0dec7ea7da 100644 --- a/crates/engine/src/tests/script_modules.rs +++ b/crates/engine/src/tests/script_modules.rs @@ -225,3 +225,78 @@ fn script_module_is_listed_and_taken_by_path() { 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); +} diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a5d39c0b06..ce1e66f6d1 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -483,7 +483,11 @@ pub enum ImportName { /// 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, } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 537752b9fe..eae7ae1924 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -250,8 +250,10 @@ impl<'a> FnCompiler<'a> { let mut seen = HashSet::new(); // The `let` and `const` names and the block functions of each statement list and loop the // walk enters, with the index of the one around it; the body's are first, and its - // functions are var-scoped. - let mut scopes: Vec<(Option, HashSet, HashSet)> = vec![(None, self.lexical_names(body), HashSet::new())]; + // functions are var-scoped. Only Annex B's block functions read them, so without + // [`crate::Options::es2015`] none is collected. + let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() }; + let mut scopes: Vec<(Option, HashSet, HashSet)> = vec![(None, top, HashSet::new())]; let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect(); let mut add_var = |out: &mut Hoisted, k: Key| { if seen.insert(k.clone()) { @@ -285,7 +287,7 @@ impl<'a> FnCompiler<'a> { } } Stmt::Block(list) => { - let s = enter(self.lexical_names(list), self.block_function_names(list)); + let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope }; work.extend(list.iter().rev().map(|&st| (st, nested || inner, s))); } Stmt::If { consequent, alternate, .. } => { @@ -293,7 +295,7 @@ impl<'a> FnCompiler<'a> { // (Annex B.3.4). for &branch in alternate.iter().chain(std::iter::once(consequent)) { let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_))); - let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope }; + let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope }; work.push((branch, nested || inner, s)); } } @@ -322,23 +324,27 @@ impl<'a> FnCompiler<'a> { work.push((*body, nested || inner, s)); } Stmt::Switch { cases, .. } => { - let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect(); - let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect(); - let s = enter(names, funcs); + let s = if inner { + let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect(); + let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect(); + enter(names, funcs) + } else { + scope + }; for case in cases.iter().rev() { work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s))); } } Stmt::Try { block, handler, finalizer } => { if let Some(f) = finalizer { - let s = enter(self.lexical_names(f), self.block_function_names(f)); + let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope }; work.extend(f.iter().rev().map(|&st| (st, nested || inner, s))); } if let Some(h) = handler { - let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body)); + let s = if inner { enter(self.lexical_names(&h.body), self.block_function_names(&h.body)) } else { scope }; work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s))); } - let s = enter(self.lexical_names(block), self.block_function_names(block)); + let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope }; work.extend(block.iter().rev().map(|&st| (st, nested || inner, s))); } Stmt::Expr(_) @@ -921,8 +927,12 @@ impl<'a> FnCompiler<'a> { fn switch_stmt(&mut self, id: StmtId, labels: Vec) -> CResult<()> { let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") }; self.expr(*discriminant)?; - let all: Vec = cases.iter().flat_map(|c| c.body.iter().copied()).collect(); - let scope = self.list_scope(&all, true)?; + let scope = if self.es2015 { + let all: Vec = cases.iter().flat_map(|c| c.body.iter().copied()).collect(); + self.list_scope(&all, true)? + } else { + None + }; if let Some(scope) = scope { self.emit(Op::PushBlock(scope)); self.env_depth += 1; diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 0173fb2d6c..07032c6506 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -97,8 +97,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() { syntax("'use strict'; { function f() {} function f() {} }"); syntax("for (let x = 1 in {}) {}"); syntax("if (1) let x = 1;"); + // No statement starts with `let [`, in a statement list or in the body of an `if` or a loop. + for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] { + syntax(&format!("var let = [1]; {body}")); + } // Outside strict mode code `let` is still a name where no declaration can start. truth("var let = 3; let === 3"); + truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1"); + truth("var let = [2]; if (true) let\n; let.length === 1"); + // ECMAScript 5.1 reads it as a property read. + assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0))); truth("{ function f() { return 1; } function f() { return 2; } } f() === 2"); } @@ -167,7 +175,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() { assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}"); assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0))); let restricted = realm.run("let undefined = 1;"); - assert!(restricted.is_err(), "{restricted:?}"); + assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}"); } #[test] @@ -269,8 +277,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() { assert!(is_thrown(&realm.run("let z;"), "SyntaxError")); assert_eq!(realm.run("delete z"), Ok(JsValue::Bool(true))); assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0))); + // Deleting the global object's property, not the variable, leaves the name declared + // (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`). assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true))); - assert_eq!(realm.run("let w = 4; w"), Ok(JsValue::Number(4.0))); + let after_property = realm.run("let w = 4; w"); + assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}"); + assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true))); + let after_with = realm.run("let v = 4; v"); + assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}"); } #[test] @@ -343,6 +357,17 @@ fn arrow_functions_cannot_be_constructed() { truth("((a, b) => 0).length === 2"); } +#[test] +fn an_arrow_functions_length_is_configurable_and_read_only() { + truth( + "var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \ + d.configurable && !d.writable && !d.enumerable && d.value === 1", + ); + truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')"); + // Other functions keep their attributes. + truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); !d.configurable && !d.writable && !d.enumerable"); +} + #[test] fn bad_arrow_functions_are_syntax_errors() { syntax("var f = x\n=> x;"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f158f45a0f..34ac97155d 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -186,7 +186,7 @@ pub(crate) enum Func { Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, - Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, + Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc, site: bool }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..156849035f 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -148,11 +148,14 @@ pub enum HostItem { /// that is not a string is the call's result. `end` is called when the source has run, /// normally or not. Each source given has the next tag of [`crate::Realm::error_source`], /// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`] - /// for that source alone; with `None` it takes the calling code's. + /// for that source alone; with `None` it takes the calling code's. With `site`, `source` is + /// given the [`CallSite`] of the code that calls it first, as the three numbers its source + /// tag, line and column, and the arguments after them. Evaluator { source: HostFunction, end: Rc, strict_writes: Rc Option>, + site: bool, }, /// A read-only property that reads the interpreter's own state. Script(ScriptItem), @@ -414,7 +417,8 @@ impl Interp { /// source it gives as global code, as an indirect `eval` does, giving that code's completion /// value. A result that is not a string is given to the script as it is. `end` is called once /// the source has run, normally or not. `strict_writes` gives the source's - /// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. + /// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`, + /// `f` is given the calling code's [`CallSite`] before the arguments. pub(crate) fn call_evaluator( &mut self, f: &crate::heap::DataFn, @@ -422,8 +426,13 @@ impl Interp { strict_writes: &Rc Option>, name: &Rc, args: &[Value], + site: bool, ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let caller = site.then(|| self.call_site()); + let mut data = self.read_args(name, args, &ArgRead::Data)?; + if let Some(caller) = caller { + data.splice(0..0, site_data(caller)); + } let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -586,9 +595,9 @@ impl Interp { HostItem::Converted(list, f) => { Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } } - HostItem::Evaluator { source, end, strict_writes } => { + HostItem::Evaluator { source, end, strict_writes, site } => { let proto = self.intrinsics.function_proto; - let func = Func::Eval { f: source, end, strict_writes, name: full.into() }; + let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site }; let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto))); Prop::Data { value: Value::Object(f), flags: ENUMERABLE } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..2df62d419f 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -284,7 +284,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() { Ok(Data::Number(f64::from(s.line))) }); let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap(); r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap(); let first = r.script_tag(); @@ -306,6 +306,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() { assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag())); } +/// An evaluator made with `site` is given the place of the code that calls it before its +/// arguments; one made without it is given only the arguments. +#[test] +fn an_evaluator_with_site_is_told_where_it_is_called() { + let mut r = realm(10_000_000); + let given: Rc>>> = Rc::default(); + let evaluator = |site: bool| { + let log = given.clone(); + let source: HostFunction = Rc::new(move |a| { + log.borrow_mut().push(a); + Ok(Data::String("1".into())) + }); + HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site } + }; + r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap(); + r.run("\n\n host.at('x');\nhost.plain('y');").unwrap(); + let tag = f64::from(r.script_tag()); + let given = given.borrow(); + assert_eq!(given.len(), 2, "{given:?}"); + assert_eq!(given[0].len(), 4, "{given:?}"); + assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}"); + assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}"); + assert_eq!(given[1], vec![Data::String("y".into())]); +} + #[test] fn a_text_function_takes_each_argument_as_string_gives_it() { let mut r = realm(1_000_000); @@ -658,7 +683,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() { fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() { let mut r = realm(10_000_000); let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("load".into(), load)]).unwrap(); r.run("function late() { throw new Error('late'); }").unwrap(); assert!(r.run("host.load()").is_err()); @@ -680,7 +705,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() { let s = seen.clone(); r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("load".into(), load)]).unwrap(); let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); assert_eq!(out, JsValue::Number(49.0)); @@ -695,7 +720,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() { fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("load".into(), load)]).unwrap(); assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet"); r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap(); @@ -728,7 +753,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() { let ends = Rc::new(Cell::new(0)); let ended = ends.clone(); let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17))))); - let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) }; + let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false }; let mut r = realm(10_000); r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); let e = r.run("host.evaluate()").unwrap_err(); @@ -749,7 +774,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() { // The source does not parse, so a parse would throw a syntax error instead. let n = (1 << 17) + 1; let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1))))); - let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; let mut r = realm(1_000_000); r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); r.interp().collect_for_room(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ae755f3aa3..a3b62411e1 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1387,7 +1387,17 @@ impl Interp { } _ => return internal("not a declarative environment"), }, - Resolved::Obj { object, .. } => self.delete(object, &name, false)?, + Resolved::Obj { object, with_this } => { + let deleted = self.delete(object, &name, false)?; + // A deleted global variable no longer stops a `let` or `const` of its name: the + // global environment's DeleteBinding drops it from its var names (ECMA-262 2015 + // section 8.1.1.4.7). Deleting the global object's property by any other route + // leaves the name recorded. + if deleted && !with_this && object == self.global { + self.global_vars.remove(&name); + } + deleted + } }; self.push(Value::Bool(result)) } @@ -1532,11 +1542,16 @@ impl Interp { /// [[GetProperty]]: the property found on the object or its prototype chain. pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { + Ok(self.find_property_on(id, k)?.map(|(_, p)| p)) + } + + /// [`Self::find_property`], with the object on the prototype chain that has the property. + fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult> { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { if let Some(p) = self.get_own_property(o, k)? { - return Ok(Some(p)); + return Ok(Some((o, p))); } cur = self.object(o)?.proto; steps += 1; @@ -1553,10 +1568,14 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + let found = self.find_property_on(start, k)?; // A module's export read before the module ran is in its temporal dead zone (ECMA-262 - // 2015 section 9.4.6.8). - self.check_namespace_export(start, k)?; - match self.find_property(start, k)? { + // 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it + // through a prototype chain. + if let Some((holder, _)) = &found { + self.check_namespace_export(*holder, k)?; + } + match found.map(|(_, p)| p) { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), @@ -1863,8 +1882,26 @@ impl Interp { Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), None => {} } - let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { + let mut inherited = None; + let mut cur = self.object(id)?.proto; + let mut steps = 0usize; + while let Some(o) = cur { + // A write that reaches a module namespace object on the prototype chain is refused + // there too: its [[Set]] returns false for every key. + if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { + return self.reject(throw, &k, "a module namespace object is read-only"); + } + if let Some(p) = self.get_own_property(o, &k)? { + inherited = Some(p); + break; + } + cur = self.object(o)?.proto; + steps += 1; + if steps > 1_000_000 { + return internal("prototype chain too long"); + } + } + match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), @@ -1930,12 +1967,6 @@ impl Interp { match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { - // A deleted global variable no longer stops a `let` or `const` of its name - // (ECMA-262 2015 section 8.1.1.4.7), and the names kept are never more than the - // global object's properties. - if id == self.global { - self.global_vars.remove(k); - } let o = self.object_mut(id)?; o.props.remove(k); if let Class::Arguments(map) = &mut o.class @@ -2216,7 +2247,10 @@ impl Interp { let arrow = code.arrow; let self_name = code.self_name.clone(); let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto))); - self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + // An arrow function's `length` is configurable (ECMA-262 2015 section 9.2.4, + // FunctionInitialize); the other forms keep their earlier attributes. + let length_flags = if arrow { CONFIGURABLE } else { 0 }; + self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: length_flags })?; // An arrow function has no `prototype` and cannot be constructed (section 14.2.16). if arrow { return Ok(f); @@ -2670,14 +2704,9 @@ impl Interp { // listed or their bytes reserved must not free it. let saved = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); - // Listing a namespace object's exports reads each one (ECMA-262 2015 section 9.4.6.5). + // Listing a namespace object's exports does not read them (ECMA-262 2015 section + // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. let keys = self.enumerable_keys(o).and_then(|keys| { - for k in &keys { - self.check_namespace_export(o, k)?; - } - Ok(keys) - }); - let keys = keys.and_then(|keys| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); @@ -2780,8 +2809,8 @@ impl Interp { // keeps itself reachable. return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); } - Func::Eval { f, end, strict_writes, name } => { - return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); + Func::Eval { f, end, strict_writes, name, site } => { + return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?)); } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); @@ -3435,7 +3464,8 @@ impl Interp { /// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary /// roots for the caller to remove. pub(crate) fn instantiate_module(&mut self, code: &Rc) -> JsResult<(EnvId, EnvId)> { - self.charge_code(code, declaration_bytes(code).saturating_add(ENV_BYTES))?; + // The code itself was counted when the module was loaded ([`Self::hold_module_code`]). + self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?; let scope = self.global_lex; let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); self.temp_envs.push(env); @@ -3501,6 +3531,24 @@ impl Interp { self.temp_envs.len() } + /// Counts a loaded module's code against the heap once, when the module is loaded, and keeps + /// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules + /// load counts it too. + pub(crate) fn hold_module_code(&mut self, code: &Rc) -> JsResult<()> { + self.charge_code(code, 0)?; + self.temp_codes.push(code.clone()); + Ok(()) + } + + pub(crate) fn temp_codes_mark(&self) -> usize { + self.temp_codes.len() + } + + /// Ends module linking: drops the modules' code held from `mark` on. + pub(crate) fn drop_temp_codes(&mut self, mark: usize) { + self.temp_codes.truncate(mark); + } + /// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it. pub(crate) fn hold(&mut self, v: Value) { self.temp_roots.push(v); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 8f99275192..09fdc4b715 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -61,7 +61,10 @@ //! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import` //! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a //! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module -//! once, after the modules it imports, with each import reading the exporting module's binding. +//! once, after the modules it imports, with each import reading the exporting module's binding. In +//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does +//! not wait for a module that is still waiting for its own imports, and reading a binding of that +//! module before it is initialized throws a `ReferenceError`. //! Dynamic `import()` is a syntax error. #![forbid(unsafe_code)] diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs index b706c280f5..e8147668cd 100644 --- a/crates/js/src/module.rs +++ b/crates/js/src/module.rs @@ -17,7 +17,7 @@ //! properties. `export *` passes on every name but `default`; a name two `export *` give from //! different bindings is left out of a namespace and is a `SyntaxError` to import. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ExportEntry, ImportName, ModuleInfo}; @@ -84,6 +84,11 @@ struct Record { /// The environment its code runs in and the outer one, once instantiated. envs: Option<(EnvId, EnvId)>, namespace: Option, + /// Each name the module exports itself or re-exports by name, with its entry in + /// `info.exports`. + explicit: HashMap, + /// The request each `export *` of the module names, in order. + stars: Vec, } /// Why a module run could not start. @@ -153,7 +158,19 @@ impl Graph<'_, '_> { Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }), Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))), }; - self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None }); + // The record keeps the code from here on, so the heap counts it from here on. + self.interp.hold_module_code(&code).map_err(LinkFail::Run)?; + let mut explicit = HashMap::new(); + let mut stars = Vec::new(); + for (i, e) in info.exports.iter().enumerate() { + match e { + ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { + explicit.entry(export_name.clone()).or_insert(i); + } + ExportEntry::Star { request, .. } => stars.push(*request), + } + } + self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars }); let index = self.records.len() - 1; self.by_key.insert(key_name, index); Ok(index) @@ -175,10 +192,21 @@ impl Graph<'_, '_> { let mut depths = vec![0usize]; let mut i = 0; while i < self.records.len() { - let requests: Vec<(String, u32)> = self.records[i].info.requests.iter().map(|r| (r.specifier.clone(), r.span.start)).collect(); + let requests: Vec<(String, bool, u32)> = self.records[i] + .info + .requests + .iter() + .map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start)) + .collect(); let depth = depths.get(i).copied().unwrap_or(0); - for (specifier, offset) in requests { + for (specifier, text, offset) in requests { self.interp.use_fuel().map_err(LinkFail::Run)?; + // The host maps text to modules, and a specifier with an unpaired surrogate is not + // text, so it is refused here, as a host refuses a specifier it does not read. + if !text { + let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate"); + return Err(self.fail_at(i, offset, ErrorType::Syntax, &message)); + } let referrer = self.records[i].key.clone(); let loaded = match (self.load)(&referrer, &specifier) { Ok(loaded) => loaded, @@ -247,29 +275,28 @@ impl Graph<'_, '_> { } self.interp.use_fuel().map_err(LinkFail::Run)?; seen.push((m, name.to_string())); - let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); - for e in &exports { - match e { - ExportEntry::Local { export_name, local, .. } if export_name == name => { - return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))); - } - ExportEntry::Indirect { export_name, request, import, .. } if export_name == name => { - let Some(t) = self.target(m, *request) else { return Ok(Ok(None)) }; - return match import { - ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))), - ImportName::Name(n) => self.resolve_export(t, n, seen), - }; - } - _ => {} + let Some(record) = self.records.get(m) else { return Ok(Ok(None)) }; + // The module's own export of the name, looked up in its index, comes before any `export *`. + let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i)); + match explicit { + Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))), + Some(ExportEntry::Indirect { request, import, .. }) => { + let (request, import) = (*request, import.clone()); + let Some(t) = self.target(m, request) else { return Ok(Ok(None)) }; + return match import { + ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))), + ImportName::Name(n) => self.resolve_export(t, &n, seen), + }; } + _ => {} } if name == "default" { return Ok(Ok(None)); } let mut star = None; - for e in &exports { - let ExportEntry::Star { request, .. } = e else { continue }; - let Some(t) = self.target(m, *request) else { continue }; + let stars = record.stars.clone(); + for request in stars { + let Some(t) = self.target(m, request) else { continue }; match self.resolve_export(t, name, seen)? { Err(Ambiguous) => return Ok(Err(Ambiguous)), Ok(None) => {} @@ -285,23 +312,32 @@ impl Graph<'_, '_> { /// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its /// `export *` modules but `default` included, each once. - fn exported_names(&mut self, m: usize, star: bool, visited: &mut Vec, names: &mut Vec) -> Result<(), LinkFail> { + fn exported_names( + &mut self, + m: usize, + star: bool, + visited: &mut Vec, + names: &mut Vec, + seen: &mut HashSet, + ) -> Result<(), LinkFail> { if visited.contains(&m) { return Ok(()); } visited.push(m); - let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); - for e in &exports { + let count = self.records.get(m).map_or(0, |r| r.info.exports.len()); + for i in 0..count { self.interp.use_fuel().map_err(LinkFail::Run)?; + let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break }; match e { ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { - if !(star && export_name == "default") && !names.contains(export_name) { + if !(star && export_name == "default") && !seen.contains(export_name) { + seen.insert(export_name.clone()); names.push(export_name.clone()); } } ExportEntry::Star { request, .. } => { if let Some(t) = self.target(m, *request) { - self.exported_names(t, true, visited, names)?; + self.exported_names(t, true, visited, names, seen)?; } } } @@ -322,7 +358,7 @@ impl Graph<'_, '_> { return Ok(ns); } let mut names = Vec::new(); - self.exported_names(m, false, &mut Vec::new(), &mut names)?; + self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?; let mut resolved = Vec::new(); for name in names { if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs index 26f453b652..55c75139b4 100644 --- a/crates/js/src/module_tests.rs +++ b/crates/js/src/module_tests.rs @@ -105,6 +105,31 @@ fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() { assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true"); } +#[test] +fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() { + let m = "export var alpha = 1;"; + let out = run( + "import * as ns from './m.mjs'; + var o = Object.create(ns); + Object.defineProperty(o, 'own', { value: 1, writable: true }); + o.own = 2; + try { o.alpha = 5; } catch (e) { out.push(e.name); } + try { o.fresh = 5; } catch (e) { out.push(e.name); } + try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); } + out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);", + &[("./m.mjs", m)], + ); + assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1"); + // A script's sloppy write is ignored. + let mut realm = es(); + let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default()); + assert_eq!(out, (Ok(JsValue::Undefined), String::new())); + // A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`. + let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \ + [own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()"; + assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into()))); +} + #[test] fn a_namespace_takes_only_definitions_that_change_nothing() { let m = "export var a = 1;"; @@ -175,10 +200,14 @@ fn reading_an_import_before_its_module_ran_is_a_reference_error() { fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { let b = "import * as ns from 'main'; var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'), - () => Object.getOwnPropertyDescriptor(ns, 'a'), () => { for (var k in ns) {} }, () => Object.isSealed(ns), () => Object.isFrozen(ns), - () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns)]; + () => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns), + () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns), + () => Object.create(ns).a, () => Object.create(Object.create(ns)).a]; tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } }); - out.push('a' in ns, Object.getOwnPropertyNames(ns).join());"; + // Listing the export names reads none of them. + var names = []; + for (var k in ns) names.push(k); + out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());"; let mut realm = es(); let mut inner = loader(&[("./b.mjs", b)]); let mut load = |referrer: &str, specifier: &str| { @@ -186,8 +215,8 @@ fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { }; let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load); assert_eq!(r, Ok(JsValue::Undefined)); - let errors = "ReferenceError|".repeat(12); - assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}true|a")))); + let errors = "ReferenceError|".repeat(13); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a")))); } #[test] @@ -401,19 +430,79 @@ fn a_module_lists_what_it_imports_and_exports() { ); } +#[test] +fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() { + let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';"; + let (_, info) = match parse_module(src, &Options::default()) { + Ok(p) => p, + Err(e) => panic!("{e:?}"), + }; + let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect(); + let dot = [u16::from(b'.'), u16::from(b'/')]; + let ext: Vec = ".mjs".encode_utf16().collect(); + let with = |u: u16| [&dot[..], &[u], &ext[..]].concat(); + assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]); + assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs"); + // The run stops when the module is to be loaded, before any module runs, and the loader is + // not asked for it. + let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", ""); + assert_eq!(e.line, 1); +} + +#[test] +fn a_namespace_of_many_exports_lists_each_once_in_order() { + let names: Vec = (0..3000).rev().map(|i| format!("e{i}")).collect(); + let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect(); + let star = "export * from './m.mjs'; export var e5 = 'own';"; + let out = run( + "import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);", + &[("./m.mjs", m.as_str()), ("./star.mjs", star)], + ); + assert_eq!(out, "3000|e0|e999|own|e2999"); +} + #[test] fn modules_survive_a_collection_while_they_link() { let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() }); assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok()); let m = "export var v = 'kept'; export function f() { return v; }"; let mut load = loader(&[("./m.mjs", m)]); - let r = realm.run_module( + // A collection runs at every heap reservation while the modules load and link, before any + // of their code runs. + let before = realm.interp().heap.collections; + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let started = realm.start_module( "main.mjs", "import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());", ModuleLimits::default(), &mut load, ); - assert_eq!(r, Ok(JsValue::Undefined)); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(started, Ok(())); + assert!(realm.interp().heap.collections > before); + assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined)))); realm.collect_garbage(); assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into()))); } + +#[test] +fn the_heap_counts_each_module_from_when_it_loads() { + // Each module holds about 4 MB of code (its text and its string). The heap holds one of them, + // and not two, so the run stops while the second loads and never asks for the third. + let body = format!("export var v = '{}';", "x".repeat(1_000_000)); + let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits()); + assert!(realm.run("var out = [];").is_ok()); + let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default()); + assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string())); + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits()); + let asked = std::cell::RefCell::new(Vec::new()); + let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]); + let mut load = |referrer: &str, specifier: &str| { + asked.borrow_mut().push(specifier.to_string()); + inner(referrer, specifier) + }; + let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load); + assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}"); + assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]); +} diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 28b7cd5f72..573bd06072 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -533,6 +533,11 @@ impl<'s> Parser<'s> { Ok(self.ast.push_stmt(Stmt::Empty, start)) } TokenKind::Keyword(k) => self.keyword_statement(*k, start), + // An expression statement cannot start with `let [` (ECMA-262 2015 section 13.5), so + // the body of an `if` or a loop cannot be a `let` declaration with a pattern either. + _ if self.es2015 && self.tok.ident() == Some("let") && !self.tok.escaped && self.peek().is_some_and(|t| t.is_punct(Punct::LBracket)) => { + Err(self.error_at_token(&self.tok, "a lexical declaration cannot stand here; put it in a block")) + } _ => { let expr = self.parse_expression(false)?; self.semicolon()?; diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index ec39092afb..ca5317ca4e 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -65,18 +65,18 @@ impl Parser<'_> { } /// A module specifier: a string literal, added to the module's requests once. → its index. + /// Any string value is a specifier here; the host decides which it can load. fn module_specifier(&mut self, info: &mut ModuleInfo) -> Result { let TokenKind::String(units) = &self.tok.kind else { return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok)))); }; - let Ok(specifier) = String::from_utf16(units) else { - return Err(self.error_at_token(&self.tok, "a module specifier must be valid text")); - }; + let units = units.to_vec(); let span = self.bump()?.span; - if let Some(i) = info.requests.iter().position(|r| r.specifier == specifier) { + if let Some(i) = info.requests.iter().position(|r| r.units == units) { return Ok(i); } - info.requests.push(ModuleRequest { specifier, span }); + let specifier = String::from_utf16_lossy(&units); + info.requests.push(ModuleRequest { specifier, units, span }); Ok(info.requests.len() - 1) } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 1765d6d9d1..0e648d4fcc 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -295,7 +295,7 @@ impl Realm { let interp = &mut self.interp; interp.evaluated = next_tag(interp.evaluated); self.script_tag = interp.evaluated; - let marks = (interp.temp_envs_mark(), interp.temp_roots_mark()); + let marks = (interp.temp_envs_mark(), interp.temp_roots_mark(), interp.temp_codes_mark()); let linked = crate::module::link(interp, key, source, self.script_tag, limits, load); let pushed = match linked { Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run), @@ -304,6 +304,7 @@ impl Realm { let interp = &mut self.interp; interp.drop_temp_envs(marks.0); interp.drop_temp_roots(marks.1); + interp.drop_temp_codes(marks.2); match pushed { Ok(()) => Ok(()), Err(LinkFail::Syntax { tag, error }) => { diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 3e3472d634..01d9e98665 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -50,7 +50,8 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{ - JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, tokenize_module, + JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, + tokenize_module, }; /// A test file's metadata, from its `/*--- … ---*/` block. @@ -845,9 +846,12 @@ fn module_path(referrer: &str, specifier: &str) -> Result { /// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with /// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the -/// suite. `Err` describes a failure. A `negative_type` is the error the run must end with: thrown, -/// or, for a `SyntaxError`, also a module that does not parse. -fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> { +/// suite. `Err` describes a failure. `negative` is the phase (`resolution` or `runtime`) and the +/// error the test expects. A `resolution` test's module must parse, and the run must end with the +/// error while the modules load and link, before any runs; an imported module that does not parse +/// counts for a `SyntaxError`. A `runtime` test's modules must load and link, and the error must be thrown +/// while they run. +fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative: Option<(&str, &str)>, options: &Options) -> Result<(), String> { let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?; let mut given = HashSet::new(); @@ -857,10 +861,29 @@ fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_t let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None }; Ok(LoadedModule { key, source }) }; - match (realm.run_module(rel, source, ModuleLimits::default(), &mut load), negative_type) { + let resolution = negative.is_some_and(|(phase, _)| phase == "resolution"); + if resolution && let Err(e) = vectorcraft_js::parse_module(source, options) { + return Err(format!("did not parse; a resolution error was expected: {} (line {})", e.message, e.line)); + } + let started = realm.start_module(rel, source, ModuleLimits::default(), &mut load); + let result = match started { + Ok(()) if resolution => return Err("linked; an error while linking was expected".to_string()), + Err(e) if !resolution && negative.is_some() => { + return Err(format!("did not start; an error while running was expected: {:?}: {} (line {})", e.kind, e.message, e.line)); + } + Err(e) => Err(e), + Ok(()) => loop { + match realm.advance(u64::MAX) { + Ok(Progress::Paused) => {} + Ok(Progress::Done(v)) => break Ok(v), + Err(e) => break Err(e), + } + }, + }; + match (result, negative.map(|(_, t)| t)) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), - (Err(e), Some("SyntaxError")) if e.kind == RunErrorKind::Syntax => Ok(()), + (Err(e), Some("SyntaxError")) if resolution && e.kind == RunErrorKind::Syntax => Ok(()), (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { realm.bind_last_thrown("__thrown"); match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { @@ -886,6 +909,7 @@ fn run_modules(dir: &Path) { let (mut selected, mut skipped) = (0usize, 0usize); let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize)); let mut failures = String::new(); + let mut panics = 0usize; for folder in MODULE_FOLDERS { let root = or_fail(inside(dir, &format!("test/language/{folder}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); @@ -913,6 +937,7 @@ fn run_modules(dir: &Path) { } selected += 1; let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution"))); + let negative = phase.zip(negative_type.as_deref()); let as_script = if matches!(phase, Some("parse" | "resolution")) { parse(&source, &Options { strict: true, ..options.clone() }).is_err() } else { @@ -930,9 +955,12 @@ fn run_modules(dir: &Path) { } } else { let prelude = format!("{prelude}{includes}"); - match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative_type.as_deref(), &options)) { + match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative, &options)) { Ok(r) => r, - Err(_) => Err("PANIC".to_string()), + Err(_) => { + panics += 1; + Err("PANIC".to_string()) + } } }; match outcome { @@ -958,7 +986,7 @@ fn run_modules(dir: &Path) { after.1, report.display() ); - assert!(!failures.contains("PANIC"), "the interpreter panicked; see {}", report.display()); + assert_eq!(panics, 0, "the interpreter panicked; see {}", report.display()); } #[test] diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f281431dc5..46ddcfeb3d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -119,7 +119,10 @@ pub(crate) fn drain(app: &mut VectorcraftApp) { let Some((name, bytes)) = app.services.script_inbox.as_ref().and_then(|q| q.lock().unwrap_or_else(|e| e.into_inner()).pop()) else { return }; let result = match bytes.as_deref().map(std::str::from_utf8) { None => Err(TOO_LARGE.to_string()), - Some(Ok(source)) => chosen(app, json!({"source": source, "name": name})), + Some(Ok(source)) => { + let module = std::path::Path::new(&name).extension().is_some_and(|e| e.eq_ignore_ascii_case("mjs")); + chosen(app, json!({"source": source, "name": name, "module": module})) + } Some(Err(_)) => Err("the script is not UTF-8 text".to_string()), }; if let Err(e) = result { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index f8d3d4c39e..7106b22f14 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -164,6 +164,18 @@ fn a_web_pick_goes_to_the_warning_and_waits_for_an_open_dialog() { assert_eq!(objects(&app), 2); } +#[test] +fn a_web_pick_of_a_mjs_file_runs_as_a_module() { + let (mut app, inbox, _picks) = app_with_picker(); + app.session.prefs.show_external_script_warning = false; + // `export` is a syntax error outside a module, and `this` is undefined at a module's top. + let module = format!("export var a = 1;\nif (this !== undefined) throw new Error('not a module');\n{DRAW}"); + inbox.lock().unwrap().push(("Picked.MJS".to_string(), Some(module.into_bytes()))); + script_runs::poll(&mut app); + finish(&mut app); + assert_eq!(objects(&app), 2, "{}", app.ui.status); +} + #[test] fn a_web_pick_that_is_not_text_is_reported() { let (mut app, inbox, _picks) = app_with_picker(); diff --git a/docs/mcp.md b/docs/mcp.md index b34a4ebed6..5a882a3371 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2610,7 +2610,7 @@ the included files too. vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` -`script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. +`script.run {path? | source?, module?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. File › Scripts › Other Script… (Cmd+F12) picks a `.js`, `.mjs` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in @@ -2630,6 +2630,10 @@ an engine that `#targetengine` keeps reads each run the way that run's script do A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module (https://262.ecma-international.org/6.0/#sec-modules): strict mode code with the forms above, and `import` and `export` declarations at its top level. `import` and `export` are syntax errors in a `.js` or `.jsx` script. +`module` (true or false) chooses this for any `path` or `source`; it defaults to true for a `path` that ends in +`.mjs` and false otherwise. The app passes `module: true` for a `.mjs` file picked on the web, where the script +arrives as `source`. A `source` that runs as a module imports no files: each import ends the run with an error that +names the specifier. - A specifier is a path relative to the file that imports it. It starts with `./` or `../`, separates names with `/` and names a `.mjs` or `.js` file, which is read as a module. A bare name such as `'lib'`, a URL, an absolute @@ -2641,8 +2645,11 @@ A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module - Every module is read, parsed and linked before any of them runs. A syntax error, a missing or refused file, an import of a name the module does not export, and an import of a name that two `export *` declarations give from different modules end the run with no code run, at the file, line and column of the module they are in. -- Each module runs once in a run, after the modules it imports, in the order it imports them; two paths to one file - (a link, `sub/../x.mjs`, or names that differ only in letter case on Windows) are one module. An import reads +- Each module runs once in a run, after the modules it imports, in the order it imports them. In a cycle of imports + a module does not wait for a module that is still waiting for its own imports, so it can run before that module + has initialized its bindings. Two paths to one file + (a link, `sub/../x.mjs`, or names that differ only in letter case in a Windows folder that ignores case) are one + module, and a module's relative imports are read from the folder the file is in, whichever path reached it first. An import reads the exporting module's binding each time, so it sees later assignments, and reading it before that module has initialized it (in a cycle of imports) throws a `ReferenceError`. Assigning to an import throws a `TypeError`. - `import * as ns` gives a namespace object: not extensible, with no prototype, its export names in code unit order diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 15745fc595..04effe52c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,7 +1080,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From b61c09379033e228808454a3742482f1d4529ba5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:59:05 -0800 Subject: [PATCH 09/17] JavaScript: $.evalFile in a module script's own code reads beside the script A function defined in a .mjs script that runs while a file `$.evalFile` loaded from a subfolder is the file being run now read its own `$.evalFile` paths from that subfolder. The script's folder is now kept for the run and used for code from the script itself, as it already was for the modules it imports; a script run keeps reading beside the file being run. The test262 counts in docs/target-app-parity.md are those of this branch: 535 of 708 ES2015 runs (173 failing, 22 of them for function `name`, `length` and `caller` rules) and 232 of 263 module tests. --- crates/engine/src/script/include.rs | 10 ++++++++++ crates/engine/src/script/mod.rs | 10 +++++++--- crates/engine/src/tests/script_modules.rs | 13 +++++++++++++ docs/target-app-parity.md | 4 ++-- 4 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index bc91914f0b..fb7d0a2c3a 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -234,6 +234,8 @@ pub(crate) struct Files { 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 @@ -383,6 +385,7 @@ impl Files { es2015: es2015_script(path), module_dirs: HashMap::new(), module_paths: HashMap::new(), + entry_key: None, } } @@ -397,6 +400,7 @@ impl Files { 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 })) } @@ -509,6 +513,12 @@ impl Files { 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`]. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 101cdc2bac..cdba1c8a4c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -937,14 +937,18 @@ impl Host { } } - /// The folder of the module whose source has `tag`, when it is a module the script imported - /// (not the script itself, a file `$.evalFile` gave, or code from another run). + /// 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).filter(|n| *n > 0)?; + 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) } diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs index 0dec7ea7da..45d5a22417 100644 --- a/crates/engine/src/tests/script_modules.rs +++ b/crates/engine/src/tests/script_modules.rs @@ -300,3 +300,16 @@ fn script_module_eval_file_reads_beside_the_module_that_calls_it() { 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/docs/target-app-parity.md b/docs/target-app-parity.md index 04effe52c8..773a38c172 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,8 +1079,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 535 of 708 other runs pass with it (373 and 27 without it). Of the 173 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 22 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From 6cf8b4606ac47f48c22a3986e036f92acdae5d98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:41:14 -0800 Subject: [PATCH 10/17] JavaScript: module code drops each expression statement's value Module code was compiled as eval code, so every expression statement stored its value as the completion value. A module never reads that value, and the stored value stayed reachable until the module finished, so a large temporary result counted against the heap limit for the rest of the module. Module code now pops the value, as function code does. Script and eval code keep their completion values, including through finally blocks. --- crates/js/src/compiler.rs | 14 ++++++++++++-- crates/js/src/module_tests.rs | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 714211ef85..bb76d8621d 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -90,6 +90,8 @@ struct FnCompiler<'a> { 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