Open source CapCut alternative.
TypeScript
feat(app): parse app scripting dictionaries into a typed, cached model
David Le86bed8fbf4b4
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppScriptingDictionary.swift b/apps/Donkey/Sources/DonkeyRuntime/AppScriptingDictionary.swiftnew file mode 100644index 00000000..d7a13acc--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/AppScriptingDictionary.swift@@ -0,0 +1,427 @@+import Foundation++/// A parsed app scripting dictionary: the app's real AppleScript vocabulary, read from its+/// `.sdef`. This is the ground truth that script generation and validation work against, so+/// generated scripts use terminology the app actually understands instead of guessed names.+public struct ScriptingDictionary: Equatable, Sendable, Codable {+ public var appName: String+ public var bundleIdentifier: String+ public var appVersion: String+ public var suites: [ScriptingSuite]++ public init(appName: String, bundleIdentifier: String, appVersion: String, suites: [ScriptingSuite]) {+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier+ self.appVersion = appVersion+ self.suites = suites+ }++ /// Every command name across all suites, in dictionary order (deduplicated).+ public var commandNames: [String] {+ var seen = Set<String>()+ return suites.flatMap(\.commands).map(\.name).filter { seen.insert($0).inserted }+ }+}++public struct ScriptingSuite: Equatable, Sendable, Codable {+ public var name: String+ public var code: String+ public var summary: String+ public var commands: [ScriptingCommand]+ public var classes: [ScriptingClass]+ public var enumerations: [ScriptingEnumeration]++ public init(+ name: String,+ code: String,+ summary: String = "",+ commands: [ScriptingCommand] = [],+ classes: [ScriptingClass] = [],+ enumerations: [ScriptingEnumeration] = []+ ) {+ self.name = name+ self.code = code+ self.summary = summary+ self.commands = commands+ self.classes = classes+ self.enumerations = enumerations+ }+}++public struct ScriptingCommand: Equatable, Sendable, Codable {+ public var name: String+ public var code: String+ public var summary: String+ public var directParameter: ScriptingParameter?+ public var parameters: [ScriptingParameter]+ public var resultType: String++ public init(+ name: String,+ code: String,+ summary: String = "",+ directParameter: ScriptingParameter? = nil,+ parameters: [ScriptingParameter] = [],+ resultType: String = ""+ ) {+ self.name = name+ self.code = code+ self.summary = summary+ self.directParameter = directParameter+ self.parameters = parameters+ self.resultType = resultType+ }+}++public struct ScriptingParameter: Equatable, Sendable, Codable {+ /// Empty for a command's direct parameter.+ public var name: String+ public var type: String+ public var isOptional: Bool+ public var summary: String++ public init(name: String = "", type: String, isOptional: Bool = false, summary: String = "") {+ self.name = name+ self.type = type+ self.isOptional = isOptional+ self.summary = summary+ }+}++public struct ScriptingClass: Equatable, Sendable, Codable {+ public var name: String+ public var pluralName: String+ public var summary: String+ public var properties: [ScriptingProperty]+ public var elementClassNames: [String]++ public init(+ name: String,+ pluralName: String = "",+ summary: String = "",+ properties: [ScriptingProperty] = [],+ elementClassNames: [String] = []+ ) {+ self.name = name+ self.pluralName = pluralName+ self.summary = summary+ self.properties = properties+ self.elementClassNames = elementClassNames+ }+}++public struct ScriptingProperty: Equatable, Sendable, Codable {+ public var name: String+ public var type: String+ public var isReadOnly: Bool+ public var summary: String++ public init(name: String, type: String, isReadOnly: Bool = false, summary: String = "") {+ self.name = name+ self.type = type+ self.isReadOnly = isReadOnly+ self.summary = summary+ }+}++public struct ScriptingEnumeration: Equatable, Sendable, Codable {+ public var name: String+ public var enumeratorNames: [String]++ public init(name: String, enumeratorNames: [String]) {+ self.name = name+ self.enumeratorNames = enumeratorNames+ }+}++/// Parses sdef XML into the typed model. `XMLDocument` resolves `xi:include` natively (apps like+/// Notes pull in the shared Standard Suite that way), so loading from the file URL gives the full+/// dictionary without the Xcode-only `sdef` CLI.+public enum ScriptingDictionaryParser {+ public static func suites(contentsOf url: URL) throws -> [ScriptingSuite] {+ let document = try XMLDocument(contentsOf: url, options: [.documentXInclude])+ return suites(in: document)+ }++ public static func suites(from data: Data) throws -> [ScriptingSuite] {+ let document = try XMLDocument(data: data, options: [.documentXInclude])+ return suites(in: document)+ }++ private static func suites(in document: XMLDocument) -> [ScriptingSuite] {+ guard let root = document.rootElement() else { return [] }+ return root.elements(forName: "suite").compactMap { suite in+ guard !isHidden(suite) else { return nil }+ return ScriptingSuite(+ name: attribute(suite, "name"),+ code: attribute(suite, "code"),+ summary: attribute(suite, "description"),+ commands: suite.elements(forName: "command").compactMap(command(from:)),+ classes: classes(in: suite),+ enumerations: suite.elements(forName: "enumeration").compactMap(enumeration(from:))+ )+ }+ }++ private static func command(from element: XMLElement) -> ScriptingCommand? {+ guard !isHidden(element) else { return nil }+ let direct = element.elements(forName: "direct-parameter").first.map { directElement in+ ScriptingParameter(+ type: typeString(of: directElement),+ isOptional: attribute(directElement, "optional") == "yes",+ summary: attribute(directElement, "description")+ )+ }+ let parameters = element.elements(forName: "parameter").compactMap { parameter -> ScriptingParameter? in+ guard !isHidden(parameter) else { return nil }+ return ScriptingParameter(+ name: attribute(parameter, "name"),+ type: typeString(of: parameter),+ isOptional: attribute(parameter, "optional") == "yes",+ summary: attribute(parameter, "description")+ )+ }+ let result = element.elements(forName: "result").first.map(typeString(of:)) ?? ""+ return ScriptingCommand(+ name: attribute(element, "name"),+ code: attribute(element, "code"),+ summary: attribute(element, "description"),+ directParameter: direct,+ parameters: parameters,+ resultType: result+ )+ }++ private static func classes(in suite: XMLElement) -> [ScriptingClass] {+ // `class-extension` extends an existing class (usually `application`); surface it as a+ // class named after what it extends so its properties/elements stay discoverable.+ let plain = suite.elements(forName: "class").compactMap { element -> ScriptingClass? in+ scriptingClass(from: element, name: attribute(element, "name"))+ }+ let extensions = suite.elements(forName: "class-extension").compactMap { element -> ScriptingClass? in+ scriptingClass(from: element, name: attribute(element, "extends"))+ }+ return plain + extensions+ }++ private static func scriptingClass(from element: XMLElement, name: String) -> ScriptingClass? {+ guard !isHidden(element), !name.isEmpty else { return nil }+ let properties = element.elements(forName: "property").compactMap { property -> ScriptingProperty? in+ guard !isHidden(property) else { return nil }+ return ScriptingProperty(+ name: attribute(property, "name"),+ type: typeString(of: property),+ isReadOnly: attribute(property, "access") == "r",+ summary: attribute(property, "description")+ )+ }+ let elements = element.elements(forName: "element").compactMap { child -> String? in+ guard !isHidden(child) else { return nil }+ let type = attribute(child, "type")+ return type.isEmpty ? nil : type+ }+ return ScriptingClass(+ name: name,+ pluralName: attribute(element, "plural"),+ summary: attribute(element, "description"),+ properties: properties,+ elementClassNames: elements+ )+ }++ private static func enumeration(from element: XMLElement) -> ScriptingEnumeration? {+ guard !isHidden(element) else { return nil }+ let enumerators = element.elements(forName: "enumerator").compactMap { enumerator -> String? in+ guard !isHidden(enumerator) else { return nil }+ let name = attribute(enumerator, "name")+ return name.isEmpty ? nil : name+ }+ let name = attribute(element, "name")+ guard !name.isEmpty, !enumerators.isEmpty else { return nil }+ return ScriptingEnumeration(name: name, enumeratorNames: enumerators)+ }++ /// The AppleScript type of a parameter/property/result: either a `type` attribute or nested+ /// `<type>` elements (used for union types and `list of` markers).+ private static func typeString(of element: XMLElement) -> String {+ if case let type = attribute(element, "type"), !type.isEmpty {+ return type+ }+ return element.elements(forName: "type")+ .map { nested -> String in+ let name = attribute(nested, "type")+ return attribute(nested, "list") == "yes" ? "list of \(name)" : name+ }+ .filter { !$0.isEmpty }+ .joined(separator: " | ")+ }++ private static func isHidden(_ element: XMLElement) -> Bool {+ let hidden = attribute(element, "hidden").lowercased()+ return hidden == "yes" || hidden == "true"+ }++ private static func attribute(_ element: XMLElement, _ name: String) -> String {+ element.attribute(forName: name)?.stringValue ?? ""+ }+}++/// Finds the sdef file an installed app ships.+public enum ScriptingDefinitionLocator {+ public static func sdefURL(forBundleAt bundleURL: URL) -> URL? {+ let resources = bundleURL.appendingPathComponent("Contents/Resources", isDirectory: true)+ let info = Bundle(url: bundleURL)?.infoDictionary+ if let declared = info?["OSAScriptingDefinition"] as? String, !declared.isEmpty {+ // Usually a Resources-relative filename; some apps use bundle-relative or absolute paths.+ let candidates = [+ resources.appendingPathComponent(declared),+ bundleURL.appendingPathComponent(declared),+ URL(fileURLWithPath: declared)+ ]+ if let found = candidates.first(where: { FileManager.default.fileExists(atPath: $0.path) }) {+ return found+ }+ }+ guard let items = try? FileManager.default.contentsOfDirectory(atPath: resources.path) else {+ return nil+ }+ return items+ .filter { $0.lowercased().hasSuffix(".sdef") }+ .sorted()+ .first+ .map { resources.appendingPathComponent($0) }+ }+}++/// Fallback for apps with no plain `.sdef` on disk (aete-only or dynamically generated+/// dictionaries): the public OpenScripting API resolves the full dictionary the same way Script+/// Editor does. The symbol ships in Carbon but has no header in the Command Line Tools SDK, so it+/// is resolved at runtime instead of imported.+public enum OpenScriptingSdefLoader {+ public static func copySdefData(forBundleAt bundleURL: URL) -> Data? {+ typealias CopyScriptingDefinition = @convention(c) (+ CFURL, Int32, UnsafeMutablePointer<Unmanaged<CFData>?>+ ) -> Int32+ guard let carbon = dlopen("/System/Library/Frameworks/Carbon.framework/Carbon", RTLD_LAZY) else {+ return nil+ }+ defer { dlclose(carbon) }+ guard let symbol = dlsym(carbon, "OSACopyScriptingDefinitionFromURL") else { return nil }+ let copy = unsafeBitCast(symbol, to: CopyScriptingDefinition.self)+ var sdef: Unmanaged<CFData>?+ guard copy(bundleURL as CFURL, 0, &sdef) == 0, let sdef else { return nil }+ return sdef.takeRetainedValue() as Data+ }+}++/// Renders a dictionary into a bounded plain-text digest for prompts and planner results.+/// Condensing is structural only (drop descriptions, collapse the training-data-known Standard+/// Suite, shrink classes) — never filtered against the user's goal text.+public enum ScriptingDictionaryDigest {+ public static let defaultBudget = 4_500+ public static let truncationMarker = "…truncated; call app_commands with suite=<name> for full detail"++ /// Suite names whose contents every AppleScript author already knows; collapsed first.+ private static let standardSuiteNames: Set<String> = ["standard suite"]++ struct Options {+ var includeSummaries = true+ var collapseStandardSuites = false+ var classPropertyNamesOnly = false+ }++ public static func render(_ dictionary: ScriptingDictionary, budget: Int = defaultBudget) -> String {+ let tiers: [Options] = [+ Options(),+ Options(includeSummaries: false, collapseStandardSuites: true),+ Options(includeSummaries: false, collapseStandardSuites: true, classPropertyNamesOnly: true)+ ]+ for options in tiers {+ let rendered = render(dictionary, options: options)+ if rendered.count <= budget { return rendered }+ }+ let smallest = render(dictionary, options: tiers[tiers.count - 1])+ return String(smallest.prefix(max(0, budget - truncationMarker.count - 1))) + "\n" + truncationMarker+ }++ /// Full detail for one suite — the drill-down path when the whole-dictionary digest condensed it.+ public static func render(suite: ScriptingSuite, of dictionary: ScriptingDictionary, budget: Int = defaultBudget) -> String {+ let header = headerLine(dictionary)+ let body = renderSuite(suite, options: Options())+ let rendered = header + "\n" + body+ guard rendered.count > budget else { return rendered }+ return String(rendered.prefix(max(0, budget - truncationMarker.count - 1))) + "\n" + truncationMarker+ }++ static func render(_ dictionary: ScriptingDictionary, options: Options) -> String {+ // App-specific suites carry the unfamiliar terminology; keep them ahead of standard suites+ // so condensation trims the well-known material first.+ let ordered = dictionary.suites.sorted { isStandard($0) == isStandard($1) ? false : !isStandard($0) }+ let body = ordered.map { suite in+ if options.collapseStandardSuites, isStandard(suite) {+ let names = suite.commands.map(\.name).joined(separator: ", ")+ return "suite \"\(suite.name)\": commands(\(names))"+ }+ return renderSuite(suite, options: options)+ }+ return ([headerLine(dictionary)] + body).joined(separator: "\n")+ }++ private static func headerLine(_ dictionary: ScriptingDictionary) -> String {+ var header = "app \"\(dictionary.appName)\""+ if !dictionary.bundleIdentifier.isEmpty { header += " (\(dictionary.bundleIdentifier))" }+ return header + " scripting dictionary:"+ }++ private static func renderSuite(_ suite: ScriptingSuite, options: Options) -> String {+ var lines = ["suite \"\(suite.name)\":"]+ for command in suite.commands {+ lines.append(" " + renderCommand(command, options: options))+ }+ for scriptingClass in suite.classes {+ lines.append(" " + renderClass(scriptingClass, options: options))+ }+ for enumeration in suite.enumerations {+ lines.append(" enum \(enumeration.name): \(enumeration.enumeratorNames.joined(separator: " / "))")+ }+ return lines.joined(separator: "\n")+ }++ private static func renderCommand(_ command: ScriptingCommand, options: Options) -> String {+ var parts: [String] = []+ if let direct = command.directParameter {+ parts.append("direct=(\(direct.type))" + (direct.isOptional ? " optional" : ""))+ }+ let parameters = command.parameters.map { parameter in+ "\(parameter.name) (\(parameter.type)\(parameter.isOptional ? ", optional" : ""))"+ }+ parts.append(contentsOf: parameters)+ var line = "command \"\(command.name)\""+ if !parts.isEmpty { line += ": " + parts.joined(separator: "; ") }+ if !command.resultType.isEmpty { line += " -> \(command.resultType)" }+ if options.includeSummaries, !command.summary.isEmpty { line += " — \(command.summary)" }+ return line+ }++ private static func renderClass(_ scriptingClass: ScriptingClass, options: Options) -> String {+ var line = "class \(scriptingClass.name)"+ if !scriptingClass.properties.isEmpty {+ let properties = scriptingClass.properties.map { property -> String in+ if options.classPropertyNamesOnly { return property.name }+ var rendered = "\(property.name): \(property.type)"+ if property.isReadOnly { rendered += " [r]" }+ return rendered+ }+ line += ": properties(\(properties.joined(separator: ", ")))"+ }+ if !scriptingClass.elementClassNames.isEmpty {+ line += "; elements(\(scriptingClass.elementClassNames.joined(separator: ", ")))"+ }+ if options.includeSummaries, !scriptingClass.summary.isEmpty { line += " — \(scriptingClass.summary)" }+ return line+ }++ private static func isStandard(_ suite: ScriptingSuite) -> Bool {+ standardSuiteNames.contains(suite.name.lowercased())+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppScriptingDictionaryService.swift b/apps/Donkey/Sources/DonkeyRuntime/AppScriptingDictionaryService.swiftnew file mode 100644index 00000000..23396e4a--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/AppScriptingDictionaryService.swift@@ -0,0 +1,195 @@+import Foundation++/// One cached parse of an app's scripting dictionary, invalidated when the app updates.+public struct ScriptingDictionaryCacheRecord: Equatable, Sendable, Codable {+ public var appVersion: String+ public var sdefPath: String+ public var sdefModificationDate: Date?+ public var dictionary: ScriptingDictionary++ public init(appVersion: String, sdefPath: String, sdefModificationDate: Date?, dictionary: ScriptingDictionary) {+ self.appVersion = appVersion+ self.sdefPath = sdefPath+ self.sdefModificationDate = sdefModificationDate+ self.dictionary = dictionary+ }+}++/// JSON-per-app store under Application Support so a dictionary is parsed once per app version,+/// then served from disk. Same shape as `FileAppScriptabilityStore`.+public final class FileScriptingDictionaryStore: @unchecked Sendable {+ private let directoryURL: URL+ private let lock = NSLock()++ public init(directoryURL: URL? = nil) {+ self.directoryURL = directoryURL ?? Self.defaultDirectoryURL()+ }++ public func record(bundleIdentifier: String) -> ScriptingDictionaryCacheRecord? {+ lock.lock(); defer { lock.unlock() }+ guard let data = try? Data(contentsOf: fileURL(bundleIdentifier: bundleIdentifier)) else { return nil }+ return try? JSONDecoder().decode(ScriptingDictionaryCacheRecord.self, from: data)+ }++ public func save(_ record: ScriptingDictionaryCacheRecord, bundleIdentifier: String) {+ lock.lock(); defer { lock.unlock() }+ guard let data = try? JSONEncoder().encode(record) else { return }+ try? FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)+ try? data.write(to: fileURL(bundleIdentifier: bundleIdentifier), options: .atomic)+ }++ private func fileURL(bundleIdentifier: String) -> URL {+ let safeName = bundleIdentifier.replacingOccurrences(of: "/", with: "_")+ return directoryURL.appendingPathComponent("\(safeName).json", isDirectory: false)+ }++ private static func defaultDirectoryURL() -> URL {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? URL(fileURLWithPath: NSTemporaryDirectory())+ return base+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("scripting-dictionaries", isDirectory: true)+ }+}++/// Front door for "what can this app actually do via AppleScript": resolves the installed bundle,+/// short-circuits non-scriptable apps via the existing probe, parses + caches the sdef, and renders+/// the bounded digest that grounds script generation and the `app_commands` command.+public actor AppScriptingDictionaryService {+ public static let shared = AppScriptingDictionaryService()++ public struct Lookup: Equatable, Sendable {+ public var scriptability: AppScriptability+ public var dictionary: ScriptingDictionary?+ public var digest: String+ public var commandNames: [String]++ public init(+ scriptability: AppScriptability,+ dictionary: ScriptingDictionary? = nil,+ digest: String = "",+ commandNames: [String] = []+ ) {+ self.scriptability = scriptability+ self.dictionary = dictionary+ self.digest = digest+ self.commandNames = commandNames+ }+ }++ private let store: FileScriptingDictionaryStore+ private let probe: MacAppScriptabilityProbe+ private var memo: [String: Lookup] = [:]++ public init(+ store: FileScriptingDictionaryStore = FileScriptingDictionaryStore(),+ probe: MacAppScriptabilityProbe = MacAppScriptabilityProbe()+ ) {+ self.store = store+ self.probe = probe+ }++ public func lookup(appName: String?, bundleIdentifier: String?) -> Lookup {+ guard let bundleURL = probe.bundleURL(bundleIdentifier: bundleIdentifier, appName: appName) else {+ return Lookup(scriptability: .unknown)+ }+ let info = Bundle(url: bundleURL)?.infoDictionary+ let resolvedBundleID = (bundleIdentifier?.isEmpty == false ? bundleIdentifier : nil)+ ?? info?["CFBundleIdentifier"] as? String+ ?? ""+ let appVersion = (info?["CFBundleShortVersionString"] as? String)+ ?? (info?["CFBundleVersion"] as? String)+ ?? ""+ let resolvedName = (info?["CFBundleName"] as? String)+ ?? appName+ ?? bundleURL.deletingPathExtension().lastPathComponent++ let memoKey = "\(resolvedBundleID)|\(appVersion)"+ if let cached = memo[memoKey] { return cached }++ let scriptability = probe.scriptability(bundleIdentifier: resolvedBundleID, appName: resolvedName)+ guard scriptability != .notScriptable else {+ let lookup = Lookup(scriptability: .notScriptable)+ memo[memoKey] = lookup+ return lookup+ }++ guard let dictionary = loadDictionary(+ bundleURL: bundleURL,+ bundleIdentifier: resolvedBundleID,+ appName: resolvedName,+ appVersion: appVersion+ ) else {+ let lookup = Lookup(scriptability: scriptability)+ memo[memoKey] = lookup+ return lookup+ }++ let lookup = Lookup(+ scriptability: scriptability,+ dictionary: dictionary,+ digest: ScriptingDictionaryDigest.render(dictionary),+ commandNames: dictionary.commandNames+ )+ memo[memoKey] = lookup+ return lookup+ }++ /// Full detail for one suite, matched case-insensitively on the suite's declared name.+ public func suiteDigest(appName: String?, bundleIdentifier: String?, suiteName: String) -> String? {+ let lookup = lookup(appName: appName, bundleIdentifier: bundleIdentifier)+ guard let dictionary = lookup.dictionary else { return nil }+ let wanted = suiteName.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ guard let suite = dictionary.suites.first(where: { $0.name.lowercased() == wanted }) else { return nil }+ return ScriptingDictionaryDigest.render(suite: suite, of: dictionary)+ }++ private func loadDictionary(+ bundleURL: URL,+ bundleIdentifier: String,+ appName: String,+ appVersion: String+ ) -> ScriptingDictionary? {+ let sdefURL = ScriptingDefinitionLocator.sdefURL(forBundleAt: bundleURL)+ let sdefModificationDate = sdefURL.flatMap { url in+ try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate] as? Date+ }++ if !bundleIdentifier.isEmpty,+ let cached = store.record(bundleIdentifier: bundleIdentifier),+ cached.appVersion == appVersion,+ cached.sdefPath == (sdefURL?.path ?? ""),+ cached.sdefModificationDate == sdefModificationDate {+ return cached.dictionary+ }++ var suites: [ScriptingSuite] = []+ if let sdefURL {+ suites = (try? ScriptingDictionaryParser.suites(contentsOf: sdefURL)) ?? []+ }+ if suites.isEmpty,+ let data = OpenScriptingSdefLoader.copySdefData(forBundleAt: bundleURL) {+ suites = (try? ScriptingDictionaryParser.suites(from: data)) ?? []+ }+ guard !suites.isEmpty else { return nil }++ let dictionary = ScriptingDictionary(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ appVersion: appVersion,+ suites: suites+ )+ if !bundleIdentifier.isEmpty {+ store.save(+ ScriptingDictionaryCacheRecord(+ appVersion: appVersion,+ sdefPath: sdefURL?.path ?? "",+ sdefModificationDate: sdefModificationDate,+ dictionary: dictionary+ ),+ bundleIdentifier: bundleIdentifier+ )+ }+ return dictionary+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift b/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swiftindex 31d79099..eb1faa4c 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift@@ -113,7 +113,10 @@ public struct MacAppScriptabilityProbe: Sendable {AppScriptabilityClassifier.classify(facts(bundleIdentifier: bundleIdentifier, appName: appName))}- private func bundleURL(bundleIdentifier: String?, appName: String?) -> URL? {+ /// Resolves the installed bundle for an app the planner may know only by display name.+ /// Shared by the scriptability probe, the scripting-dictionary service, and the+ /// AppleScript compile gate so they all agree on which bundle "the app" means.+ public func bundleURL(bundleIdentifier: String?, appName: String?) -> URL? {// Resolve by bundle identifier first (reliable).if let bundleIdentifier, !bundleIdentifier.isEmpty,let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppScriptingDictionaryTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppScriptingDictionaryTests.swiftnew file mode 100644index 00000000..ae93dc03--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppScriptingDictionaryTests.swift@@ -0,0 +1,187 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct AppScriptingDictionaryTests {+ // A small synthetic sdef exercising direct/optional parameters, union types, classes,+ // class-extensions, enumerations, and hidden filtering.+ private static let fixtureSdef = """+ <?xml version="1.0" encoding="UTF-8"?>+ <dictionary>+ <suite name="Widget Suite" code="wdgt" description="Terms for widgets">+ <command name="forge" code="wdgtforg" description="Forge a widget.">+ <direct-parameter description="The widget name.">+ <type type="text"/>+ </direct-parameter>+ <parameter name="with strength" code="strn" type="integer" optional="yes" description="How strong."/>+ <parameter name="secret" code="secr" type="text" hidden="yes"/>+ <result type="widget"/>+ </command>+ <command name="vanish" code="wdgtvnsh" hidden="yes"/>+ <command name="show" code="wdgtshow">+ <direct-parameter>+ <type type="widget"/>+ <type type="gadget"/>+ </direct-parameter>+ </command>+ <class name="widget" plural="widgets" description="One widget.">+ <property name="name" code="pnam" type="text" description="Its name."/>+ <property name="age" code="wage" type="integer" access="r"/>+ <element type="gadget"/>+ </class>+ <class-extension extends="application">+ <property name="default widget" code="dwdg" type="widget"/>+ </class-extension>+ <enumeration name="finish" code="fnsh">+ <enumerator name="matte" code="matt"/>+ <enumerator name="glossy" code="glos"/>+ </enumeration>+ </suite>+ <suite name="Standard Suite" code="????" description="Common terms">+ <command name="count" code="corecnte"/>+ <command name="exists" code="coredoex"/>+ </suite>+ <suite name="Hidden Suite" code="hdnn" hidden="yes">+ <command name="lurk" code="hdnnlurk"/>+ </suite>+ </dictionary>+ """++ private func parsedFixture() throws -> ScriptingDictionary {+ let suites = try ScriptingDictionaryParser.suites(from: Data(Self.fixtureSdef.utf8))+ return ScriptingDictionary(+ appName: "Widgetry",+ bundleIdentifier: "com.example.widgetry",+ appVersion: "1.0",+ suites: suites+ )+ }++ // MARK: Parser++ @Test+ func parsesCommandsParametersClassesAndEnumerations() throws {+ let dictionary = try parsedFixture()+ #expect(dictionary.suites.map(\.name) == ["Widget Suite", "Standard Suite"])++ let widgetSuite = dictionary.suites[0]+ #expect(widgetSuite.commands.map(\.name) == ["forge", "show"])++ let forge = widgetSuite.commands[0]+ #expect(forge.directParameter?.type == "text")+ #expect(forge.parameters.map(\.name) == ["with strength"])+ #expect(forge.parameters[0].isOptional)+ #expect(forge.parameters[0].type == "integer")+ #expect(forge.resultType == "widget")++ let show = widgetSuite.commands[1]+ #expect(show.directParameter?.type == "widget | gadget")++ #expect(widgetSuite.classes.map(\.name) == ["widget", "application"])+ let widget = widgetSuite.classes[0]+ #expect(widget.properties.map(\.name) == ["name", "age"])+ #expect(widget.properties[1].isReadOnly)+ #expect(widget.elementClassNames == ["gadget"])++ #expect(widgetSuite.enumerations == [ScriptingEnumeration(name: "finish", enumeratorNames: ["matte", "glossy"])])+ }++ @Test+ func skipsHiddenSuitesCommandsAndParameters() throws {+ let dictionary = try parsedFixture()+ #expect(!dictionary.suites.contains { $0.name == "Hidden Suite" })+ #expect(!dictionary.commandNames.contains("vanish"))+ #expect(!dictionary.suites[0].commands[0].parameters.contains { $0.name == "secret" })+ }++ @Test+ func commandNamesSpanAllSuites() throws {+ let dictionary = try parsedFixture()+ #expect(dictionary.commandNames == ["forge", "show", "count", "exists"])+ }++ // MARK: Digest++ @Test+ func fullDigestIncludesTerminologyAndDescriptions() throws {+ let digest = ScriptingDictionaryDigest.render(try parsedFixture())+ #expect(digest.contains("app \"Widgetry\" (com.example.widgetry) scripting dictionary:"))+ #expect(digest.contains("command \"forge\": direct=(text); with strength (integer, optional) -> widget — Forge a widget."))+ #expect(digest.contains("class widget: properties(name: text, age: integer [r]); elements(gadget)"))+ #expect(digest.contains("enum finish: matte / glossy"))+ // App-specific suite renders before the standard suite.+ let widgetIndex = try #require(digest.range(of: "Widget Suite")).lowerBound+ let standardIndex = try #require(digest.range(of: "Standard Suite")).lowerBound+ #expect(widgetIndex < standardIndex)+ }++ @Test+ func tightBudgetCollapsesStandardSuiteAndDropsDescriptions() throws {+ let dictionary = try parsedFixture()+ let full = ScriptingDictionaryDigest.render(dictionary)+ let condensed = ScriptingDictionaryDigest.render(dictionary, budget: full.count - 1)+ #expect(condensed.count < full.count)+ #expect(condensed.contains("suite \"Standard Suite\": commands(count, exists)"))+ #expect(!condensed.contains("Forge a widget."))+ // App-specific terminology survives condensation.+ #expect(condensed.contains("command \"forge\""))+ }++ @Test+ func impossibleBudgetHardTruncatesWithMarker() throws {+ let digest = ScriptingDictionaryDigest.render(try parsedFixture(), budget: 120)+ #expect(digest.count <= 120)+ #expect(digest.hasSuffix(ScriptingDictionaryDigest.truncationMarker))+ }++ @Test+ func singleSuiteDigestKeepsFullDetail() throws {+ let dictionary = try parsedFixture()+ let digest = ScriptingDictionaryDigest.render(suite: dictionary.suites[0], of: dictionary)+ #expect(digest.contains("Forge a widget."))+ #expect(!digest.contains("Standard Suite"))+ }++ // MARK: Cache store++ @Test+ func roundTripsAndDetectsStaleRecords() throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("scripting-dictionary-tests-\(UUID().uuidString)", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let store = FileScriptingDictionaryStore(directoryURL: directory)+ let dictionary = try parsedFixture()+ let record = ScriptingDictionaryCacheRecord(+ appVersion: "1.0",+ sdefPath: "/Applications/Widgetry.app/Contents/Resources/Widgetry.sdef",+ sdefModificationDate: Date(timeIntervalSince1970: 1_000),+ dictionary: dictionary+ )++ #expect(store.record(bundleIdentifier: "com.example.widgetry") == nil)+ store.save(record, bundleIdentifier: "com.example.widgetry")+ let loaded = try #require(store.record(bundleIdentifier: "com.example.widgetry"))+ #expect(loaded == record)+ // Staleness is decided by the caller comparing version/path/mtime; a changed version+ // means the cached parse must not be served.+ #expect(loaded.appVersion != "2.0")+ }++ // MARK: Locator + live parse (skips cleanly on machines without Notes)++ @Test+ func parsesARealInstalledDictionaryWithXInclude() throws {+ let notes = URL(fileURLWithPath: "/System/Applications/Notes.app")+ guard FileManager.default.fileExists(atPath: notes.path) else { return }+ let sdefURL = try #require(ScriptingDefinitionLocator.sdefURL(forBundleAt: notes))+ let suites = try ScriptingDictionaryParser.suites(contentsOf: sdefURL)+ let names = suites.map(\.name)+ // The Notes-specific suite is declared inline; the Standard Suite arrives via xi:include.+ #expect(names.contains("Notes Suite"))+ #expect(names.contains("Standard Suite"))+ let allCommands = suites.flatMap(\.commands).map(\.name)+ #expect(allCommands.contains("show"))+ #expect(allCommands.contains("make"))+ }+}