"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var clipboardUtils_exports = {};
__export(clipboardUtils_exports, {
  clipboardHasImage: () => clipboardHasImage,
  readClipboardImage: () => readClipboardImage,
  writeToClipboard: () => writeToClipboard
});
module.exports = __toCommonJS(clipboardUtils_exports);
var import_node_child_process = require("node:child_process");
var import_node_os = require("node:os");
var fs = __toESM(require("node:fs/promises"), 1);
var path = __toESM(require("node:path"), 1);
var os = __toESM(require("node:os"), 1);
async function execCommand(command, args, timeoutMs = 1e4) {
  return new Promise((resolve) => {
    let timedOut = false;
    const proc = (0, import_node_child_process.spawn)(command, args);
    const stdoutChunks = [];
    let stderr = "";
    const timer = setTimeout(() => {
      timedOut = true;
      proc.kill();
      resolve({
        stdout: Buffer.concat(stdoutChunks),
        stderr: stderr + "\nCommand timed out",
        exitCode: 1
      });
    }, timeoutMs);
    proc.stdout.on("data", (chunk) => {
      stdoutChunks.push(chunk);
    });
    proc.stderr.on("data", (chunk) => {
      stderr += chunk.toString();
    });
    proc.on("close", (exitCode) => {
      if (timedOut) return;
      clearTimeout(timer);
      resolve({
        stdout: Buffer.concat(stdoutChunks),
        stderr,
        exitCode: exitCode ?? 1
      });
    });
    proc.on("error", () => {
      if (timedOut) return;
      clearTimeout(timer);
      resolve({
        stdout: Buffer.concat(stdoutChunks),
        stderr,
        exitCode: 1
      });
    });
  });
}
async function execOsascript(script) {
  const result = await execCommand("osascript", ["-e", script]);
  return {
    stdout: result.stdout.toString().trim(),
    success: result.exitCode === 0
  };
}
async function readClipboardImageMacOS() {
  const tmpFile = path.join(os.tmpdir(), `dexto-clipboard-${Date.now()}-${process.pid}.png`);
  try {
    const script = `
            set imageData to the clipboard as "PNGf"
            set fileRef to open for access POSIX file "${tmpFile}" with write permission
            set eof fileRef to 0
            write imageData to fileRef
            close access fileRef
        `;
    const result = await execOsascript(script);
    if (!result.success) {
      return void 0;
    }
    const buffer = await fs.readFile(tmpFile);
    if (buffer.length === 0) {
      return void 0;
    }
    return {
      data: buffer.toString("base64"),
      mimeType: "image/png"
    };
  } catch {
    return void 0;
  } finally {
    try {
      await fs.unlink(tmpFile);
    } catch {
    }
  }
}
async function readClipboardImageWindows() {
  try {
    const script = `
            Add-Type -AssemblyName System.Windows.Forms
            $img = [System.Windows.Forms.Clipboard]::GetImage()
            if ($img) {
                $ms = New-Object System.IO.MemoryStream
                $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
                [System.Convert]::ToBase64String($ms.ToArray())
            }
        `.trim();
    const powershellCmd = "powershell.exe";
    const result = await execCommand(powershellCmd, ["-command", script]);
    const base64 = result.stdout.toString().trim();
    if (!base64 || result.exitCode !== 0) {
      return void 0;
    }
    const buffer = Buffer.from(base64, "base64");
    if (buffer.length === 0) {
      return void 0;
    }
    return {
      data: base64,
      mimeType: "image/png"
    };
  } catch {
    return void 0;
  }
}
function isWSL() {
  if ((0, import_node_os.platform)() !== "linux") return false;
  const rel = (0, import_node_os.release)().toLowerCase();
  return rel.includes("wsl") || rel.includes("microsoft");
}
async function readClipboardImageLinux() {
  try {
    const result = await execCommand("wl-paste", ["-t", "image/png"]);
    if (result.exitCode === 0 && result.stdout.length > 0) {
      return {
        data: result.stdout.toString("base64"),
        mimeType: "image/png"
      };
    }
  } catch {
  }
  try {
    const result = await execCommand("xclip", [
      "-selection",
      "clipboard",
      "-t",
      "image/png",
      "-o"
    ]);
    if (result.exitCode === 0 && result.stdout.length > 0) {
      return {
        data: result.stdout.toString("base64"),
        mimeType: "image/png"
      };
    }
  } catch {
  }
  return void 0;
}
async function readClipboardImage() {
  const os2 = (0, import_node_os.platform)();
  if (os2 === "darwin") {
    return readClipboardImageMacOS();
  }
  if (os2 === "win32" || isWSL()) {
    return readClipboardImageWindows();
  }
  if (os2 === "linux") {
    return readClipboardImageLinux();
  }
  return void 0;
}
async function writeToClipboard(text) {
  const os2 = (0, import_node_os.platform)();
  try {
    if (os2 === "darwin") {
      const proc = (0, import_node_child_process.spawn)("pbcopy");
      proc.stdin.write(text);
      proc.stdin.end();
      return new Promise((resolve) => {
        proc.on("close", (code) => resolve(code === 0));
        proc.on("error", () => resolve(false));
      });
    }
    if (os2 === "win32" || isWSL()) {
      const proc = (0, import_node_child_process.spawn)("clip.exe");
      proc.stdin.write(text);
      proc.stdin.end();
      return new Promise((resolve) => {
        proc.on("close", (code) => resolve(code === 0));
        proc.on("error", () => resolve(false));
      });
    }
    if (os2 === "linux") {
      const tryClipboardTool = (cmd, args = []) => {
        return new Promise((resolve) => {
          const proc = (0, import_node_child_process.spawn)(cmd, args);
          let errorOccurred = false;
          proc.on("error", () => {
            errorOccurred = true;
            resolve(false);
          });
          proc.stdin.write(text);
          proc.stdin.end();
          proc.on("close", (code) => {
            if (!errorOccurred) {
              resolve(code === 0);
            }
          });
        });
      };
      const wlResult = await tryClipboardTool("wl-copy");
      if (wlResult) return true;
      return tryClipboardTool("xclip", ["-selection", "clipboard"]);
    }
    return false;
  } catch {
    return false;
  }
}
async function clipboardHasImage() {
  const os2 = (0, import_node_os.platform)();
  if (os2 === "darwin") {
    try {
      const result = await execOsascript("clipboard info");
      const imageRegex = /«class PNGf»|TIFF picture|JPEG picture|GIF picture|«class JPEG»|«class TIFF»/;
      return imageRegex.test(result.stdout);
    } catch {
      return false;
    }
  }
  if (os2 === "win32" || isWSL()) {
    try {
      const script = `
                Add-Type -AssemblyName System.Windows.Forms
                [System.Windows.Forms.Clipboard]::ContainsImage()
            `.trim();
      const powershellCmd = "powershell.exe";
      const result = await execCommand(powershellCmd, ["-command", script]);
      return result.stdout.toString().trim().toLowerCase() === "true";
    } catch {
      return false;
    }
  }
  if (os2 === "linux") {
    try {
      const result = await execCommand("wl-paste", ["--list-types"]);
      if (result.exitCode === 0 && result.stdout.toString().includes("image/")) {
        return true;
      }
    } catch {
    }
    try {
      const result = await execCommand("xclip", [
        "-selection",
        "clipboard",
        "-t",
        "TARGETS",
        "-o"
      ]);
      if (result.exitCode === 0 && result.stdout.toString().includes("image/")) {
        return true;
      }
    } catch {
    }
  }
  return false;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  clipboardHasImage,
  readClipboardImage,
  writeToClipboard
});
