-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOsascript.js
More file actions
346 lines (301 loc) · 9.32 KB
/
Copy pathOsascript.js
File metadata and controls
346 lines (301 loc) · 9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
const path = require("path");
const { AppleScript } = require("./apple-script/Apple.js");
const { spawn } = require("child_process");
const { TimeoutError, WorkerError, PermissionError, AppNotFoundError } = require("./lib/errors");
const { Logger } = require("./lib/logger");
const { Templates } = require("./lib/templates");
const { PluginManager } = require("./lib/PluginManager");
/**
* @class Osascript
* @classdesc A production-ready AppleScript executor with error handling, timeouts, and worker stability
*
* @example
* const { Osascript } = require('./index.js');
* const script = new Osascript({ logLevel: 'info', timeout: 60000 });
*
* await script.executeScript([
* script.appleCommands.speak("Hello"),
* script.appleCommands.activateApp("Music")
* ]);
*
* // Use templates
* await script.templates.pomodoro({ duration: 25 });
*
* // Use plugins
* const spotifyPlugin = require('./plugins/spotify');
* script.use(spotifyPlugin);
* await script.spotify.play('Bohemian Rhapsody');
*
* script.close();
*/
class Osascript {
/**
* @private
* @type {import('child_process').ChildProcessWithoutNullStreams | null}
*/
mainThread;
/**
* @type {typeof AppleScript}
* @description Exposes static AppleScript builder commands
*/
appleCommands = AppleScript;
/**
* @type {Templates}
* @description Template system for common workflows
*/
templates;
/**
* @private
* @type {PluginManager}
*/
#pluginManager;
/**
* @private
* @type {Array<{resolve: Function, reject: Function, timer: NodeJS.Timeout}>}
* @description Tracks pending promises with their timeout timers
*/
#pending = [];
/**
* @private
* @type {number}
*/
#restartAttempts = 0;
/**
* @private
* @type {number}
*/
#maxRestartAttempts = 5;
/**
* @private
* @type {Logger}
*/
#logger;
/**
* @private
* @type {number}
*/
#defaultTimeout;
/**
* Spawns the persistent background process with production-ready error handling
* @param {Object} options - Configuration options
* @param {string} options.logLevel - Log level: 'debug', 'info', 'warn', 'error', 'silent'
* @param {number} options.timeout - Default timeout for commands in milliseconds (default: 120000 = 2 minutes)
* @param {number} options.maxRestartAttempts - Maximum automatic restart attempts
*/
constructor(options = {}) {
const {
logLevel = 'info',
timeout = 120000, // 2 minutes default (increased from 30s for long-running commands)
maxRestartAttempts = 5
} = options;
this.#logger = new Logger(logLevel);
this.#defaultTimeout = timeout;
this.#maxRestartAttempts = maxRestartAttempts;
// Initialize templates and plugin manager
this.templates = new Templates(this);
this.#pluginManager = new PluginManager(this);
this.#spawnWorker();
}
/**
* @private
* Spawns the worker process
*/
#spawnWorker() {
const workerPath = path.join(__dirname, "workers", "index.js");
this.mainThread = spawn(
process.execPath,
[workerPath],
{
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }
}
);
this.mainThread.stderr.on("data", this.#errorHandler.bind(this));
this.mainThread.stdout.on("data", this.#handleOutput.bind(this));
// Handle worker exit
this.mainThread.on("exit", (code, signal) => {
this.#logger.error(`Worker exited with code ${code}, signal ${signal}`);
// Reject all pending promises
while (this.#pending.length > 0) {
const pending = this.#pending.shift();
if (pending.timer) clearTimeout(pending.timer);
pending.reject(new WorkerError('Worker process exited unexpectedly'));
}
// Auto-restart with exponential backoff
if (this.#restartAttempts < this.#maxRestartAttempts) {
const delay = Math.min(1000 * Math.pow(2, this.#restartAttempts), 10000);
this.#logger.warn(`Restarting worker in ${delay}ms (attempt ${this.#restartAttempts + 1}/${this.#maxRestartAttempts})`);
setTimeout(() => {
this.#spawnWorker();
this.#restartAttempts++;
}, delay);
} else {
this.#logger.error('Max restart attempts reached. Worker is dead.');
}
});
this.#logger.info('Worker process started');
}
/**
* @private
* @param {Buffer} err
* Handles error output with intelligent error classification
*/
#errorHandler(err) {
const errorMessage = err?.toString() || 'Unknown error';
this.#logger.error('[stderr]', errorMessage);
const current = this.#pending.shift();
if (current) {
if (current.timer) clearTimeout(current.timer);
// Intelligent error classification
let error;
if (errorMessage.includes('not allowed') || errorMessage.includes('not authorized')) {
error = new PermissionError('AppleScript automation');
} else if (errorMessage.includes('application') && errorMessage.includes('not found')) {
const match = errorMessage.match(/application "([^"]+)"/);
const appName = match ? match[1] : 'Unknown';
error = new AppNotFoundError(appName);
} else {
error = new WorkerError(errorMessage, err);
}
current.reject(error);
}
}
/**
* @private
* @param {Buffer} out
* Handles stdout output from the child process
*/
#handleOutput(out) {
const output = out?.toString();
this.#logger.debug('[stdout]', output);
const current = this.#pending.shift();
if (current) {
if (current.timer) clearTimeout(current.timer);
current.resolve(output);
}
}
/**
* Executes AppleScript commands with timeout and error handling
* @param {Array<string>} appleCodeArray - Array of AppleScript command strings
* @param {number|null} timeout - Timeout in milliseconds. Use null or 0 to disable timeout for long-running commands
* @returns {Promise<string>} Output from AppleScript
*
* @example
* // Use default timeout (120 seconds)
* await script.executeScript([commands]);
*
* // Custom timeout (5 minutes)
* await script.executeScript([commands], 300000);
*
* // Disable timeout for very long operations
* await script.executeScript([longRunningCommands], null);
*/
async executeScript(appleCodeArray, timeout = this.#defaultTimeout) {
if (!this.mainThread) {
throw new WorkerError('Osascript runtime error: mainThread is not running');
}
if (!Array.isArray(appleCodeArray) || appleCodeArray.length === 0) {
throw new Error('executeScript expects a non-empty array of AppleScript lines');
}
const scriptText = appleCodeArray.join("\n");
const command = `osascript <<'__APPLESCRIPT__'\n${scriptText}\n__APPLESCRIPT__\n`;
this.#logger.debug('Running AppleScript:', scriptText);
return new Promise((resolve, reject) => {
let timer = null;
// Only set timeout if timeout value is provided and greater than 0
if (timeout && timeout > 0) {
timer = setTimeout(() => {
// Remove from queue on timeout
const idx = this.#pending.findIndex(p => p.resolve === resolve);
if (idx !== -1) this.#pending.splice(idx, 1);
reject(new TimeoutError(`AppleScript execution timed out after ${timeout}ms`, timeout));
}, timeout);
}
const pending = {
resolve: (val) => {
if (timer) clearTimeout(timer);
resolve(val);
},
reject: (err) => {
if (timer) clearTimeout(timer);
reject(err);
},
timer
};
this.#pending.push(pending);
this.mainThread.stdin.write(command);
});
}
/**
* Health check to verify worker is responsive
* @returns {Promise<boolean>} True if worker is healthy
*/
async healthCheck() {
try {
await this.executeScript([AppleScript.log('healthcheck')], 5000);
this.#logger.debug('Health check passed');
return true;
} catch (err) {
this.#logger.error('Health check failed:', err.message);
return false;
}
}
/**
* Restarts the background AppleScript execution thread
*/
restart() {
this.#logger.info('Manually restarting worker');
if (this.mainThread) {
this.mainThread.kill();
}
this.#restartAttempts = 0;
this.#spawnWorker();
}
/**
* Gracefully shuts down the background process
*/
close() {
if (this.mainThread) {
this.#logger.info('Closing worker process');
this.mainThread.stdin.write("exit\n");
this.mainThread.stdin.end();
this.mainThread = null;
}
}
/**
* Set log level dynamically
* @param {string} level - 'debug', 'info', 'warn', 'error', 'silent'
*/
setLogLevel(level) {
this.#logger.setLevel(level);
}
/**
* Get current queue size (for monitoring)
* @returns {number} Number of pending commands
*/
getQueueSize() {
return this.#pending.length;
}
/**
* Install a plugin
* @param {Object} plugin - Plugin object
*/
use(plugin) {
this.#pluginManager.use(plugin);
}
/**
* Uninstall a plugin
* @param {string} pluginName
*/
uninstallPlugin(pluginName) {
this.#pluginManager.uninstall(pluginName);
}
/**
* Get list of installed plugins
* @returns {string[]}
*/
listPlugins() {
return this.#pluginManager.list();
}
}
module.exports = { Osascript };