JavaScript: version-independent Application setting

If using JavaScript, one has to use with DT 3
app = Application("DEVONthink 3");
while with DT 4 and up, you’d have to use
app = Application("DEVONthink")

The function getDTApplication below will return the correct Application object. It might help writing scripts that work for new and old DT versions.

The code assumes that DT is installed in the global “Applications” folder. It will throw an error if no DT or more than one are found there.

function getDTApplication() {
  const fileManager = $.NSFileManager.defaultManager;
  const err = $();
  const applications = fileManager.contentsOfDirectoryAtPathError($('/Applications/'), err);
  if (!applications) {
    throw (`Couldn't get applications ${err.localizedMessage.js}`);
  }
  const validApps = (applications.js.filter(app => app.js.startsWith('DEVONthink') && app.js.endsWith('app')).map(a => a.js));
  if (validApps.length > 1) {
    throw ('More than one DEVONthink app found.')
  } else if (validApps.length === 0) {
    throw ('No DEVONthink app found.')
  }
  return Application(validApps[0].replace(".app",""));
}

As a lot of things have changed in the new script suite or are only available in version 4 and as JXA doesn’t support synonyms, this might actually require additional work and it might be easier to write two scripts in the end.

Right. I was curious how one could figure out the version. For the rest… Either writing a second script or wrapping the alternatives in conditionals.