( script: string, args: (string | boolean | number)[], language = "AppleScript", stderrCallback?: (data: string) => void, )
| 18 | * @returns A promise that resolves to the output of the script. |
| 19 | */ |
| 20 | export const execScript = ( |
| 21 | script: string, |
| 22 | args: (string | boolean | number)[], |
| 23 | language = "AppleScript", |
| 24 | stderrCallback?: (data: string) => void, |
| 25 | ): { data: Promise<string>; sendMessage: (msg: string) => void } => { |
| 26 | let data = ""; |
| 27 | let sendMessage: (msg: string) => void = (msg: string) => { |
| 28 | msg; |
| 29 | }; |
| 30 | const proc = spawn("osascript", [ |
| 31 | ...(script.startsWith("/") ? [] : ["-e"]), |
| 32 | script, |
| 33 | "-l", |
| 34 | language, |
| 35 | ...args.map((x) => x.toString()), |
| 36 | ]); |
| 37 | |
| 38 | logDebug( |
| 39 | `Running shell command "osascript ${[ |
| 40 | ...(script.startsWith("/") ? [] : ["-e"]), |
| 41 | script, |
| 42 | "-l", |
| 43 | language, |
| 44 | ...args.map((x) => x.toString()), |
| 45 | ].join(" ")}"`, |
| 46 | ); |
| 47 | |
| 48 | proc.stdout?.on("data", (chunk) => { |
| 49 | data += chunk.toString(); |
| 50 | }); |
| 51 | |
| 52 | proc.stderr?.on("data", (chunk) => { |
| 53 | if (stderrCallback) { |
| 54 | stderrCallback(chunk.toString()); |
| 55 | } |
| 56 | }); |
| 57 | |
| 58 | proc.stdin.on("error", (err) => { |
| 59 | logDebug(`Error writing to stdin: ${err}`, DebugStyle.Error); |
| 60 | }); |
| 61 | |
| 62 | sendMessage = async (message: string) => { |
| 63 | if (message?.length > 0) { |
| 64 | proc.stdin.cork(); |
| 65 | proc.stdin.write(`${message}\r\n`); |
| 66 | proc.stdin.pipe(proc.stdin, { end: false }); |
| 67 | process.nextTick(() => proc.stdin.uncork()); |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | const waitForFinish = async () => { |
| 72 | while (proc.stdout?.readable && proc.stderr?.readable && proc.stdin?.writable) { |
| 73 | await util.promisify(setTimeout)(100); |
| 74 | } |
| 75 | return data; |
| 76 | }; |
| 77 |
no test coverage detected