import { toRaw, isRef, isReactive, toRef, getCurrentInstance, toRefs, reactive, effectScope, ref, markRaw, onServerPrefetch, inject, unref, watch, computed, getCurrentScope, onScopeDispose, nextTick } from 'vue';
import { h as useNuxtApp, u as useRoute, c as useRuntimeConfig, j as useRouter } from './nuxt-link-5ac46069.mjs';
import { createError as createError$1 } from 'h3';
import { u as useHead } from './composables-31566dd1.mjs';
import { guard } from '@ucast/mongo2js';
import { pascalCase } from 'change-case';
import { BaseError, mergeOptions } from '@ebec/http';
import { isClientError } from 'hapic';
import { Client } from '@hapic/oauth2';

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
const useError = () => toRef(useNuxtApp().payload, "error");
const showError = (_err) => {
  const err = createError(_err);
  try {
    const nuxtApp = useNuxtApp();
    nuxtApp.callHook("app:error", err);
    const error = useError();
    error.value = error.value || err;
  } catch {
    throw err;
  }
  return err;
};
const createError = (err) => {
  const _err = createError$1(err);
  _err.__nuxt_error = true;
  return _err;
};
const getDefault = () => null;
function useAsyncData(...args) {
  var _a2, _b, _c, _d, _e, _f;
  var _a;
  const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
  if (typeof args[0] !== "string") {
    args.unshift(autoKey);
  }
  let [key, handler, options = {}] = args;
  if (typeof key !== "string") {
    throw new TypeError("[nuxt] [asyncData] key must be a string.");
  }
  if (typeof handler !== "function") {
    throw new TypeError("[nuxt] [asyncData] handler must be a function.");
  }
  options.server = (_a2 = options.server) != null ? _a2 : true;
  options.default = (_b = options.default) != null ? _b : getDefault;
  options.lazy = (_c = options.lazy) != null ? _c : false;
  options.immediate = (_d = options.immediate) != null ? _d : true;
  const nuxt = useNuxtApp();
  const getCachedData = () => nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key];
  const hasCachedData = () => getCachedData() !== void 0;
  if (!nuxt._asyncData[key]) {
    nuxt._asyncData[key] = {
      data: ref((_f = (_e = getCachedData()) != null ? _e : (_a = options.default) == null ? void 0 : _a.call(options)) != null ? _f : null),
      pending: ref(!hasCachedData()),
      error: ref(nuxt.payload._errors[key] ? createError(nuxt.payload._errors[key]) : null)
    };
  }
  const asyncData = { ...nuxt._asyncData[key] };
  asyncData.refresh = asyncData.execute = (opts = {}) => {
    if (nuxt._asyncDataPromises[key]) {
      if (opts.dedupe === false) {
        return nuxt._asyncDataPromises[key];
      }
      nuxt._asyncDataPromises[key].cancelled = true;
    }
    if (opts._initial && hasCachedData()) {
      return getCachedData();
    }
    asyncData.pending.value = true;
    const promise = new Promise(
      (resolve, reject) => {
        try {
          resolve(handler(nuxt));
        } catch (err) {
          reject(err);
        }
      }
    ).then((result) => {
      if (promise.cancelled) {
        return nuxt._asyncDataPromises[key];
      }
      if (options.transform) {
        result = options.transform(result);
      }
      if (options.pick) {
        result = pick(result, options.pick);
      }
      asyncData.data.value = result;
      asyncData.error.value = null;
    }).catch((error) => {
      var _a3;
      var _a22;
      if (promise.cancelled) {
        return nuxt._asyncDataPromises[key];
      }
      asyncData.error.value = error;
      asyncData.data.value = unref((_a3 = (_a22 = options.default) == null ? void 0 : _a22.call(options)) != null ? _a3 : null);
    }).finally(() => {
      if (promise.cancelled) {
        return;
      }
      asyncData.pending.value = false;
      nuxt.payload.data[key] = asyncData.data.value;
      if (asyncData.error.value) {
        nuxt.payload._errors[key] = createError(asyncData.error.value);
      }
      delete nuxt._asyncDataPromises[key];
    });
    nuxt._asyncDataPromises[key] = promise;
    return nuxt._asyncDataPromises[key];
  };
  const initialFetch = () => asyncData.refresh({ _initial: true });
  const fetchOnServer = options.server !== false && nuxt.payload.serverRendered;
  if (fetchOnServer && options.immediate) {
    const promise = initialFetch();
    if (getCurrentInstance()) {
      onServerPrefetch(() => promise);
    } else {
      nuxt.hook("app:created", () => promise);
    }
  }
  const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData);
  Object.assign(asyncDataPromise, asyncData);
  return asyncDataPromise;
}
function pick(obj, keys) {
  const newObj = {};
  for (const key of keys) {
    newObj[key] = obj[key];
  }
  return newObj;
}
const NuxtComponentIndicator = "__nuxt_component";
async function runLegacyAsyncData(res, fn) {
  const nuxt = useNuxtApp();
  const route = useRoute();
  const vm = getCurrentInstance();
  const { fetchKey } = vm.proxy.$options;
  const key = typeof fetchKey === "function" ? fetchKey(() => "") : fetchKey || route.fullPath;
  const { data } = await useAsyncData(`options:asyncdata:${key}`, () => fn(nuxt));
  if (data.value && typeof data.value === "object") {
    Object.assign(await res, toRefs(reactive(data.value)));
  }
}
const defineNuxtComponent = function defineNuxtComponent2(options) {
  const { setup } = options;
  if (!setup && !options.asyncData && !options.head) {
    return {
      [NuxtComponentIndicator]: true,
      ...options
    };
  }
  return {
    [NuxtComponentIndicator]: true,
    ...options,
    setup(props, ctx) {
      const res = (setup == null ? void 0 : setup(props, ctx)) || {};
      const promises = [];
      if (options.asyncData) {
        promises.push(runLegacyAsyncData(res, options.asyncData));
      }
      if (options.head) {
        const nuxtApp = useNuxtApp();
        useHead(typeof options.head === "function" ? () => options.head(nuxtApp) : options.head);
      }
      return Promise.resolve(res).then(() => Promise.all(promises)).then(() => res).finally(() => {
        promises.length = 0;
      });
    }
  };
};
const isVue2 = false;
/*!
  * pinia v2.0.29
  * (c) 2023 Eduardo San Martin Morote
  * @license MIT
  */
