2

I've created a custom .scpt file with some library functions and want to load that library in my other scripts.

I've followed the official guide by Apple, and here is what I've got:

A) Test with AppleScript

Library File: ~/Library/Script Libraries/Sample Library 1.scpt

on changeCase(theText)
    set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
    set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    set theAlteredText to ""
    
    repeat with aCharacter in theText
        set theOffset to offset of aCharacter in theComparisonCharacters
        if theOffset is not 0 then
            set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
        else
            set theAlteredText to (theAlteredText & aCharacter) as string
        end if
    end repeat
    return theAlteredText
end changeCase

Test Script

tell script "Sample Library 1"
    changeCase("Hello World")
end tell

Result: This solution works. But I'd like to use JXA, so I created the second test case below.

B) Test with JXA

Library File: ~/Library/Script Libraries/Sample Library 2.scpt

function changeCase(text) {
    return text.toUpperCase();
}

Test Script

var lib = Library("Sample Library 2")
lib.changeCase("Hello World")

Result: The Script Editor crashes when I run the script. The following error is displayed in the error report

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSXMLDocument initWithData:options:error:]: nil argument'
abort() called
terminating with uncaught exception of type NSException

What is happening here, and how can I fix that crash when using JXA?

Philipp
  • 10,240
  • 8
  • 59
  • 71

1 Answers1

3

I found the solution:

The Library file ~/Library/Script Libraries/Sample Library 2.scpt needs to be a "Script Bundle" with the extension .scptd

Summary:

  1. JXA libraries need to be saved as "Script-Bundles" ("Save As ... → Script-Bundle").
  2. JXA libraries can only be used by other JXA scripts
  3. AppleScript files can never load a JXA library.
  4. AppleScript libraries that are "Script" type can be used by other AppleScript files.
  5. AppleScript libraries that are "Script-Bundles" can be used by JXA scripts and AppleScript files.

To make it simple, I recommend saving all libraries as a "Script Bundle"

Philipp
  • 10,240
  • 8
  • 59
  • 71