Merge main into feat/scripts-doc-defaults

This commit is contained in:
dotCooCoo committed 2026-11-28 23:20:21 -08:00
commit 0bd735f53d
201 files changed
+13721 -999

No files matched your search

+142 -10
View File
@@ -66,7 +66,8 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
Realm, RunError, RunErrorKind,
};
use crate::{
@@ -207,6 +208,8 @@ pub(crate) struct Request {
pub locale: String,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
pub module: bool,
/// The actions `app.doScript` can play.
pub actions: Vec<actions::Playable>,
}
@@ -784,6 +787,9 @@ struct Host {
script_map: RefCell<include::SourceMap>,
/// The same for each source `$.evalFile` gave, in order.
eval_maps: RefCell<Vec<include::SourceMap>>,
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
/// module's, by its index there.
module_maps: RefCell<HashMap<usize, String>>,
/// 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<Vec<(Arc<str>, u32, u32)>>,
@@ -979,6 +985,22 @@ impl Host {
}
}
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
/// run).
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
let script = self.script_tag.get();
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
return None;
}
let n = tag.checked_sub(script)?;
if n == 0 {
return self.files.borrow().entry_module_dir();
}
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
self.files.borrow().module_dir(&key)
}
/// Adds a line to the run's console and, during a slice, to the session's.
fn line(&self, entry: console::Entry, cut: bool) {
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
@@ -1297,6 +1319,7 @@ fn note_ids(s: &mut Session) {
/// it, for a result that cannot cross to the script.
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
raise_ids(s);
s.script_style_trail = StyleTrail::start(s);
let mutating = waits_for_tool_edit(id);
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
@@ -1344,6 +1367,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
Ok((v, objects, bytes, save))
}
Err(e) => {
s.script_style_trail = StyleTrail::default();
if let Some(save) = save
&& !save.restore(s)
{
@@ -1424,12 +1448,77 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
}
}
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::see_points(host);
dom::after_kept_command(host);
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
}
crossed.map(|data| (data, value))
}
/// A document's uid, revert count, and character and paragraph style lists.
pub(crate) type StyleLists =
(u64, u64, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>);
/// What the steps of a command a script runs did to the documents' style lists
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
/// documents a step reverted.
#[derive(Default)]
pub(crate) struct StyleTrail {
lists: Vec<StyleLists>,
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
pub(crate) reverted: Vec<u64>,
}
impl StyleTrail {
/// A trail that starts from the documents' style lists now.
fn start(s: &Session) -> Self {
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
StyleTrail { lists, ..Default::default() }
}
}
/// After a step of a batch a script runs: notes the styles the step removed or renamed and the
/// documents it reverted, so the style objects see a style the batch removed and made again under
/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open
/// document's lists, however many steps change them.
pub(crate) fn note_style_lists(s: &mut Session) {
let trail = &mut s.script_style_trail;
trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid));
for st in &s.docs {
let (c, p) = (&st.doc.char_styles, &st.doc.para_styles);
let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else {
trail.lists.push((st.uid, st.reverts, c.clone(), p.clone()));
continue;
};
if last.1 != st.reverts {
if !trail.reverted.contains(&st.uid) {
trail.reverted.push(st.uid);
}
} else {
for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] {
if vectorcraft_doc::Shared::ptr_eq(old, new) {
continue;
}
let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect();
for d in old.iter().filter(|d| !names.contains(d.name.as_str())) {
trail.gone.insert((st.uid, para, d.name.clone()));
}
}
}
*last = (st.uid, st.reverts, c.clone(), p.clone());
}
}
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
#[cfg(test)]
pub(crate) fn retained_style_lists(s: &Session) -> usize {
s.script_style_trail.lists.len()
}
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
/// of a crossing throws a `RangeError`.
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
@@ -1535,6 +1624,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
}),
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
site: true,
}
};
let mut items = vec![
@@ -1549,9 +1639,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
/// run, 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.
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
/// 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<Data>) -> std::result::Result<Data, HostError> {
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()));
};
@@ -1565,7 +1663,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
}
host.charge_call(path.len() as u64 + 2)?;
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
let error = match f.kind {
include::FailKind::Limit => HostError::Abort(message),
@@ -1675,6 +1773,22 @@ fn explained(e: &RunError) -> String {
}
}
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
/// the modules are read, which is the order of their sources' tags.
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
let source = read.map(|(text, map)| {
let mut maps = host.eval_maps.borrow_mut();
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
maps.push(map);
drop(maps);
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
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<Arc<str>>) {
let (kind, message) = match f.kind {
@@ -2092,7 +2206,19 @@ impl Session {
self.script_stop.clear();
self.script_report = None;
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
let expanded = files.expand_script(&request.source);
if request.module {
files.read_es2015();
}
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
// `module_key` names it among the modules it imports.
let (expanded, module_key) = if request.module {
match files.module_entry(&request.source) {
Ok((key, expanded)) => (Ok(expanded), Some(key)),
Err(f) => (Err(f), None),
}
} else {
(files.expand_script(&request.source), None)
};
let name = match &expanded {
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
_ => request.name,
@@ -2123,9 +2249,8 @@ impl Session {
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
// `.js` run that names it, and keeps it as it keeps its globals.
let es2015 = include::es2015_script(request.file.as_deref());
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
let es2015 = request.module || include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
@@ -2194,6 +2319,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()),
@@ -2258,7 +2384,13 @@ impl Session {
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
.and_then(|()| {
let r = realm.start(&expanded.source);
let r = match &module_key {
None => realm.start(&expanded.source),
Some(key) => {
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
}
};
// Source that does not compile defines no code, so its map is not kept.
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
host.script_tag.set(realm.script_tag());