let activePinia;
const setActivePinia = (pinia) => activePinia = pinia;
const piniaSymbol = (
  /* istanbul ignore next */
  Symbol()
);
function isPlainObject(o) {
  return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
}
var MutationType;
(function(MutationType2) {
  MutationType2["direct"] = "direct";
  MutationType2["patchObject"] = "patch object";
  MutationType2["patchFunction"] = "patch function";
})(MutationType || (MutationType = {}));
function createPinia() {
  const scope = effectScope(true);
  const state = scope.run(() => ref({}));
  let _p = [];
  let toBeInstalled = [];
  const pinia = markRaw({
    install(app) {
      setActivePinia(pinia);
      {
        pinia._a = app;
        app.provide(piniaSymbol, pinia);
        app.config.globalProperties.$pinia = pinia;
        toBeInstalled.forEach((plugin) => _p.push(plugin));
        toBeInstalled = [];
      }
    },
    use(plugin) {
      if (!this._a && !isVue2) {
        toBeInstalled.push(plugin);
      } else {
        _p.push(plugin);
      }
      return this;
    },
    _p,
    // it's actually undefined here
    // @ts-expect-error
    _a: null,
    _e: scope,
    _s: /* @__PURE__ */ new Map(),
    state
  });
  return pinia;
}
const noop = () => {
};
function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  subscriptions.push(callback);
  const removeSubscription = () => {
    const idx = subscriptions.indexOf(callback);
    if (idx > -1) {
      subscriptions.splice(idx, 1);
      onCleanup();
    }
  };
  if (!detached && getCurrentScope()) {
    onScopeDispose(removeSubscription);
  }
  return removeSubscription;
}
function triggerSubscriptions(subscriptions, ...args) {
  subscriptions.slice().forEach((callback) => {
    callback(...args);
  });
}
function mergeReactiveObjects(target, patchToApply) {
  if (target instanceof Map && patchToApply instanceof Map) {
    patchToApply.forEach((value, key) => target.set(key, value));
  }
  if (target instanceof Set && patchToApply instanceof Set) {
    patchToApply.forEach(target.add, target);
  }
  for (const key in patchToApply) {
    if (!patchToApply.hasOwnProperty(key))
      continue;
    const subPatch = patchToApply[key];
    const targetValue = target[key];
    if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) {
      target[key] = mergeReactiveObjects(targetValue, subPatch);
    } else {
      target[key] = subPatch;
    }
  }
  return target;
}
const skipHydrateSymbol = (
  /* istanbul ignore next */
  Symbol()
);
function shouldHydrate(obj) {
  return !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
}
const { assign } = Object;
function isComputed(o) {
  return !!(isRef(o) && o.effect);
}
function createOptionsStore(id, options, pinia, hot) {
  const { state, actions, getters } = options;
  const initialState = pinia.state.value[id];
  let store;
  function setup() {
    if (!initialState && true) {
      {
        pinia.state.value[id] = state ? state() : {};
      }
    }
    const localState = toRefs(pinia.state.value[id]);
    return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
      computedGetters[name] = markRaw(computed(() => {
        setActivePinia(pinia);
        const store2 = pinia._s.get(id);
        return getters[name].call(store2, store2);
      }));
      return computedGetters;
    }, {}));
  }
  store = createSetupStore(id, setup, options, pinia, hot, true);
  store.$reset = function $reset() {
    const newState = state ? state() : {};
    this.$patch(($state) => {
      assign($state, newState);
    });
  };
  return store;
}
function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  let scope;
  const optionsForPlugin = assign({ actions: {} }, options);
  const $subscribeOptions = {
    deep: true
    // flush: 'post',
  };
  let isListening;
  let isSyncListening;
  let subscriptions = markRaw([]);
  let actionSubscriptions = markRaw([]);
  let debuggerEvents;
  const initialState = pinia.state.value[$id];
  if (!isOptionsStore && !initialState && true) {
    {
      pinia.state.value[$id] = {};
    }
  }
  ref({});
  let activeListener;
  function $patch(partialStateOrMutator) {
    let subscriptionMutation;
    isListening = isSyncListening = false;
    if (typeof partialStateOrMutator === "function") {
      partialStateOrMutator(pinia.state.value[$id]);
      subscriptionMutation = {
        type: MutationType.patchFunction,
        storeId: $id,
        events: debuggerEvents
      };
    } else {
      mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
      subscriptionMutation = {
        type: MutationType.patchObject,
        payload: partialStateOrMutator,
        storeId: $id,
        events: debuggerEvents
      };
    }
    const myListenerId = activeListener = Symbol();
    nextTick().then(() => {
      if (activeListener === myListenerId) {
        isListening = true;
      }
    });
    isSyncListening = true;
    triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  }
  const $reset = noop;
  function $dispose() {
    scope.stop();
    subscriptions = [];
    actionSubscriptions = [];
    pinia._s.delete($id);
  }
  function wrapAction(name, action) {
    return function() {
      setActivePinia(pinia);
      const args = Array.from(arguments);
      const afterCallbackList = [];
      const onErrorCallbackList = [];
      function after(callback) {
        afterCallbackList.push(callback);
      }
      function onError(callback) {
        onErrorCallbackList.push(callback);
      }
      triggerSubscriptions(actionSubscriptions, {
        args,
        name,
        store,
        after,
        onError
      });
      let ret;
      try {
        ret = action.apply(this && this.$id === $id ? this : store, args);
      } catch (error) {
        triggerSubscriptions(onErrorCallbackList, error);
        throw error;
      }
      if (ret instanceof Promise) {
        return ret.then((value) => {
          triggerSubscriptions(afterCallbackList, value);
          return value;
        }).catch((error) => {
          triggerSubscriptions(onErrorCallbackList, error);
          return Promise.reject(error);
        });
      }
      triggerSubscriptions(afterCallbackList, ret);
      return ret;
    };
  }
  const partialStore = {
    _p: pinia,
    // _s: scope,
    $id,
    $onAction: addSubscription.bind(null, actionSubscriptions),
    $patch,
    $reset,
    $subscribe(callback, options2 = {}) {
      const removeSubscription = addSubscription(subscriptions, callback, options2.detached, () => stopWatcher());
      const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
        if (options2.flush === "sync" ? isSyncListening : isListening) {
          callback({
            storeId: $id,
            type: MutationType.direct,
            events: debuggerEvents
          }, state);
        }
      }, assign({}, $subscribeOptions, options2)));
      return removeSubscription;
    },
    $dispose
  };
  const store = reactive(partialStore);
  pinia._s.set($id, store);
  const setupStore = pinia._e.run(() => {
    scope = effectScope();
    return scope.run(() => setup());
  });
  for (const key in setupStore) {
    const prop = setupStore[key];
    if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
      if (!isOptionsStore) {
        if (initialState && shouldHydrate(prop)) {
          if (isRef(prop)) {
            prop.value = initialState[key];
          } else {
            mergeReactiveObjects(prop, initialState[key]);
          }
        }
        {
          pinia.state.value[$id][key] = prop;
        }
      }
    } else if (typeof prop === "function") {
      const actionValue = wrapAction(key, prop);
      {
        setupStore[key] = actionValue;
      }
      optionsForPlugin.actions[key] = prop;
    } else ;
  }
  {
    assign(store, setupStore);
    assign(toRaw(store), setupStore);
  }
  Object.defineProperty(store, "$state", {
    get: () => pinia.state.value[$id],
    set: (state) => {
      $patch(($state) => {
        assign($state, state);
      });
    }
  });
  pinia._p.forEach((extender) => {
    {
      assign(store, scope.run(() => extender({
        store,
        app: pinia._a,
        pinia,
        options: optionsForPlugin
      })));
    }
  });
  if (initialState && isOptionsStore && options.hydrate) {
    options.hydrate(store.$state, initialState);
  }
  isListening = true;
  isSyncListening = true;
  return store;
}
function defineStore(idOrOptions, setup, setupOptions) {
  let id;
  let options;
  const isSetupStore = typeof setup === "function";
  if (typeof idOrOptions === "string") {
    id = idOrOptions;
    options = isSetupStore ? setupOptions : setup;
  } else {
    options = idOrOptions;
    id = idOrOptions.id;
  }
  function useStore(pinia, hot) {
    const currentInstance = getCurrentInstance();
    pinia = // in test mode, ignore the argument provided as we can always retrieve a
    // pinia instance with getActivePinia()
    (pinia) || currentInstance && inject(piniaSymbol, null);
    if (pinia)
      setActivePinia(pinia);
    pinia = activePinia;
    if (!pinia._s.has(id)) {
      if (isSetupStore) {
        createSetupStore(id, setup, options, pinia);
      } else {
        createOptionsStore(id, options, pinia);
      }
    }
    const store = pinia._s.get(id);
    return store;
  }
  useStore.$id = id;
  return useStore;
}
function storeToRefs(store) {
  {
    store = toRaw(store);
    const refs = {};
    for (const key in store) {
      const value = store[key];
      if (isRef(value) || isReactive(value)) {
        refs[key] = // ---
        toRef(store, key);
      }
    }
    return refs;
  }
}
function extendPermissionDescriptor(descriptor) {
  if (typeof descriptor.target === "undefined") {
    descriptor.target = null;
  }
  if (typeof descriptor.inverse === "undefined") {
    descriptor.inverse = null;
  }
  return descriptor;
}
var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
  ErrorCode2["ABILITY_INVALID"] = "invalid_ability";
  ErrorCode2["HEADER_INVALID"] = "invalid_header";
  ErrorCode2["HEADER_AUTH_TYPE_UNSUPPORTED"] = "unsupported_auth_header_type";
  ErrorCode2["CREDENTIALS_INVALID"] = "invalid_credentials";
  ErrorCode2["ENTITY_INACTIVE"] = "inactive_entity";
  ErrorCode2["TOKEN_REDIRECT_URI_MISMATCH"] = "redirect_uri_mismatch";
  ErrorCode2["TOKEN_INVALID"] = "invalid_token";
  ErrorCode2["TOKEN_INACTIVE"] = "inactive_token";
  ErrorCode2["TOKEN_EXPIRED"] = "expired_token";
  ErrorCode2["TOKEN_CLIENT_INVALID"] = "invalid_client";
  ErrorCode2["TOKEN_GRANT_INVALID"] = "invalid_grant";
  ErrorCode2["TOKEN_GRANT_TYPE_UNSUPPORTED"] = "unsupported_token_grant_type";
  ErrorCode2["TOKEN_SCOPE_INVALID"] = "invalid_scope";
  ErrorCode2["TOKEN_SUB_KIND_INVALID"] = "invalid_token_sub_kind";
  return ErrorCode2;
})(ErrorCode || {});
class AbilityError extends BaseError {
  constructor(options) {
    super(mergeOptions({
      code: ErrorCode.ABILITY_INVALID
    }, options || {}));
  }
  static buildMeta() {
    return new AbilityError({
      message: "The ability meta could not be built."
    });
  }
}
function buildAbilityMetaFromName(name, delimiter = "_") {
  const parts = name.split(delimiter);
  if (parts.length < 2) {
    throw AbilityError.buildMeta();
  }
  const action = parts.pop();
  const subject = pascalCase(parts.join(" "));
  return {
    action,
    subject
  };
}
function buildNameFromAbilityID(meta) {
  return `${meta.subject}_${meta.subject}`;
}
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
function isPropertySet(obj, prop) {
  return hasOwnProperty(obj, prop);
}
function isAbilityID(input) {
  return typeof input === "object" && hasOwnProperty(input, "action") && hasOwnProperty(input, "subject") && (typeof input.subject === "string" || typeof input.subject === "object");
}
class AbilityManager {
  // ----------------------------------------------
  constructor(input = []) {
    __publicField(this, "items");
    this.set(input);
  }
  // ----------------------------------------------
  /**
   * Check if permission is assigned with field and condition restriction.
   *
   * @param action
   * @param subject
   * @param field
   */
  verify(action, subject, field) {
    if (isAbilityID(action)) {
      action = buildNameFromAbilityID(action);
    }
    const item = this.getOne(action, {
      withoutInverse: true,
      subject,
      field
    });
    return !!item;
  }
  /**
   * Check if permission is assigned without field or condition restriction.
   *
   * @param action
   * @param withoutInverse
   */
  has(action, withoutInverse = true) {
    if (Array.isArray(action)) {
      return action.some((item2) => this.has(item2));
    }
    if (typeof action !== "string") {
      action = buildNameFromAbilityID(action);
    }
    const item = this.getOne(action, {
      withoutInverse
    });
    return !!item;
  }
  // ----------------------------------------------
  satisfy(predicate, subject) {
    const item = this.getOne(predicate, {
      subject
    });
    return !!item;
  }
  // ----------------------------------------------
  getTarget(value) {
    let predicate;
    if (typeof value === "string") {
      predicate = { name: { $eq: value } };
    } else {
      predicate = value;
    }
    predicate.target = { $eq: null };
    let item = this.getOne(predicate);
    if (item) {
      return item.target;
    }
    delete predicate.target;
    item = this.getOne(predicate);
    return item ? item.target : void 0;
  }
  matchTarget(id, target) {
    let basePredicate;
    if (typeof id === "string") {
      basePredicate = {
        name: {
          $eq: id
        }
      };
    } else {
      basePredicate = id;
    }
    return [null, target].some((value) => this.satisfy({
      ...basePredicate,
      target: {
        $eq: value
      }
    }));
  }
  // ----------------------------------------------
  getPower(id, direction = "max") {
    let sortFn;
    if (direction === "min") {
      sortFn = (a, b) => a.power - b.power;
    } else {
      sortFn = (a, b) => b.power - a.power;
    }
    const item = this.getOne(id, {
      withoutInverse: true,
      sortFn
    });
    return item ? item.power : void 0;
  }
  // ----------------------------------------------
  getMany() {
    return this.items;
  }
  getOne(predicate, options) {
    if (typeof predicate === "string") {
      predicate = {
        name: {
          $eq: predicate
        }
      };
    }
    const test = guard(predicate);
    options = options || {};
    if (typeof options.sortFn !== "undefined") {
      this.items.sort(options.sortFn);
    }
    for (let i = 0; i < this.items.length; i++) {
      if (!test(this.items[i])) {
        continue;
      }
      if (this.items[i].condition && options.subject) {
        const conditionTest = guard(this.items[i].condition);
        if (!conditionTest(options.subject)) {
          continue;
        }
      }
      if (this.items[i].fields && options.field) {
        const index = this.items[i].fields.indexOf(options.field);
        if (index === -1) {
          continue;
        }
      }
      if (options.withoutInverse && this.items[i].inverse) {
        continue;
      }
      return this.items[i];
    }
    return void 0;
  }
  set(input, merge) {
    const configurations = Array.isArray(input) ? input : [input];
    const items = [];
    for (let i = 0; i < configurations.length; i++) {
      configurations[i] = extendPermissionDescriptor(configurations[i]);
      items[i] = {
        ...configurations[i],
        ...buildAbilityMetaFromName(configurations[i].name)
      };
    }
    if (merge) {
      this.items = [...this.items, ...items];
    } else {
      this.items = items;
    }
  }
}
var OAuth2TokenKind = /* @__PURE__ */ ((OAuth2TokenKind2) => {
  OAuth2TokenKind2["ACCESS"] = "access_token";
  OAuth2TokenKind2["ID_TOKEN"] = "id_token";
  OAuth2TokenKind2["REFRESH"] = "refresh_token";
  return OAuth2TokenKind2;
})(OAuth2TokenKind || {});
const useAuthStore = defineStore("auth", () => {
  const config = useRuntimeConfig();
  const client = new Client({
    options: {
      token_endpoint: new URL("token", config.public.apiUrl).href,
      introspection_endpoint: new URL("token/introspect", config.public.apiUrl).href,
      userinfo_endpoint: new URL("users/@me", config.public.apiUrl).href
    }
  });
  client.mountResponseInterceptor((r) => r, (error) => {
    var _a, _b;
    if (typeof ((_b = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) === "string") {
      error.message = error.response.data.message;
      return Promise.reject(error);
    }
    return Promise.reject(new Error("A network error occurred."));
  });
  const accessToken = ref(void 0);
  const accessTokenExpireDate = ref(void 0);
  const refreshToken = ref(void 0);
  let refreshTokenJob;
  const registerRefreshTokenJob = () => {
    if (!accessTokenExpireDate.value) {
      return;
    }
    const callback = async () => {
      const router = useRouter();
      await router.push({
        path: "/logout",
        query: {
          redirect: router.currentRoute.value.fullPath
        }
      });
    };
    if (refreshTokenJob) {
      clearTimeout(refreshTokenJob);
    }
    const timeoutMilliSeconds = accessTokenExpireDate.value.getTime() - Date.now() - 30;
    if (timeoutMilliSeconds < 0) {
      Promise.resolve().then(callback);
    }
    refreshTokenJob = setTimeout(callback, timeoutMilliSeconds);
  };
  const setToken = (kind, token2) => {
    switch (kind) {
      case OAuth2TokenKind.ACCESS: {
        accessToken.value = token2;
        break;
      }
      case OAuth2TokenKind.REFRESH:
        refreshToken.value = token2;
        break;
    }
  };
  const unsetToken = (kind) => {
    switch (kind) {
      case OAuth2TokenKind.ACCESS: {
        accessToken.value = void 0;
        accessTokenExpireDate.value = void 0;
        break;
      }
      case OAuth2TokenKind.REFRESH:
        refreshToken.value = void 0;
        break;
    }
  };
  const setTokenExpireDate = (date) => {
    accessTokenExpireDate.value = date;
    registerRefreshTokenJob();
  };
  let refreshTokenPromise;
  const attemptRefreshToken = () => {
    if (!refreshToken.value) {
      return Promise.reject(new Error("No refresh token is present."));
    }
    if (!refreshTokenPromise) {
      refreshTokenPromise = client.token.createWithRefreshToken({
        refresh_token: refreshToken.value
      }).then((r) => {
        refreshTokenPromise = void 0;
        return r;
      }).catch((e) => {
        logout();
        refreshTokenPromise = void 0;
        throw e;
      });
      return refreshTokenPromise;
    }
    return refreshTokenPromise;
  };
  const user = ref(void 0);
  const userId = computed(() => user.value ? user.value.id : void 0);
  let userResolved = false;
  const setUser = (entity) => {
    user.value = entity;
    userResolved = true;
  };
  const unsetUser = () => {
    user.value = void 0;
    userResolved = false;
  };
  const resolveUser = async (force) => {
    if (!accessToken.value || userResolved && !force)
      return;
    userResolved = true;
    try {
      const entity = await client.userInfo.get(accessToken.value);
      setUser(entity);
    } catch (e) {
      if (isClientError(e) && e.response && e.response.data && hasOwnProperty(e.response.data, "code") && e.response.data.code === ErrorCode.TOKEN_EXPIRED) {
        await attemptRefreshToken();
        await resolveUser(true);
        return;
      }
      throw e;
    }
  };
  const abilityManager = new AbilityManager();
  const token = ref(void 0);
  let tokenResolved = false;
  const has = (name) => abilityManager.has(name);
  const realm = ref(void 0);
  const realmId = computed(() => realm.value ? realm.value.id : void 0);
  const realmName = computed(() => realm.value ? realm.value.name : void 0);
  const setRealm = (entity) => {
    realm.value = entity;
  };
  const realmManagement = ref(void 0);
  const realmManagementId = computed(() => realmManagement.value ? realmManagement.value.id : realmId.value);
  const realmManagementName = computed(() => realmManagement.value ? realmManagement.value.name : realmName.value);
  const setRealmManagement = (entity) => {
    realmManagement.value = entity;
  };
  const setTokenInfo = (entity) => {
    tokenResolved = true;
    token.value = entity;
    if (entity.realm_id && entity.realm_name) {
      realm.value = {
        id: entity.realm_id,
        name: entity.realm_name
      };
      if (typeof realmManagement.value === "undefined") {
        setRealmManagement(realm.value);
      }
    }
    if (entity.permissions) {
      abilityManager.set(entity.permissions);
    }
  };
  const unsetTokenInfo = () => {
    tokenResolved = false;
    token.value = void 0;
    realm.value = void 0;
    realmManagement.value = void 0;
    abilityManager.set([]);
  };
  const introspectToken = async (force) => {
    if (!accessToken.value || tokenResolved && !force)
      return;
    tokenResolved = true;
    try {
      const token2 = await client.token.introspect(accessToken.value);
      setTokenInfo(token2);
    } catch (e) {
      if (isClientError(e) && e.response && e.response.data && hasOwnProperty(e.response.data, "code") && e.response.data.code === ErrorCode.TOKEN_EXPIRED) {
        await attemptRefreshToken();
        await introspectToken(true);
        return;
      }
      throw e;
    }
  };
  const resolve = async () => {
    if (!accessToken.value)
      return;
    await resolveUser();
    await introspectToken();
  };
  const loggedIn = computed(() => !!accessToken.value);
  const login = async (name, password) => {
    try {
      const data = await client.token.createWithPasswordGrant({
        username: name,
        password
      });
      const expireDate = new Date(Date.now() + data.expires_in * 1e3);
      setTokenExpireDate(expireDate);
      setToken(OAuth2TokenKind.ACCESS, data.access_token);
      if (data.refresh_token) {
        setToken(OAuth2TokenKind.REFRESH, data.refresh_token);
      }
      await resolve();
    } catch (e) {
      unsetToken(OAuth2TokenKind.ACCESS);
      unsetToken(OAuth2TokenKind.REFRESH);
      throw e;
    }
  };
  const logout = () => {
    unsetToken(OAuth2TokenKind.ACCESS);
    unsetToken(OAuth2TokenKind.REFRESH);
    unsetUser();
    unsetTokenInfo();
  };
  return {
    login,
    logout,
    loggedIn,
    resolve,
    accessToken,
    accessTokenExpireDate,
    refreshToken,
    attemptRefreshToken,
    setToken,
    setTokenExpireDate,
    unsetToken,
    token,
    setTokenInfo,
    unsetTokenInfo,
    realm,
    realmId,
    realmName,
    setRealm,
    realmManagement,
    realmManagementId,
    realmManagementName,
    setRealmManagement,
    user,
    userId,
    setUser,
    unsetUser,
    has
  };
});

export { ErrorCode as E, OAuth2TokenKind as O, useError as a, storeToRefs as b, createPinia as c, defineNuxtComponent as d, buildNameFromAbilityID as e, setActivePinia as f, createError as g, hasOwnProperty as h, isPropertySet as i, showError as s, useAuthStore as u };
//# sourceMappingURL=auth-2d06b6ac.mjs.map
