import { Clipboard, closeMainWindow } from "@raycast/api"; import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; const execFileAsync = promisify(execFile); // Raycast 2.0 Beta writes only plain text for Clipboard.copy({ html, text }). // Set both pasteboard types directly; environment variables avoid shell quoting. const RICH_COPY_SCRIPT = [ "ObjC.import('AppKit');", "const env = $.NSProcessInfo.processInfo.environment;", "const html = env.objectForKey('VELUM_HTML');", "const text = env.objectForKey('VELUM_TEXT');", "const pb = $.NSPasteboard.generalPasteboard;", "pb.clearContents;", "pb.setStringForType(html, 'public.html');", "pb.setStringForType(text, 'public.utf8-plain-text');", ].join("\n"); const RICH_READ_SCRIPT = [ "ObjC.import('AppKit');", "const pb = $.NSPasteboard.generalPasteboard;", "const html = pb.stringForType('public.html') || pb.stringForType('text/html');", "const rtf = html ? null : pb.dataForType('public.rtf');", "JSON.stringify({ html: html ? ObjC.unwrap(html) : null, rtf: rtf ? ObjC.unwrap(rtf.base64EncodedStringWithOptions(0)) : null });", ].join("\n"); async function htmlFromRtf(encoded: string): Promise { return new Promise((resolve) => { const child = spawn("textutil", ["-convert", "html", "-stdin", "-stdout"]); const chunks: Buffer[] = []; child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk)); child.on("error", () => resolve(undefined)); child.on("close", (code) => resolve(code === 0 ? Buffer.concat(chunks).toString("utf8") : undefined)); child.stdin.on("error", () => undefined); child.stdin.end(Buffer.from(encoded, "base64")); }); } /** Raycast's clipboard reader can omit HTML/RTF from app selections such as Teams. */ export async function readRichClipboardHtml(): Promise { const raycast = await Clipboard.read().catch(() => undefined); if (raycast?.html) return raycast.html; try { const { stdout } = await execFileAsync("osascript", ["-l", "JavaScript", "-e", RICH_READ_SCRIPT], { maxBuffer: 16 * 1024 * 1024 }); const native = JSON.parse(stdout.trim()) as { html: string | null; rtf: string | null }; if (native.html) return native.html; if (native.rtf) return await htmlFromRtf(native.rtf); } catch { // Plain text remains available even if macOS cannot expose the rich pasteboard types. } return undefined; } export async function copyRichText(html: string, text: string): Promise { await execFileAsync( "osascript", ["-l", "JavaScript", "-e", RICH_COPY_SCRIPT], { env: { ...process.env, VELUM_HTML: html, VELUM_TEXT: text }, }, ); } /** Paste the rich pasteboard data without Raycast replacing it with plain text. */ export async function pasteRichText(html: string, text: string): Promise { await copyRichText(html, text); await closeMainWindow(); await new Promise((resolve) => setTimeout(resolve, 150)); await execFileAsync("osascript", ["-e", 'tell application "System Events" to keystroke "v" using command down']); }