SPB Git

Repository Public License

ScriptEngine.swift 8.6 KB 160 lines swift

1import Foundation2@preconcurrency import JavaScriptCore3import PrismCore45public struct ScriptError: Error, LocalizedError, Sendable, Equatable {6    public let message: String7    public init(_ message: String) { self.message = message }8    public var errorDescription: String? { message }9}1011/// Runs the JavaScript an app carries (ADR 0009): global scripts and on-demand component definitions.12///13/// The context is a bare JavaScriptCore VM: it has no file, network, process or timer API. The only way out is the single14/// `host` callback, whose operations the owner of the engine decides. Every entry into the VM is cut off after `timeLimit`15/// seconds of execution, so a script cannot hang the app. Values cross the boundary as JSON text only.16@MainActor17public final class ScriptEngine {18    public nonisolated static let maxSourceLength = 200_0001920    /// Handles `app.<op>(…)` calls from scripts. Throwing turns into a JavaScript exception.21    public var host: ((_ op: String, _ args: [JSONValue]) throws -> JSONValue)?22    public let timeLimit: Double23    /// False when this macOS does not offer the execution watchdog; scripts then run without a time limit.24    public private(set) var hasTimeLimit = false25    public private(set) var componentIDs: Set<String> = []2627    private let vm = JSVirtualMachine()!28    private let context: JSContext2930    public init(timeLimit: Double = 0.5) {31        self.timeLimit = timeLimit32        context = JSContext(virtualMachine: vm)!33        installWatchdog()34        let bridge: @convention(block) (String, String) -> String = { [weak self] op, argsJSON in35            MainActor.assumeIsolated {36                guard let self, let host = self.host else { return #"{"error":"This operation is not available here."}"# }37                do {38                    let args = (try JSONValue.parse(Data(argsJSON.utf8))).arrayValue ?? []39                    return JSONValue.object(["value": try host(op, args)]).canonicalString()40                } catch {41                    return JSONValue.object(["error": .string(error.localizedDescription)]).canonicalString()42                }43            }44        }45        context.setObject(bridge, forKeyedSubscript: "__host" as NSString)46        context.evaluateScript(Self.prelude)47        context.exception = nil48    }4950    private static let prelude = """51    var app = (function () {52      var host = __host;53      function h(op, args) {54        var r = JSON.parse(host(op, JSON.stringify(args === undefined ? [] : args)));55        if (r.error) throw new Error(r.error);56        return r.value;57      }58      var api = {};59      ['get', 'set', 'local', 'setLocal', 'setProp', 'query', 'insert', 'update', 'remove', 'notify', 'navigate', 'log', 'emit', 'today'].forEach(function (op) {60        api[op] = function () { return h(op, Array.prototype.slice.call(arguments)); };61      });62      return Object.freeze(api);63    })();64    var console = Object.freeze({ log: function () { app.log(Array.prototype.slice.call(arguments).map(String).join(' ')); } });65    var __components = {};66    function __define(id, source) {67      __components[id] = (0, eval)('(function(){' + source + '\\n;return function(__name){ try { return eval(__name); } catch (e) { return undefined; } }; })()');68    }69    function __lookup(id, name) { return id ? (__components[id] ? __components[id](name) : undefined) : globalThis[name]; }70    function __has(id, name) { return typeof __lookup(id, name) === 'function'; }71    function __invoke(id, name, argsJSON) {72      var f = __lookup(id, name);73      if (typeof f !== 'function') throw new Error('There is no function `' + name + '`.');74      var r = f.apply(null, JSON.parse(argsJSON));75      return JSON.stringify(r === undefined ? null : r);76    }77    delete globalThis.__host;78    """7980    private typealias TerminateCallback = @convention(c) (JSContextRef?, UnsafeMutableRawPointer?) -> Bool81    private typealias SetLimit = @convention(c) (JSContextGroupRef?, Double, TerminateCallback?, UnsafeMutableRawPointer?) -> Void8283    /// JavaScriptCore's execution watchdog is exported but not declared in the public headers, so it is looked up at run time84    /// and its absence is tolerated (and reported through `hasTimeLimit`).85    private func installWatchdog() {86        guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "JSContextGroupSetExecutionTimeLimit") else { return }87        let setLimit = unsafeBitCast(symbol, to: SetLimit.self)88        setLimit(JSContextGetGroup(context.jsGlobalContextRef), timeLimit, { _, _ in true }, nil)89        hasTimeLimit = true90    }9192    private func takeException(_ what: String) -> ScriptError? {93        guard let exception = context.exception else { return nil }94        context.exception = nil95        var text = exception.toString() ?? "unknown error"96        if text.contains("execution terminated") { return ScriptError("\(what) ran for more than \(timeLimit) s and was stopped. Avoid long loops; do less work per call.") }97        if let line = exception.objectForKeyedSubscript("line"), line.isNumber { text += " (line \(line.toInt32()))" }98        return ScriptError("\(what): \(text)")99    }100101    /// A syntax error in `source`, or nil. Nothing is executed.102    public nonisolated static func syntaxError(_ source: String, asFunctionBody: Bool = false) -> String? {103        guard source.utf8.count <= maxSourceLength else { return "The source is longer than \(maxSourceLength) characters." }104        let ctx = JSGlobalContextCreate(nil)105        defer { JSGlobalContextRelease(ctx) }106        let script = JSStringCreateWithUTF8CString(asFunctionBody ? "(function(){\(source)\n})" : source)107        defer { JSStringRelease(script) }108        var exception: JSValueRef?109        if JSCheckScriptSyntax(ctx, script, nil, 1, &exception) { return nil }110        guard let exception, let s = JSValueToStringCopy(ctx, exception, nil) else { return "Syntax error." }111        defer { JSStringRelease(s) }112        var message = JSStringCopyCFString(kCFAllocatorDefault, s) as String113        if let object = JSValueToObject(ctx, exception, nil) {114            let key = JSStringCreateWithUTF8CString("line")115            defer { JSStringRelease(key) }116            let line = JSValueToNumber(ctx, JSObjectGetProperty(ctx, object, key, nil), nil)117            if line.isFinite, line > 0 { message += " (line \(Int(line)))" }118        }119        return message120    }121122    /// Evaluates a global script: its top-level functions become callable by name.123    public func load(script source: String, name: String) throws {124        if let problem = Self.syntaxError(source) { throw ScriptError("Script `\(name)`: \(problem)") }125        context.evaluateScript(source)126        if let e = takeException("Script `\(name)`") { throw e }127    }128129    /// Evaluates a component definition in its own scope; its functions are reached with `call(_:_:component:)`.130    public func define(component id: String, source: String) throws {131        if let problem = Self.syntaxError(source, asFunctionBody: true) { throw ScriptError("Component `\(id)`: \(problem)") }132        context.objectForKeyedSubscript("__define").call(withArguments: [id, source])133        if let e = takeException("Component `\(id)`") { throw e }134        componentIDs.insert(id)135    }136137    public nonisolated static func isIdentifier(_ name: String) -> Bool {138        guard let first = name.unicodeScalars.first, name.utf8.count <= 64, CharacterSet.letters.union(CharacterSet(charactersIn: "_$")).contains(first) else { return false }139        return name.unicodeScalars.allSatisfy { CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "_$")).contains($0) } && !name.hasPrefix("__")140    }141142    public func has(_ function: String, component: String? = nil) -> Bool {143        guard Self.isIdentifier(function) else { return false }144        let r = context.objectForKeyedSubscript("__has").call(withArguments: [component as Any? ?? NSNull(), function])145        context.exception = nil146        return r?.toBool() ?? false147    }148149    /// Calls a function with JSON arguments and returns its JSON result.150    @discardableResult151    public func call(_ function: String, _ args: [JSONValue] = [], component: String? = nil) throws -> JSONValue {152        guard Self.isIdentifier(function) else { throw ScriptError("`\(function)` is not a function name.") }153        let what = component.map { "`\(function)` of component `\($0)`" } ?? "`\(function)`"154        let r = context.objectForKeyedSubscript("__invoke").call(withArguments: [component as Any? ?? NSNull(), function, JSONValue.array(args).canonicalString()])155        if let e = takeException(what) { throw e }156        guard let text = r?.toString(), let value = try? JSONValue.parse(Data(text.utf8)) else { return .null }157        return value158    }159}160
Files main
Menu

Theme