Apple js is the extension of osascript to javascript, run applescript commands via node js, and implement js-like logic. New methods are introduced in this version in ui, notifications and ai check out.
npm install apple-js-stable> The Ultimate macOS Automation Library for Node.js.
apple-js is a high-performance, production-ready framework that bridges JavaScript and AppleScript. It allows you to automate every aspect of macOS ā from browser DOM manipulation and application control to system events and file operations ā using modern, type-safe JavaScript.
This document serves as the Master Specification for the library, including every available namespace and production feature.
---
- ā” Persistent Worker Engine: Uses a single, low-latency background subprocess (via stdin) to execute commands instantly without the overhead of spawning new processes.
- š”ļø Industrial-Strength Error Handling: Returns structured error objects (TimeoutError, PermissionError, AppNotFoundError) instead of raw strings.
- š§© Extensible Plugin Architecture: Easily register custom AppleScript namespaces at runtime.
- š Workflow Templates: Pre-configured complex automations like "Focus Mode", "Pomodoro", and "Clean Desktop".
- š Voice Fallback Safety: Automated try-catch voice selection. If a requested voice is missing, it falls back to the system default gracefully.
- š» Cross-Runtime CLI: Full-featured CLI tool for controlling your Mac from shell scripts or CI/CD.
- š TypeScript First: 100% type definitions covering 150+ methods with rich JSDoc.
---
exec("osascript -e '...' "). This is slow and prone to escaping issues. apple-js spawns a persistent worker thread that stays open. Commands are sent as a stream to stdin, and result data/errors are piped back. This allows for queued execution and state persistence (if implemented in script blocks).stderr from macOS to identify:application "X" target is not installed.---
``bash`
npm install apple-js-stable
---
Class)The engine orchestrates the background worker and exposes the command library.
`javascript
const { Osascript } = require('apple-js-stable');
const script = new Osascript({
logLevel: 'info', // 'debug' | 'info' | 'warn' | 'error' | 'silent'
timeout: 120000, // Default 2-minute timeout
maxRestartAttempts: 5 // Automatic worker recovery
});
`
: Run multiple commands in sequence. Set timeout to null for infinite duration.
- healthCheck(): Verify worker responsiveness.
- use(plugin): Inject new functionality.
- close() / restart(): Manage worker lifecycle.
- getQueueSize(): Monitor pending tasks.---
ļæ½ Exhaustive API Reference (
script.appleCommands)The command library is organized into 22+ logical namespaces. Every method returns a valid AppleScript string.
$3
Basic building blocks for AppleScript.
- set(var, val): Variable assignment.
- if(condition, lines[]) / ifElse(...): Logic flow.
- repeatWith(var, from, to, lines[]): Loops.
- repeatWhile(condition, lines[]): Conditional loops.
- delay(seconds): Pause execution.
- shell(command): Execute standard shell scripts.
- activateApp(name) / quit(name): App lifecycle.$3
Manage hardware and global settings.
- setVolume(0-100) / toggleMute(bool): Audio.
- setBrightness(0.0-1.0): (Requires 'brightness' CLI tool).
- screenshotToDesktop(): Take a full capture.
- toggleDarkMode() / enableDarkMode() / disableDarkMode(): Appearance.
- lockScreen() / sleepMac() / shutdown() / restart(): Power.
- getBatteryLevel() / getPowerSource(): Energy info.
- getScreenResolution() / getMacOSVersion(): Hardware info.
- toggleNightShift(): Blue light filter.$3
Native Safari support and basic Chrome control.
- openInSafari(url) / openInChrome(url) / openInDefaultBrowser(url)
- getCurrentURLFromSafari(): URL extraction.
- newSafariTab(url?): Tab management.
- activateSafari(): Focus browser.$3
Inject and run JavaScript inside active tabs.
- dom.run(jsCode, app): Execute raw JS in Safari/Chrome.
- dom.click(selector): UI interaction.
- dom.type(selector, text): Form filling.
- dom.setContent(selector, val, isHtml): Update text/HTML.
- dom.scrollBy(x, y) / dom.scrollTo(pos): Navigation.
- dom.injectCSS(css) / dom.injectScript(url): Real-time modifications.$3
File system interaction via the macOS Desktop.
- finder.openFolder(path) / finder.revealInFinder(path)
- finder.createFolder(path, name) / finder.moveToTrash(path)
- finder.setDesktopWallpaper(path): Visual customization.
- fileOps.read(path) / fileOps.write(path, data): Low-level file I/O.
- fileOps.exists(path) / fileOps.getSize(path): Attributes.
- fileOps.ls(dir) / fileOps.mkdir(dir): Directory management.$3
Speech and integrated workflow utilities.
- speak(text, voice): Smart speech with auto-fallback.
- ai.introduceYourself() / ai.tellJoke(): Social logic.
- ai.motivateUser() / ai.dailyAffirmation(): Productivity.
- ai.startMeditation(): Guided mindfulness workflow.
- ai.askSiri(question): Automation-to-Siri bridge.
- ai.askChatGPT(prompt): Browser-based GPT automation.
- fun.screenFlash(): Visual camera-flash effect.
- fun.playSosumi(): Classic alert sound.$3
Simulate keyboard and mouse events.
- ui.typeText(text, delay): Simulate keystrokes.
- ui.clickAt(x, y) / ui.doubleClickAt(x, y): Coordinates.
- ui.pressHotkey(key, modifiers[]): Global shortcuts (e.g., ["command", "shift"]).
- ui.copy() / ui.paste() / ui.selectAll(): Generic edits.
- ui.resizeFrontWindow(w, h) / ui.moveWindow(x, y): Window positioning.$3
- clipboard.copy(text) / clipboard.get()
- clipboard.clear(): Security.
- clipboard.copyFile(path): Binary copy.$3
- notifications.banner(msg): Native system banners.
- notifications.alertWithSound(title, msg, sound): High-priority.
- advancedNotifications.withButtons(title, msg, buttons[]): Get user input.
- advancedNotifications.progress(msg, total): Show progress bars in Script Editor.$3
- calendar.createEvent(title, start, end, location, notes)
- calendar.getTodayEvents(): Schedule parsing.
- reminders.create(title, notes, dueDate)
- reminders.complete(name) / reminders.getAll(list)$3
- network.getWiFiName() / network.getIPAddress() / network.getPublicIP()
- network.testConnection(host): Internet verification.
- process.list() / process.kill(name): Task management.
- process.cpuUsage(name) / process.memoryUsage(name): Performance tracking.$3
- shortcuts.run(name) / shortcuts.runWithInput(name, input)
- shortcuts.list(): Retrieve local shortcuts.$3
- time.now() / time.getDate(format) / time.getTimeInZone(tz)
- time.sleep(seconds): Alias for delay.$3
- workspace.openInVSCode(path)
- workspace.openInTerminal(path)
- workspace.searchMDN(query) / workspace.searchStackOverflow(query)---
š§© Templates & Plugins
$3
Built-in composite workflows.
`javascript
await script.templates.pomodoro({ duration: 25, breakDuration: 5 });
await script.templates.websiteScreenshot(url, path);
await script.templates.cleanDesktop();
`$3
Example Spotify integration:
`javascript
const spotifyPlugin = require('apple-js/plugins/spotify');
script.use(spotifyPlugin);
await script.spotify.play("Jazz");
`---
āØļø CLI Tool (
apple-js)Control your machine without using Node.js directly.
| Command | Usage |
| --- | --- |
|
apple-js speak "Hello" | Smart speech output. |
| apple-js open Safari | Launch any application. |
| apple-js notify "Title" "Msg" | Quick custom alerts. |
| apple-js screenshot [path] | Instant screen capture. |
| apple-js volume 50 | Volume control. |
| apple-js mute / apple-js dark-mode / apple-js lock` | Toggle system states. |---