#!/usr/bin/env node
import {
  atomicWriteFile,
  withFileLock
} from "./chunk-TAEQKBJB.mjs";
import {
  ensureDir,
  readJsonFile
} from "./chunk-IAYRNVUC.mjs";
import {
  PROJECT_DIR_NAME
} from "./chunk-H76MT5UR.mjs";

// src/config/global-config.ts
import os2 from "os";
import path2 from "path";

// src/config/credential-store.ts
import os from "os";
import path from "path";
import { promises as fs } from "fs";
function getCredentialFilePath() {
  return path.join(os.homedir(), PROJECT_DIR_NAME, "auth.json");
}
function getCredentialLockPath() {
  return `${getCredentialFilePath()}.lock`;
}
async function fileRead() {
  const filePath = getCredentialFilePath();
  let data;
  try {
    data = await fs.readFile(filePath, "utf8");
  } catch (err) {
    if (err.code === "ENOENT") return null;
    throw err;
  }
  if (data.trim().length === 0) {
    return null;
  }
  let parsed;
  try {
    parsed = JSON.parse(data);
  } catch {
    return null;
  }
  const accessToken = parsed.accessToken ?? parsed.authToken;
  const refreshToken = parsed.refreshToken;
  if (!accessToken && !refreshToken) return null;
  return {
    accessToken: accessToken || void 0,
    refreshToken: refreshToken || void 0,
    tokenExpiresAt: parsed.tokenExpiresAt || void 0,
    clerkOAuthIssuer: parsed.clerkOAuthIssuer || void 0,
    clerkOAuthClientId: parsed.clerkOAuthClientId || void 0,
    clerkOAuthTokenUrl: parsed.clerkOAuthTokenUrl || void 0,
    environment: parsed.environment || void 0
  };
}
async function writeFilePayload(payload) {
  await atomicWriteFile(
    getCredentialFilePath(),
    `${JSON.stringify(payload, null, 2)}
`,
    { mode: 384 }
  );
}
async function fileWriteFull(creds) {
  if (!creds.accessToken || !creds.refreshToken) {
    throw new Error(
      "Refusing to persist credentials with an empty accessToken or refreshToken."
    );
  }
  await writeFilePayload({
    authToken: creds.accessToken,
    refreshToken: creds.refreshToken,
    tokenExpiresAt: creds.tokenExpiresAt,
    clerkOAuthIssuer: creds.clerkOAuthIssuer,
    clerkOAuthClientId: creds.clerkOAuthClientId,
    clerkOAuthTokenUrl: creds.clerkOAuthTokenUrl,
    environment: creds.environment
  });
}
async function fileWriteAccessOnly(accessToken) {
  if (!accessToken) {
    throw new Error("Refusing to persist an empty access token.");
  }
  await writeFilePayload({ authToken: accessToken });
}
async function fileClear() {
  const filePath = getCredentialFilePath();
  try {
    await fs.unlink(filePath);
  } catch (err) {
    if (err.code !== "ENOENT") throw err;
  }
}
var fileCredentialBackend = {
  name: "file",
  read: fileRead,
  writeFull: fileWriteFull,
  writeAccessOnly: fileWriteAccessOnly,
  clear: fileClear
};
var cachedBackend = null;
var migrationCompleted = false;
var backendResolver = defaultBackendResolver;
async function defaultBackendResolver() {
  const override = (process.env.DREAMBOARD_CREDENTIAL_BACKEND ?? "").trim().toLowerCase();
  if (override === "file") {
    return fileCredentialBackend;
  }
  if (override && override !== "keychain" && override !== "auto") {
    throw new Error(
      `Unknown DREAMBOARD_CREDENTIAL_BACKEND value "${override}" (expected "file", "keychain", or "auto").`
    );
  }
  const useKeychain = override === "keychain" || await readCredentialBackendPreference();
  if (!useKeychain) {
    return fileCredentialBackend;
  }
  const { tryKeychainBackend } = await import("./keychain-backend-A3MRWLPF.mjs");
  const keychain = await tryKeychainBackend();
  if (keychain.available) {
    return keychain.backend;
  }
  return fileCredentialBackend;
}
async function readCredentialBackendPreference() {
  try {
    const { loadGlobalConfig: loadGlobalConfig2 } = await import("./global-config-NYCSCAUI.mjs");
    const config = await loadGlobalConfig2();
    return config.credentialBackend === "keychain";
  } catch {
    return false;
  }
}
async function getCredentialBackend() {
  if (cachedBackend === null) {
    cachedBackend = await backendResolver();
    if (!migrationCompleted && cachedBackend.name !== "file") {
      await migrateFromFileBackendIfNeeded(cachedBackend);
    }
    migrationCompleted = true;
  }
  return cachedBackend;
}
async function migrateFromFileBackendIfNeeded(target) {
  try {
    const [onDisk, onTarget] = await Promise.all([
      fileCredentialBackend.read(),
      target.read()
    ]);
    if (!onDisk) return;
    if (onTarget) {
      await fileCredentialBackend.clear();
      return;
    }
    if (onDisk.accessToken && onDisk.refreshToken) {
      await target.writeFull({
        accessToken: onDisk.accessToken,
        refreshToken: onDisk.refreshToken
      });
    } else if (onDisk.accessToken) {
      await target.writeAccessOnly(onDisk.accessToken);
    } else {
      return;
    }
    await fileCredentialBackend.clear();
  } catch {
  }
}
async function getStoredSession() {
  const backend = await getCredentialBackend();
  return backend.read();
}
async function setCredentials(creds) {
  await withFileLock(getCredentialLockPath(), async () => {
    const backend = await getCredentialBackend();
    await backend.writeFull(creds);
  });
}

// src/config/global-config.ts
function normalizeCredentialBackend(value) {
  if (value === "file" || value === "keychain") return value;
  return void 0;
}
function getGlobalConfigPath() {
  return path2.join(os2.homedir(), PROJECT_DIR_NAME, "config.json");
}
function getGlobalAuthPath() {
  return getCredentialFilePath();
}
async function loadGlobalConfig() {
  const config = await readJsonFile(getGlobalConfigPath()).catch(
    () => ({})
  );
  return {
    environment: config.environment,
    credentialBackend: normalizeCredentialBackend(config.credentialBackend)
  };
}
async function saveGlobalConfig(config) {
  const configDir = path2.join(os2.homedir(), PROJECT_DIR_NAME);
  await ensureDir(configDir);
  const normalized = {
    environment: config.environment,
    credentialBackend: normalizeCredentialBackend(config.credentialBackend)
  };
  await atomicWriteFile(
    getGlobalConfigPath(),
    `${JSON.stringify(normalized, null, 2)}
`,
    { mode: 384 }
  );
}

export {
  getStoredSession,
  setCredentials,
  getGlobalConfigPath,
  getGlobalAuthPath,
  loadGlobalConfig,
  saveGlobalConfig
};
//# sourceMappingURL=chunk-5NYBTZB4.mjs.map