import { validateJwt as c } from "./jwt.js";
const S = async (o, r) => {
  if (!o)
    return "";
  if (!(r != null && r.apiKey))
    throw new Error("apiKey not found.");
  if (!(r != null && r.apiSecret))
    throw new Error("apiSecret not found.");
  if (!(r != null && r.userName))
    throw new Error("userName not found.");
  if (!(r != null && r.userUid))
    throw new Error("userUid not found.");
  const s = r == null ? void 0 : r.apiKey, p = r == null ? void 0 : r.apiSecret, e = JSON.parse(JSON.stringify(r));
  e.apiKey = void 0, e.apiSecret = void 0;
  let n = localStorage.getItem(`runnerToken${o}`) ?? "";
  if (!n || !c(n)) {
    const i = await (await fetch(
      `${(r == null ? void 0 : r.env) === "development" ? "https://api-dev.virtuals.io" : "https://api.virtuals.io"}/api/access/token`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(
          e ? {
            metadata: {
              virtualId: o,
              ...e
            },
            apiKey: s,
            apiSecret: p
          } : {
            metadata: {
              virtualId: o
            },
            apiKey: s,
            apiSecret: p
          }
        )
      }
    )).json();
    if (i.error)
      throw new Error(i.error.message);
    n = i.accessToken ?? "", localStorage.setItem(`runnerToken${o}`, n);
  }
  return n;
};
export {
  S as UNSAFE_initAccessToken
};
