( targetDir?: string, )
| 39 | * @returns The path to the saved image file, or null if no image or error |
| 40 | */ |
| 41 | export async function saveClipboardImage( |
| 42 | targetDir?: string, |
| 43 | ): Promise<string | null> { |
| 44 | if (process.platform !== 'darwin') { |
| 45 | return null; |
| 46 | } |
| 47 | |
| 48 | try { |
| 49 | // Create a temporary directory for clipboard images within the target directory |
| 50 | // This avoids security restrictions on paths outside the target directory |
| 51 | const baseDir = targetDir || process.cwd(); |
| 52 | const tempDir = path.join(baseDir, '.anus-clipboard'); |
| 53 | await fs.mkdir(tempDir, { recursive: true }); |
| 54 | |
| 55 | // Generate a unique filename with timestamp |
| 56 | const timestamp = new Date().getTime(); |
| 57 | |
| 58 | // Try different image formats in order of preference |
| 59 | const formats = [ |
| 60 | { class: 'PNGf', extension: 'png' }, |
| 61 | { class: 'JPEG', extension: 'jpg' }, |
| 62 | { class: 'TIFF', extension: 'tiff' }, |
| 63 | { class: 'GIFf', extension: 'gif' }, |
| 64 | ]; |
| 65 | |
| 66 | for (const format of formats) { |
| 67 | const tempFilePath = path.join( |
| 68 | tempDir, |
| 69 | `clipboard-${timestamp}.${format.extension}`, |
| 70 | ); |
| 71 | |
| 72 | // Try to save clipboard as this format |
| 73 | const script = ` |
| 74 | try |
| 75 | set imageData to the clipboard as «class ${format.class}» |
| 76 | set fileRef to open for access POSIX file "${tempFilePath}" with write permission |
| 77 | write imageData to fileRef |
| 78 | close access fileRef |
| 79 | return "success" |
| 80 | on error errMsg |
| 81 | try |
| 82 | close access POSIX file "${tempFilePath}" |
| 83 | end try |
| 84 | return "error" |
| 85 | end try |
| 86 | `; |
| 87 | |
| 88 | const { stdout } = await execAsync(`osascript -e '${script}'`); |
| 89 | |
| 90 | if (stdout.trim() === 'success') { |
| 91 | // Verify the file was created and has content |
| 92 | try { |
| 93 | const stats = await fs.stat(tempFilePath); |
| 94 | if (stats.size > 0) { |
| 95 | return tempFilePath; |
| 96 | } |
| 97 | } catch { |
| 98 | // File doesn't exist, continue to next format |
no test coverage detected