"use strict";
/* Socket Lib - Built with esbuild */
"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 windows_exports = {};
__export(windows_exports, {
  buildTarget: () => buildTarget,
  deleteWindows: () => deleteWindows,
  deleteWindowsSync: () => deleteWindowsSync,
  getDpapiFilePath: () => getDpapiFilePath,
  isWindowsBackendAvailable: () => isWindowsBackendAvailable,
  quotePs: () => quotePs,
  readDpapi: () => readDpapi,
  readDpapiSync: () => readDpapiSync,
  readWindows: () => readWindows,
  readWindowsSync: () => readWindowsSync,
  runPsAsync: () => runPsAsync,
  runPsSync: () => runPsSync,
  validateKeychainComponent: () => validateKeychainComponent,
  writeDpapi: () => writeDpapi,
  writeDpapiSync: () => writeDpapiSync,
  writeWindows: () => writeWindows,
  writeWindowsSync: () => writeWindowsSync
});
module.exports = __toCommonJS(windows_exports);
var import_node_child_process = require("node:child_process");
var import_node_fs = require("node:fs");
var import_node_os = require("node:os");
var import_node_path = __toESM(require("node:path"));
var import_node_process = __toESM(require("node:process"));
const POWERSHELL_BIN = "powershell";
function buildTarget(service, account) {
  return `${service}:${account}`;
}
async function deleteWindows(service, account) {
  const target = buildTarget(service, account);
  let removedAny = false;
  const psScript = `
    try { Remove-StoredCredential -Target ${quotePs(target)}; exit 0 }
    catch { exit 1 }
  `;
  const ps = await runPsAsync(psScript);
  if (ps.status === 0) {
    removedAny = true;
  }
  const filePath = getDpapiFilePath(service, account);
  if ((0, import_node_fs.existsSync)(filePath)) {
    try {
      const { rmSync } = await import("node:fs");
      rmSync(filePath, { force: true });
      removedAny = true;
    } catch {
    }
  }
  return removedAny ? "removed" : "absent";
}
function deleteWindowsSync(service, account) {
  const target = buildTarget(service, account);
  let removedAny = false;
  const psScript = `
    try { Remove-StoredCredential -Target ${quotePs(target)}; exit 0 }
    catch { exit 1 }
  `;
  const ps = runPsSync(psScript);
  if (ps.status === 0) {
    removedAny = true;
  }
  const filePath = getDpapiFilePath(service, account);
  if ((0, import_node_fs.existsSync)(filePath)) {
    try {
      const fsMod = require("node:fs");
      fsMod.rmSync(filePath, { force: true });
      removedAny = true;
    } catch {
    }
  }
  return removedAny ? "removed" : "absent";
}
function getDpapiFilePath(service, account) {
  validateKeychainComponent(service, "service");
  validateKeychainComponent(account, "account");
  const appData = import_node_process.default.env["APPDATA"] ?? import_node_path.default.join((0, import_node_os.homedir)(), "AppData", "Roaming");
  return import_node_path.default.join(appData, service, `${account}.enc`);
}
function isWindowsBackendAvailable() {
  const r = (0, import_node_child_process.spawnSync)(POWERSHELL_BIN, ["-NoProfile", "-Command", "exit 0"], {
    stdio: "ignore"
  });
  return r.status === 0;
}
function quotePs(value) {
  return `'${value.replace(/'/g, "''")}'`;
}
async function readDpapi(filePath) {
  if (!(0, import_node_fs.existsSync)(filePath)) {
    return void 0;
  }
  const script = `
    Add-Type -AssemblyName System.Security
    $bytes = [Convert]::FromBase64String((Get-Content -Raw ${quotePs(filePath)}))
    $plain = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $null, 'CurrentUser')
    [System.Text.Encoding]::UTF8.GetString($plain)
  `;
  const r = await runPsAsync(script);
  if (r.status !== 0) {
    return void 0;
  }
  const out = r.stdout.trim();
  return out || void 0;
}
function readDpapiSync(filePath) {
  if (!(0, import_node_fs.existsSync)(filePath)) {
    return void 0;
  }
  const script = `
    Add-Type -AssemblyName System.Security
    $bytes = [Convert]::FromBase64String((Get-Content -Raw ${quotePs(filePath)}))
    $plain = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $null, 'CurrentUser')
    [System.Text.Encoding]::UTF8.GetString($plain)
  `;
  const r = runPsSync(script);
  if (r.status !== 0) {
    return void 0;
  }
  const out = r.stdout.trim();
  return out || void 0;
}
async function readWindows(service, account) {
  const target = buildTarget(service, account);
  const script = `
    try {
      (Get-StoredCredential -Target ${quotePs(target)}).Password |
        ConvertFrom-SecureString -AsPlainText
    } catch { exit 1 }
  `;
  const ps = await runPsAsync(script);
  if (ps.status === 0) {
    const out = ps.stdout.trim();
    if (out) {
      return out;
    }
  }
  return readDpapi(getDpapiFilePath(service, account));
}
function readWindowsSync(service, account) {
  const target = buildTarget(service, account);
  const script = `
    try {
      (Get-StoredCredential -Target ${quotePs(target)}).Password |
        ConvertFrom-SecureString -AsPlainText
    } catch { exit 1 }
  `;
  const ps = runPsSync(script);
  if (ps.status === 0) {
    const out = ps.stdout.trim();
    if (out) {
      return out;
    }
  }
  return readDpapiSync(getDpapiFilePath(service, account));
}
function runPsAsync(script, input) {
  return new Promise((resolve) => {
    const child = (0, import_node_child_process.spawn)(POWERSHELL_BIN, ["-NoProfile", "-Command", script], {
      stdio: ["pipe", "pipe", "pipe"]
    });
    let stdout = "";
    let stderr = "";
    child.stdout.setEncoding("utf8");
    child.stdout.on("data", (chunk) => {
      stdout += chunk;
    });
    child.stderr.setEncoding("utf8");
    child.stderr.on("data", (chunk) => {
      stderr += chunk;
    });
    child.on("error", () => resolve({ status: -1, stdout, stderr }));
    child.on("close", (status) => resolve({ status, stdout, stderr }));
    if (input !== void 0) {
      child.stdin.end(input);
    } else {
      child.stdin.end();
    }
  });
}
function runPsSync(script, input) {
  const r = (0, import_node_child_process.spawnSync)(POWERSHELL_BIN, ["-NoProfile", "-Command", script], {
    encoding: "utf8",
    input,
    stdio: ["pipe", "pipe", "pipe"]
  });
  return { status: r.status, stdout: r.stdout, stderr: r.stderr };
}
function validateKeychainComponent(value, name) {
  if (/[\\/]/.test(value) || value.includes("..") || value.includes("\0") || value === "" || value === ".") {
    throw new Error(
      `secrets/windows: ${name} contains path-traversal characters: ${JSON.stringify(value)}. Use a plain identifier (no \\\\, /, .., or NUL).`
    );
  }
}
async function writeDpapi(filePath, value) {
  const dir = import_node_path.default.dirname(filePath);
  if (!(0, import_node_fs.existsSync)(dir)) {
    (0, import_node_fs.mkdirSync)(dir, { recursive: true });
  }
  const script = `
    Add-Type -AssemblyName System.Security
    $token = [Console]::In.ReadToEnd().Trim()
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($token)
    $protected = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
    [Convert]::ToBase64String($protected) | Set-Content -Path ${quotePs(filePath)} -NoNewline
  `;
  const r = await runPsAsync(script, value);
  if (r.status !== 0) {
    throw new Error(
      `DPAPI file write failed: ${r.stderr.trim()}. Install the CredentialManager PowerShell module (\`Install-Module CredentialManager -Scope CurrentUser\`) for a cleaner storage path.`
    );
  }
}
function writeDpapiSync(filePath, value) {
  const dir = import_node_path.default.dirname(filePath);
  if (!(0, import_node_fs.existsSync)(dir)) {
    (0, import_node_fs.mkdirSync)(dir, { recursive: true });
  }
  const script = `
    Add-Type -AssemblyName System.Security
    $token = [Console]::In.ReadToEnd().Trim()
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($token)
    $protected = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
    [Convert]::ToBase64String($protected) | Set-Content -Path ${quotePs(filePath)} -NoNewline
  `;
  const r = runPsSync(script, value);
  if (r.status !== 0) {
    throw new Error(
      `DPAPI file write failed: ${r.stderr.trim()}. Install the CredentialManager PowerShell module (\`Install-Module CredentialManager -Scope CurrentUser\`) for a cleaner storage path.`
    );
  }
}
async function writeWindows(service, account, value, _label) {
  const target = buildTarget(service, account);
  const psScript = `
    $token = $input | Out-String
    $token = $token.Trim()
    $secure = ConvertTo-SecureString $token -AsPlainText -Force
    try {
      New-StoredCredential -Target ${quotePs(target)} -UserName ${quotePs(account)} -SecurePassword $secure -Persist LocalMachine | Out-Null
      exit 0
    } catch { exit 1 }
  `;
  const ps = await runPsAsync(psScript, value);
  if (ps.status === 0) {
    return;
  }
  await writeDpapi(getDpapiFilePath(service, account), value);
}
function writeWindowsSync(service, account, value, _label) {
  const target = buildTarget(service, account);
  const psScript = `
    $token = $input | Out-String
    $token = $token.Trim()
    $secure = ConvertTo-SecureString $token -AsPlainText -Force
    try {
      New-StoredCredential -Target ${quotePs(target)} -UserName ${quotePs(account)} -SecurePassword $secure -Persist LocalMachine | Out-Null
      exit 0
    } catch { exit 1 }
  `;
  const ps = runPsSync(psScript, value);
  if (ps.status === 0) {
    return;
  }
  writeDpapiSync(getDpapiFilePath(service, account), value);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildTarget,
  deleteWindows,
  deleteWindowsSync,
  getDpapiFilePath,
  isWindowsBackendAvailable,
  quotePs,
  readDpapi,
  readDpapiSync,
  readWindows,
  readWindowsSync,
  runPsAsync,
  runPsSync,
  validateKeychainComponent,
  writeDpapi,
  writeDpapiSync,
  writeWindows,
  writeWindowsSync
});
