mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge main into feat/scripts-api-d8b-tracing
This commit is contained in:
commit
226eb80e6f
1182 files changed
+178402
-264198
No files matched your search
@@ -292,7 +292,7 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
/// Whether the script may read `path` now by its own read scope and the read roots
|
||||
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
|
||||
fn may_read(h: &Host, path: &str) -> bool {
|
||||
let gate = h.disk.borrow().gate(Vec::new());
|
||||
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
|
||||
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,9 @@
|
||||
//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and
|
||||
//! [`NO_PICKER`].
|
||||
//! - The commands a script runs with `vc.run` read and write only in the places above and in the
|
||||
//! files of the open documents ([`crate::file_access::ScriptGate`]).
|
||||
//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read
|
||||
//! the files that the documents open when the run began link to, as the person last left those
|
||||
//! documents and as those links led then.
|
||||
//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most
|
||||
//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at
|
||||
//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an
|
||||
@@ -468,13 +470,15 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The gate for a command the script runs: the places it reads and writes now, and the files of
|
||||
/// the open documents, `documents`, but not the files its `File` objects hold open for writing.
|
||||
pub(crate) fn gate(&self, documents: Vec<String>) -> crate::file_access::ScriptGate {
|
||||
/// The gate for a command the script runs: the places it reads and writes now, the files of
|
||||
/// the open documents, `documents`, but not the files its `File` objects hold open for writing,
|
||||
/// and the files it may only read because the documents open when the run began link to them,
|
||||
/// `linked`.
|
||||
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
|
||||
// A save, export or open of a `File` the script names reads and writes as its `File` would.
|
||||
let documents = if self.exact { Vec::new() } else { documents };
|
||||
let held = self.open.values().filter_map(|o| o.target.clone()).collect();
|
||||
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, also: None }
|
||||
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None }
|
||||
}
|
||||
|
||||
/// The files written since this was last asked, to name in the report.
|
||||
@@ -962,8 +966,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
|
||||
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
|
||||
/// between two changes, and none are read when the lock cannot be taken.
|
||||
fn read_store(store: &Path) -> Vec<serde_json::Value> {
|
||||
let Ok(_lock) = lock_store(store) else { return Vec::new() };
|
||||
load_store(store, false).unwrap_or_default()
|
||||
list_store(store).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
|
||||
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
|
||||
/// this version or holds no list of grants.
|
||||
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
let _lock = lock_store(store)?;
|
||||
load_store(store, false)
|
||||
}
|
||||
|
||||
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
|
||||
@@ -979,7 +990,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
let bytes = match read_head(store, MAX_STORE_BYTES) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
// A link whose target is missing is there but cannot be read.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if bytes.len() > MAX_STORE_BYTES {
|
||||
@@ -997,14 +1009,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
|
||||
&& g["write"].is_boolean()
|
||||
&& g["folder"].is_boolean()
|
||||
};
|
||||
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
|
||||
if strict {
|
||||
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
|
||||
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
|
||||
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
|
||||
}
|
||||
return Ok(grants.clone());
|
||||
}
|
||||
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
|
||||
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
|
||||
}
|
||||
|
||||
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
|
||||
@@ -1104,9 +1116,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
}
|
||||
|
||||
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
|
||||
/// its text, the path and whether it may be written (`script.grants`).
|
||||
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
|
||||
read_store(&data_dir.with_file_name(GRANTS_FILE))
|
||||
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
|
||||
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
list_store(&data_dir.with_file_name(GRANTS_FILE))
|
||||
}
|
||||
|
||||
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
|
||||
|
||||
@@ -217,6 +217,15 @@ pub(crate) struct Files {
|
||||
levels: usize,
|
||||
/// The files `$.evalFile` is running, the script first.
|
||||
frames: Vec<Frame>,
|
||||
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
|
||||
es2015: bool,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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"))
|
||||
}
|
||||
|
||||
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
|
||||
@@ -311,9 +320,15 @@ impl Files {
|
||||
chain: real.into_iter().collect(),
|
||||
levels: 0,
|
||||
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
|
||||
es2015: es2015_script(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() }
|
||||
}
|
||||
|
||||
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
|
||||
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
|
||||
#[cfg(test)]
|
||||
@@ -456,7 +471,7 @@ impl Files {
|
||||
return Ok(());
|
||||
}
|
||||
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
|
||||
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
|
||||
let options = Options { preprocessor_lines: true, ..self.options() };
|
||||
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
|
||||
let mut cursor = 0usize;
|
||||
for d in &program.directives {
|
||||
|
||||
@@ -802,6 +802,35 @@ struct Host {
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// The documents open when the run began as the person last left them, each with its own file
|
||||
/// and the file it was read from ([`crate::DocState::as_person_left`],
|
||||
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
|
||||
/// they link to from them ([`Host::linked`]).
|
||||
run_docs: RefCell<Vec<RunDoc>>,
|
||||
/// The files the documents open when the run began link to as the person left them
|
||||
/// ([`crate::file_access::ScriptGate::linked`]).
|
||||
linked: std::cell::OnceCell<crate::file_access::LinkedFiles>,
|
||||
}
|
||||
|
||||
/// A document open when a run began, with its own file and the file it was read from.
|
||||
type RunDoc = (Arc<crate::Document>, Option<String>, Option<String>);
|
||||
|
||||
impl Host {
|
||||
/// The files the commands the run runs may read because the documents open when the run began
|
||||
/// link to them, found once, from those documents as the person left them: a link a script's
|
||||
/// command added or changed, in this run or an earlier one, and a document it opened, give it
|
||||
/// no file to read.
|
||||
fn linked(&self) -> crate::file_access::LinkedFiles {
|
||||
self.linked
|
||||
.get_or_init(|| {
|
||||
let docs = std::mem::take(&mut *self.run_docs.borrow_mut());
|
||||
let files = docs.iter().flat_map(|(d, path, from)| {
|
||||
crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref()))
|
||||
});
|
||||
crate::file_access::ScriptGate::real_files(files.collect::<Vec<_>>())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
|
||||
@@ -1242,9 +1271,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
let before: Vec<(u64, Arc<crate::Document>, u64)> =
|
||||
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
|
||||
crate::file_access::start_recording_writes();
|
||||
// The command reads and writes only where the script's own files may, and the open documents' files.
|
||||
let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect());
|
||||
// The command reads and writes only where the script's own files may, and the files the person gave
|
||||
// the open documents; it also reads the files the documents open when the run began link to, as the
|
||||
// person left them. A document a script's command opened gives it no file.
|
||||
let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect();
|
||||
let gate = host.disk.borrow().gate(documents, host.linked());
|
||||
let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect();
|
||||
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
|
||||
// What the command opened, changed or gave another file is not as the person left it.
|
||||
for st in &mut s.docs {
|
||||
let prior = was.iter().find(|(uid, _)| *uid == st.uid);
|
||||
st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from)));
|
||||
}
|
||||
drop(was);
|
||||
// A file a command wrote before it failed is on disk all the same.
|
||||
let mut written = host.written.borrow_mut();
|
||||
for path in crate::file_access::finish_recording_writes(r.is_ok()) {
|
||||
@@ -1493,7 +1532,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
|
||||
})?;
|
||||
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
|
||||
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
|
||||
let options = host.files.borrow().options();
|
||||
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
|
||||
host.files.borrow_mut().end_eval();
|
||||
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
|
||||
@@ -1991,11 +2030,16 @@ impl Session {
|
||||
// A realm made here gets the script extensions, `$` and the dialogs; a kept one has them
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
|
||||
// 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 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.
|
||||
let mut realm = match realm {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
realm
|
||||
}
|
||||
None => {
|
||||
@@ -2065,6 +2109,14 @@ impl Session {
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::default(),
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
.filter_map(DocState::as_person_left)
|
||||
.map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string)))
|
||||
.collect(),
|
||||
),
|
||||
linked: std::cell::OnceCell::new(),
|
||||
});
|
||||
*link.borrow_mut() = Some(host.clone());
|
||||
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
|
||||
@@ -2090,6 +2142,7 @@ impl Session {
|
||||
Ok(expanded) => {
|
||||
*host.script_map.borrow_mut() = expanded.map;
|
||||
realm.set_strict_writes(expanded.strict == Some(true));
|
||||
realm.set_script_name(Some(host.name.to_string()));
|
||||
if fresh {
|
||||
let l = link.clone();
|
||||
realm.set_source_locator(Rc::new(move |tag, line| match current(&l) {
|
||||
@@ -2098,6 +2151,7 @@ impl Session {
|
||||
}));
|
||||
}
|
||||
(if fresh { realm.add_script_extensions() } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
|
||||
|
||||
Reference in new issue
Block a user