(text: string)
| 30 | |
| 31 | // Copies a string snippet to the clipboard for different platforms |
| 32 | export const copyToClipboard = async (text: string): Promise<void> => { |
| 33 | const run = (cmd: string, args: string[]) => |
| 34 | new Promise<void>((resolve, reject) => { |
| 35 | const child = spawn(cmd, args); |
| 36 | let stderr = ''; |
| 37 | child.stderr.on('data', (chunk) => (stderr += chunk.toString())); |
| 38 | child.on('error', reject); |
| 39 | child.on('close', (code) => { |
| 40 | if (code === 0) return resolve(); |
| 41 | const errorMsg = stderr.trim(); |
| 42 | reject( |
| 43 | new Error( |
| 44 | `'${cmd}' exited with code ${code}${errorMsg ? `: ${errorMsg}` : ''}`, |
| 45 | ), |
| 46 | ); |
| 47 | }); |
| 48 | child.stdin.on('error', reject); |
| 49 | child.stdin.write(text); |
| 50 | child.stdin.end(); |
| 51 | }); |
| 52 | |
| 53 | switch (process.platform) { |
| 54 | case 'win32': |
| 55 | return run('clip', []); |
| 56 | case 'darwin': |
| 57 | return run('pbcopy', []); |
| 58 | case 'linux': |
| 59 | try { |
| 60 | await run('xclip', ['-selection', 'clipboard']); |
| 61 | } catch (primaryError) { |
| 62 | try { |
| 63 | // If xclip fails for any reason, try xsel as a fallback. |
| 64 | await run('xsel', ['--clipboard', '--input']); |
| 65 | } catch (fallbackError) { |
| 66 | const primaryMsg = |
| 67 | primaryError instanceof Error |
| 68 | ? primaryError.message |
| 69 | : String(primaryError); |
| 70 | const fallbackMsg = |
| 71 | fallbackError instanceof Error |
| 72 | ? fallbackError.message |
| 73 | : String(fallbackError); |
| 74 | throw new Error( |
| 75 | `All copy commands failed. xclip: "${primaryMsg}", xsel: "${fallbackMsg}". Please ensure xclip or xsel is installed and configured.`, |
| 76 | ); |
| 77 | } |
| 78 | } |
| 79 | return; |
| 80 | default: |
| 81 | throw new Error(`Unsupported platform: ${process.platform}`); |
| 82 | } |
| 83 | }; |
| 84 | |
| 85 | export const getUrlOpenCommand = (): string => { |
| 86 | // --- Determine the OS-specific command to open URLs --- |
no test coverage detected