import { defineComponent as y, computed as h, ref as c, openBlock as E, createElementBlock as w, renderSlot as x } from "vue";
import s from "@leaflink/snitch";
import P from "./usePlaidLink.js";
const L = /* @__PURE__ */ y({
  __name: "PlaidLink",
  props: {
    initScriptUrl: { default: "https://cdn.plaid.com/link/v2/stable/link-initialize.js" },
    storageKey: { default: void 0 },
    returnTo: { default: window.location.href },
    token: { default: void 0 },
    env: { default: "sandbox" },
    createToken: { type: Function, default: void 0 }
  },
  emits: ["error", "success", "exit", "load", "event"],
  setup(u, { expose: d, emit: p }) {
    const t = u, i = h(() => t.storageKey ? t.storageKey : `${window.location.host.split(".").splice(-3).join(".")}-plaid`), n = p, r = c(!1), f = (e, o) => {
      r.value = !1, e && (s.error(new Error("Plaid: Error trying to link an account"), {
        tags: { plaid: !0 },
        extra: { PlaidError: e }
      }), n("error", e, o)), sessionStorage.removeItem(i.value), n("exit", o);
    }, k = (e, o) => {
      r.value = !1, sessionStorage.removeItem(i.value), n("success", e, o);
    }, v = (...e) => n("load", ...e), m = (...e) => n("event", ...e), a = c({
      env: t.env,
      onSuccess: k,
      onEvent: m,
      onLoad: v,
      onExit: f
    }), { open: g } = P(a);
    async function l() {
      if (r.value !== !0) {
        if (r.value = !0, typeof t.createToken == "function")
          try {
            const { link_token: e } = await t.createToken();
            a.value.token = e;
          } catch (e) {
            const o = new Error("Plaid: Error trying to invoke createToken");
            s.error(o, {
              tags: { plaid: !0 },
              extra: { error: e }
            }), n("error", o);
          }
        else t.token && (a.value.token = t.token);
        if (!a.value.token) {
          const e = new Error("Plaid: link token not found");
          s.error(e, { tags: { plaid: !0 } }), n("error", e), r.value = !1;
          return;
        }
        sessionStorage.setItem(
          i.value,
          JSON.stringify({ token: a.value.token, returnTo: t.returnTo, env: t.env })
        ), g();
      }
    }
    return d({
      handleClick: l
    }), (e, o) => (E(), w("span", {
      "data-test": "stash-plaid-link",
      onClick: l
    }, [
      x(e.$slots, "default", { open: r.value })
    ]));
  }
});
export {
  L as default
};
//# sourceMappingURL=PlaidLink.js.map
