Scripts: unlisted save, export and open options throw, and an object's own saveAs is not a file write

- saveAs, exportFile and app.open throw "<Class> has no option <name>" for a
  property their option class's help page does not list, instead of leaving it
  out. An undefined property is still left out, and PDFFileOptions also takes
  its read-only typename and parent.
- The script checker no longer reports a file write for saveAs or exportFile
  called on a variable holding the script's own object literal that defines
  that method, with `.` or in brackets. It reports it again once the method is
  assigned or deleted, the object is indexed with a computed key, or another
  name may hold the object.
- The read-only file test checks the open-document grant on its own, with no
  folder scope that also covers the file.
This commit is contained in:
dotCooCoo committed 2026-11-22 01:49:59 -08:00
1 parent 3f293b1c10
commit f31cb42fd8
7 files changed
+203 -14

No files matched your search

+5 -2
View File
@@ -992,14 +992,17 @@ mod tests {
};
let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg")));
let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok()));
// The open document's file is the only grant: no folder scope covers it.
let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() };
let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok());
assert_eq!(check(&kept), (true, true));
assert!(document_write(), "an open document's file is written");
let mut perms = std::fs::metadata(&out).unwrap().permissions();
perms.set_readonly(true);
std::fs::set_permissions(&out, perms.clone()).unwrap();
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
assert!(check(&fresh).0, "a new file next to it is written");
let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() };
assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file");
assert!(!document_write(), "also when it is an open document's file");
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
std::fs::set_permissions(&out, perms).unwrap();
+17 -5
View File
@@ -27,10 +27,12 @@
//! and when one of those files may not be written, none of them is.
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
//! the default its help page gives and throws an error that says it is not available yet at any
//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a
//! `PDFSaveOptions` option still at a new object's default keeps the preset's value.
//! other value; a property the help pages do not list throws an error that names it, unless it is
//! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
//! keeps the preset's value.
//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record:
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only.
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property
//! but `typename` and `parent` throws the same error, unless it is `undefined`.
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
//! commands a script runs never show a dialog, so the level does not change what they do, and it
//! never allows a file the script's grants do not.
@@ -131,6 +133,11 @@ fn not_available(class: &str, name: &str) -> HostError {
HostError::Error(format!("{class}.{name} is not available yet"))
}
/// The error a property that the help page of `class` does not list throws.
fn not_an_option(class: &str, name: &str) -> HostError {
HostError::Error(format!("{class} has no option {name}"))
}
fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result<u64, HostError> {
match d {
Data::Number(n) => {
@@ -522,7 +529,7 @@ fn options_params(class: &OptionClass, d: &Data) -> std::result::Result<Map<Stri
match class.kept.iter().find(|(n, _)| n == k) {
Some((_, default)) if default.matches(v) => {}
Some(_) => return Err(not_available(class.name, k)),
None => {}
None => return Err(not_an_option(class.name, k)),
}
}
Ok(p)
@@ -670,6 +677,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Type("open's options must be a PDFFileOptions record".into()));
}
for (k, v) in items {
if matches!(v, Data::Undefined) {
continue;
}
match k.as_str() {
"pageToOpen" => {
p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?));
@@ -686,7 +696,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
};
p.insert("cropTo".into(), json!(crop));
}
_ => {}
// The read-only members the help page lists.
"typename" | "parent" => {}
_ => return Err(not_an_option("PDFFileOptions", k)),
}
}
}
+13 -2
View File
@@ -64,7 +64,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
d.saveAs(new File(dir + '/a.svg'));\n\
var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\
o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\
o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.pDFXStandardDescription = undefined;\n\
o.colorCompression = 'CompressionQuality.None';\n\
d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\
var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 200; p.artBoardClipping = true;\n\
@@ -481,6 +481,12 @@ fn bad_arguments_are_refused_with_an_error() {
(format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"),
(format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"),
(format!("app.open({f}, undefined, 5);"), "PDFFileOptions"),
(format!("var o = new PDFSaveOptions(); o.trimMark = true; app.activeDocument.saveAs({f}, o);"), "PDFSaveOptions has no option trimMark"),
(
format!("var p = new ExportOptionsPNG24(); p.transparancy = false; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"),
"ExportOptionsPNG24 has no option transparancy",
),
(format!("app.open({f}, undefined, {{pageToOpne: 2}});"), "PDFFileOptions has no option pageToOpne"),
("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"),
(format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"),
];
@@ -560,7 +566,7 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
&mut s,
&base,
&format!(
"Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX}});\n\
"Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX, typename: 'PDFFileOptions', later: undefined}});\n\
vc.log(g.documentColorSpace);",
quoted(&pdf)
),
@@ -570,5 +576,10 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
assert!(!e.is_empty(), "a page the file does not have");
assert_eq!(s.documents().len(), 2);
assert_eq!(s.active().unwrap().doc.artboards.len(), 1, "one page");
// Options left undefined are left out: the file opens as it does without options.
let undefined = format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: undefined, pDFCropToBox: undefined}});", quoted(&pdf));
logged(&mut s, &base, &undefined);
assert_eq!(s.documents().len(), 3);
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages");
let _ = std::fs::remove_dir_all(base);
}
+54
View File
@@ -495,6 +495,8 @@ struct Saved {
shadowed: Option<bool>,
/// It was a platform name the script had a meaning of its own for.
own: bool,
/// What it held in [`Analyzer::writers`], 0 for nothing.
writer: u8,
}
/// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are
@@ -566,6 +568,16 @@ struct Analyzer<'s, 'a, 'l> {
maybe_files: HashSet<String>,
/// `maybe_files` ran out of room: no variable counts as holding a Folder object.
maybe_files_full: bool,
/// The variables holding an object literal of the script's own that defines a method named as a
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
writers: HashMap<String, u8>,
/// The object literals being assigned to a variable, the innermost last, each with the bracket
/// depth inside its `{`, up to [`crate::Limits::nesting`] of them.
objects: Vec<(String, usize)>,
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
/// that is not such a variable.
index_receiver: u8,
/// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own
/// for: they no longer stand for the platform's objects.
own_names: HashSet<String>,
@@ -637,6 +649,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
folders: known.folders.clone(),
maybe_files: known.files.difference(&known.folders).cloned().collect(),
maybe_files_full: false,
writers: HashMap::new(),
objects: vec![],
index_receiver: 0,
own_names: HashSet::new(),
scopes: vec![],
declared,
@@ -742,6 +757,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.group_step(&t, started, before);
self.paren_step(&t, before);
self.assignment(&t, started);
self.object_key(&t);
self.features(&t);
self.newer(&t);
self.module_check(&t);
@@ -841,6 +857,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn bind(&mut self, name: String, path: String) {
self.files.remove(&name);
self.folders.remove(&name);
self.writers.remove(&name);
if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) {
self.bound.insert(name, path);
}
@@ -850,6 +867,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn hold_file(&mut self, name: String, folder: bool) {
self.bound.remove(&name);
self.folders.remove(&name);
self.writers.remove(&name);
if !folder && !self.maybe_files.contains(&name) {
if self.acc.room(self.maybe_files.len()) {
self.maybe_files.insert(name.clone());
@@ -973,6 +991,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
local: false,
shadowed,
own: self.own_names.contains(name),
writer: self.writers.get(name).copied().unwrap_or(0),
}
}
@@ -1007,6 +1026,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
} else {
self.own_names.remove(&name);
}
if saved.writer != 0 {
self.writers.insert(name.clone(), saved.writer);
} else {
self.writers.remove(&name);
}
if let Some(hidden) = saved.shadowed
&& let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name)
&& let Some(s) = self.shadowed.get_mut(i)
@@ -1056,6 +1080,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.bound.remove(name);
self.files.remove(name);
self.folders.remove(name);
self.writers.remove(name);
self.hide_root(name);
}
@@ -1249,6 +1274,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
local: false,
shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true),
own: platform_name(name),
writer: 0,
};
let outside = std::mem::replace(&mut c.saved, empty);
if let Some(scope) = self.scopes.last_mut() {
@@ -1272,6 +1298,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.start_value(a.name, Operand::Done(Held::File { folder: false }));
} else if !a.after_new && t.is("(") {
self.start_group(a.name);
} else if !a.after_new && t.is("{") {
// An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]).
self.unbind(&a.name);
if self.objects.len() < self.acc.limits.nesting {
self.objects.push((a.name, self.depth()));
}
} else {
self.unbind(&a.name);
}
@@ -1310,6 +1342,28 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// `t` in an object literal assigned to a variable: a `:` directly inside its braces after a key
/// that names a document method writing a file (`{saveAs: …}`, `{'exportFile': …}`) makes the
/// variable one of [`Analyzer::writers`]. A closing brace ends the literals it closes.
fn object_key(&mut self, t: &Sig<'s>) {
let depth = self.depth();
while self.objects.pop_if(|(_, d)| *d > depth).is_some() {}
if !t.is(":") {
return;
}
let [h0, h1, ..] = self.h;
let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return };
let key = match h0 {
Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text),
Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)),
_ => return,
};
let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return };
if (is(h1, "{") || is(h1, ",")) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) {
*self.writers.entry(name).or_insert(0) |= 1 << i;
}
}
/// The variable that `t` changes to a number or a string, nothing the check follows, and whether
/// the change waits for the value on the right. `name += …` and the other compound assignments
/// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the
+60 -3
View File
@@ -84,6 +84,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
}
self.writer_use(t);
match t.kind {
T::Ident => self.name(t, line),
T::Punct => self.punct(t, line),
@@ -272,6 +273,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default();
self.setter(&name, h2, h3, line);
}
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
"[" => self.index_receiver = self.writer_bits(h0, h1),
"(" => self.call(line),
// `Name.prototype["+"] = …` defines an operator.
"=" => {
@@ -292,8 +295,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
if is(h0, "]")
&& is(h2, "[")
&& let Some(name) = h1.filter(|s| s.kind == T::Str)
&& catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str())
&& let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
&& catalog::DOM_FILE_WRITES.contains(&method.as_str())
&& !Self::defines(self.index_receiver, &method)
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
@@ -313,7 +317,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.acc.feature(FeatureId::FileDialog, line);
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
self.acc.feature(FeatureId::FileRead, line);
} else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) {
} else if (file && catalog::FILE_WRITES.contains(&n))
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
} else if n == catalog::EXECUTE {
@@ -336,6 +342,57 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
/// 0 for anything else. A receiver the check does not follow may be a document.
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> u8 {
match receiver {
Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0),
_ => 0,
}
}
/// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`,
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
/// `local[k] = w`, `delete local.saveAs`).
fn writer_use(&mut self, t: &Sig<'s>) {
let [h0, h1, h2, h3] = self.h;
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text);
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
let escaped = if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
} else if let Some(name) = writer(h0, h1) {
// `local` followed by anything but a member, its own assignment or an object key's `:`.
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
// `local.saveAs = …`
writer(h2, h3)
} else if is(h0, "[") {
// `local[k]` with a key that is not a string literal.
writer(h1, h2).filter(|_| t.kind != T::Str)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`
writer(h3, None)
} else {
None
};
if let Some(name) = escaped {
self.writers.remove(name);
}
}
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
fn defines(bits: u8, method: &str) -> bool {
catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0)
}
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
/// (not a property of the same name), or a File or Folder object made in place or held in
/// grouping parentheses ([`Sig::file`]).
+51
View File
@@ -558,6 +558,57 @@ fn save_as_and_export_file_in_brackets_write_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write
/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one
/// assigned something else since, and for a method the literal does not define, they write the file.
#[test]
fn the_scripts_own_save_as_writes_no_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}, 'n': 1};\n",
"local.saveAs(f);\n",
"local['saveAs'](f);\n",
"app.activeDocument.saveAs(f);\n",
"local.exportFile(f);\n",
"other.saveAs(f);\n",
"local = app.activeDocument;\n",
"local.saveAs(f);\n",
"var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n",
"t['exportFile'](f);\n",
"t.saveAs(f);\n",
"var activeDocument = {saveAs: function () {}};\n",
"app.activeDocument['saveAs'](f);\n",
"app.activeDocument.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]);
}
/// Once the script replaces or deletes such a method, indexes the object with a computed key, or
/// lets another name hold the object, its `saveAs` may write a file again.
#[test]
fn a_changed_or_shared_own_save_as_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}, b = {saveAs: function () {}}, c = {saveAs: function () {}};\n",
"var d = {saveAs: function () {}}, e = {saveAs: function () {}}, g = {saveAs: function () {}};\n",
"a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n",
"a.saveAs = app.activeDocument.saveAs;\n",
"b['saveAs'] = w;\n",
"c[k] = w;\n",
"delete d.saveAs;\n",
"var h = e;\n",
"use(g);\n",
"a.saveAs(f);\n",
"b.saveAs(f);\n",
"c.saveAs(f);\n",
"d.saveAs(f);\n",
"e.saveAs(f);\n",
"g['saveAs'](f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16][..]));
}
/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing
/// them and setting them on another object does not.
#[test]
+3 -2
View File
@@ -2726,8 +2726,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help
pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help
pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and
`parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
keeps the preset's value. A bad value throws an error before anything is written.
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.