SPB Git

Repository Public License

AppRuntime+Scripts.swift 8.2 KB 164 lines swift

1import Foundation2import PrismComponentSDK3import PrismCore4import PrismDataRuntime5import PrismLogicRuntime6import PrismObjectModel7import PrismScriptRuntime89/// The app's custom logic (ADR 0009): global scripts and on-demand components, run in a confined JavaScript engine.10extension AppRuntime {11    /// The engine with every script and component definition loaded; nil when the app carries none or may not run them.12    func scripts() -> ScriptEngine? {13        if let engine { return engine }14        guard !(blueprint.scripts.isEmpty && blueprint.componentDefinitions.isEmpty) else { return nil }15        guard has(Permission.scripts) else { reportScript("This app is not allowed to run custom logic."); return nil }16        let e = ScriptEngine()17        e.host = { [weak self] op, args in18            guard let self else { throw ScriptError("The app is closing.") }19            return try self.hostCall(op, args)20        }21        for s in blueprint.scripts {22            do { try e.load(script: s.props["source"]?.stringValue ?? "", name: s.id) } catch { reportScript(error.localizedDescription) }23        }24        for d in blueprint.componentDefinitions {25            do { try e.define(component: d.id, source: d.props["source"]?.stringValue ?? "") } catch { reportScript(error.localizedDescription) }26        }27        if !e.hasTimeLimit { log(.warning, "This macOS does not offer the script watchdog; custom logic runs without a time limit.") }28        engine = e29        return e30    }3132    /// Logs a script problem once, so a failing render does not flood the log.33    func reportScript(_ message: String) {34        guard reportedScriptErrors.insert(message).inserted else { return }35        log(.error, message)36    }3738    /// Calls a function of the global scripts.39    @discardableResult40    public func callScript(_ function: String, _ args: [JSONValue] = [], readOnly: Bool = false) throws -> JSONValue {41        guard let engine = scripts() else { throw ScriptError("This app has no scripts.") }42        return try withScriptContext(instance: nil, readOnly: readOnly) { try engine.call(function, args) }43    }4445    /// Calls a function of an on-demand component for one instance. Errors are logged and yield nil: the UI never crashes on bad logic.46    @discardableResult47    public func callComponent(_ definition: String, _ function: String, _ args: [JSONValue], instance: String, readOnly: Bool = false, optional: Bool = false) -> JSONValue? {48        guard let engine = scripts() else { return nil }49        if optional, !engine.has(function, component: definition) { return nil }50        do { return try withScriptContext(instance: instance, readOnly: readOnly) { try engine.call(function, args, component: definition) } } catch {51            reportScript(error.localizedDescription)52            return nil53        }54    }5556    public func componentHas(_ definition: String, _ function: String) -> Bool { scripts()?.has(function, component: definition) ?? false }5758    private func withScriptContext<T>(instance: String?, readOnly: Bool, _ body: () throws -> T) rethrows -> T {59        let saved = (scriptInstance, scriptReadOnly)60        scriptInstance = instance61        // Read-only is sticky: code reached from a render or an expression cannot change anything, however it got there.62        scriptReadOnly = readOnly || saved.163        defer { (scriptInstance, scriptReadOnly) = saved }64        return try body()65    }6667    /// Everything a script can do. Nothing here reaches outside the app.68    private func hostCall(_ op: String, _ args: [JSONValue]) throws -> JSONValue {69        func arg(_ i: Int) -> JSONValue { i < args.count ? args[i] : .null }70        func text(_ i: Int, _ what: String) throws -> String {71            guard let s = arg(i).stringValue, !s.isEmpty else { throw ScriptError("app.\(op): \(what) must be text.") }72            return s73        }74        func mutating() throws {75            if scriptReadOnly { throw ScriptError("app.\(op) cannot be called while rendering or inside an expression. Change things from an event handler.") }76        }77        func storage() throws {78            guard has(Permission.storageLocal) else { throw ScriptError("This app is not allowed to store data.") }79        }80        switch op {81        case "get":82            let key = try text(0, "the state key")83            guard StatePath.isValid(key) else { throw ScriptError("`\(key)` is not a valid state key.") }84            return StatePath.get(key, in: .object(state))85        case "set":86            try mutating()87            let key = try text(0, "the state key")88            guard StatePath.isValid(key), let top = key.split(separator: ".").first, blueprint.state[String(top)] != nil else {89                throw ScriptError("`\(key)` is not declared in the app's state. Declare it with logic.bind first.")90            }91            setState(key, arg(1))92            return .null93        case "local":94            let key = try text(0, "the key")95            guard let instance = scriptInstance else { throw ScriptError("app.local is only available inside a component.") }96            return localState[instance]?[key] ?? arg(1)97        case "setLocal":98            try mutating()99            let key = try text(0, "the key")100            guard let instance = scriptInstance else { throw ScriptError("app.setLocal is only available inside a component.") }101            if localState[instance]?[key] != arg(1) { localState[instance, default: [:]][key] = arg(1) }102            return .null103        case "setProp":104            try mutating()105            let name = try text(0, "the prop name")106            guard let instance = scriptInstance, let path = bindingPath(blueprint.object(instance)?.props[name]) else {107                throw ScriptError("`\(name)` is not bound to state on this instance (use {\"$bind\": \"key\"} for it).")108            }109            setState(path, arg(1))110            return .null111        case "query":112            try storage()113            if let id = arg(0).stringValue {114                guard blueprint.object(id)?.isQuery == true else { throw ScriptError("There is no query `\(id)`.") }115                return .array(namedQueryRows(id).map(JSONValue.object))116            }117            let query = try DataQuery(json: arg(0))118            let schema = try store.schema(query.table)119            if let problem = query.problems(schema: schema).first { throw ScriptError(problem) }120            _ = dataRevision121            return .array(try store.run(query, scope: scope()).map(JSONValue.object))122        case "insert":123            try mutating(); try storage()124            let id = try store.insert(into: try text(0, "the table"), values: arg(1).objectValue ?? [:])125            invalidate()126            return .int(id)127        case "update":128            try mutating(); try storage()129            guard let id = arg(1).intValue else { throw ScriptError("app.update: the record id must be a number.") }130            try store.update(try text(0, "the table"), id: id, values: arg(2).objectValue ?? [:])131            invalidate()132            return .null133        case "remove":134            try mutating(); try storage()135            guard let id = arg(1).intValue else { throw ScriptError("app.remove: the record id must be a number.") }136            try store.delete(from: try text(0, "the table"), id: id)137            invalidate()138            return .null139        case "notify":140            try mutating()141            notify(arg(0).displayString, tone: arg(1).stringValue ?? "info")142            return .null143        case "navigate":144            try mutating()145            let page = try text(0, "the page")146            guard blueprint.object(page)?.isPage == true else { throw ScriptError("There is no page `\(page)`.") }147            currentPage = page148            return .null149        case "emit":150            try mutating()151            guard let instance = scriptInstance else { throw ScriptError("app.emit is only available inside a component.") }152            fire(try text(0, "the event name"), on: instance, value: arg(1))153            return .null154        case "log":155            log(.info, "Script: \(String(arg(0).displayString.prefix(500)))")156            return .null157        case "today":158            return .string(DateCoding.string(from: Date()))159        default:160            throw ScriptError("app.\(op) does not exist.")161        }162    }163}164
Files main
Menu

Theme